XRControllerModelFactory.js 7.2 KB

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