Viewport.VR.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import * as THREE from '../../build/three.module.js';
  2. import { HTMLMesh } from './libs/three.html.js';
  3. import { XRControllerModelFactory } from '../../examples/jsm/webxr/XRControllerModelFactory.js';
  4. class VR {
  5. constructor( editor ) {
  6. const signals = editor.signals;
  7. let group = null;
  8. let camera = null;
  9. let renderer = null;
  10. this.currentSession = null;
  11. const onSessionStarted = async ( session ) => {
  12. if ( group === null ) {
  13. group = new THREE.Group();
  14. editor.sceneHelpers.add( group );
  15. const mesh = new HTMLMesh( document.getElementById( 'sidebar' ) );
  16. mesh.position.set( 1, 1.5, 0 );
  17. mesh.rotation.y = - 0.5;
  18. group.add( mesh );
  19. //
  20. const controllerModelFactory = new XRControllerModelFactory();
  21. const controllerGrip1 = renderer.xr.getControllerGrip( 0 );
  22. controllerGrip1.add( controllerModelFactory.createControllerModel( controllerGrip1 ) );
  23. group.add( controllerGrip1 );
  24. const controllerGrip2 = renderer.xr.getControllerGrip( 1 );
  25. controllerGrip2.add( controllerModelFactory.createControllerModel( controllerGrip2 ) );
  26. group.add( controllerGrip2 );
  27. }
  28. camera = editor.camera.clone();
  29. group.visible = true;
  30. this.currentSession = session;
  31. this.currentSession.addEventListener( 'end', onSessionEnded );
  32. await renderer.xr.setSession( this.currentSession );
  33. };
  34. const onSessionEnded = async () => {
  35. editor.camera.copy( camera );
  36. group.visible = false;
  37. this.currentSession.removeEventListener( 'end', onSessionEnded );
  38. this.currentSession = null;
  39. await renderer.xr.setSession( null );
  40. signals.exitedVR.dispatch();
  41. };
  42. signals.toggleVR.add( () => {
  43. if ( this.currentSession === null ) {
  44. const sessionInit = { optionalFeatures: [ 'local-floor', 'bounded-floor' ] };
  45. navigator.xr.requestSession( 'immersive-vr', sessionInit ).then( onSessionStarted );
  46. } else {
  47. this.currentSession.end();
  48. }
  49. } );
  50. signals.rendererChanged.add( ( value ) => {
  51. renderer = value;
  52. renderer.xr.enabled = true;
  53. } );
  54. }
  55. }
  56. export { VR };