WebXRManager.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. import { ArrayCamera } from '../../cameras/ArrayCamera.js';
  2. import { EventDispatcher } from '../../core/EventDispatcher.js';
  3. import { PerspectiveCamera } from '../../cameras/PerspectiveCamera.js';
  4. import { Vector3 } from '../../math/Vector3.js';
  5. import { Vector4 } from '../../math/Vector4.js';
  6. import { WebGLAnimation } from '../webgl/WebGLAnimation.js';
  7. import { WebGLRenderTarget } from '../WebGLRenderTarget.js';
  8. import { WebXRController } from './WebXRController.js';
  9. import { DepthTexture } from '../../textures/DepthTexture.js';
  10. import { WebGLMultisampleRenderTarget } from '../WebGLMultisampleRenderTarget.js';
  11. import {
  12. DepthFormat,
  13. DepthStencilFormat,
  14. RGBAFormat,
  15. sRGBEncoding,
  16. UnsignedByteType,
  17. UnsignedShortType,
  18. UnsignedInt248Type,
  19. } from '../../constants.js';
  20. class WebXRManager extends EventDispatcher {
  21. constructor( renderer, gl ) {
  22. super();
  23. const scope = this;
  24. let session = null;
  25. let framebufferScaleFactor = 1.0;
  26. let referenceSpace = null;
  27. let referenceSpaceType = 'local-floor';
  28. const hasMultisampledRenderToTexture = renderer.extensions.has( 'WEBGL_multisampled_render_to_texture' );
  29. let pose = null;
  30. let glBinding = null;
  31. let glProjLayer = null;
  32. let glBaseLayer = null;
  33. let isMultisample = false;
  34. let xrFrame = null;
  35. const attributes = gl.getContextAttributes();
  36. let initialRenderTarget = null;
  37. let newRenderTarget = null;
  38. const controllers = [];
  39. const inputSourcesMap = new Map();
  40. //
  41. const cameraL = new PerspectiveCamera();
  42. cameraL.layers.enable( 1 );
  43. cameraL.viewport = new Vector4();
  44. const cameraR = new PerspectiveCamera();
  45. cameraR.layers.enable( 2 );
  46. cameraR.viewport = new Vector4();
  47. const cameras = [ cameraL, cameraR ];
  48. const cameraVR = new ArrayCamera();
  49. cameraVR.layers.enable( 1 );
  50. cameraVR.layers.enable( 2 );
  51. let _currentDepthNear = null;
  52. let _currentDepthFar = null;
  53. //
  54. this.cameraAutoUpdate = true;
  55. this.enabled = false;
  56. this.isPresenting = false;
  57. this.getController = function ( index ) {
  58. let controller = controllers[ index ];
  59. if ( controller === undefined ) {
  60. controller = new WebXRController();
  61. controllers[ index ] = controller;
  62. }
  63. return controller.getTargetRaySpace();
  64. };
  65. this.getControllerGrip = function ( index ) {
  66. let controller = controllers[ index ];
  67. if ( controller === undefined ) {
  68. controller = new WebXRController();
  69. controllers[ index ] = controller;
  70. }
  71. return controller.getGripSpace();
  72. };
  73. this.getHand = function ( index ) {
  74. let controller = controllers[ index ];
  75. if ( controller === undefined ) {
  76. controller = new WebXRController();
  77. controllers[ index ] = controller;
  78. }
  79. return controller.getHandSpace();
  80. };
  81. //
  82. function onSessionEvent( event ) {
  83. const controller = inputSourcesMap.get( event.inputSource );
  84. if ( controller ) {
  85. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  86. }
  87. }
  88. function onSessionEnd() {
  89. inputSourcesMap.forEach( function ( controller, inputSource ) {
  90. controller.disconnect( inputSource );
  91. } );
  92. inputSourcesMap.clear();
  93. _currentDepthNear = null;
  94. _currentDepthFar = null;
  95. // restore framebuffer/rendering state
  96. renderer.setRenderTarget( initialRenderTarget );
  97. glBaseLayer = null;
  98. glProjLayer = null;
  99. glBinding = null;
  100. session = null;
  101. newRenderTarget = null;
  102. //
  103. animation.stop();
  104. scope.isPresenting = false;
  105. scope.dispatchEvent( { type: 'sessionend' } );
  106. }
  107. this.setFramebufferScaleFactor = function ( value ) {
  108. framebufferScaleFactor = value;
  109. if ( scope.isPresenting === true ) {
  110. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  111. }
  112. };
  113. this.setReferenceSpaceType = function ( value ) {
  114. referenceSpaceType = value;
  115. if ( scope.isPresenting === true ) {
  116. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  117. }
  118. };
  119. this.getReferenceSpace = function () {
  120. return referenceSpace;
  121. };
  122. this.getBaseLayer = function () {
  123. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  124. };
  125. this.getBinding = function () {
  126. return glBinding;
  127. };
  128. this.getFrame = function () {
  129. return xrFrame;
  130. };
  131. this.getSession = function () {
  132. return session;
  133. };
  134. this.setSession = async function ( value ) {
  135. session = value;
  136. if ( session !== null ) {
  137. initialRenderTarget = renderer.getRenderTarget();
  138. session.addEventListener( 'select', onSessionEvent );
  139. session.addEventListener( 'selectstart', onSessionEvent );
  140. session.addEventListener( 'selectend', onSessionEvent );
  141. session.addEventListener( 'squeeze', onSessionEvent );
  142. session.addEventListener( 'squeezestart', onSessionEvent );
  143. session.addEventListener( 'squeezeend', onSessionEvent );
  144. session.addEventListener( 'end', onSessionEnd );
  145. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  146. if ( attributes.xrCompatible !== true ) {
  147. await gl.makeXRCompatible();
  148. }
  149. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  150. const layerInit = {
  151. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  152. alpha: attributes.alpha,
  153. depth: attributes.depth,
  154. stencil: attributes.stencil,
  155. framebufferScaleFactor: framebufferScaleFactor
  156. };
  157. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  158. session.updateRenderState( { baseLayer: glBaseLayer } );
  159. newRenderTarget = new WebGLRenderTarget(
  160. glBaseLayer.framebufferWidth,
  161. glBaseLayer.framebufferHeight,
  162. {
  163. format: RGBAFormat,
  164. type: UnsignedByteType,
  165. encoding: renderer.outputEncoding
  166. }
  167. );
  168. } else {
  169. isMultisample = attributes.antialias;
  170. let depthFormat = null;
  171. let depthType = null;
  172. let glDepthFormat = null;
  173. if ( attributes.depth ) {
  174. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  175. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  176. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType;
  177. }
  178. const projectionlayerInit = {
  179. colorFormat: ( renderer.outputEncoding === sRGBEncoding ) ? gl.SRGB8_ALPHA8 : gl.RGBA8,
  180. depthFormat: glDepthFormat,
  181. scaleFactor: framebufferScaleFactor
  182. };
  183. glBinding = new XRWebGLBinding( session, gl );
  184. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  185. session.updateRenderState( { layers: [ glProjLayer ] } );
  186. if ( isMultisample ) {
  187. newRenderTarget = new WebGLMultisampleRenderTarget(
  188. glProjLayer.textureWidth,
  189. glProjLayer.textureHeight,
  190. {
  191. format: RGBAFormat,
  192. type: UnsignedByteType,
  193. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  194. stencilBuffer: attributes.stencil,
  195. ignoreDepth: glProjLayer.ignoreDepthValues,
  196. useRenderToTexture: hasMultisampledRenderToTexture,
  197. encoding: renderer.outputEncoding
  198. } );
  199. } else {
  200. newRenderTarget = new WebGLRenderTarget(
  201. glProjLayer.textureWidth,
  202. glProjLayer.textureHeight,
  203. {
  204. format: RGBAFormat,
  205. type: UnsignedByteType,
  206. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  207. stencilBuffer: attributes.stencil,
  208. ignoreDepth: glProjLayer.ignoreDepthValues,
  209. encoding: renderer.outputEncoding
  210. } );
  211. }
  212. }
  213. // Set foveation to maximum.
  214. this.setFoveation( 1.0 );
  215. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  216. animation.setContext( session );
  217. animation.start();
  218. scope.isPresenting = true;
  219. scope.dispatchEvent( { type: 'sessionstart' } );
  220. }
  221. };
  222. function onInputSourcesChange( event ) {
  223. const inputSources = session.inputSources;
  224. // Assign inputSources to available controllers
  225. for ( let i = 0; i < controllers.length; i ++ ) {
  226. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  227. }
  228. // Notify disconnected
  229. for ( let i = 0; i < event.removed.length; i ++ ) {
  230. const inputSource = event.removed[ i ];
  231. const controller = inputSourcesMap.get( inputSource );
  232. if ( controller ) {
  233. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  234. inputSourcesMap.delete( inputSource );
  235. }
  236. }
  237. // Notify connected
  238. for ( let i = 0; i < event.added.length; i ++ ) {
  239. const inputSource = event.added[ i ];
  240. const controller = inputSourcesMap.get( inputSource );
  241. if ( controller ) {
  242. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  243. }
  244. }
  245. }
  246. //
  247. const cameraLPos = new Vector3();
  248. const cameraRPos = new Vector3();
  249. /**
  250. * Assumes 2 cameras that are parallel and share an X-axis, and that
  251. * the cameras' projection and world matrices have already been set.
  252. * And that near and far planes are identical for both cameras.
  253. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  254. */
  255. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  256. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  257. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  258. const ipd = cameraLPos.distanceTo( cameraRPos );
  259. const projL = cameraL.projectionMatrix.elements;
  260. const projR = cameraR.projectionMatrix.elements;
  261. // VR systems will have identical far and near planes, and
  262. // most likely identical top and bottom frustum extents.
  263. // Use the left camera for these values.
  264. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  265. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  266. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  267. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  268. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  269. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  270. const left = near * leftFov;
  271. const right = near * rightFov;
  272. // Calculate the new camera's position offset from the
  273. // left camera. xOffset should be roughly half `ipd`.
  274. const zOffset = ipd / ( - leftFov + rightFov );
  275. const xOffset = zOffset * - leftFov;
  276. // TODO: Better way to apply this offset?
  277. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  278. camera.translateX( xOffset );
  279. camera.translateZ( zOffset );
  280. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  281. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  282. // Find the union of the frustum values of the cameras and scale
  283. // the values so that the near plane's position does not change in world space,
  284. // although must now be relative to the new union camera.
  285. const near2 = near + zOffset;
  286. const far2 = far + zOffset;
  287. const left2 = left - xOffset;
  288. const right2 = right + ( ipd - xOffset );
  289. const top2 = topFov * far / far2 * near2;
  290. const bottom2 = bottomFov * far / far2 * near2;
  291. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  292. }
  293. function updateCamera( camera, parent ) {
  294. if ( parent === null ) {
  295. camera.matrixWorld.copy( camera.matrix );
  296. } else {
  297. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  298. }
  299. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  300. }
  301. this.updateCamera = function ( camera ) {
  302. if ( session === null ) return;
  303. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  304. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  305. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  306. // Note that the new renderState won't apply until the next frame. See #18320
  307. session.updateRenderState( {
  308. depthNear: cameraVR.near,
  309. depthFar: cameraVR.far
  310. } );
  311. _currentDepthNear = cameraVR.near;
  312. _currentDepthFar = cameraVR.far;
  313. }
  314. const parent = camera.parent;
  315. const cameras = cameraVR.cameras;
  316. updateCamera( cameraVR, parent );
  317. for ( let i = 0; i < cameras.length; i ++ ) {
  318. updateCamera( cameras[ i ], parent );
  319. }
  320. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  321. // update user camera and its children
  322. camera.position.copy( cameraVR.position );
  323. camera.quaternion.copy( cameraVR.quaternion );
  324. camera.scale.copy( cameraVR.scale );
  325. camera.matrix.copy( cameraVR.matrix );
  326. camera.matrixWorld.copy( cameraVR.matrixWorld );
  327. const children = camera.children;
  328. for ( let i = 0, l = children.length; i < l; i ++ ) {
  329. children[ i ].updateMatrixWorld( true );
  330. }
  331. // update projection matrix for proper view frustum culling
  332. if ( cameras.length === 2 ) {
  333. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  334. } else {
  335. // assume single camera setup (AR)
  336. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  337. }
  338. };
  339. this.getCamera = function () {
  340. return cameraVR;
  341. };
  342. this.getFoveation = function () {
  343. if ( glProjLayer !== null ) {
  344. return glProjLayer.fixedFoveation;
  345. }
  346. if ( glBaseLayer !== null ) {
  347. return glBaseLayer.fixedFoveation;
  348. }
  349. return undefined;
  350. };
  351. this.setFoveation = function ( foveation ) {
  352. // 0 = no foveation = full resolution
  353. // 1 = maximum foveation = the edges render at lower resolution
  354. if ( glProjLayer !== null ) {
  355. glProjLayer.fixedFoveation = foveation;
  356. }
  357. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  358. glBaseLayer.fixedFoveation = foveation;
  359. }
  360. };
  361. // Animation Loop
  362. let onAnimationFrameCallback = null;
  363. function onAnimationFrame( time, frame ) {
  364. pose = frame.getViewerPose( referenceSpace );
  365. xrFrame = frame;
  366. if ( pose !== null ) {
  367. const views = pose.views;
  368. if ( glBaseLayer !== null ) {
  369. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  370. renderer.setRenderTarget( newRenderTarget );
  371. }
  372. let cameraVRNeedsUpdate = false;
  373. // check if it's necessary to rebuild cameraVR's camera list
  374. if ( views.length !== cameraVR.cameras.length ) {
  375. cameraVR.cameras.length = 0;
  376. cameraVRNeedsUpdate = true;
  377. }
  378. for ( let i = 0; i < views.length; i ++ ) {
  379. const view = views[ i ];
  380. let viewport = null;
  381. if ( glBaseLayer !== null ) {
  382. viewport = glBaseLayer.getViewport( view );
  383. } else {
  384. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  385. viewport = glSubImage.viewport;
  386. // For side-by-side projection, we only produce a single texture for both eyes.
  387. if ( i === 0 ) {
  388. renderer.setRenderTargetTextures(
  389. newRenderTarget,
  390. glSubImage.colorTexture,
  391. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  392. renderer.setRenderTarget( newRenderTarget );
  393. }
  394. }
  395. const camera = cameras[ i ];
  396. camera.matrix.fromArray( view.transform.matrix );
  397. camera.projectionMatrix.fromArray( view.projectionMatrix );
  398. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  399. if ( i === 0 ) {
  400. cameraVR.matrix.copy( camera.matrix );
  401. }
  402. if ( cameraVRNeedsUpdate === true ) {
  403. cameraVR.cameras.push( camera );
  404. }
  405. }
  406. }
  407. //
  408. const inputSources = session.inputSources;
  409. for ( let i = 0; i < controllers.length; i ++ ) {
  410. const controller = controllers[ i ];
  411. const inputSource = inputSources[ i ];
  412. controller.update( inputSource, frame, referenceSpace );
  413. }
  414. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  415. xrFrame = null;
  416. }
  417. const animation = new WebGLAnimation();
  418. animation.setAnimationLoop( onAnimationFrame );
  419. this.setAnimationLoop = function ( callback ) {
  420. onAnimationFrameCallback = callback;
  421. };
  422. this.dispose = function () {};
  423. }
  424. }
  425. export { WebXRManager };