webgl_animation_skinning_additive_blending
对应 three.js 示例地址 。
仅需关注 init
函数的内容,其他部分都是示例小程序所使用的描述配置。
js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
name: "webgl_animation_skinning_additive_blending",
useLoaders: [GLTFLoader],
info: [
[
{ tag: "a", link: "https://threejs.org", content: "three.js" },
{ tag: "text", content: "- Skeletal Additive Animation Blending (model from" }
],
[
{ tag: "a", link: "https://www.mixamo.com/", content: "mixamo.com" },
{ tag: "text", content: ")" }
]
],
init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
let scene, renderer, camera, stats;
let model, skeleton, mixer, clock;
const crossFadeControls = [];
let currentBaseAction = "idle";
const allActions = [];
const baseActions = {
idle: { weight: 1 },
walk: { weight: 0 },
run: { weight: 0 }
};
const additiveActions = {
sneak_pose: { weight: 0 },
sad_pose: { weight: 0 },
agree: { weight: 0 },
headShake: { weight: 0 }
};
let panelSettings, numAnimations;
init();
function init() {
clock = new THREE.Clock();
scene = new THREE.Scene();
scene.background = new THREE.Color(10526880);
scene.fog = new THREE.Fog(10526880, 10, 50);
const hemiLight = new THREE.HemisphereLight(16777215, 9276813, 3);
hemiLight.position.set(0, 20, 0);
scene.add(hemiLight);
const dirLight = new THREE.DirectionalLight(16777215, 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);
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshPhongMaterial({ color: 13355979, depthWrite: false })
);
mesh.rotation.x = -Math.PI / 2;
mesh.receiveShadow = true;
scene.add(mesh);
const loader = new GLTFLoader();
loader.load("models/gltf/Xbot.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);
const animations = gltf.animations;
mixer = new THREE.AnimationMixer(model);
numAnimations = animations.length;
for (let i = 0; i !== numAnimations; ++i) {
let clip = animations[i];
const name = clip.name;
if (baseActions[name]) {
const action = mixer.clipAction(clip);
activateAction(action);
baseActions[name].action = action;
allActions.push(action);
} else if (additiveActions[name]) {
THREE.AnimationUtils.makeClipAdditive(clip);
if (clip.name.endsWith("_pose")) {
clip = THREE.AnimationUtils.subclip(clip, clip.name, 2, 3, 30);
}
const action = mixer.clipAction(clip);
activateAction(action);
additiveActions[name].action = action;
allActions.push(action);
}
}
createPanel();
renderer.setAnimationLoop(animate);
});
renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 100);
camera.position.set(-1, 2, 3);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enablePan = false;
controls.enableZoom = false;
controls.target.set(0, 1, 0);
controls.update();
stats = new Stats(renderer);
window.addEventListener("resize", onWindowResize);
needToDispose(renderer, scene, controls);
}
function createPanel() {
const panel = new GUI();
const folder1 = panel.addFolder("Base Actions");
const folder2 = panel.addFolder("Additive Action Weights");
const folder3 = panel.addFolder("General Speed");
panelSettings = {
"modify time scale": 1
};
const baseNames = ["None", ...Object.keys(baseActions)];
for (let i = 0, l = baseNames.length; i !== l; ++i) {
const name = baseNames[i];
const settings = baseActions[name];
panelSettings[name] = function() {
const currentSettings = baseActions[currentBaseAction];
const currentAction = currentSettings ? currentSettings.action : null;
const action = settings ? settings.action : null;
if (currentAction !== action) {
prepareCrossFade(currentAction, action, 0.35);
}
};
crossFadeControls.push(folder1.add(panelSettings, name));
}
for (const name of Object.keys(additiveActions)) {
const settings = additiveActions[name];
panelSettings[name] = settings.weight;
folder2.add(panelSettings, name, 0, 1, 0.01).listen().onChange(function(weight) {
setWeight(settings.action, weight);
settings.weight = weight;
});
}
folder3.add(panelSettings, "modify time scale", 0, 1.5, 0.01).onChange(modifyTimeScale);
folder1.open();
folder2.open();
folder3.open();
crossFadeControls.forEach(function(control) {
control.setInactive = function() {
control.domElement.classList.add("control-inactive");
};
control.setActive = function() {
control.domElement.classList.remove("control-inactive");
};
const settings = baseActions[control.property];
if (!settings || !settings.weight) {
control.setInactive();
}
});
}
function activateAction(action) {
const clip = action.getClip();
const settings = baseActions[clip.name] || additiveActions[clip.name];
setWeight(action, settings.weight);
action.play();
}
function modifyTimeScale(speed) {
mixer.timeScale = speed;
}
function prepareCrossFade(startAction, endAction, duration) {
if (currentBaseAction === "idle" || !startAction || !endAction) {
executeCrossFade(startAction, endAction, duration);
} else {
synchronizeCrossFade(startAction, endAction, duration);
}
if (endAction) {
const clip = endAction.getClip();
currentBaseAction = clip.name;
} else {
currentBaseAction = "None";
}
crossFadeControls.forEach(function(control) {
const name = control.property;
if (name === currentBaseAction) {
control.setActive();
} else {
control.setInactive();
}
});
}
function synchronizeCrossFade(startAction, endAction, duration) {
mixer.addEventListener("loop", onLoopFinished);
function onLoopFinished(event) {
if (event.action === startAction) {
mixer.removeEventListener("loop", onLoopFinished);
executeCrossFade(startAction, endAction, duration);
}
}
}
function executeCrossFade(startAction, endAction, duration) {
if (endAction) {
setWeight(endAction, 1);
endAction.time = 0;
if (startAction) {
startAction.crossFadeTo(endAction, duration, true);
} else {
endAction.fadeIn(duration);
}
} else {
startAction.fadeOut(duration);
}
}
function setWeight(action, weight) {
action.enabled = true;
action.setEffectiveTimeScale(1);
action.setEffectiveWeight(weight);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
for (let i = 0; i !== numAnimations; ++i) {
const action = allActions[i];
const clip = action.getClip();
const settings = baseActions[clip.name] || additiveActions[clip.name];
settings.weight = action.getEffectiveWeight();
}
const mixerUpdateDelta = clock.getDelta();
mixer.update(mixerUpdateDelta);
renderer.render(scene, camera);
stats.update();
}
}
};
export {
exampleInfo as default
};
ts
import { Loader, TypedArray } from 'three';
/**
* 官网示例的多端使用封装把版本
* */
export interface OfficialExampleInfo extends MiniProgramMeta {
/*** 示例名称(保持和官网一致)*/
name: string;
/** main */
init: (context: LoadContext) => void;
}
export interface LoadContext {
//为了减少官方代码的改动,实际上等同于 canvas
window: EventTarget & { innerWidth: number; innerHeight: number; devicePixelRatio: number };
/** HTMLCanvasElement */
canvas: any;
/** https://www.npmjs.com/package/lil-gui */
GUI: any;
/**
* https://www.npmjs.com/package/stats.js
* 也可以使用其他受支持的版本
* */
Stats: any;
/** 收集需要 dispose 的对象(官方示例没有处理这部分)*/
needToDispose: (...objs: any[]) => void | ((fromFn: () => any[]) => void);
/**基于 raq 的通用封装 */
useFrame(animateFunc: (/** ms */ delta: number) => void): { cancel: () => void };
/** 显示加载模态框 */
requestLoading(text?: string): Promise<void>;
/** 隐藏加载模态框*/
cancelLoading(): void;
/** 保存文件的通用封装*/
saveFile(
fileName: string,
data: ArrayBuffer | TypedArray | DataView | string
): Promise<string | null>;
/** 示例使用 DracoDecoder 时的资源路径 */
DecoderPath: {
GLTF: string;
STANDARD: string;
};
/** 为资源路径拼上 CDN 前缀 */
withCDNPrefix(path: string): string;
/**
* 在小程序中应使用 import { VideoTexture } from '@minisheep/three-platform-adapter/override/jsm/textures/VideoTexture.js';
* 正常情况(web) 可直接使用 THREE.VideoTexture
* */
getVideoTexture(videoOptions: VideoOptions): Promise<[{ isVideoTexture: true }, video: any]>;
/**
* 在小程序中应使用 import { CameraTexture } from '@minisheep/three-platform-adapter/override/jsm/textures/CameraTexture.js';
* 正常情况(web) 可参考示例 webgl_materials_video_webcam
* */
getCameraTexture(): { isVideoTexture: true };
/** 用于动态修改 info 中的占位符*/
bindInfoText(template: `$${string}$`, initValue?: string): { value: string };
/** 分屏控件对应的事件回调 */
onSlideStart(handle: () => void): void;
/** 分屏控件对应的事件回调 */
onSlideEnd(handle: () => void): void;
/** 分屏控件对应的事件回调 */
onSlideChange(handle: (offset: number, boxSize: number) => void): void;
}
export type VideoOptions = {
src: string;
/** 相当于 HTMLVideoElement 的 naturalWidth (小程序中获取不到)*/
width: number;
/** 相当于 HTMLVideoElement 的 naturalHeight (小程序中获取不到)*/
height: number;
loop?: boolean;
autoplay?: boolean;
muted?: boolean;
};
/** 示例小程序中使用的一些配置 */
export interface MiniProgramMeta {
/** 用于统计加载相关信息 */
useLoaders: Loader[];
/** 通用 info */
info: TagItem[][];
/** 特殊 info */
infoPanel?: {
left?: [string, string][];
right?: [string, string][];
};
/** 分屏控件配置 */
needSlider?: {
/** 方向 */
direction?: 'horizontal' | 'vertical';
/** 初始偏移 0-100 */
initPosition?: number;
};
/** 操作摇杆控件 */
needArrowControls?: boolean;
/** 默认需要的画布类型 */
canvasType?: '2d' | 'webgl' | 'webgl2';
/** 为保持效果一致所需要的画布样式 */
canvasStyle?: {
bgColor?: string;
width?: number | string;
height?: number | string;
};
/** 部分示例需要在加载前进行一些提示 */
initAfterConfirm?: {
/**
* 提示类型
* @default 'default'
* */
type?: 'warning' | 'default';
text: string[];
};
}
export interface BaseTag<T extends string> {
tag: T;
content: string;
}
export interface ATag extends BaseTag<'a'> {
link: string;
}
export type TextTag = BaseTag<'text'>;
export type TagItem = TextTag | ATag;