XRControllerModelFactory.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import {
  2. Mesh,
  3. MeshBasicMaterial,
  4. Object3D,
  5. SphereGeometry,
  6. } from '../../../build/three.module.js';
  7. import { GLTFLoader } from '../loaders/GLTFLoader.js';
  8. import {
  9. Constants as MotionControllerConstants,
  10. fetchProfile,
  11. MotionController
  12. } from '../libs/motion-controllers.module.js';
  13. const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/[email protected]/dist/profiles';
  14. const DEFAULT_PROFILE = 'generic-trigger';
  15. function XRControllerModel( ) {
  16. Object3D.call( this );
  17. this.motionController = null;
  18. this.envMap = null;
  19. }
  20. XRControllerModel.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21. constructor: XRControllerModel,
  22. setEnvironmentMap: function ( envMap ) {
  23. if ( this.envMap == envMap ) {
  24. return this;
  25. }
  26. this.envMap = envMap;
  27. this.traverse( ( child ) => {
  28. if ( child.isMesh ) {
  29. child.material.envMap = this.envMap;
  30. child.material.needsUpdate = true;
  31. }
  32. } );
  33. return this;
  34. },
  35. /**
  36. * Polls data from the XRInputSource and updates the model's components to match
  37. * the real world data
  38. */
  39. updateMatrixWorld: function ( force ) {
  40. Object3D.prototype.updateMatrixWorld.call( this, force );
  41. if ( ! this.motionController ) return;
  42. // Cause the MotionController to poll the Gamepad for data
  43. this.motionController.updateFromGamepad();
  44. // Update the 3D model to reflect the button, thumbstick, and touchpad state
  45. Object.values( this.motionController.components ).forEach( ( component ) => {
  46. // Update node data based on the visual responses' current states
  47. Object.values( component.visualResponses ).forEach( ( visualResponse ) => {
  48. const { valueNode, minNode, maxNode, value, valueNodeProperty } = visualResponse;
  49. // Skip if the visual response node is not found. No error is needed,
  50. // because it will have been reported at load time.
  51. if ( ! valueNode ) return;
  52. // Calculate the new properties based on the weight supplied
  53. if ( valueNodeProperty === MotionControllerConstants.VisualResponseProperty.VISIBILITY ) {
  54. valueNode.visible = value;
  55. } else if ( valueNodeProperty === MotionControllerConstants.VisualResponseProperty.TRANSFORM ) {
  56. valueNode.quaternion.slerpQuaternions(
  57. minNode.quaternion,
  58. maxNode.quaternion,
  59. value
  60. );
  61. valueNode.position.lerpVectors(
  62. minNode.position,
  63. maxNode.position,
  64. value
  65. );
  66. }
  67. } );
  68. } );
  69. }
  70. } );
  71. /**
  72. * Walks the model's tree to find the nodes needed to animate the components and
  73. * saves them to the motionContoller components for use in the frame loop. When
  74. * touchpads are found, attaches a touch dot to them.
  75. */
  76. function findNodes( motionController, scene ) {
  77. // Loop through the components and find the nodes needed for each components' visual responses
  78. Object.values( motionController.components ).forEach( ( component ) => {
  79. const { type, touchPointNodeName, visualResponses } = component;
  80. if ( type === MotionControllerConstants.ComponentType.TOUCHPAD ) {
  81. component.touchPointNode = scene.getObjectByName( touchPointNodeName );
  82. if ( component.touchPointNode ) {
  83. // Attach a touch dot to the touchpad.
  84. const sphereGeometry = new SphereGeometry( 0.001 );
  85. const material = new MeshBasicMaterial( { color: 0x0000FF } );
  86. const sphere = new Mesh( sphereGeometry, material );
  87. component.touchPointNode.add( sphere );
  88. } else {
  89. console.warn( `Could not find touch dot, ${component.touchPointNodeName}, in touchpad component ${component.id}` );
  90. }
  91. }
  92. // Loop through all the visual responses to be applied to this component
  93. Object.values( visualResponses ).forEach( ( visualResponse ) => {
  94. const { valueNodeName, minNodeName, maxNodeName, valueNodeProperty } = visualResponse;
  95. // If animating a transform, find the two nodes to be interpolated between.
  96. if ( valueNodeProperty === MotionControllerConstants.VisualResponseProperty.TRANSFORM ) {
  97. visualResponse.minNode = scene.getObjectByName( minNodeName );
  98. visualResponse.maxNode = scene.getObjectByName( maxNodeName );
  99. // If the extents cannot be found, skip this animation
  100. if ( ! visualResponse.minNode ) {
  101. console.warn( `Could not find ${minNodeName} in the model` );
  102. return;
  103. }
  104. if ( ! visualResponse.maxNode ) {
  105. console.warn( `Could not find ${maxNodeName} in the model` );
  106. return;
  107. }
  108. }
  109. // If the target node cannot be found, skip this animation
  110. visualResponse.valueNode = scene.getObjectByName( valueNodeName );
  111. if ( ! visualResponse.valueNode ) {
  112. console.warn( `Could not find ${valueNodeName} in the model` );
  113. }
  114. } );
  115. } );
  116. }
  117. function addAssetSceneToControllerModel( controllerModel, scene ) {
  118. // Find the nodes needed for animation and cache them on the motionController.
  119. findNodes( controllerModel.motionController, scene );
  120. // Apply any environment map that the mesh already has set.
  121. if ( controllerModel.envMap ) {
  122. scene.traverse( ( child ) => {
  123. if ( child.isMesh ) {
  124. child.material.envMap = controllerModel.envMap;
  125. child.material.needsUpdate = true;
  126. }
  127. } );
  128. }
  129. // Add the glTF scene to the controllerModel.
  130. controllerModel.add( scene );
  131. }
  132. var XRControllerModelFactory = ( function () {
  133. function XRControllerModelFactory( gltfLoader = null ) {
  134. this.gltfLoader = gltfLoader;
  135. this.path = DEFAULT_PROFILES_PATH;
  136. this._assetCache = {};
  137. // If a GLTFLoader wasn't supplied to the constructor create a new one.
  138. if ( ! this.gltfLoader ) {
  139. this.gltfLoader = new GLTFLoader();
  140. }
  141. }
  142. XRControllerModelFactory.prototype = {
  143. constructor: XRControllerModelFactory,
  144. createControllerModel: function ( controller ) {
  145. const controllerModel = new XRControllerModel();
  146. let scene = null;
  147. controller.addEventListener( 'connected', ( event ) => {
  148. const xrInputSource = event.data;
  149. if ( xrInputSource.targetRayMode !== 'tracked-pointer' || ! xrInputSource.gamepad ) return;
  150. fetchProfile( xrInputSource, this.path, DEFAULT_PROFILE ).then( ( { profile, assetPath } ) => {
  151. controllerModel.motionController = new MotionController(
  152. xrInputSource,
  153. profile,
  154. assetPath
  155. );
  156. const cachedAsset = this._assetCache[ controllerModel.motionController.assetUrl ];
  157. if ( cachedAsset ) {
  158. scene = cachedAsset.scene.clone();
  159. addAssetSceneToControllerModel( controllerModel, scene );
  160. } else {
  161. if ( ! this.gltfLoader ) {
  162. throw new Error( 'GLTFLoader not set.' );
  163. }
  164. this.gltfLoader.setPath( '' );
  165. this.gltfLoader.load( controllerModel.motionController.assetUrl, ( asset ) => {
  166. this._assetCache[ controllerModel.motionController.assetUrl ] = asset;
  167. scene = asset.scene.clone();
  168. addAssetSceneToControllerModel( controllerModel, scene );
  169. },
  170. null,
  171. () => {
  172. throw new Error( `Asset ${controllerModel.motionController.assetUrl} missing or malformed.` );
  173. } );
  174. }
  175. } ).catch( ( err ) => {
  176. console.warn( err );
  177. } );
  178. } );
  179. controller.addEventListener( 'disconnected', () => {
  180. controllerModel.motionController = null;
  181. controllerModel.remove( scene );
  182. scene = null;
  183. } );
  184. return controllerModel;
  185. }
  186. };
  187. return XRControllerModelFactory;
  188. } )();
  189. export { XRControllerModelFactory };