webxr_vr_handinput_pressbutton.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js vr - handinput - press button</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> vr - handinput - press button<br />
  12. (Oculus Browser 15.1+)
  13. </div>
  14. <script type="importmap">
  15. {
  16. "imports": {
  17. "three": "../build/three.module.js",
  18. "three/addons/": "./jsm/"
  19. }
  20. }
  21. </script>
  22. <script type="module">
  23. import * as THREE from 'three';
  24. import { VRButton } from 'three/addons/webxr/VRButton.js';
  25. import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
  26. import { OculusHandModel } from 'three/addons/webxr/OculusHandModel.js';
  27. import { createText } from 'three/addons/webxr/Text2D.js';
  28. import { World, System, Component, TagComponent, Types } from 'three/addons/libs/ecsy.module.js';
  29. class Object3D extends Component { }
  30. Object3D.schema = {
  31. object: { type: Types.Ref }
  32. };
  33. class Button extends Component { }
  34. Button.schema = {
  35. // button states: [resting, pressed, fully_pressed, recovering]
  36. currState: { type: Types.String, default: 'resting' },
  37. prevState: { type: Types.String, default: 'resting' },
  38. pressSound: { type: Types.Ref, default: null },
  39. releaseSound: { type: Types.Ref, default: null },
  40. restingY: { type: Types.Number, default: null },
  41. surfaceY: { type: Types.Number, default: null },
  42. recoverySpeed: { type: Types.Number, default: 0.4 },
  43. fullPressDistance: { type: Types.Number, default: null },
  44. action: { type: Types.Ref, default: () => { } }
  45. };
  46. class ButtonSystem extends System {
  47. init( attributes ) {
  48. this.renderer = attributes.renderer;
  49. this.soundAdded = false;
  50. }
  51. execute( /*delta, time*/ ) {
  52. let buttonPressSound, buttonReleaseSound;
  53. if ( this.renderer.xr.getSession() && ! this.soundAdded ) {
  54. const xrCamera = this.renderer.xr.getCamera();
  55. const listener = new THREE.AudioListener();
  56. xrCamera.add( listener );
  57. // create a global audio source
  58. buttonPressSound = new THREE.Audio( listener );
  59. buttonReleaseSound = new THREE.Audio( listener );
  60. // load a sound and set it as the Audio object's buffer
  61. const audioLoader = new THREE.AudioLoader();
  62. audioLoader.load( 'sounds/button-press.ogg', function ( buffer ) {
  63. buttonPressSound.setBuffer( buffer );
  64. } );
  65. audioLoader.load( 'sounds/button-release.ogg', function ( buffer ) {
  66. buttonReleaseSound.setBuffer( buffer );
  67. } );
  68. this.soundAdded = true;
  69. }
  70. this.queries.buttons.results.forEach( entity => {
  71. const button = entity.getMutableComponent( Button );
  72. const buttonMesh = entity.getComponent( Object3D ).object;
  73. // populate restingY
  74. if ( button.restingY == null ) {
  75. button.restingY = buttonMesh.position.y;
  76. }
  77. if ( buttonPressSound ) {
  78. button.pressSound = buttonPressSound;
  79. }
  80. if ( buttonReleaseSound ) {
  81. button.releaseSound = buttonReleaseSound;
  82. }
  83. if ( button.currState == 'fully_pressed' && button.prevState != 'fully_pressed' ) {
  84. if ( button.pressSound ) button.pressSound.play();
  85. button.action();
  86. }
  87. if ( button.currState == 'recovering' && button.prevState != 'recovering' ) {
  88. if ( button.releaseSound ) button.releaseSound.play();
  89. }
  90. // preserve prevState, clear currState
  91. // FingerInputSystem will update currState
  92. button.prevState = button.currState;
  93. button.currState = 'resting';
  94. } );
  95. }
  96. }
  97. ButtonSystem.queries = {
  98. buttons: {
  99. components: [ Button ]
  100. }
  101. };
  102. class Pressable extends TagComponent { }
  103. class FingerInputSystem extends System {
  104. init( attributes ) {
  105. this.hands = attributes.hands;
  106. }
  107. execute( delta/*, time*/ ) {
  108. this.queries.pressable.results.forEach( entity => {
  109. const button = entity.getMutableComponent( Button );
  110. const object = entity.getComponent( Object3D ).object;
  111. const pressingDistances = [];
  112. this.hands.forEach( hand => {
  113. if ( hand && hand.intersectBoxObject( object ) ) {
  114. const pressingPosition = hand.getPointerPosition();
  115. pressingDistances.push( button.surfaceY - object.worldToLocal( pressingPosition ).y );
  116. }
  117. } );
  118. if ( pressingDistances.length == 0 ) { // not pressed this frame
  119. if ( object.position.y < button.restingY ) {
  120. object.position.y += button.recoverySpeed * delta;
  121. button.currState = 'recovering';
  122. } else {
  123. object.position.y = button.restingY;
  124. button.currState = 'resting';
  125. }
  126. } else {
  127. button.currState = 'pressed';
  128. const pressingDistance = Math.max( pressingDistances );
  129. if ( pressingDistance > 0 ) {
  130. object.position.y -= pressingDistance;
  131. }
  132. if ( object.position.y <= button.restingY - button.fullPressDistance ) {
  133. button.currState = 'fully_pressed';
  134. object.position.y = button.restingY - button.fullPressDistance;
  135. }
  136. }
  137. } );
  138. }
  139. }
  140. FingerInputSystem.queries = {
  141. pressable: {
  142. components: [ Pressable ]
  143. }
  144. };
  145. class Rotating extends TagComponent { }
  146. class RotatingSystem extends System {
  147. execute( delta/*, time*/ ) {
  148. this.queries.rotatingObjects.results.forEach( entity => {
  149. const object = entity.getComponent( Object3D ).object;
  150. object.rotation.x += 0.4 * delta;
  151. object.rotation.y += 0.4 * delta;
  152. } );
  153. }
  154. }
  155. RotatingSystem.queries = {
  156. rotatingObjects: {
  157. components: [ Rotating ]
  158. }
  159. };
  160. class HandsInstructionText extends TagComponent { }
  161. class InstructionSystem extends System {
  162. init( attributes ) {
  163. this.controllers = attributes.controllers;
  164. }
  165. execute( /*delta, time*/ ) {
  166. let visible = false;
  167. this.controllers.forEach( controller => {
  168. if ( controller.visible ) {
  169. visible = true;
  170. }
  171. } );
  172. this.queries.instructionTexts.results.forEach( entity => {
  173. const object = entity.getComponent( Object3D ).object;
  174. object.visible = visible;
  175. } );
  176. }
  177. }
  178. InstructionSystem.queries = {
  179. instructionTexts: {
  180. components: [ HandsInstructionText ]
  181. }
  182. };
  183. class OffsetFromCamera extends Component { }
  184. OffsetFromCamera.schema = {
  185. x: { type: Types.Number, default: 0 },
  186. y: { type: Types.Number, default: 0 },
  187. z: { type: Types.Number, default: 0 },
  188. };
  189. class NeedCalibration extends TagComponent { }
  190. class CalibrationSystem extends System {
  191. init( attributes ) {
  192. this.camera = attributes.camera;
  193. this.renderer = attributes.renderer;
  194. }
  195. execute( /*delta, time*/ ) {
  196. this.queries.needCalibration.results.forEach( entity => {
  197. if ( this.renderer.xr.getSession() ) {
  198. const offset = entity.getComponent( OffsetFromCamera );
  199. const object = entity.getComponent( Object3D ).object;
  200. const xrCamera = this.renderer.xr.getCamera();
  201. object.position.x = xrCamera.position.x + offset.x;
  202. object.position.y = xrCamera.position.y + offset.y;
  203. object.position.z = xrCamera.position.z + offset.z;
  204. entity.removeComponent( NeedCalibration );
  205. }
  206. } );
  207. }
  208. }
  209. CalibrationSystem.queries = {
  210. needCalibration: {
  211. components: [ NeedCalibration ]
  212. }
  213. };
  214. const world = new World();
  215. const clock = new THREE.Clock();
  216. let camera, scene, renderer;
  217. init();
  218. function makeButtonMesh( x, y, z, color ) {
  219. const geometry = new THREE.BoxGeometry( x, y, z );
  220. const material = new THREE.MeshPhongMaterial( { color: color } );
  221. const buttonMesh = new THREE.Mesh( geometry, material );
  222. buttonMesh.castShadow = true;
  223. buttonMesh.receiveShadow = true;
  224. return buttonMesh;
  225. }
  226. function init() {
  227. const container = document.createElement( 'div' );
  228. document.body.appendChild( container );
  229. scene = new THREE.Scene();
  230. scene.background = new THREE.Color( 0x444444 );
  231. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 10 );
  232. camera.position.set( 0, 1.2, 0.3 );
  233. scene.add( new THREE.HemisphereLight( 0xcccccc, 0x999999, 3 ) );
  234. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  235. light.position.set( 0, 6, 0 );
  236. light.castShadow = true;
  237. light.shadow.camera.top = 2;
  238. light.shadow.camera.bottom = - 2;
  239. light.shadow.camera.right = 2;
  240. light.shadow.camera.left = - 2;
  241. light.shadow.mapSize.set( 4096, 4096 );
  242. scene.add( light );
  243. renderer = new THREE.WebGLRenderer( { antialias: true } );
  244. renderer.setPixelRatio( window.devicePixelRatio );
  245. renderer.setSize( window.innerWidth, window.innerHeight );
  246. renderer.setAnimationLoop( animate );
  247. renderer.shadowMap.enabled = true;
  248. renderer.xr.enabled = true;
  249. renderer.xr.cameraAutoUpdate = false;
  250. container.appendChild( renderer.domElement );
  251. const sessionInit = {
  252. requiredFeatures: [ 'hand-tracking' ]
  253. };
  254. document.body.appendChild( VRButton.createButton( renderer, sessionInit ) );
  255. // controllers
  256. const controller1 = renderer.xr.getController( 0 );
  257. scene.add( controller1 );
  258. const controller2 = renderer.xr.getController( 1 );
  259. scene.add( controller2 );
  260. const controllerModelFactory = new XRControllerModelFactory();
  261. // Hand 1
  262. const controllerGrip1 = renderer.xr.getControllerGrip( 0 );
  263. controllerGrip1.add( controllerModelFactory.createControllerModel( controllerGrip1 ) );
  264. scene.add( controllerGrip1 );
  265. const hand1 = renderer.xr.getHand( 0 );
  266. const handModel1 = new OculusHandModel( hand1 );
  267. hand1.add( handModel1 );
  268. scene.add( hand1 );
  269. // Hand 2
  270. const controllerGrip2 = renderer.xr.getControllerGrip( 1 );
  271. controllerGrip2.add( controllerModelFactory.createControllerModel( controllerGrip2 ) );
  272. scene.add( controllerGrip2 );
  273. const hand2 = renderer.xr.getHand( 1 );
  274. const handModel2 = new OculusHandModel( hand2 );
  275. hand2.add( handModel2 );
  276. scene.add( hand2 );
  277. // buttons
  278. const floorGeometry = new THREE.PlaneGeometry( 4, 4 );
  279. const floorMaterial = new THREE.MeshPhongMaterial( { color: 0x222222 } );
  280. const floor = new THREE.Mesh( floorGeometry, floorMaterial );
  281. floor.rotation.x = - Math.PI / 2;
  282. floor.receiveShadow = true;
  283. scene.add( floor );
  284. const consoleGeometry = new THREE.BoxGeometry( 0.5, 0.12, 0.15 );
  285. const consoleMaterial = new THREE.MeshPhongMaterial( { color: 0x595959 } );
  286. const consoleMesh = new THREE.Mesh( consoleGeometry, consoleMaterial );
  287. consoleMesh.position.set( 0, 1, - 0.3 );
  288. consoleMesh.castShadow = true;
  289. consoleMesh.receiveShadow = true;
  290. scene.add( consoleMesh );
  291. const orangeButton = makeButtonMesh( 0.08, 0.1, 0.08, 0xffd3b5 );
  292. orangeButton.position.set( - 0.15, 0.04, 0 );
  293. consoleMesh.add( orangeButton );
  294. const pinkButton = makeButtonMesh( 0.08, 0.1, 0.08, 0xe84a5f );
  295. pinkButton.position.set( - 0.05, 0.04, 0 );
  296. consoleMesh.add( pinkButton );
  297. const resetButton = makeButtonMesh( 0.08, 0.1, 0.08, 0x355c7d );
  298. const resetButtonText = createText( 'reset', 0.03 );
  299. resetButton.add( resetButtonText );
  300. resetButtonText.rotation.x = - Math.PI / 2;
  301. resetButtonText.position.set( 0, 0.051, 0 );
  302. resetButton.position.set( 0.05, 0.04, 0 );
  303. consoleMesh.add( resetButton );
  304. const exitButton = makeButtonMesh( 0.08, 0.1, 0.08, 0xff0000 );
  305. const exitButtonText = createText( 'exit', 0.03 );
  306. exitButton.add( exitButtonText );
  307. exitButtonText.rotation.x = - Math.PI / 2;
  308. exitButtonText.position.set( 0, 0.051, 0 );
  309. exitButton.position.set( 0.15, 0.04, 0 );
  310. consoleMesh.add( exitButton );
  311. const tkGeometry = new THREE.TorusKnotGeometry( 0.5, 0.2, 200, 32 );
  312. const tkMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff } );
  313. tkMaterial.metalness = 0.8;
  314. const torusKnot = new THREE.Mesh( tkGeometry, tkMaterial );
  315. torusKnot.position.set( 0, 1, - 5 );
  316. scene.add( torusKnot );
  317. const instructionText = createText( 'This is a WebXR Hands demo, please explore with hands.', 0.04 );
  318. instructionText.position.set( 0, 1.6, - 0.6 );
  319. scene.add( instructionText );
  320. const exitText = createText( 'Exiting session...', 0.04 );
  321. exitText.position.set( 0, 1.5, - 0.6 );
  322. exitText.visible = false;
  323. scene.add( exitText );
  324. world
  325. .registerComponent( Object3D )
  326. .registerComponent( Button )
  327. .registerComponent( Pressable )
  328. .registerComponent( Rotating )
  329. .registerComponent( HandsInstructionText )
  330. .registerComponent( OffsetFromCamera )
  331. .registerComponent( NeedCalibration );
  332. world
  333. .registerSystem( RotatingSystem )
  334. .registerSystem( InstructionSystem, { controllers: [ controllerGrip1, controllerGrip2 ] } )
  335. .registerSystem( CalibrationSystem, { renderer: renderer, camera: camera } )
  336. .registerSystem( ButtonSystem, { renderer: renderer, camera: camera } )
  337. .registerSystem( FingerInputSystem, { hands: [ handModel1, handModel2 ] } );
  338. const csEntity = world.createEntity();
  339. csEntity.addComponent( OffsetFromCamera, { x: 0, y: - 0.4, z: - 0.3 } );
  340. csEntity.addComponent( NeedCalibration );
  341. csEntity.addComponent( Object3D, { object: consoleMesh } );
  342. const obEntity = world.createEntity();
  343. obEntity.addComponent( Pressable );
  344. obEntity.addComponent( Object3D, { object: orangeButton } );
  345. const obAction = function () {
  346. torusKnot.material.color.setHex( 0xffd3b5 );
  347. };
  348. obEntity.addComponent( Button, { action: obAction, surfaceY: 0.05, fullPressDistance: 0.02 } );
  349. const pbEntity = world.createEntity();
  350. pbEntity.addComponent( Pressable );
  351. pbEntity.addComponent( Object3D, { object: pinkButton } );
  352. const pbAction = function () {
  353. torusKnot.material.color.setHex( 0xe84a5f );
  354. };
  355. pbEntity.addComponent( Button, { action: pbAction, surfaceY: 0.05, fullPressDistance: 0.02 } );
  356. const rbEntity = world.createEntity();
  357. rbEntity.addComponent( Pressable );
  358. rbEntity.addComponent( Object3D, { object: resetButton } );
  359. const rbAction = function () {
  360. torusKnot.material.color.setHex( 0xffffff );
  361. };
  362. rbEntity.addComponent( Button, { action: rbAction, surfaceY: 0.05, fullPressDistance: 0.02 } );
  363. const ebEntity = world.createEntity();
  364. ebEntity.addComponent( Pressable );
  365. ebEntity.addComponent( Object3D, { object: exitButton } );
  366. const ebAction = function () {
  367. exitText.visible = true;
  368. setTimeout( function () {
  369. exitText.visible = false; renderer.xr.getSession().end();
  370. }, 2000 );
  371. };
  372. ebEntity.addComponent( Button, { action: ebAction, surfaceY: 0.05, recoverySpeed: 0.2, fullPressDistance: 0.03 } );
  373. const tkEntity = world.createEntity();
  374. tkEntity.addComponent( Rotating );
  375. tkEntity.addComponent( Object3D, { object: torusKnot } );
  376. const itEntity = world.createEntity();
  377. itEntity.addComponent( HandsInstructionText );
  378. itEntity.addComponent( Object3D, { object: instructionText } );
  379. window.addEventListener( 'resize', onWindowResize );
  380. }
  381. function onWindowResize() {
  382. camera.aspect = window.innerWidth / window.innerHeight;
  383. camera.updateProjectionMatrix();
  384. renderer.setSize( window.innerWidth, window.innerHeight );
  385. }
  386. function animate() {
  387. const delta = clock.getDelta();
  388. const elapsedTime = clock.elapsedTime;
  389. renderer.xr.updateCamera( camera );
  390. world.execute( delta, elapsedTime );
  391. renderer.render( scene, camera );
  392. }
  393. </script>
  394. </body>
  395. </html>