webxr_vr_handinput_pressbutton.html 15 KB

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