handle different skinning roots (#4525)

* better opt

* handle different skinning roots
This commit is contained in:
Yun Hsiao Wu
2019-05-30 17:36:13 +08:00
committed by Weiliang Wang
parent d5ed76c475
commit 7103999d68
10 changed files with 196 additions and 163 deletions
+2 -1
View File
@@ -110,7 +110,7 @@ export class Material extends Asset {
}
public destroy () {
if (!this._effectAsset) { return; }
if (!this._effectAsset) { return false; }
if (this._passes) {
for (const pass of this._passes) {
pass.destroy();
@@ -118,6 +118,7 @@ export class Material extends Asset {
this._passes.length = 0;
}
this._effectAsset = null;
return true;
}
/**
+82 -71
View File
@@ -26,13 +26,15 @@ import { Texture2D } from '../../assets';
import { Filter, PixelFormat } from '../../assets/asset-enum';
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator';
import { Vec2 } from '../../core/value-types';
import { GFXAttributeName, GFXBufferTextureCopy, GFXFormatInfos } from '../../gfx/define';
import { vec2 } from '../../core/vmath';
import { GFXFormat } from '../../gfx/define';
import { GFXAttributeName, GFXBufferTextureCopy, GFXFormatInfos } from '../../gfx/define';
import { GFXDevice } from '../../gfx/device';
import { Node } from '../../scene-graph';
import { Mesh } from '../assets';
import { Skeleton } from '../assets/skeleton';
import { mapBuffer } from '../misc/utils';
import { SkinningModelComponent } from './skinning-model-component';
import { LCA, SkinningModelComponent } from './skinning-model-component';
const _vec2 = new Vec2();
@@ -41,61 +43,42 @@ const repeat = (n: number) => n - Math.floor(n);
@ccclass('cc.AvatarUnit')
export class AvatarUnit {
@property({ type: Mesh })
get mesh (): Mesh | null {
return this._mesh;
}
@property(Mesh)
public mesh: Mesh | null = null;
@property(Skeleton)
public skeleton: Skeleton | null = null;
@property(Node)
public skinningRoot: Node | null = null;
@property
private _offset: Vec2 = new Vec2(0, 0);
@property
private _atlasSize: Vec2 = new Vec2(256, 256);
@property(Texture2D)
private _albedoMap: Texture2D | null = null;
set mesh (mesh: Mesh | null) {
if (this._mesh !== mesh) {
this._mesh = mesh;
}
@property
set atlasSize (atlasSize) {
vec2.copy(this._atlasSize, atlasSize);
}
@property({ type: Skeleton })
get skeleton () {
return this._skeleton;
}
set skeleton (skeleton: Skeleton | null) {
if (this._skeleton !== skeleton) {
this._skeleton = skeleton;
}
}
@property({ type: cc.Vec2 })
get atlasSize (): Vec2 {
get atlasSize () {
return this._atlasSize;
}
set atlasSize (atlasSize: Vec2) {
if (this._atlasSize.x !== atlasSize.x ||
this._atlasSize.y !== atlasSize.y) {
this._atlasSize = atlasSize;
}
@property
set offset (offset) {
vec2.copy(this._offset, offset);
}
@property({ type: cc.Vec2 })
get offset (): Vec2 {
get offset () {
return this._offset;
}
set offset (offset: Vec2) {
if (this._offset.x !== offset.x ||
this._offset.y !== offset.y) {
this._offset = offset;
}
}
@property({ type: Texture2D })
get albedoMap (): Texture2D | null {
get albedoMap () {
return this._albedoMap;
}
set albedoMap (albedoMap: Texture2D | null) {
set albedoMap (albedoMap) {
if (this._albedoMap !== albedoMap) {
this._albedoMap = albedoMap;
if (this._albedoMap) {
_vec2.x = this._albedoMap.width;
_vec2.y = this._albedoMap.height;
@@ -104,22 +87,29 @@ export class AvatarUnit {
}
}
@property
private _mesh: Mesh | null = null;
@property
private _skeleton: Skeleton | null = null;
@property
private _offset: Vec2 = new Vec2(0, 0);
@property
private _atlasSize: Vec2 = new Vec2(256, 256);
@property
private _albedoMap: Texture2D | null = null;
@property({ type: SkinningModelComponent })
set source (comp: SkinningModelComponent | null) {
if (!comp) { return; }
this.mesh = comp.mesh;
this.skeleton = comp.skeleton;
this.skinningRoot = comp.skinningRoot;
}
get source () {
return null;
}
}
const getPrefix = (lca: Node, target: Node) => {
let prefix = '';
let cur: Node | null = target;
while (cur && cur !== lca) {
prefix = `${cur.name}/` + prefix;
cur = cur.parent;
}
return prefix;
};
const concatPath = (prefix: string, path: string) => path ? prefix + path : prefix.slice(0, -1);
/**
* !#en The Avatar Model Component
* !#ch 换装模型组件
@@ -150,6 +140,11 @@ export class AvatarModelComponent extends SkinningModelComponent {
return this._skeleton;
}
@property({ override: true, visible: false })
get skinningRoot () {
return this._skinningRoot;
}
@property({ type: Number })
get combinedTexSize (): number {
return this._combinedTexSize;
@@ -189,10 +184,6 @@ export class AvatarModelComponent extends SkinningModelComponent {
this.combine();
}
public update (dt) {
super.update(dt);
}
public onDestroy () {
if (this._combinedTex) {
this._combinedTex.destroy();
@@ -225,11 +216,6 @@ export class AvatarModelComponent extends SkinningModelComponent {
}
public combine () {
// batched skinning model shouldn't have local transform
this.node.setPosition(0, 0, 0);
this.node.setRotation(0, 0, 0, 1);
this.node.setScale(1, 1, 1);
this.combineTextures();
this.combineSkeletons();
this.combineMeshes();
@@ -302,18 +288,39 @@ export class AvatarModelComponent extends SkinningModelComponent {
}
public combineSkeletons () {
// find lowest common ancestor as the new skinning root
let lca: Node | null = null;
for (const unit of this._avatarUnits) {
if (!unit || !unit.skinningRoot) { continue; }
const cur = unit.skinningRoot;
if (!lca) { lca = cur; continue; }
lca = LCA(lca, cur);
}
this._skinningRoot = lca;
if (!lca) { console.warn('illegal skinning roots'); return; }
// merge joints accordingly
const skeleton = new Skeleton();
for (const unit of this._avatarUnits) {
if (!unit || !unit.skeleton) { continue; }
if (!unit || !unit.skeleton || !unit.skinningRoot) { continue; }
const partial = unit.skeleton;
const prefix = getPrefix(lca, unit.skinningRoot);
for (let i = 0; i < partial.joints.length; i++) {
const path = partial.joints[i];
const path = concatPath(prefix, partial.joints[i]);
const idx = skeleton.joints.findIndex((p) => p === path);
if (idx >= 0) { continue; }
skeleton.joints.push(path);
skeleton.bindposes.push(partial.bindposes[i]);
}
}
// sort the array to be more cache-friendly
const idxMap = [...Array(skeleton.joints.length).keys()].sort((a, b) => {
if (skeleton.joints[a] > skeleton.joints[b]) { return 1; }
if (skeleton.joints[a] < skeleton.joints[b]) { return -1; }
return 0;
});
skeleton.joints = skeleton.joints.map((_, idx, arr) => arr[idxMap[idx]]);
skeleton.bindposes = skeleton.bindposes.map((_, idx, arr) => arr[idxMap[idx]]);
// apply
super.skeleton = skeleton;
}
@@ -332,7 +339,7 @@ export class AvatarModelComponent extends SkinningModelComponent {
this._mesh = new Mesh();
}
if (!isValid) {
if (!isValid || !this._skinningRoot) {
return;
}
@@ -347,8 +354,12 @@ export class AvatarModelComponent extends SkinningModelComponent {
const avatarLen = this._avatarUnits.length;
for (let i = 0; i < avatarLen; i++) {
const unit = this._avatarUnits[i];
if (!unit || !unit.skeleton) { continue; }
jointIndexMap[i] = unit.skeleton.joints.map((j) => this._skeleton!.joints.findIndex((ref) => j === ref));
if (!unit || !unit.skeleton || !unit.skinningRoot) { continue; }
const prefix = getPrefix(this._skinningRoot, unit.skinningRoot);
jointIndexMap[i] = unit.skeleton.joints.map((j) => {
const path = concatPath(prefix, j);
return this._skeleton!.joints.findIndex((ref) => path === ref);
});
}
for (let i = 0; i < avatarLen; i++) {
+4 -1
View File
@@ -25,7 +25,7 @@
****************************************************************************/
import { AudioSourceComponent } from './audio-source-component';
import { AvatarModelComponent } from './avatar-model-component';
import { AvatarModelComponent, AvatarUnit } from './avatar-model-component';
import { CameraComponent } from './camera-component';
import { DirectionalLightComponent } from './directional-light-component';
import { EditorCameraComponent } from './editor-camera-component';
@@ -49,6 +49,8 @@ export {
LightComponent,
ModelComponent,
SkinningModelComponent,
AvatarModelComponent,
AvatarUnit,
BoxColliderComponent,
ParticleSystemComponent,
@@ -68,6 +70,7 @@ cc.RenderableComponent = RenderableComponent;
cc.ModelComponent = ModelComponent;
cc.SkinningModelComponent = SkinningModelComponent;
cc.AvatarModelComponent = AvatarModelComponent;
cc.AvatarUnit = AvatarUnit;
cc.LightComponent = LightComponent;
cc.DirectionalLightComponent = DirectionalLightComponent;
+35 -28
View File
@@ -40,7 +40,6 @@ import { ModelComponent } from './model-component';
const v3_1 = new Vec3();
const qt_1 = new Quat();
const v3_2 = new Vec3();
const v3_3 = new Vec3();
const m4_1 = new Mat4();
const ab_1 = new aabb();
@@ -49,35 +48,53 @@ class Joint {
public position: Vec3 = new Vec3();
public rotation: Quat = new Quat();
public scale: Vec3 = new Vec3(1, 1, 1);
public parent: Joint | null = null;
protected _lastUpdate = -1;
constructor (node: Node) { this.node = node; }
public update (parent: Joint) {
public update () {
// if (!this.node.hasChanged) { return; }
const totalFrames = cc.director.totalFrames;
if (this._lastUpdate >= totalFrames) { return; }
this._lastUpdate = totalFrames;
const parent = this.parent;
if (parent) {
parent.update();
vec3.multiply(this.position, this.node.localPosition, parent.scale);
vec3.transformQuat(this.position, this.position, parent.rotation);
vec3.add(this.position, this.position, parent.position);
quat.multiply(this.rotation, parent.rotation, this.node.localRotation);
vec3.multiply(this.scale, parent.scale, this.node.localScale);
} else {
vec3.copy(this.position, this.node.localPosition);
quat.copy(this.rotation, this.node.localRotation);
vec3.copy(this.scale, this.node.localScale);
}
}
}
class JointManager {
public static get (node: Node) {
public static get (node: Node, root: Node) {
let joint = JointManager._joints.get(node);
if (!joint) { joint = new Joint(node); JointManager._joints.set(node, joint); }
if (joint) { return joint; }
joint = new Joint(node);
if (node !== root && node.parent) { joint.parent = JointManager.get(node.parent, root); }
JointManager._joints.set(node, joint);
return joint;
}
protected static _joints: Map<Node, Joint> = new Map();
}
const _path: Node[] = [];
export const LCA = (a: Node, b: Node) => {
if (a === b) { return a; }
let cur: Node | null = b;
_path.length = 0;
while (cur) { _path.push(cur); cur = cur.parent; }
cur = a;
while (cur) {
if (_path.find((n) => n === cur)) { return cur; }
cur = cur.parent;
}
return null;
};
/**
* @en The Skinning Model Component
* @zh 蒙皮模型组件
@@ -125,7 +142,6 @@ export class SkinningModelComponent extends ModelComponent {
protected _skinningRoot: Node | null = null;
protected _joints: Joint[] = [];
protected _jointParentIndices: number[] = [];
protected _boneSpaceBounds: null | Array<aabb | null> = null;
protected _jointCount = JointUniformCapacity;
@@ -135,13 +151,13 @@ export class SkinningModelComponent extends ModelComponent {
if (CC_EDITOR && this.mesh && this._skeleton) {
this._boneSpaceBounds = boneSpaceBoundsManager.use(this.mesh, this._skeleton);
}
// skinning model shouldn't have local transform
this.node.setPosition(0, 0, 0);
this.node.setRotation(0, 0, 0, 1);
this.node.setScale(1, 1, 1);
}
public update (dt) {
this._tryUpdateMatrices();
}
public _tryUpdateMatrices () {
public update () {
if (!this._skeleton || !this._model) {
return;
}
@@ -152,7 +168,7 @@ export class SkinningModelComponent extends ModelComponent {
for (let i = 0; i < len; ++i) {
const cur = this._joints[i];
cur.update(this._joints[this._jointParentIndices[i]]);
cur.update();
const bindpose = skeleton.bindposes[i];
vec3.multiply(v3_1, bindpose.localPosition, cur.scale);
@@ -161,12 +177,6 @@ export class SkinningModelComponent extends ModelComponent {
quat.multiply(qt_1, cur.rotation, bindpose.localRotation);
vec3.multiply(v3_2, cur.scale, bindpose.localScale);
vec3.multiply(v3_3, this.node._lpos, v3_2);
vec3.transformQuat(v3_3, v3_3, qt_1);
vec3.add(v3_1, v3_3, v3_1);
quat.multiply(qt_1, qt_1, this.node._lrot);
vec3.multiply(v3_2, v3_2, this.node._lscale);
skinningModel.updateJointData(i, v3_1, qt_1, v3_2);
}
@@ -245,9 +255,9 @@ export class SkinningModelComponent extends ModelComponent {
}
private _resetSkinningTarget () {
if (!this._skeleton || !this._skinningRoot) {
return;
}
if (!this._skeleton || !this._skinningRoot) { return; }
const root = LCA(this.node, this._skinningRoot);
if (!root) { return; }
this._joints.length = 0;
const rootNode = this._skinningRoot;
@@ -257,10 +267,7 @@ export class SkinningModelComponent extends ModelComponent {
console.warn(`Skinning target ${path} not found in scene graph.`);
return;
}
// guaranteed to exist except the root
const parentIdx = this._joints.findIndex((j) => j.node === targetNode.parent);
this._joints.push(JointManager.get(targetNode));
this._jointParentIndices.push(parentIdx);
this._joints.push(JointManager.get(targetNode, root));
});
}
}
-4
View File
@@ -114,10 +114,6 @@ export class Texture2D extends TextureBase {
}
}
public directUpdate (source: HTMLImageElement | HTMLCanvasElement | ArrayBuffer, level: number = 0) {
this._uploadData(source, level);
}
/**
* !#en
* HTMLElement Object getter, available only on web.
+41 -49
View File
@@ -40,6 +40,28 @@ const CHAR_CODE_1 = 49; // '1'
const idGenerator = new IDGenerator('Tex');
const _regions: GFXBufferTextureCopy[] = [{
buffOffset: 0,
buffStride: 0,
buffTexHeight: 0,
texOffset: {
x: 0,
y: 0,
z: 0,
},
texExtent: {
width: 1,
height: 1,
depth: 1,
},
texSubres: {
baseMipLevel: 1,
levelCount: 1,
baseArrayLayer: 0,
layerCount: 1,
},
}];
@ccclass('cc.TextureBase')
export class TextureBase extends Asset {
@@ -335,14 +357,28 @@ export class TextureBase extends Asset {
}
protected _getGlobalDevice (): GFXDevice | null {
if (cc.director && cc.director.root) {
return cc.director.root.device;
public uploadData (source: HTMLCanvasElement | HTMLImageElement | ArrayBuffer, level: number = 0, arrayIndex: number = 0) {
if (!this._texture || this._texture.mipLevel <= level) { return; }
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) { return; }
const region = _regions[0];
region.texExtent.width = this._texture.width >> level;
region.texExtent.height = this._texture.height >> level;
region.texSubres.baseMipLevel = level;
region.texSubres.baseArrayLayer = arrayIndex;
if (source instanceof ArrayBuffer) {
gfxDevice.copyBuffersToTexture([source], this._texture, _regions);
} else {
return null;
gfxDevice.copyTexImagesToTexture([source], this._texture, _regions);
}
}
protected _getGlobalDevice (): GFXDevice | null {
return cc.director.root && cc.director.root.device;
}
protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) {
const upload = () => {
const data = image.data;
@@ -355,7 +391,7 @@ export class TextureBase extends Asset {
} else {
source = data;
}
this._uploadData(source, level, arrayIndex);
this.uploadData(source, level, arrayIndex);
};
if (image.loaded) {
upload();
@@ -371,50 +407,6 @@ export class TextureBase extends Asset {
}
}
protected _uploadData (
source: HTMLCanvasElement | HTMLImageElement | ArrayBuffer, level: number, arrayIndex?: number) {
if (!this._texture) {
return;
}
if (level >= this._texture.mipLevel) {
return;
}
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) {
return;
}
const region: GFXBufferTextureCopy = {
buffOffset: 0,
buffStride: 0,
buffTexHeight: 0,
texOffset: {
x: 0,
y: 0,
z: 0,
},
texExtent: {
width: this._texture.width >> level,
height: this._texture.height >> level,
depth: 1,
},
texSubres: {
baseMipLevel: level,
levelCount: 1,
baseArrayLayer: arrayIndex || 0,
layerCount: 1,
},
};
if (source instanceof ArrayBuffer) {
gfxDevice.copyBuffersToTexture([source], this._texture, [region]);
} else {
gfxDevice.copyTexImagesToTexture([source], this._texture, [region]);
}
}
protected _getTextureCreateInfo (): IGFXTextureInfo {
return {
type: GFXTextureType.TEX2D,
+5 -1
View File
@@ -1030,7 +1030,7 @@ class mat4 {
/**
* Decompose an affine matrix to a quaternion rotation, a translation offset and a scale vector.
* Assumes the transformation is combined in the order of Scale -> Rotate -> Translate.
* Not applicable when containing negative scaling.
* Shearing and projective transformations will surely be lost.
* @param m - Matrix to decompose.
* @param q - Resulting rotation quaternion.
* @param v - Resulting translation offset.
@@ -1049,6 +1049,10 @@ class mat4 {
m3_1.m06 = m.m08 / s.z;
m3_1.m07 = m.m09 / s.z;
m3_1.m08 = m.m10 / s.z;
const det = mat3.determinant(m3_1);
if (det < 0) {
s.x *= -1; m3_1.m00 *= -1; m3_1.m01 *= -1; m3_1.m02 *= -1;
}
quat.fromMat3(q, m3_1); // already normalized
vec3.set(v, m.m12, m.m13, m.m14);
}
+22 -5
View File
@@ -3,8 +3,8 @@
import { Skeleton } from '../../3d/assets/skeleton';
import { Filter, PixelFormat, WrapMode } from '../../assets/asset-enum';
import { Texture2D } from '../../assets/texture-2d';
import { Quat, Vec3 } from '../../core/value-types';
import { quat, vec4 } from '../../core/vmath';
import { Mat4, Quat, Vec3 } from '../../core/value-types';
import { mat4, quat, vec4 } from '../../core/vmath';
import { GFXBuffer } from '../../gfx/buffer';
import { GFXBufferUsageBit, GFXFormatInfos, GFXMemoryUsageBit } from '../../gfx/define';
import { GFXDevice, GFXFeature } from '../../gfx/device';
@@ -46,6 +46,7 @@ const _jointsFormat = {
[JointsMediumType.RGBA32F]: PixelFormat.RGBA32F,
};
const m4_1 = new Mat4();
const qt_0 = new Quat();
const qt_1 = new Quat();
const f4_1 = new Float32Array(4);
@@ -90,6 +91,23 @@ export class SkinningModel extends Model {
public updateJointData (idx: number, pos: Vec3, rot: Quat, scale: Vec3) {
if (!this._jointsMedium) { return; }
const out = this._jointsMedium.nativeData;
const base = 12 * idx;
/* Linear Blending Skinning */
mat4.fromRTS(m4_1, rot, pos, scale);
out[base + 0] = m4_1.m00;
out[base + 1] = m4_1.m01;
out[base + 2] = m4_1.m02;
out[base + 3] = m4_1.m12;
out[base + 4] = m4_1.m04;
out[base + 5] = m4_1.m05;
out[base + 6] = m4_1.m06;
out[base + 7] = m4_1.m13;
out[base + 8] = m4_1.m08;
out[base + 9] = m4_1.m09;
out[base + 10] = m4_1.m10;
out[base + 11] = m4_1.m14;
/* Dual Quaternion Skinning *
// sign consistency
if (idx === 0) { quat.copy(qt_0, rot); }
else if (quat.dot(qt_0, rot) < 0) { quat.scale(rot, rot, -1); }
@@ -97,8 +115,6 @@ export class SkinningModel extends Model {
quat.set(qt_1, pos.x, pos.y, pos.z, 0);
quat.scale(qt_1, quat.multiply(qt_1, qt_1, rot), 0.5);
// upload
const out = this._jointsMedium.nativeData;
const base = 12 * idx;
out[base + 0] = rot.x;
out[base + 1] = rot.y;
out[base + 2] = rot.z;
@@ -110,6 +126,7 @@ export class SkinningModel extends Model {
out[base + 8] = scale.x;
out[base + 9] = scale.y;
out[base + 10] = scale.z;
/* */
}
public commitJointData () {
@@ -118,7 +135,7 @@ export class SkinningModel extends Model {
if (type === JointsMediumType.UNIFORM) {
buffer.update(nativeData, UBOSkinning.MAT_JOINT_OFFSET);
} else {
texture!.directUpdate(nativeData.buffer);
texture!.uploadData(nativeData.buffer);
}
}
+4 -2
View File
@@ -227,6 +227,8 @@ export class Model {
if (!minPos || !maxPos) { return; }
this._modelBounds = aabb.fromPoints(aabb.create(), minPos, maxPos);
this._worldBounds = aabb.clone(this._modelBounds);
this._modelBounds.transform(this._node._mat, this._node._pos,
this._node._rot, this._node._scale, this._worldBounds);
}
public initSubModel (idx: number, subMeshData: IRenderingSubmesh, mat: Material) {
@@ -288,7 +290,7 @@ export class Model {
const ret = new Array<GFXPipelineState>(mat.passes.length);
for (let i = 0; i < ret.length; i++) {
const pass = mat.passes[i];
// for (const cus of pass.customizations) { customizationManager.attach(cus, this); }
for (const cus of pass.customizations) { customizationManager.attach(cus, this); }
ret[i] = this._doCreatePSO(pass);
}
return ret;
@@ -298,7 +300,7 @@ export class Model {
for (let i = 0; i < mat.passes.length; i++) {
const pass = mat.passes[i];
pass.destroyPipelineState(pso[i]);
// for (const cus of pass.customizations) { customizationManager.detach(cus, this); }
for (const cus of pass.customizations) { customizationManager.detach(cus, this); }
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ class Node extends BaseNode {
public static NodeSpace = NodeSpace;
// is node but not scene
public static isNode (obj: object) {
public static isNode (obj: object | null): obj is Node {
return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene));
}