three.jss官方案例(animation / skinning / blending)webgl_animation_skinning_blending.html学习记录

目录

1 打印动画

2 全部脚本和注释


1 打印动画

2 全部脚本和注释

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js webgl - animation - skinning</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="../three.js-r163/examples/main.css">
		<style>
			a {
				color: #f00;
			}
		</style>
	</head>
	<body>
		<div id="container"></div>
		<div id="info">
			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Skeletal Animation Blending
			(model from <a href="https://www.mixamo.com/" target="_blank" rel="noopener">mixamo.com</a>)<br/>
			Note: crossfades are possible with blend weights being set to (1,0,0), (0,1,0) or (0,0,1)
		</div>

		<script type="importmap">
			{
				"imports": {
					"three": "../three.js-r163/build/three.module.js",
					"three/addons/": "../three.js-r163/examples/jsm/"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three';

			import Stats from 'three/addons/libs/stats.module.js';
			import { GUI } from 'three/addons/libs/lil-gui.module.min.js';

			import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

			let scene, renderer, camera, stats;
			//模型    骨骼辅助对象,动画混合器 , clock对象用于跟踪时间
			let model, skeleton, mixer, clock;
            //交叉淡入淡出控件组
			const crossFadeControls = [];
            //三个动作
			let idleAction, walkAction, runAction;
			//三个动作的Weight
			let idleWeight, walkWeight, runWeight;
			//
			let actions, settings;

			let singleStepMode = false;//单步模式
			let sizeOfNextStep = 0;

			init();

			function init() {

				const container = document.getElementById( 'container' );

				camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 100 );
				camera.position.set( 1, 2, - 3 );
				camera.lookAt( 0, 1, 0 );

				clock = new THREE.Clock();

				scene = new THREE.Scene();
				scene.background = new THREE.Color( 0xa0a0a0 );
				scene.fog = new THREE.Fog( 0xa0a0a0, 10, 50 );

				const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x8d8d8d, 3 );
				hemiLight.position.set( 0, 20, 0 );
				scene.add( hemiLight );

				const dirLight = new THREE.DirectionalLight( 0xffffff, 3 );
				dirLight.position.set( - 3, 10, - 10 );
				dirLight.castShadow = true;
				dirLight.shadow.camera.top = 2;
				dirLight.shadow.camera.bottom = - 2;
				dirLight.shadow.camera.left = - 2;
				dirLight.shadow.camera.right = 2;
				dirLight.shadow.camera.near = 0.1;
				dirLight.shadow.camera.far = 40;
				scene.add( dirLight );

				 scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) );

				// ground

				const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), new THREE.MeshPhongMaterial( { color: 0xcbcbcb, depthWrite: false } ) );
				mesh.rotation.x = - Math.PI / 2;
				mesh.receiveShadow = true;
				scene.add( mesh );

				const loader = new GLTFLoader();
				loader.load( '../three.js-r163/examples/models/gltf/Soldier.glb', function ( gltf ) {

					model = gltf.scene;
					scene.add( model );

					model.traverse( function ( object ) {

						if ( object.isMesh ) object.castShadow = true;

					} );

					//

					skeleton = new THREE.SkeletonHelper( model );
					skeleton.visible = false;
					scene.add( skeleton );

					// UI 模块

					createPanel();


					//动画

					const animations = gltf.animations;
                    console.log(animations);
					mixer = new THREE.AnimationMixer( model );//动画混合器

					idleAction = mixer.clipAction( animations[ 0 ] );
					walkAction = mixer.clipAction( animations[ 3 ] );
					runAction = mixer.clipAction( animations[ 1 ] );

					actions = [ idleAction, walkAction, runAction ];

					activateAllActions();

					animate();

				} );

				renderer = new THREE.WebGLRenderer( { antialias: true } );
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				renderer.shadowMap.enabled = true;
				container.appendChild( renderer.domElement );

				stats = new Stats();
				container.appendChild( stats.dom );

				window.addEventListener( 'resize', onWindowResize );

			}

			function createPanel() {

				const panel = new GUI( { width: 310 } );

				const folder1 = panel.addFolder( 'Visibility' );
				const folder2 = panel.addFolder( 'Activation/Deactivation' );
				const folder3 = panel.addFolder( 'Pausing/Stepping' );
				const folder4 = panel.addFolder( 'Crossfading淡入淡出' );
				const folder5 = panel.addFolder( 'Blend Weights混合权重' );
				const folder6 = panel.addFolder( 'General Speed 速度' );

				settings = {
					'show model': true,
					'show skeleton': false,
					'deactivate all': deactivateAllActions,//停用所有动作
					'activate all': activateAllActions,//激活所有动作
					'pause/continue': pauseContinue,//暂停继续
					'make single step': toSingleStepMode,//单步模式
					'modify step size': 0.05,//修改步长

					//动画切换
					'from walk to idle': function () {

						prepareCrossFade( walkAction, idleAction, 1.0 );

					},
					'from idle to walk': function () {

						prepareCrossFade( idleAction, walkAction, 0.5 );

					},
					'from walk to run': function () {

						prepareCrossFade( walkAction, runAction, 2.5 );

					},
					'from run to walk': function () {

						prepareCrossFade( runAction, walkAction, 5.0 );

					},
					'use default duration': true,
					'set custom duration': 3.5,
					'modify idle weight': 0.0,
					'modify walk weight': 1.0,
					'modify run weight': 0.0,
					'modify time scale': 1.0
				};

				folder1.add( settings, 'show model' ).onChange( showModel );
				folder1.add( settings, 'show skeleton' ).onChange( showSkeleton );//显示骨骼
				folder2.add( settings, 'deactivate all' );
				folder2.add( settings, 'activate all' );
				folder3.add( settings, 'pause/continue' );//暂停/继续
				folder3.add( settings, 'make single step' );
				folder3.add( settings, 'modify step size', 0.01, 0.1, 0.001 );
				crossFadeControls.push( folder4.add( settings, 'from walk to idle' ) );
				crossFadeControls.push( folder4.add( settings, 'from idle to walk' ) );
				crossFadeControls.push( folder4.add( settings, 'from walk to run' ) );
				crossFadeControls.push( folder4.add( settings, 'from run to walk' ) );
				folder4.add( settings, 'use default duration' );
				folder4.add( settings, 'set custom duration', 0, 10, 0.01 );
				folder5.add( settings, 'modify idle weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {

					setWeight( idleAction, weight );//修改weight值

				} );
				folder5.add( settings, 'modify walk weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {

					setWeight( walkAction, weight );

				} );
				folder5.add( settings, 'modify run weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {

					setWeight( runAction, weight );

				} );
				folder6.add( settings, 'modify time scale', 0.0, 1.5, 0.01 ).onChange( modifyTimeScale );

				folder1.open();
				folder2.open();
				folder3.open();
				folder4.open();
				folder5.open();
				folder6.open();

			}

            //模型是否显示
			function showModel( visibility ) {

				model.visible = visibility;

			}

            //骨骼是否显示
			function showSkeleton( visibility ) {

				skeleton.visible = visibility;

			}

             //更改速度
			function modifyTimeScale( speed ) {

				mixer.timeScale = speed;

			}

            //停用所有动作
			function deactivateAllActions() {

				actions.forEach( function ( action ) {

					action.stop();

				} );

			}
            //激活所有动作
			function activateAllActions() {

				setWeight( idleAction, settings[ 'modify idle weight' ] );
				setWeight( walkAction, settings[ 'modify walk weight' ] );
				setWeight( runAction, settings[ 'modify run weight' ] );

				actions.forEach( function ( action ) {

					action.play();

				} );

			}
            //暂停继续
			function pauseContinue() {

				if ( singleStepMode ) {

					singleStepMode = false;
					unPauseAllActions();

				} else {

					if ( idleAction.paused ) {

						unPauseAllActions();//继续

					} else {

						pauseAllActions();//暂停

					}

				}

			}

			function pauseAllActions() {

				actions.forEach( function ( action ) {

					action.paused = true;//暂停

				} );

			}

			function unPauseAllActions() {

				actions.forEach( function ( action ) {

					action.paused = false;//取消暂停  继续

				} );

			}

			function toSingleStepMode() {

				unPauseAllActions();

				singleStepMode = true;
				sizeOfNextStep = settings[ 'modify step size' ];

			}

			function prepareCrossFade( startAction, endAction, defaultDuration ) {

				// Switch default / custom crossfade duration (according to the user's choice)
				//切换默认/自定义交叉渐变持续时间(根据用户选择)
				const duration = setCrossFadeDuration( defaultDuration );

				// Make sure that we don't go on in singleStepMode, and that all actions are unpaused
				//确保我们在singleStepMode中没有继续,并且所有的动作都是非暂停的
				singleStepMode = false;
				unPauseAllActions();

				// If the current action is 'idle' (duration 4 sec), execute the crossfade immediately;
				// else wait until the current action has finished its current loop
//如果当前动作为'idle'(持续时间为4秒),立即执行crossfade;
//否则等待当前动作完成当前循环
				if ( startAction === idleAction ) {

					executeCrossFade( startAction, endAction, duration );

				} else {

					synchronizeCrossFade( startAction, endAction, duration );

				}

			}

			function setCrossFadeDuration( defaultDuration ) {

				// Switch default crossfade duration <-> custom crossfade duration
//切换默认交叉渐变持续时间<->自定义交叉渐变持续时间
				if ( settings[ 'use default duration' ] ) {

					return defaultDuration;

				} else {

					return settings[ 'set custom duration' ];

				}

			}
            //同步淡入淡出
			function synchronizeCrossFade( startAction, endAction, duration ) {

				//事件
//有两个事件分别表示了单次循环的结束和全部动作的结束,你可以这样对它们做出响应:
//mixer.addEventListener( 'loop', function( e ) { …} ); // properties of e: type, action and loopDelta
//mixer.addEventListener( 'finished', function( e ) { …} ); // properties of e: type, action and direction
				mixer.addEventListener( 'loop', onLoopFinished );//单次循环的结束

				function onLoopFinished( event ) {

					if ( event.action === startAction ) {

						mixer.removeEventListener( 'loop', onLoopFinished );//这个动画结束时移除 

						executeCrossFade( startAction, endAction, duration );//这个动画结束时执行淡入淡出

					}

				}

			}
            //执行淡入淡出
			function executeCrossFade( startAction, endAction, duration ) {

				// Not only the start action, but also the end action must get a weight of 1 before fading
				// (concerning the start action this is already guaranteed in this place)
//不仅开始动作,结束动作的权重也必须为1
//(关于启动动作,这个地方已经保证了)
				setWeight( endAction, 1 );
				endAction.time = 0;

				// Crossfade with warping - you can also try without warping by setting the third parameter to false
				//带扭曲的交叉渐变-你也可以通过将第三个参数设置为false来尝试不扭曲
				startAction.crossFadeTo( endAction, duration, true );

			}

			// This function is needed, since animationAction.crossFadeTo() disables its start action and sets
			// the start action's timeScale to ((start animation's duration) / (end animation's duration))
//这个函数是必需的,因为animationAction.crossFadeTo()会禁用它的开始动作和设置
//开始动作的时间刻度到((开始动画的持续时间)/(结束动画的持续时间))

			function setWeight( action, weight ) {

				action.enabled = true;
				//设置时间比例(timeScale)以及停用所有的变形)。 此方法可以链式调用。
//如果暂停 (paused)值为false, 有效的时间比例(一个内部属性) 也会被设为该值; 否则有效时间比例 (直接影响当前动画 将会被设为0.
//说明: 如果时间比例.timeScale 被此方法设为0,暂停值paused不会被自动改为true。
				action.setEffectiveTimeScale( 1 );
				//设置权重(weight)以及停止所有淡入淡出。该方法可以链式调用。
//如果启用属性(enabled)为true, 那么有效权重(一个内部属性) 也会被设为该值; 否则有效权重 (直接影响当前动画)将会被设为0.
//说明: 如果该方法将权重weight值设为0,启用值enabled不会被自动改为false。
				action.setEffectiveWeight( weight );

			}

			// Called by the render loop由渲染循环调用
			function updateWeightSliders() {

				settings[ 'modify idle weight' ] = idleWeight;
				settings[ 'modify walk weight' ] = walkWeight;
				settings[ 'modify run weight' ] = runWeight;

			}

			// Called by the render loop由渲染循环调用
			function updateCrossFadeControls() {

				if ( idleWeight === 1 && walkWeight === 0 && runWeight === 0 ) {

					crossFadeControls[ 0 ].disable();
					crossFadeControls[ 1 ].enable();
					crossFadeControls[ 2 ].disable();
					crossFadeControls[ 3 ].disable();

				}

				if ( idleWeight === 0 && walkWeight === 1 && runWeight === 0 ) {

					crossFadeControls[ 0 ].enable();
					crossFadeControls[ 1 ].disable();
					crossFadeControls[ 2 ].enable();
					crossFadeControls[ 3 ].disable();

				}

				if ( idleWeight === 0 && walkWeight === 0 && runWeight === 1 ) {

					crossFadeControls[ 0 ].disable();
					crossFadeControls[ 1 ].disable();
					crossFadeControls[ 2 ].disable();
					crossFadeControls[ 3 ].enable();

				}

			}

			function onWindowResize() {

				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();

				renderer.setSize( window.innerWidth, window.innerHeight );

			}

			function animate() {

				// Render loop

				requestAnimationFrame( animate );

				idleWeight = idleAction.getEffectiveWeight();//返回影响权重(考虑当前淡入淡出状态和enabled的值)
				walkWeight = walkAction.getEffectiveWeight();
				runWeight = runAction.getEffectiveWeight();

				// Update the panel values if weights are modified from "outside" (by crossfadings)
				//如果权重从“外部”修改(通过交叉渐变),则更新面板值
				updateWeightSliders();

				// Enable/disable crossfade controls according to current weight values
				//根据当前权重值启用/禁用交叉渐变控件
				updateCrossFadeControls();

				// Get the time elapsed since the last frame, used for mixer update (if not in single step mode)
//获取自上一帧以来经过的时间,用于混音器更新(如果不是单步模式)
				let mixerUpdateDelta = clock.getDelta();

				// If in single step mode, make one step and then do nothing (until the user clicks again)
				//如果是在单步模式下,做一步然后什么都不做(直到用户再次点击)
				if ( singleStepMode ) {

					mixerUpdateDelta = sizeOfNextStep;
					sizeOfNextStep = 0;

				}

				// Update the animation mixer, the stats panel, and render this frame
				//更新动画混合器,统计面板,并渲染这一帧
				mixer.update( mixerUpdateDelta );//

				stats.update();

				renderer.render( scene, camera );

			}

		</script>

	</body>
</html>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hemy1989

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值