VRButton.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /**
  2. * A utility class for creating a button that allows to initiate
  3. * immersive VR sessions based on WebXR. The button can be created
  4. * with a factory method and then appended ot the website's DOM.
  5. *
  6. * ```js
  7. * document.body.appendChild( VRButton.createButton( renderer ) );
  8. * ```
  9. *
  10. * @hideconstructor
  11. * @three_import import { VRButton } from 'three/addons/webxr/VRButton.js';
  12. */
  13. class VRButton {
  14. /**
  15. * Constructs a new VR button.
  16. *
  17. * @param {WebGLRenderer|WebGPURenderer} renderer - The renderer.
  18. * @param {XRSessionInit} [sessionInit] - The a configuration object for the AR session.
  19. * @return {HTMLElement} The button or an error message if `immersive-ar` isn't supported.
  20. */
  21. static createButton( renderer, sessionInit = {} ) {
  22. const button = document.createElement( 'button' );
  23. function showEnterVR( /*device*/ ) {
  24. let currentSession = null;
  25. async function onSessionStarted( session ) {
  26. session.addEventListener( 'end', onSessionEnded );
  27. await renderer.xr.setSession( session );
  28. button.textContent = 'EXIT VR';
  29. currentSession = session;
  30. }
  31. function onSessionEnded( /*event*/ ) {
  32. currentSession.removeEventListener( 'end', onSessionEnded );
  33. button.textContent = 'ENTER VR';
  34. currentSession = null;
  35. }
  36. //
  37. button.style.display = '';
  38. button.style.cursor = 'pointer';
  39. button.style.left = 'calc(50% - 50px)';
  40. button.style.width = '100px';
  41. button.textContent = 'ENTER VR';
  42. // WebXR's requestReferenceSpace only works if the corresponding feature
  43. // was requested at session creation time. For simplicity, just ask for
  44. // the interesting ones as optional features, but be aware that the
  45. // requestReferenceSpace call will fail if it turns out to be unavailable.
  46. // ('local' is always available for immersive sessions and doesn't need to
  47. // be requested separately.)
  48. const sessionOptions = {
  49. ...sessionInit,
  50. optionalFeatures: [
  51. 'local-floor',
  52. 'bounded-floor',
  53. 'layers',
  54. ...( sessionInit.optionalFeatures || [] )
  55. ],
  56. };
  57. button.onmouseenter = function () {
  58. button.style.opacity = '1.0';
  59. };
  60. button.onmouseleave = function () {
  61. button.style.opacity = '0.5';
  62. };
  63. button.onclick = function () {
  64. if ( currentSession === null ) {
  65. navigator.xr.requestSession( 'immersive-vr', sessionOptions ).then( onSessionStarted );
  66. } else {
  67. currentSession.end();
  68. if ( navigator.xr.offerSession !== undefined ) {
  69. navigator.xr.offerSession( 'immersive-vr', sessionOptions )
  70. .then( onSessionStarted )
  71. .catch( ( err ) => {
  72. console.warn( err );
  73. } );
  74. }
  75. }
  76. };
  77. if ( navigator.xr.offerSession !== undefined ) {
  78. navigator.xr.offerSession( 'immersive-vr', sessionOptions )
  79. .then( onSessionStarted )
  80. .catch( ( err ) => {
  81. console.warn( err );
  82. } );
  83. }
  84. }
  85. function disableButton() {
  86. button.style.display = '';
  87. button.style.cursor = 'auto';
  88. button.style.left = 'calc(50% - 75px)';
  89. button.style.width = '150px';
  90. button.onmouseenter = null;
  91. button.onmouseleave = null;
  92. button.onclick = null;
  93. }
  94. function showWebXRNotFound() {
  95. disableButton();
  96. button.textContent = 'VR NOT SUPPORTED';
  97. }
  98. function showVRNotAllowed( exception ) {
  99. disableButton();
  100. console.warn( 'Exception when trying to call xr.isSessionSupported', exception );
  101. button.textContent = 'VR NOT ALLOWED';
  102. }
  103. function stylizeElement( element ) {
  104. element.style.position = 'absolute';
  105. element.style.bottom = '20px';
  106. element.style.padding = '12px 6px';
  107. element.style.border = '1px solid #fff';
  108. element.style.borderRadius = '4px';
  109. element.style.background = 'rgba(0,0,0,0.1)';
  110. element.style.color = '#fff';
  111. element.style.font = 'normal 13px sans-serif';
  112. element.style.textAlign = 'center';
  113. element.style.opacity = '0.5';
  114. element.style.outline = 'none';
  115. element.style.zIndex = '999';
  116. }
  117. if ( 'xr' in navigator ) {
  118. button.id = 'VRButton';
  119. button.style.display = 'none';
  120. stylizeElement( button );
  121. navigator.xr.isSessionSupported( 'immersive-vr' ).then( function ( supported ) {
  122. supported ? showEnterVR() : showWebXRNotFound();
  123. if ( supported && VRButton.xrSessionIsGranted ) {
  124. button.click();
  125. }
  126. } ).catch( showVRNotAllowed );
  127. return button;
  128. } else {
  129. const message = document.createElement( 'a' );
  130. if ( window.isSecureContext === false ) {
  131. message.href = document.location.href.replace( /^http:/, 'https:' );
  132. message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message
  133. } else {
  134. message.href = 'https://immersiveweb.dev/';
  135. message.innerHTML = 'WEBXR NOT AVAILABLE';
  136. }
  137. message.style.left = 'calc(50% - 90px)';
  138. message.style.width = '180px';
  139. message.style.textDecoration = 'none';
  140. stylizeElement( message );
  141. return message;
  142. }
  143. }
  144. /**
  145. * Registers a `sessiongranted` event listener. When a session is granted, the {@link VRButton#xrSessionIsGranted}
  146. * flag will evaluate to `true`. This method is automatically called by the module itself so there
  147. * should be no need to use it on app level.
  148. */
  149. static registerSessionGrantedListener() {
  150. if ( typeof navigator !== 'undefined' && 'xr' in navigator ) {
  151. // WebXRViewer (based on Firefox) has a bug where addEventListener
  152. // throws a silent exception and aborts execution entirely.
  153. if ( /WebXRViewer\//i.test( navigator.userAgent ) ) return;
  154. navigator.xr.addEventListener( 'sessiongranted', () => {
  155. VRButton.xrSessionIsGranted = true;
  156. } );
  157. }
  158. }
  159. }
  160. /**
  161. * Whether a XR session has been granted or not.
  162. *
  163. * @static
  164. * @type {boolean}
  165. * @default false
  166. */
  167. VRButton.xrSessionIsGranted = false;
  168. VRButton.registerSessionGrantedListener();
  169. export { VRButton };