XRControllerModelLoader.js 6.6 KB
Newer Older
B
Brandon Jones 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
/**
 * @author Nell Waliczek / https://github.com/NellWaliczek
 * @author Brandon Jones / https://github.com/toji
 */

import {
	Mesh,
	MeshBasicMaterial,
	Object3D,
	Quaternion,
	SphereGeometry,
} from "../../../build/three.module.js";

import {
	Constants as MotionControllerConstants,
	fetchProfile,
	MotionController
} from 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/motion-controllers@0.1.0/dist/motion-controllers.module.js'

const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@0.1.0/dist/profiles'

function XRControllerModel( ) {

	Object3D.call( this );

	this.motionController = null;
	this.envMap = null;

}

XRControllerModel.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: XRControllerModel,

	setEnvironmentMap: function ( envMap ) {

		if ( this.envMap == envMap ) {

			return this;

		}

		this.envMap = envMap;
		this.traverse(( child ) => {

			if ( child.isMesh ) {

				child.material.envMap = this.envMap;
				child.material.needsUpdate = true;

			}

		});

		return this;

	},

	/**
	 * Polls data from the XRInputSource and updates the model's components to match
	 * the real world data
	 */
	updateMatrixWorld: function ( force ) {

		Object3D.prototype.updateMatrixWorld.call( this, force );

		if ( !this.motionController ) return;

		// Cause the MotionController to poll the Gamepad for data
		this.motionController.updateFromGamepad();

		// Update the 3D model to reflect the button, thumbstick, and touchpad state
		Object.values( this.motionController.components ).forEach(( component ) => {

			// Update node data based on the visual responses' current states
			Object.values( component.visualResponses ).forEach(( visualResponse ) => {

				const { valueNode, minNode, maxNode, value, valueNodeProperty } = visualResponse;

				// Skip if the visual response node is not found. No error is needed,
				// because it will have been reported at load time.
				if ( !valueNode ) return;

				// Calculate the new properties based on the weight supplied
				if ( valueNodeProperty === MotionControllerConstants.VisualResponseProperty.VISIBILITY ) {

					valueNode.visible = value;

				} else if ( valueNodeProperty === MotionControllerConstants.VisualResponseProperty.TRANSFORM ) {

					Quaternion.slerp(
						minNode.quaternion,
						maxNode.quaternion,
						valueNode.quaternion,
						value
					);

					valueNode.position.lerpVectors(
						minNode.position,
						maxNode.position,
						value
					);

				}

			});

		});

	}

} );

/**
 * Walks the model's tree to find the nodes needed to animate the components and
 * saves them to the motionContoller components for use in the frame loop. When
 * touchpads are found, attaches a touch dot to them.
 */
function findNodes( motionController, scene ) {

	// Loop through the components and find the nodes needed for each components' visual responses
	Object.values( motionController.components ).forEach(( component ) => {

		const { type, touchPointNodeName, visualResponses } = component;

		if (type === MotionControllerConstants.ComponentType.TOUCHPAD) {

			component.touchPointNode = scene.getObjectByName( touchPointNodeName );
			if ( component.touchPointNode ) {

				// Attach a touch dot to the touchpad.
				const sphereGeometry = new SphereGeometry( 0.001 );
				const material = new MeshBasicMaterial({ color: 0x0000FF });
				const sphere = new Mesh( sphereGeometry, material );
				component.touchPointNode.add( sphere );

			} else {

				console.warn(`Could not find touch dot, ${component.touchPointNodeName}, in touchpad component ${componentId}`);

			}

		}

		// Loop through all the visual responses to be applied to this component
		Object.values( visualResponses ).forEach(( visualResponse ) => {

			const { valueNodeName, minNodeName, maxNodeName, valueNodeProperty } = visualResponse;

			// If animating a transform, find the two nodes to be interpolated between.
			if ( valueNodeProperty === MotionControllerConstants.VisualResponseProperty.TRANSFORM ) {

				visualResponse.minNode = scene.getObjectByName(minNodeName);
				visualResponse.maxNode = scene.getObjectByName(maxNodeName);

				// If the extents cannot be found, skip this animation
				if ( !visualResponse.minNode ) {

					console.warn(`Could not find ${minNodeName} in the model`);
					return;

				}

				if ( !visualResponse.maxNode ) {

					console.warn(`Could not find ${maxNodeName} in the model`);
					return;

				}
			}

			// If the target node cannot be found, skip this animation
			visualResponse.valueNode = scene.getObjectByName(valueNodeName);
			if ( !visualResponse.valueNode ) {

				console.warn(`Could not find ${valueNodeName} in the model`);

			}
		});
	});
}

var XRControllerModelLoader = ( function () {

	function XRControllerModelLoader( gltfLoader ) {

		this.gltfLoader = gltfLoader;
		this.path = DEFAULT_PROFILES_PATH;

	}

	XRControllerModelLoader.prototype = {

		constructor: XRControllerModelLoader,

		setGLTFLoader: function ( gltfLoader ) {

			this.gltfLoader = gltfLoader;
			return this;

		},

		getControllerModel: function ( controller ) {

			if ( !this.gltfLoader ) {

				throw new Error(`GLTFLoader not set.`);

			}

			const controllerModel = new XRControllerModel();
			let scene = null;

			controller.addEventListener( 'connected', ( event ) => {

				const xrInputSource = event.data;

				fetchProfile(xrInputSource, this.path).then(({ profile, assetPath }) => {

					controllerModel.motionController = new MotionController(
						xrInputSource,
						profile,
						assetPath
					);

					this.gltfLoader.setPath('');
					this.gltfLoader.load( controllerModel.motionController.assetUrl, ( asset ) => {

						scene = asset.scene;

						// Find the nodes needed for animation and cache them on the motionController.
						findNodes( controllerModel.motionController, scene );

						// Apply any environment map that the mesh already has set.
						if ( controllerModel.envMap ) {

							scene.traverse(( child ) => {

								if ( child.isMesh ) {

									child.material.envMap = controllerModel.envMap;
									child.material.needsUpdate = true;

								}

							});

						}

						// Add the glTF scene to the controllerModel.
						controllerModel.add( scene );

					},
					null,
					() => {

						throw new Error(`Asset ${motionController.assetUrl} missing or malformed.`);

					});

				}).catch((err) => {

					console.warn(err);

				});

			});

			controller.addEventListener( 'disconnected', () => {

				controllerModel.motionController = null;
				controllerModel.remove( scene );

			});

			return controllerModel;

		}

	};

	return XRControllerModelLoader;

} )();

export { XRControllerModelLoader };