From 626ebe2b9db1f5290f33d003cb85745d8e804309 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 24 Jan 2019 15:36:00 +0800 Subject: [PATCH] add animation support/add webgl debug support --- cocos/3d/assets/animation-clip.js | 398 -------------- cocos/3d/assets/animation-clip.ts | 319 +++++++++++ cocos/3d/framework/animation-component.js | 495 ------------------ cocos/3d/framework/animation-component.ts | 426 +++++++++++++++ cocos/3d/framework/animation-system.js | 63 --- cocos/3d/framework/renderable-component.ts | 4 + cocos/3d/framework/skeleton-instance.js | 176 ------- .../3d/framework/skinning-model-component.ts | 151 ++---- cocos/3d/framework/skinning-model-system.js | 76 --- cocos/core/director.js | 1 - cocos/core/game.js | 1 + cocos/gfx/device.ts | 1 + cocos/gfx/webgl/webgl-device.ts | 8 + cocos/renderer/models/skinning-model.ts | 99 +++- globals.d.ts | 11 +- package.json | 1 + 16 files changed, 904 insertions(+), 1326 deletions(-) delete mode 100644 cocos/3d/assets/animation-clip.js create mode 100644 cocos/3d/assets/animation-clip.ts delete mode 100644 cocos/3d/framework/animation-component.js create mode 100644 cocos/3d/framework/animation-component.ts delete mode 100644 cocos/3d/framework/animation-system.js delete mode 100644 cocos/3d/framework/skeleton-instance.js delete mode 100644 cocos/3d/framework/skinning-model-system.js diff --git a/cocos/3d/assets/animation-clip.js b/cocos/3d/assets/animation-clip.js deleted file mode 100644 index 432d15bbe2..0000000000 --- a/cocos/3d/assets/animation-clip.js +++ /dev/null @@ -1,398 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -// @ts-check -import { _decorator } from "../../core/data/index"; -const { ccclass, property } = _decorator; -import { Asset } from "../../assets/asset"; -import vec3 from "../../core/vmath/vec3"; -import quat from "../../core/vmath/quat"; -import { clamp } from "../../core/vmath/utils"; - -/** - * @typedef {import("../framework/skeleton-instance").SkeletonMask} SkeletonMask - * @typedef {import("../../scene-graph/node").default} Node - */ - -let tmpvec3 = vec3.create(0, 0, 0); -let tmpquat = quat.create(); - -function _binaryIndexOf(array, key) { - let lo = 0; - let hi = array.length - 1; - let mid; - - while (lo <= hi) { - mid = ((lo + hi) >> 1); - let val = array[mid]; - - if (val < key) { - lo = mid + 1; - } else if (val > key) { - hi = mid - 1; - } else { - return mid; - } - } - - return lo; -} - -@ccclass('cc.AnimationChannel') -export class AnimationChannel { - /** - * Target node's path into virtual hierarchy. - * @type {string} - */ - @property - target = ""; - - /** - * Target node's position animation curve. - * @type {cc.Vec3[]} - */ - @property - positionCurve = []; - - /** - * Target node's scale animation curve. - * @type {cc.Vec3[]} - */ - @property - scaleCurve = []; - - /** - * Target node's rotation animation curve. - * @type {cc.Quat[]} - */ - @property - rotationCurve = []; -} -cc.AnimationChannel = AnimationChannel; - -@ccclass('cc.AnimationFrame') -export class AnimationFrame { - @property - _name = ""; - - /** - * @type {AnimationChannel[]} - */ - @property - _channels = []; - - /** - * @type {number[]} - */ - @property - _times = []; - - get channels() { - return this._channels; - } - - get times() { - return this._times; - } -} -cc.AnimationFrame = AnimationFrame; - -@ccclass('cc.AnimationClip') -export default class AnimationClip extends Asset { - /** - * @type {AnimationFrame[]} - */ - @property - _frames = []; - - /** - * @type {number} - */ - @property - _length = 0.0; - - get frames() { - return this._frames; - } - - get length() { - return this._length; - } -} -cc.AnimationClip = AnimationClip; - -export class AnimationTarget { - constructor() { - /** - * @type {Node[]} - */ - this._nodes = []; - - /** - * @type {Map} - */ - this._pathMap = new Map(); - } - - add(path, node) { - if (this._pathMap.has(path)) { - return; - } - const index = this._nodes.length; - this._nodes.push(node); - this._pathMap.set(path, index); - } - - get(path) { - return this._pathMap.get(path); - } - - get nodes() { - return this._nodes; - } - - getDefaultPosition(nodeIndex) { - return this._nodes[nodeIndex].getPosition(); - //return this._defaultPositions[nodeIndex]; - } - - getDefaultScale(nodeIndex) { - return this._nodes[nodeIndex].getScale(); - //return this._defaultScales[nodeIndex]; - } - - getDefaultRotation(nodeIndex) { - return this._nodes[nodeIndex].getRotation(); - //return this._defaultRotations[nodeIndex]; - } - - // _saveDefaultTRS() { - // this._defaultPositions = new Array(this._nodes.length); - // this._defaultScales = new Array(this._nodes.length); - // this._defaultRotations = new Array(this._nodes.length); - // this._nodes.forEach((node, index) => { - // this._defaultPositions[index] = node.getPosition(); - // this._defaultScales[index] = node.getScale(); - // this._defaultRotations[index] = node.getRotation(); - // }); - // } -} - -/** - * The AnimationTarget class represents the progress of blended sampling. - */ -export class AnimationSampler { - /** - * - * @param {AnimationTarget} animationTarget - */ - constructor(animationTarget) { - /** - * @type {AnimationTarget} - */ - this._animationTarget = animationTarget; - - const targetNodes = this._animationTarget.nodes; - /** - * @type {NodeSamplingState[]} - */ - this._nodeSamplingStates = new Array(targetNodes.length); - this._animationTarget.nodes.forEach((targetNode, index) => { - this._nodeSamplingStates[index] = new NodeSamplingState( - targetNode, - this._animationTarget.getDefaultPosition(index), - this._animationTarget.getDefaultScale(index), - this._animationTarget.getDefaultRotation(index)); - }); - } - - /** - * Resets this state to get sampling start. - */ - reset() { - this._nodeSamplingStates.forEach( - nodeSamlingState => nodeSamlingState.reset()); - } - - /** - * Updates the sampling result. - */ - apply() { - this._nodeSamplingStates.forEach( - nodeSamlingState => nodeSamlingState.apply()); - } - - /** Sample data of this animation clip in a specific time and blend that data - * with a weight together with previous data(if exist, or blank if not exists) sampled before. - * - * @param {AnimationClip} clip - * @param {Number} t The time. - * @param {Number} weight The weight. - * @param {SkeletonMask} [mask] The skeleton mask. - */ - sample(clip, t, weight, mask) { - t = clamp(t, 0, clip.length); - - const getState = /** @param {AnimationChannel} [channel] */(channel) => { - return this._nodeSamplingStates[this._animationTarget.get(channel.target)]; - }; - - clip.frames.forEach((frame) => { - let idx = 0; - if (frame.times.length != 1) - idx = _binaryIndexOf(frame.times, t); - if (idx == 0) { - frame.channels.forEach((channel) => { - const nodeSamlingState = getState(channel); - if (!nodeSamlingState) { - return; - } - if (channel.positionCurve.length != 0) { - nodeSamlingState.blendPosition(channel.positionCurve[0], weight); - } - if (channel.rotationCurve.length != 0) { - nodeSamlingState.blendRotation(channel.rotationCurve[0], weight); - } - if (channel.scaleCurve.length != 0) { - nodeSamlingState.blendScale(channel.scaleCurve[0], weight); - } - }); - } - else { - let loIdx = Math.max(idx - 1, 0); - let hiIdx = Math.min(idx, frame.times.length); - let ratio = (t - frame.times[loIdx]) / (frame.times[hiIdx] - frame.times[loIdx]); - - frame.channels.forEach((channel) => { - const nodeSamlingState = getState(channel); - if (!nodeSamlingState) { - return; - } - if (channel.positionCurve.length != 0) { - let a = channel.positionCurve[loIdx]; - let b = channel.positionCurve[hiIdx]; - vec3.lerp(tmpvec3, a, b, ratio); - nodeSamlingState.blendPosition(tmpvec3, weight); - } - if (channel.rotationCurve.length != 0) { - let a = channel.rotationCurve[loIdx]; - let b = channel.rotationCurve[hiIdx]; - quat.slerp(tmpquat, a, b, ratio); - nodeSamlingState.blendRotation(tmpquat, weight); - } - if (channel.scaleCurve.length != 0) { - let a = channel.scaleCurve[loIdx]; - let b = channel.scaleCurve[hiIdx]; - vec3.lerp(tmpvec3, a, b, ratio); - nodeSamlingState.blendScale(tmpvec3, weight); - } - }); - } - }); - } -} - -class NodeSamplingState { - /** - * - * @param {Node} target - * @param {cc.Vec3} defaultPosition - * @param {cc.Vec3} defaultScale - * @param {cc.Quat} defaultRotation - */ - constructor(target, defaultPosition, defaultScale, defaultRotation) { - /** - * @type {Node} - */ - this._target = target; - - /** - * @type {cc.Vec3} - */ - this._defaultPosition = defaultPosition; - - /** - * @type {cc.Vec3} - */ - this._defaultScale = defaultScale; - - /** - * @type {cc.Quat} - */ - this._defaultRotation = defaultRotation; - } - - reset() { - /** - * @type {Number} - */ - this._sumPosWeight = 0.0; - - /** - * @type {Number} - */ - this._sumScaleWeight = 0.0; - - /** - * @type {Number} - */ - this._sumRotWeight = 0.0; - this._target.setPosition(0, 0, 0); - this._target.setScale(0, 0, 0); - this._target.setRotation(0, 0, 0, 1); - } - - blendPosition(pos, weight) { - vec3.scaleAndAdd(tmpvec3, this._target._lpos, pos, weight); - this._target.setPosition(tmpvec3); - this._sumPosWeight += weight; - } - - blendScale(scale, weight) { - vec3.scaleAndAdd(tmpvec3, this._target._lscale, scale, weight); - this._target.setScale(tmpvec3); - this._sumScaleWeight += weight; - } - - /** - * Inspired by: - * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions - */ - blendRotation(rot, weight) { - let t = weight / (this._sumRotWeight + weight); - quat.slerp(tmpquat, this._target._lrot, rot, t); - this._target.setRotation(tmpquat); - this._sumRotWeight += weight; - } - - apply() { - if (this._sumPosWeight < 1.0) - this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight); - if (this._sumScaleWeight < 1.0) - this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight); - if (this._sumRotWeight < 1.0) - this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight); - } -} diff --git a/cocos/3d/assets/animation-clip.ts b/cocos/3d/assets/animation-clip.ts new file mode 100644 index 0000000000..321ff63aaf --- /dev/null +++ b/cocos/3d/assets/animation-clip.ts @@ -0,0 +1,319 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +// @ts-check +import { _decorator } from '../../core/data/index'; +const { ccclass, property } = _decorator; +import { Asset } from '../../assets/asset'; +import { Quat, Vec3 } from '../../core/value-types'; +import quat from '../../core/vmath/quat'; +import { clamp } from '../../core/vmath/utils'; +import vec3 from '../../core/vmath/vec3'; +import { Node } from '../../scene-graph/node'; + +const tmpvec3 = new Vec3(); +const tmpquat = new Quat(); + +function _binaryIndexOf (array: number[], key: number) { + let lo = 0; + let hi = array.length - 1; + while (lo <= hi) { + const mid = ((lo + hi) >> 1); + const val = array[mid]; + if (val < key) { + lo = mid + 1; + } else if (val > key) { + hi = mid - 1; + } else { + return mid; + } + } + return lo; +} + +export interface IAnimationChannel { + /** + * Target node's path in scene graph. + */ + target: string; + + /** + * Target node's position animation curve. + */ + positionCurve: Vec3[]; + + /** + * Target node's scale animation curve. + */ + scaleCurve: Vec3[]; + + /** + * Target node's rotation animation curve. + */ + rotationCurve: Quat[]; +} + +@ccclass('cc.AnimationClip') +export default class AnimationClip extends Asset { + @property + private _channels: IAnimationChannel[] = []; + + @property + private _times: number[] = []; + + @property + private _length: number = 0.0; + + get times () { + return this._times; + } + + get channels () { + return this._channels; + } + + get length () { + return this._length; + } +} +cc.AnimationClip = AnimationClip; + +export class AnimationTarget { + private _nodes: Node[] = []; + private _pathMap: Map = new Map(); + + public add (path: string, node: Node) { + if (this._pathMap.has(path)) { + return; + } + const index = this._nodes.length; + this._nodes.push(node); + this._pathMap.set(path, index); + } + + public get (path: string) { + return this._pathMap.get(path); + } + + get nodes () { + return this._nodes; + } + + public getDefaultPosition (nodeIndex: number) { + return this._nodes[nodeIndex].getPosition(); + // return this._defaultPositions[nodeIndex]; + } + + public getDefaultScale (nodeIndex: number) { + return this._nodes[nodeIndex].getScale(); + // return this._defaultScales[nodeIndex]; + } + + public getDefaultRotation (nodeIndex: number) { + return this._nodes[nodeIndex].getRotation(); + // return this._defaultRotations[nodeIndex]; + } + + // _saveDefaultTRS() { + // this._defaultPositions = new Array(this._nodes.length); + // this._defaultScales = new Array(this._nodes.length); + // this._defaultRotations = new Array(this._nodes.length); + // this._nodes.forEach((node, index) => { + // this._defaultPositions[index] = node.getPosition(); + // this._defaultScales[index] = node.getScale(); + // this._defaultRotations[index] = node.getRotation(); + // }); + // } +} + +/** + * The AnimationTarget class represents the progress of blended sampling. + */ +export class AnimationSampler { + private _animationTarget: AnimationTarget; + private _nodeSamplingStates: NodeSamplingState[]; + + constructor (animationTarget: AnimationTarget) { + this._animationTarget = animationTarget; + + const targetNodes = this._animationTarget.nodes; + this._nodeSamplingStates = new Array(targetNodes.length); + this._animationTarget.nodes.forEach((targetNode, index) => { + this._nodeSamplingStates[index] = new NodeSamplingState( + targetNode, + this._animationTarget.getDefaultPosition(index), + this._animationTarget.getDefaultScale(index), + this._animationTarget.getDefaultRotation(index)); + }); + } + + /** + * Resets this state to get sampling start. + */ + public reset () { + this._nodeSamplingStates.forEach( + (nodeSamlingState) => nodeSamlingState.reset()); + } + + /** + * Updates the sampling result. + */ + public apply () { + this._nodeSamplingStates.forEach( + (nodeSamlingState) => nodeSamlingState.apply()); + } + + /** Sample data of this animation clip in a specific time and blend that data + * with a weight together with previous data(if exist, or blank if not exists) sampled before. + * + * @param clip + * @param t The time. + * @param weight The weight. + * @param [mask] The skeleton mask. + */ + public sample (clip: AnimationClip, t: number, weight: number, mask?: any) { + t = clamp(t, 0, clip.length); + + const getState = (channel: IAnimationChannel) => { + const iNode = this._animationTarget.get(channel.target); + if (!iNode) { + return null; + } + return this._nodeSamplingStates[iNode]; + }; + + let idx = 0; + if (clip.times.length !== 1) { + idx = _binaryIndexOf(clip.times, t); + } + if (idx === 0) { + clip.channels.forEach((channel) => { + const nodeSamlingState = getState(channel); + if (!nodeSamlingState) { + return; + } + if (channel.positionCurve.length !== 0) { + nodeSamlingState.blendPosition(channel.positionCurve[0], weight); + } + if (channel.rotationCurve.length !== 0) { + nodeSamlingState.blendRotation(channel.rotationCurve[0], weight); + } + if (channel.scaleCurve.length !== 0) { + nodeSamlingState.blendScale(channel.scaleCurve[0], weight); + } + }); + } else { + const loIdx = Math.max(idx - 1, 0); + const hiIdx = Math.min(idx, clip.times.length); + const ratio = (t - clip.times[loIdx]) / (clip.times[hiIdx] - clip.times[loIdx]); + + clip.channels.forEach((channel) => { + const nodeSamlingState = getState(channel); + if (!nodeSamlingState) { + return; + } + if (channel.positionCurve.length !== 0) { + const a = channel.positionCurve[loIdx]; + const b = channel.positionCurve[hiIdx]; + vec3.lerp(tmpvec3, a, b, ratio); + nodeSamlingState.blendPosition(tmpvec3, weight); + } + if (channel.rotationCurve.length !== 0) { + const a = channel.rotationCurve[loIdx]; + const b = channel.rotationCurve[hiIdx]; + quat.slerp(tmpquat, a, b, ratio); + nodeSamlingState.blendRotation(tmpquat, weight); + } + if (channel.scaleCurve.length !== 0) { + const a = channel.scaleCurve[loIdx]; + const b = channel.scaleCurve[hiIdx]; + vec3.lerp(tmpvec3, a, b, ratio); + nodeSamlingState.blendScale(tmpvec3, weight); + } + }); + } + } +} + +class NodeSamplingState { + private _target: Node; + private _defaultPosition: Vec3; + private _defaultScale: Vec3; + private _defaultRotation: Quat; + private _sumPosWeight = 0; + private _sumScaleWeight = 0; + private _sumRotWeight = 0; + + constructor (target: Node, defaultPosition: Vec3, defaultScale: Vec3, defaultRotation: Quat) { + this._target = target; + this._defaultPosition = defaultPosition; + this._defaultScale = defaultScale; + this._defaultRotation = defaultRotation; + } + + public reset () { + this._sumPosWeight = 0.0; + this._sumScaleWeight = 0.0; + this._sumRotWeight = 0.0; + this._target.setPosition(0, 0, 0); + this._target.setScale(0, 0, 0); + this._target.setRotation(0, 0, 0, 1); + } + + public blendPosition (position: Vec3, weight: number) { + vec3.scaleAndAdd(tmpvec3, this._target.getPosition(), position, weight); + this._target.setPosition(tmpvec3); + this._sumPosWeight += weight; + } + + public blendScale (scale: Vec3, weight: number) { + vec3.scaleAndAdd(tmpvec3, this._target.getScale(), scale, weight); + this._target.setScale(tmpvec3); + this._sumScaleWeight += weight; + } + + /** + * Inspired by: + * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions + */ + public blendRotation (rotation: Quat, weight: number) { + const t = weight / (this._sumRotWeight + weight); + quat.slerp(tmpquat, this._target.getRotation(), rotation, t); + this._target.setRotation(tmpquat); + this._sumRotWeight += weight; + } + + public apply () { + if (this._sumPosWeight < 1.0) { + this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight); + } + if (this._sumScaleWeight < 1.0) { + this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight); + } + if (this._sumRotWeight < 1.0) { + this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight); + } + } +} diff --git a/cocos/3d/framework/animation-component.js b/cocos/3d/framework/animation-component.js deleted file mode 100644 index 0e9d1c8e4b..0000000000 --- a/cocos/3d/framework/animation-component.js +++ /dev/null @@ -1,495 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import { Component } from '../../components/component'; -import { ccclass, property, executionOrder, menu, executeInEditMode } from '../../core/data/class-decorator'; -import Enum from '../../core/value-types/enum'; -import AnimationClip, { AnimationTarget, AnimationSampler } from '../assets/animation-clip'; - -/** - * !#en Animation State Class - * - * !#ch 动画状态类 - * @class AnimationState - */ -class AnimationState { - constructor(clip) { - /** - * !#en An animation clip that is played through this state - * - * !#ch 通过此状态播放的动画剪辑 - * @property clip - * @type {AnimationClip} - */ - this.clip = clip; - - /** - * !#en Blend mode - * - * !#ch 混合模式 - * @property blendMode - * @type {String} - */ - this.blendMode = AnimationState.BlendMode.Blend; - - /** - * !#en Wrapping mode - * - * !#ch 循环模式 - * @property wrapMode - * @type {String} - */ - this.wrapMode = AnimationState.WrapMode.Loop; - - /** - * !#en The playback speed - * - * !#ch 播放速度 - * @property speed - * @type {Number} - */ - this.speed = 1.0; - - /** - * !#en The current time of the animation. - * - * !#ch 当前动画播放时间 - * @property time - * @type {Number} - */ - this.time = 0.0; - - /** - * !#en The weight of animation. - * - * !#ch 动画权重 - * @property weight - * @type {Number} - */ - this.weight = 1.0; - } - - /** - * !#en The blend mode of animation state - * - * !#ch 动画状态的混合模式 - * @static - * @enum AnimationState.BlendMode - */ - static BlendMode = Enum({ - /** - * !#en Animations will be blended. - * - * !#ch 动画将被混合 - * @property Blend - * @readonly - * @type {String} - */ - Blend: 'blend', - /** - * !#en Animations will be added. - * - * !#ch 动画将被附加 - * @property Additive - * @readonly - * @type {String} - */ - Additive: 'additive' - }); - - /** - * !#en Wrapping mode of the animation. - * - * !#ch 动画状态的循环模式 - * @static - * @enum AnimationState.WrapMode - */ - static WrapMode = Enum({ - /** - * !#en Only once - * - * !#ch 只播放一次 - * @property Once - * @readonly - * @type {String} - */ - Once: 'once', - /** - * !#en Loop - * - * !#ch 循环播放 - * @property Additive - * @readonly - * @type {String} - */ - Loop: 'loop', - /** - * !#en Ping Pong - * - * !#ch 乒乓模式播放 - * @property PinpPong - * @readonly - * @type {String} - */ - PinpPong: 'ping-pong', - /** - * !#en Plays back the animation. The last frame is played until the end. - * - * !#ch 回放动画。当到结尾时,会持续播放最后一帧。 - * @property Clamp - * @readonly - * @type {String} - */ - Clamp: 'clamp' - }); -} - -/** - * !#en Animation Controller - * - * !#ch 动画控制器 - * @class AnimationCtrl - */ -class AnimationCtrl { - constructor() { - /** - * @type {AnimationTarget} - */ - this._animationTarget = null; - - /** - * @type {AnimationSampler} - */ - this._animationSampler = null; - - this._current = null; - - this._next = null; - - this._blendTime = 0.0; - - this._blendDuration = 0.3; - } - - /** - * !#en Set up the animation target - * - * !#ch 设置动画目标 - * @param {AnimationTarget} animationTarget - */ - setAnimationTarget(animationTarget) { - this._animationTarget = animationTarget; - if (this._animationTarget) { - this._animationSampler = new AnimationSampler(this._animationTarget); - } - this._nodeIndexers = new Map(); - } - - /** - * !#en Animation fades in and out - * - * !#ch 动画的淡入淡出功能 - * @param {AnimationState} to - * @param {Number} duration - */ - crossFade(to, duration) { - if (this._current && duration > 0.0) { - this._next = to; - this._blendTime = 0.0; - this._blendDuration = duration; - } else { - this._current = to; - this._next = null; - } - } - - tick(dt) { - if (!this._animationSampler) { - return; - } - - this._animationSampler.reset(); - - // handle blend - if (this._current && this._next) { - let t0 = this._getTime(this._current); - let t1 = this._getTime(this._next); - - let alpha = this._blendTime / this._blendDuration; - - this._current.time += dt; - this._next.time += dt; - this._blendTime += dt; - - if (alpha > 1.0) { - this._current = this._next; - this._next = null; - this._animationSampler.sample(this._current.clip, t1, 1.0); - } else { - this._animationSampler.sample(this._current.clip, t0, alpha); - this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha); - } - } - - // handle playing - if (this._current) { - let t0 = this._getTime(this._current); - this._animationSampler.sample(this._current.clip, t0, 1.0); - this._current.time += dt; - } - - this._animationSampler.apply(); - } - - /** - * !#en Get the play time of an animation clip in current animation state - * - * !#ch 返回当前动画状态下的动画剪辑播放时间 - * @param {AnimationState} state - Specify animation status - */ - _getTime(state) { - let t = state.time; - let length = state.clip.length; - t *= state.speed; - - if (state.wrapMode === 'once') { - if (t > length) { - t = 0.0; - } - } else if (state.wrapMode === 'loop') { - t %= length; - } else if (state.wrapMode === 'ping-pong') { - let order = Math.floor(t / length); - if (order % 2 === 1) { - t = length - t % length; - } - } - - return t; - } -} - -/** - * !#en - * Basic animation component for playing animation - * - * !#ch - * 基础动画组件用于动画播放 - * @class AnimationComponent - * @extends Component - */ -@ccclass('cc.AnimationComponent') -@executionOrder(99) -@executeInEditMode -@menu('Components/AnimationComponent') -export default class AnimationComponent extends Component { - /** - * @type {AnimationClip[]} - */ - @property({ type: [AnimationClip] }) - _clips = []; - - /** - * !#en Current clip - * - * !#ch 当前动画剪辑 - * @property currentClip - * @type {AnimationClip} - */ - @property({ type:AnimationClip }) - currentClip = null; - - /** - * !#en Whether to start the animation automatically - * - * !#ch 是否启动时自动播放动画 - * @property playAutomatically - * @type {Boolean} - */ - @property - playAutomatically = false; - - _preview = false; - - @property({ type: Boolean }) - get preview() { - return this._preview; - } - - set preview(value) { - this._preview = value; - if (value) { - if (this.currentClip) { - cc.engine.animatingInEditMode = true; - this.play(this.currentClip.name); - } - } else { - cc.engine.animatingInEditMode = false; - this._animCtrl.crossFade(null, 0); - } - } - - /** - * !#en Animation state - * - * !#ch 动画状态列表 - * @type {Object} - */ - _name2states = {}; - - constructor() { - super(); - - /** - * @type {AnimationTarget} - */ - this._target = null; - - /** - * !#en Animation controller - * - * !#ch 动画控制器 - * @type {AnimationCtrl} - */ - this._animCtrl = new AnimationCtrl(); - } - - /** - * !#en Clip required for animation playback - * - * !#ch 动画剪辑列表 - * @property clips - * @type {AnimationClip[]} - */ - @property({ type: [AnimationClip] }) - get clips() { - return this._clips; - } - - set clips(val) { - this._clips = val; - } - - onLoad() { - this._clips.forEach(clip => { - this._name2states[clip.name] = new AnimationState(clip); - }); - - this._resetTarget(); - - if (this.playAutomatically != undefined && - this.playAutomatically && - this.currentClip != undefined && - this.currentClip) { - this.play(this.currentClip.name); - } - } - - update(dt) { - this._animCtrl.tick(dt); - } - - onDestroy() { - } - - onEnable() { - } - - onDisable() { - this._target = null; - this._animCtrl.setAnimationTarget(null); - } - - /** - * !#en Add an animation clip to the animation status list - * - * !#ch 添加动画剪辑到动画状态列表 - * @param {String} name - The name of animation clip - * @param {AnimationClip} animClip - Animation clip - */ - addClip(name, animClip) { - if (this._name2states[name]) { - console.warn(`Failed to add clip ${name}, the name already exsits.`); - return; - } - - this._clips.push(animClip); - this._name2states[name] = new AnimationState(animClip); - } - - /** - * !#en Get the animation state through the animation clip name - * - * !#ch 返回动画剪辑相对应的动画状态 - * @param {String} name - The name of animation clip - */ - getState(name) { - return this._name2states[name]; - } - - /** - * !#en Play the name of the animation clip - * - * !#ch 播放相对应名字的动画剪辑 - * @param {String} name - The name of animation clip - * @param {Number} fadeDuration - Fade duration - */ - play(name, fadeDuration = 0.3) { - if (!this._target) { - return; - } - - if (!this._name2states[name]) { - console.warn(`Failed to play animation ${name}, not found.`); - return; - } - - let animState = this._name2states[name]; - animState.time = 0.0; - - this._animCtrl.crossFade(animState, fadeDuration); - } - - _resetTarget() { - this._target = new AnimationTarget(); - this._clips.forEach(clip => { - clip.frames.forEach(frame => { - frame.channels.forEach(channel => { - const targetPath = channel.target; - if (this._target.get(targetPath)) { - return; - } - const targetNode = this.node.getChildByPath(targetPath); - if (!targetNode) { - console.warn(`Animation target ${targetPath} not found in scene graph.`); - return; - } - this._target.add(targetPath, targetNode); - }); - }); - }); - this._animCtrl.setAnimationTarget(this._target); - } -} diff --git a/cocos/3d/framework/animation-component.ts b/cocos/3d/framework/animation-component.ts new file mode 100644 index 0000000000..c308fb1f82 --- /dev/null +++ b/cocos/3d/framework/animation-component.ts @@ -0,0 +1,426 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +// @ts-check +import { Component } from '../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { ccenum } from '../../core/value-types/enum'; +import AnimationClip, { AnimationSampler, AnimationTarget } from '../assets/animation-clip'; + +enum BlendMode { + /** + * !#en Animations will be blended. + * + * !#ch 动画将被混合 + */ + Blend = 'blend', + /** + * !#en Animations will be added. + * + * !#ch 动画将被附加 + */ + Additive = 'additive', +} + +ccenum(BlendMode); + +enum WrapMode { + /** + * !#en Only once + * + * !#ch 只播放一次 + */ + Once = 'once', + + /** + * !#en Loop + * + * !#ch 循环播放 + */ + Loop = 'loop', + + /** + * !#en Ping Pong + * + * !#ch 乒乓模式播放 + */ + PinpPong = 'ping-pong', + + /** + * !#en Plays back the animation. The last frame is played until the end. + * + * !#ch 回放动画。当到结尾时,会持续播放最后一帧。 + */ + Clamp = 'clamp', +} + +ccenum(WrapMode); + +/** + * !#en Animation State Class + * + * !#ch 动画状态类 + */ +class AnimationState { + /** + * !#en The blend mode of animation state. + * + * !#ch 动画状态的混合模式 + */ + public static BlendMode = BlendMode; + + /** + * !#en Wrapping mode of the animation. + * + * !#ch 动画状态的循环模式 + */ + public static WrapMode = WrapMode; + + /** + * !#en An animation clip that is played through this state + * + * !#ch 通过此状态播放的动画剪辑 + */ + public clip: AnimationClip; + + /** + * !#en Blend mode + * + * !#ch 混合模式 + */ + public blendMode: BlendMode = BlendMode.Blend; + + /** + * !#en Wrapping mode + * + * !#ch 循环模式 + */ + public wrapMode: WrapMode = WrapMode.Loop; + + /** + * !#en The playback speed + * + * !#ch 播放速度 + */ + public speed = 1.0; + + /** + * !#en The current time of the animation. + * + * !#ch 当前动画播放时间 + */ + public time: number = 0.0; + + /** + * !#en The weight of animation. + * + * !#ch 动画权重 + */ + public weight: number = 1.0; + + constructor (clip: AnimationClip) { + this.clip = clip; + } +} + +/** + * !#en Animation Controller + * + * !#ch 动画控制器 + */ +class AnimationCtrl { + private _animationTarget: AnimationTarget | null = null; + private _animationSampler: AnimationSampler | null = null; + private _current: AnimationState | null = null; + private _next: AnimationState | null = null; + private _blendTime = 0.0; + private _blendDuration = 0.3; + + /** + * !#en Set up the animation target + * + * !#ch 设置动画目标 + */ + public setAnimationTarget (animationTarget: AnimationTarget | null) { + this._animationTarget = animationTarget; + if (this._animationTarget) { + this._animationSampler = new AnimationSampler(this._animationTarget); + } + } + + /** + * !#en Animation fades in and out + * + * !#ch 动画的淡入淡出功能 + * @param to + * @param duration + */ + public crossFade (to: AnimationState | null, duration: number) { + if (this._current && duration > 0.0) { + this._next = to; + this._blendTime = 0.0; + this._blendDuration = duration; + } else { + this._current = to; + this._next = null; + } + } + + public tick (deltaTime: number) { + if (!this._animationSampler) { + return; + } + + this._animationSampler.reset(); + + // handle blend + if (this._current && this._next) { + const t0 = this._getTime(this._current); + const t1 = this._getTime(this._next); + + const alpha = this._blendTime / this._blendDuration; + + this._current.time += deltaTime; + this._next.time += deltaTime; + this._blendTime += deltaTime; + + if (alpha > 1.0) { + this._current = this._next; + this._next = null; + this._animationSampler.sample(this._current.clip, t1, 1.0); + } else { + this._animationSampler.sample(this._current.clip, t0, alpha); + this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha); + } + } + + // handle playing + if (this._current) { + const t0 = this._getTime(this._current); + this._animationSampler.sample(this._current.clip, t0, 1.0); + this._current.time += deltaTime; + } + + this._animationSampler.apply(); + } + + /** + * !#en Get the play time of an animation clip in current animation state + * + * !#ch 返回当前动画状态下的动画剪辑播放时间 + * @param state - Specify animation status + */ + private _getTime (state: AnimationState) { + let t = state.time; + const length = state.clip.length; + t *= state.speed; + + if (state.wrapMode === 'once') { + if (t > length) { + t = 0.0; + } + } else if (state.wrapMode === 'loop') { + t %= length; + } else if (state.wrapMode === 'ping-pong') { + const order = Math.floor(t / length); + if (order % 2 === 1) { + t = length - t % length; + } + } + + return t; + } +} + +/** + * !#en + * Basic animation component for playing animation + * + * !#ch + * 基础动画组件用于动画播放 + */ +@ccclass('cc.AnimationComponent') +@executionOrder(99) +@executeInEditMode +@menu('Components/AnimationComponent') +export default class AnimationComponent extends Component { + @property({ type: [AnimationClip] }) + public _clips: AnimationClip[] = []; + + /** + * !#en Current clip + * + * !#ch 当前动画剪辑 + */ + @property({ type: AnimationClip }) + public currentClip: AnimationClip | null = null; + + /** + * !#en Whether to start the animation automatically + * + * !#ch 是否启动时自动播放动画 + */ + @property + public playAutomatically: boolean = false; + + private _preview = false; + + private _animationController: AnimationCtrl = new AnimationCtrl(); + + private _name2states: { [x: string]: AnimationState | undefined; } = {}; + + private _animationTarget: AnimationTarget | null = null; + + @property({ type: Boolean }) + get preview () { + return this._preview; + } + + set preview (value) { + this._preview = value; + if (value) { + if (this.currentClip) { + cc.engine.animatingInEditMode = true; + this.play(this.currentClip.name); + } + } else { + cc.engine.animatingInEditMode = false; + this._animationController.crossFade(null, 0); + } + } + + constructor () { + super(); + } + + /** + * !#en Clip required for animation playback + * + * !#ch 动画剪辑列表 + */ + @property({ type: [AnimationClip] }) + get clips () { + return this._clips; + } + + set clips (val) { + this._clips = val; + } + + public onLoad () { + this._clips.forEach((clip) => { + this._name2states[clip.name] = new AnimationState(clip); + }); + + this._resetTarget(); + + if (!CC_EDITOR && this.playAutomatically && this.currentClip) { + this.play(this.currentClip.name); + } + } + + public update (deltaTime: number) { + this._animationController.tick(deltaTime); + } + + public onDestroy () { + } + + public onEnable () { + } + + public onDisable () { + this._animationTarget = null; + this._animationController.setAnimationTarget(null); + } + + /** + * !#en Add an animation clip to the animation status list + * + * !#ch 添加动画剪辑到动画状态列表 + * @param name - The name of animation clip + * @param animationClip - Animation clip + */ + public addClip (name: string, animationClip: AnimationClip) { + if (this._name2states[name]) { + console.warn(`Failed to add clip ${name}, the name already exsits.`); + return; + } + + this._clips.push(animationClip); + this._name2states[name] = new AnimationState(animationClip); + } + + /** + * !#en Get the animation state through the animation clip name + * + * !#ch 返回动画剪辑相对应的动画状态 + * @param name - The name of animation clip + */ + public getState (name: string) { + return this._name2states[name]; + } + + /** + * !#en Play the name of the animation clip + * + * !#ch 播放相对应名字的动画剪辑 + * @param name - The name of animation clip + * @param fadeDuration - Fade duration + */ + public play (name: string, fadeDuration = 0.3) { + if (!this._animationTarget) { + return; + } + + const state = this._name2states[name]; + if (!state) { + console.warn(`Failed to play animation ${name}, not found.`); + return; + } + + state.time = 0.0; + this._animationController.crossFade(state, fadeDuration); + } + + public _resetTarget () { + const animationTarget = new AnimationTarget(); + this._clips.forEach((clip) => { + clip.channels.forEach((channel) => { + const targetPath = channel.target; + if (animationTarget.get(targetPath)) { + return; + } + const targetNode = this.node.getChildByPath(targetPath); + if (!targetNode) { + console.warn(`Animation target ${targetPath} not found in scene graph.`); + return; + } + animationTarget.add(targetPath, targetNode); + }); + }); + this._animationTarget = animationTarget; + this._animationController.setAnimationTarget(this._animationTarget); + } +} diff --git a/cocos/3d/framework/animation-system.js b/cocos/3d/framework/animation-system.js deleted file mode 100644 index c68d3b8165..0000000000 --- a/cocos/3d/framework/animation-system.js +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import System from '../ecs/system'; -import { FixedArray } from '../memop'; -/** - * @typedef {import('./animation-component').default} AnimationComponent - */ - -export default class AnimationSystem extends System { - constructor() { - super(); - - this._anims = new FixedArray(200); - } - - add(comp) { - this._anims.push(comp); - } - - remove(comp) { - this._anims.fastRemove(this._anims.indexOf(comp)); - } - -// update() { -// for (let i = 0; i < this._anims.length; ++i) { -// let anim = this._anims.data[i]; -// if (!anim.enabled) { -// continue; -// } -// if (!anim.skeleton) { -// // console.error(`Animation component depends on skinning model component.`); -// let skeleton = findSkeleton(anim._entity); -// anim.skeleton = skeleton; -// } -// if (anim.skeleton) { -// anim._animCtrl.tick(this._app.deltaTime); -// } -// } -// } -} diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index 2389fe921a..bbf38ac38c 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -13,6 +13,10 @@ export class RenderableComponent extends Component { super(); } + public onLoad () { + this.sharedMaterials = this._materials.concat(); + } + @property({ type: [Material], displayName: 'Materials', diff --git a/cocos/3d/framework/skeleton-instance.js b/cocos/3d/framework/skeleton-instance.js deleted file mode 100644 index 92ac204819..0000000000 --- a/cocos/3d/framework/skeleton-instance.js +++ /dev/null @@ -1,176 +0,0 @@ -// @ts-check -import { vec3, quat, mat4 } from '../../core/vmath'; -import { Node } from '../../scene-graph'; - -let _v3_tmp = vec3.create(); -let _qt_tmp = quat.create(); - -/** - * - * @param {cc.Node} node - * @param {(node: cc.Node)=>void} fx - */ -function _walk(node, fx) { - fx(node); - for (let i = 0; i < node.childrenCount; ++i) { - _walk(node.children[i], fx); - } -} - -export default class SkeletonInstance { - /** - * - * @param {import("../assets/skeleton").default} skeleton - */ - constructor(skeleton) { - this._skeleton = skeleton; - - /** - * @type {cc.Node[]} - */ - this._nodes = this._copyNodesForest(skeleton._nodes); - - /** - * @type {mat4[]} - */ - this._matrices = new Array(this._nodes.length); - for (let i = 0; i < this._nodes.length; ++i) { - this._matrices[i] = mat4.create(); - } - - this.updateMatrices(); - } - - /** - * - * @param {cc.Node[]} nodes - */ - _copyNodesForest(nodes) { - /** @type {cc.Node[]} */ - const newNodes = new Array(nodes.length); - nodes.forEach((node, index) => { - newNodes[index] = this._copyNode(node); - }); - nodes.forEach((node, index) => { - const newNode = newNodes[index]; - node.children.forEach(childNode => { - const childIndex = nodes.indexOf(childNode); - newNode.addChild(newNodes[childIndex]); - }); - }); - return newNodes; - } - - /** - * - * @param {cc.Node} node - */ - _copyNode(node) { - const newNode = new Node(node.name); - newNode.setPosition(node.getPosition()); - newNode.setScale(node.getScale()); - newNode.setRotation(node.getRotation()); - return newNode; - } - - blend(fromSkel, toSkel, alpha) { - for (let i = 0; i < this._nodes.length; ++i) { - let joint = this._nodes[i]; - let jointFrom = fromSkel._nodes[i]; - let jointTo = toSkel._nodes[i]; - - vec3.lerp(_v3_tmp, jointFrom._lpos, jointTo._lpos, alpha); - joint.setPosition(_v3_tmp); - - vec3.lerp(_v3_tmp, jointFrom._lscale, jointTo._lscale, alpha); - joint.setScale(_v3_tmp); - - quat.lerp(_qt_tmp, jointFrom._lrot, jointTo._lrot, alpha); - joint.setRotation(_qt_tmp); - } - } - - updateMatrices() { - for (let i = 0; i < this._nodes.length; ++i) { - this._nodes[i].getWorldMatrix(this._matrices[i]); - } - } - - /** - * - * @param {number} i Index of the node. - */ - getWorldMatrix(i) { - return this._matrices[i]; - } - - getJointIndex(jointName) { - for (let i = 0; i < this._nodes.length; ++i) { - let joint = this._nodes[i]; - if (joint.name == jointName) { - return i; - } - } - return -1; - } - - getJointIndexFromOrignalNodeIndex(index) { - return index; - } - - clone() { - return new SkeletonInstance(this._skeleton); - } - - createMask() { - return new SkeletonMask(this); - } -} - -export class SkeletonMask { - /** - * - * @param {SkeletonInstance} skeleton - */ - constructor(skeleton) { - /** - * @type {SkeletonInstance} - * */ - this._skeleton = skeleton; - - this._isMaskedArray = new Array(skeleton._nodes.length); - for (let i = 0; i < this._isMaskedArray.length; ++i) { - this._isMaskedArray[i] = false; - } - } - - setMasked(jointIndex, masked = true) { - this._isMaskedArray[jointIndex] = masked; - } - - setMaskedRecursive(jointIndex, masked = true) { - if (jointIndex < 0 || jointIndex >= this._skeleton._nodes.length) { - return; - } - - this._isMaskedArray[jointIndex] = masked; - _walk(this._skeleton._nodes[0], joint => { - let idx = this._skeleton._nodes.indexOf(joint); - if (idx >= 0) { - this._isMaskedArray[idx] = masked; - } - }); - } - - isMasked(jointIndex) { - return this._isMaskedArray[jointIndex]; - } - - complement() { - let ret = new SkeletonMask(this._skeleton); - for (let i = 0; i < this._isMaskedArray.length; ++i) { - ret._isMaskedArray[i] = !this._isMaskedArray[i]; - } - return ret; - } -} \ No newline at end of file diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/3d/framework/skinning-model-component.ts index 1f80f29aeb..ee0737bb9c 100644 --- a/cocos/3d/framework/skinning-model-component.ts +++ b/cocos/3d/framework/skinning-model-component.ts @@ -24,37 +24,18 @@ ****************************************************************************/ // @ts-check -import { Texture2D } from '../../assets/texture-2d'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; import { mat4 } from '../../core/vmath'; import { GFXDevice, GFXFeature } from '../../gfx/device'; import { SkinningModel } from '../../renderer/models/skinning-model'; import { Node } from '../../scene-graph/node'; +import { Material } from '../assets/material'; import Skeleton from '../assets/skeleton'; -import * as utils from '../misc/utils'; import { ModelComponent } from './model-component'; const _m4_tmp = mat4.create(); -interface IJointTextureStorage { - nativeData: Float32Array; - texture: Texture2D; -} - -interface IJointUniformsStorage { - nativeData: Float32Array; -} - -type JointStorage = IJointTextureStorage | IJointUniformsStorage; - -interface ISkinningState { - skinningTarget: Map; - storage: JointStorage; -} - -function isTextureStorage (storage: JointStorage): storage is IJointTextureStorage { - return (storage as any).texture !== undefined; -} +type SkinningTarget = Map; /** * !#en The Skinning Model Component @@ -65,17 +46,6 @@ function isTextureStorage (storage: JointStorage): storage is IJointTextureStora @executeInEditMode @menu('Components/SkinningModelComponent') export default class SkinningModelComponent extends ModelComponent { - @property(Skeleton) - private _skeleton: Skeleton | null = null; - - @property(Node) - private _skinningRoot: Node | null = null; - - private _skinningState: ISkinningState | null = null; - - constructor () { - super(); - } /** * !#en The bone nodes @@ -89,7 +59,8 @@ export default class SkinningModelComponent extends ModelComponent { set skeleton (val) { this._skeleton = val; - this._resetSkinningState(); + this._resetSkinningTarget(); + this._bindSkeleton(); } @property({type: Node}) @@ -99,11 +70,23 @@ export default class SkinningModelComponent extends ModelComponent { set skinningRoot (value) { this._skinningRoot = value; - this._resetSkinningState(); + this._resetSkinningTarget(); + } + @property(Skeleton) + private _skeleton: Skeleton | null = null; + + @property(Node) + private _skinningRoot: Node | null = null; + + private _skinningTarget: SkinningTarget | null = null; + + constructor () { + super(); } public onLoad () { - this._resetSkinningState(); + super.onLoad(); + this._resetSkinningTarget(); } public update (dt) { @@ -114,19 +97,19 @@ export default class SkinningModelComponent extends ModelComponent { } public _tryUpdateMatrices () { - if (!this._skeleton || !this._skinningState) { + if (!this._skeleton || !this._skinningTarget || !this._model) { return; } - const skinningState = this._skinningState!; - const skeleton = this._skeleton!; + const skinningModel = this._model as SkinningModel; + const skeleton = this._skeleton; + const skinningTarget = this._skinningTarget; const cancelThisNodeTransform = this.node.getWorldMatrix(); mat4.invert(cancelThisNodeTransform, cancelThisNodeTransform); - this._skeleton.joints.forEach((joint, index) => { // If target joint doesn't exists in scene graph, skip it. - const targetNode = skinningState.skinningTarget.get(joint); + const targetNode = skinningTarget.get(joint); if (!targetNode) { return; } @@ -137,13 +120,10 @@ export default class SkinningModelComponent extends ModelComponent { const jointMatrix = _m4_tmp; mat4.multiply(jointMatrix, cancelThisNodeTransform, targetNode.getWorldMatrix()); mat4.multiply(jointMatrix, jointMatrix, bindpose); - _setJointMatrix(skinningState.storage.nativeData, index, jointMatrix); + skinningModel.updateJointMatrix(index, jointMatrix); }); - const storage = skinningState.storage; - if (isTextureStorage(storage)) { - storage.texture.directUpdate(storage.nativeData.buffer); - } + skinningModel.commitJointMatrices(); } public _createModel () { @@ -152,53 +132,33 @@ export default class SkinningModelComponent extends ModelComponent { public _updateModelParams () { super._updateModelParams(); - // Upload joint matrices. - if (this._skinningState !== null) { - const skinningState = this._skinningState; - const skinningModel = this._model as SkinningModel; - if (isTextureStorage(skinningState.storage)) { - const texture = skinningState.storage.texture; - skinningModel.setJointTexture(texture); - } else { - skinningModel.setJointMatrices(skinningState.storage.nativeData); - } + this._bindSkeleton(); + } + + protected _onMaterialModified (index: number, material: Material) { + super._onMaterialModified(index, material); + + const device = _getGlobalDevice(); + const useJointTexture = device !== null && device.hasFeature(GFXFeature.TEXTURE_FLOAT) && false; + this.getMaterial(0, CC_EDITOR)!.setDefines({ + CC_USE_SKINNING: true, + CC_USE_JOINTS_TEXTURE: useJointTexture, + }); + } + + private _bindSkeleton () { + if (this._model && this._skeleton) { + (this._model as SkinningModel).bindSkeleton(this._skeleton); } } - private _resetSkinningState () { - if (this._skinningState) { - if (isTextureStorage(this._skinningState.storage)) { - this._skinningState.storage.texture.destroy(); - } - this._skinningState = null; - } - + private _resetSkinningTarget () { if (!this._skeleton || !this._skinningRoot) { return; } - let storage: JointStorage; - - // Allocate joint matrices storage. - const device = _getGlobalDevice(); - if (device && device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { - const jointsTexture = utils.createJointsTexture(this._skeleton); - storage = { - texture: jointsTexture, - nativeData: new Float32Array(jointsTexture.width * jointsTexture.height * 4), - } as IJointTextureStorage; - } else { - storage = { - nativeData: new Float32Array(this._skeleton.joints.length * 16), - } as IJointUniformsStorage; - } - - const skinningState: ISkinningState = { - skinningTarget: new Map(), - storage, - }; - // Collect target to skin. + this._skinningTarget = new Map(); const rootNode = this._skinningRoot; this._skeleton.joints.forEach((joint) => { const targetNode = rootNode.getChildByPath(joint); @@ -206,10 +166,8 @@ export default class SkinningModelComponent extends ModelComponent { console.warn(`Skinning target ${joint} not found in scene graph.`); return; } - skinningState.skinningTarget.set(joint, targetNode); + this._skinningTarget!.set(joint, targetNode); }); - - this._skinningState = skinningState; } } @@ -217,22 +175,3 @@ function _getGlobalDevice (): GFXDevice | null { // @ts-ignore return cc.director.root.device; } - -function _setJointMatrix (out: Float32Array, iMatrix: number, matrix: mat4) { - out[16 * iMatrix + 0] = matrix.m00; - out[16 * iMatrix + 1] = matrix.m01; - out[16 * iMatrix + 2] = matrix.m02; - out[16 * iMatrix + 3] = matrix.m03; - out[16 * iMatrix + 4] = matrix.m04; - out[16 * iMatrix + 5] = matrix.m05; - out[16 * iMatrix + 6] = matrix.m06; - out[16 * iMatrix + 7] = matrix.m07; - out[16 * iMatrix + 8] = matrix.m08; - out[16 * iMatrix + 9] = matrix.m09; - out[16 * iMatrix + 10] = matrix.m10; - out[16 * iMatrix + 11] = matrix.m11; - out[16 * iMatrix + 12] = matrix.m12; - out[16 * iMatrix + 13] = matrix.m13; - out[16 * iMatrix + 14] = matrix.m14; - out[16 * iMatrix + 15] = matrix.m15; -} diff --git a/cocos/3d/framework/skinning-model-system.js b/cocos/3d/framework/skinning-model-system.js deleted file mode 100644 index 25d4542bf1..0000000000 --- a/cocos/3d/framework/skinning-model-system.js +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import { System } from '../ecs'; -import { FixedArray } from '../memop'; -import { _decorator } from '../../core/data/index'; -const { ccclass, property } = _decorator; - -/** - * !#en Skinning Model Component Management System - * - * !#ch 皮肤模型管理系统 - * @class SkinningModelSystem - * @extends System - */ -@ccclass('cc.SkinningModelSystem') -export default class SkinningModelSystem extends System { - constructor() { - super(); - - this._comps = new FixedArray(200); - } - - /** - * !# Add skinning model component - * - * !#ch 添加需要统一管理的皮肤模型 - * @param {SkinningModelComponent} comp - */ - add(comp) { - this._comps.push(comp); - } - - /** - * !# Add skinning model component - * - * !#ch 添加需要统一管理的皮肤模型 - * @param {SkinningModelComponent} comp - */ - remove(comp) { - this._comps.fastRemove(this._comps.indexOf(comp)); - } - -// update() { -// for (let i = 0; i < this._comps.length; ++i) { -// let comp = this._comps.data[i]; -// if (comp.enabled === false) { -// continue; -// } - -// comp._updateMatrices(); -// } -// } -} diff --git a/cocos/core/director.js b/cocos/core/director.js index eb6e6e56d1..d701c45a1c 100644 --- a/cocos/core/director.js +++ b/cocos/core/director.js @@ -33,7 +33,6 @@ import Scheduler from './scheduler'; import { autoRelease } from '../load-pipeline/auto-release-utils'; import ComponentScheduler from '../scene-graph/component-scheduler'; import NodeActivator from '../scene-graph/node-activator'; -// import AnimationSystem from '../3d/framework/animation-system'; // import SkinningModelSystem from '../3d/framework/skinning-model-system'; import { PhysicsSystem } from '../3d/framework/physics/physics-system'; import { getClassByName } from './utils/js'; diff --git a/cocos/core/game.js b/cocos/core/game.js index b1cb8a09e1..df7594afa4 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -771,6 +771,7 @@ var game = { this._gfxDevice = new cc.WebGLGFXDevice; this._gfxDevice.initialize({ canvasElm : localCanvas, + debug: true, }); //let device = this._renderContext = new gfx.Device(localCanvas, {}); diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index e9d17c6ba7..b4d36fc1c3 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -25,6 +25,7 @@ export interface IGFXDeviceInfo { canvasElm: HTMLElement; isAntialias?: boolean; isPremultipliedAlpha?: boolean; + debug?: boolean; } // tslint:disable: max-line-length diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 07d0e3df5b..ae5a1230c4 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,3 +1,4 @@ +import * as WebGLDeveloperTools from 'webgl-debug'; import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXBuffer, GFXBufferSource, IGFXBufferInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; @@ -253,6 +254,9 @@ export class WebGLGFXDevice extends GFXDevice { }; this._webGLRC = this._canvas.getContext('webgl', webGLCtxAttribs); + if (this._webGLRC && info.debug) { + this._webGLRC = WebGLDeveloperTools.makeDebugContext(this._webGLRC, this._onWebGLError.bind(this)); + } } catch (err) { console.error(err); return false; @@ -1076,4 +1080,8 @@ export class WebGLGFXDevice extends GFXDevice { gl.colorMask(true, true, true, true); gl.blendColor(0.0, 0.0, 0.0, 0.0); } + + private _onWebGLError (error: GLenum, functionName: string, ...args: any[]) { + throw new Error(`${WebGLDeveloperTools.glEnumToString(error)} was caused by call to ${functionName}`); + } } diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/renderer/models/skinning-model.ts index 95a7a179d2..e734f8f7d6 100644 --- a/cocos/renderer/models/skinning-model.ts +++ b/cocos/renderer/models/skinning-model.ts @@ -1,8 +1,12 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +import Skeleton from '../../3d/assets/skeleton'; +import { createJointsTexture } from '../../3d/misc/utils'; import { Texture2D } from '../../assets/texture-2d'; +import { mat4 } from '../../core/vmath'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXFeature } from '../../gfx/device'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { Node } from '../../scene-graph/node'; import { Model } from '../scene/model'; @@ -11,9 +15,28 @@ import { SkinningUBO } from './model-uniforms'; const textureSizeBuffer = new Float32Array(4); +interface IJointTextureStorage { + nativeData: Float32Array; + texture: Texture2D; +} + +interface IJointUniformsStorage { + nativeData: Float32Array; +} + +type JointStorage = IJointTextureStorage | IJointUniformsStorage; + +function isTextureStorage (storage: JointStorage): storage is IJointTextureStorage { + return 'texture' in storage; +} + +function isUniformStorage (storage: JointStorage): storage is IJointUniformsStorage { + return !('texture' in storage); +} + export class SkinningModel extends Model { + private _jointStorage: JointStorage | null = null; private _skinningUBO: GFXBuffer; - private _jointTexture: Texture2D | null = null; constructor (scene: RenderScene, node: Node) { super(scene, node); @@ -26,27 +49,83 @@ export class SkinningModel extends Model { }); } - public setJointTexture (texture: Texture2D) { - this._jointTexture = texture; - textureSizeBuffer[0] = texture.width; - this._skinningUBO.update( + public bindSkeleton (skeleton: Skeleton) { + this._destroyJointStorage(); + + if (this._device.hasFeature(GFXFeature.TEXTURE_FLOAT) && false) { + const jointsTexture = createJointsTexture(skeleton); + textureSizeBuffer[0] = jointsTexture.width; + this._skinningUBO.update( textureSizeBuffer, SkinningUBO.JOINTS_TEXTURE_SIZE_OFFSET, textureSizeBuffer.byteLength); + this._jointStorage = { + texture: jointsTexture, + nativeData: new Float32Array(jointsTexture.width * jointsTexture.height * 4), + } as IJointTextureStorage; + } else { + this._jointStorage = { + nativeData: new Float32Array(skeleton.joints.length * 16), + } as IJointUniformsStorage; + } } - public setJointMatrices (data: Float32Array) { - this._skinningUBO.update(data, SkinningUBO.MAT_JOINT_OFFSET); + public updateJointMatrix (iMatrix: number, matrix: mat4) { + if (!this._jointStorage) { + return; + } + _setJointMatrix(this._jointStorage.nativeData, iMatrix, matrix); + } + + public commitJointMatrices () { + if (!this._jointStorage) { + return; + } + if (isUniformStorage(this._jointStorage)) { + this._skinningUBO.update(this._jointStorage.nativeData, SkinningUBO.MAT_JOINT_OFFSET); + } else if (isTextureStorage(this._jointStorage)) { + this._jointStorage.texture.directUpdate(this._jointStorage.nativeData.buffer); + } } protected _onCreatePSO (pso: GFXPipelineState) { super._onCreatePSO(pso); pso.pipelineLayout.layouts[0].bindBuffer(SkinningUBO.BLOCK.binding, this._skinningUBO); - if (this._jointTexture) { - const view = this._jointTexture.getGFXTextureView(); - const sampler = this._jointTexture.getGFXSampler(); + if (this._jointStorage && isTextureStorage(this._jointStorage)) { + const jointTexture = this._jointStorage.texture; + const view = jointTexture.getGFXTextureView(); + const sampler = jointTexture.getGFXSampler(); if (view && sampler) { pso.pipelineLayout.layouts[0].bindTextureView(SkinningUBO.JOINT_TEXTURE.binding, view); pso.pipelineLayout.layouts[0].bindSampler(SkinningUBO.JOINT_TEXTURE.binding, sampler); } } } + + private _destroyJointStorage () { + if (!this._jointStorage) { + return; + } + if (isTextureStorage(this._jointStorage)) { + this._jointStorage.texture.destroy(); + } + this._jointStorage = null; + } +} + +function _setJointMatrix (out: Float32Array, iMatrix: number, matrix: mat4) { + out[16 * iMatrix + 0] = matrix.m00; + out[16 * iMatrix + 1] = matrix.m01; + out[16 * iMatrix + 2] = matrix.m02; + out[16 * iMatrix + 3] = matrix.m03; + out[16 * iMatrix + 4] = matrix.m04; + out[16 * iMatrix + 5] = matrix.m05; + out[16 * iMatrix + 6] = matrix.m06; + out[16 * iMatrix + 7] = matrix.m07; + out[16 * iMatrix + 8] = matrix.m08; + out[16 * iMatrix + 9] = matrix.m09; + out[16 * iMatrix + 10] = matrix.m10; + out[16 * iMatrix + 11] = matrix.m11; + out[16 * iMatrix + 12] = matrix.m12; + out[16 * iMatrix + 13] = matrix.m13; + out[16 * iMatrix + 14] = matrix.m14; + out[16 * iMatrix + 15] = matrix.m15; } diff --git a/globals.d.ts b/globals.d.ts index 163998848c..8c476a4668 100644 --- a/globals.d.ts +++ b/globals.d.ts @@ -45,4 +45,13 @@ type RecursivePartial = { [P in keyof T]?: T[P] extends Array ? Array> : T[P] extends ReadonlyArray ? ReadonlyArray> : RecursivePartial; -}; \ No newline at end of file +}; + +declare module "webgl-debug" { + export function makeDebugContext( + webGLRenderingContext: WebGLRenderingContext, + throwOnGLError: (err: GLenum, funcName: string, ...args: any[]) => void + ): WebGLRenderingContext; + + export function glEnumToString(glEnum: GLenum): string; +} \ No newline at end of file diff --git a/package.json b/package.json index a4635ad24b..665a556c2d 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,7 @@ "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", "watchify": "^3.7.0", + "webgl-debug": "^2.0.1", "yargs": "^12.0.5" } }