define mesh its own format; improve the robust of gltf-utils; now the standard gltf can be imported (#3435)

* uuid-loader.js

* Make camera-component is available in previewing;
Remove onLoad of mesh asset class, instead do its content in model-component and skinning-model-component's _updateModels method.

* define mesh its own format; improve the robust of gltf-utils; now the standard gltf can be imported

* typo

* bugfix

* material serialization;gltf material import; fix animation component bug

* cinnebt

* remove skeleton root

* small fix

* bug fix

* remove the hack materials

* small fix
This commit is contained in:
Leslie Leigh
2018-11-05 17:48:24 +08:00
committed by pandamicro
parent 12ef67f6b4
commit 3f972a4d3c
10 changed files with 1032 additions and 628 deletions
+61 -42
View File
@@ -31,11 +31,17 @@ import Effect from '../../renderer/core/effect';
@ccclass('cc.Material')
export default class Material extends Asset {
/**
* @type {string}
*/
@property
_effectName = "";
/**
* @type {Object}
*/
@property(Object)
_effectAsset = null;
@property
_defines = {};
/**
* @type {Object}
@@ -44,44 +50,72 @@ export default class Material extends Asset {
_props = {};
/**
* @type {cc.renderer.Effect}
* @type {Effect}
*/
_effect = null;
/**
* @return {Object}
* @return {string}
*/
get effectAsset() {
return this._effectAsset;
get effectName() {
return this._effectName;
}
/**
* @param {Object} val
* @param {string} val
*/
set effectAsset(val) {
if (this._effectAsset !== val) {
this._effectAsset = val;
this._effect = Effect.parseEffect(this._effectAsset);
let propCls = cc.js.getClassByName(Effect.getPropertyClassName(this._effectAsset));
this._props = propCls ? new propCls() : {};
set effectName(val) {
if (this._effectName !== val) {
this._effectName = val;
if (cc.game._builtins) {
const effectAsset = cc.game._builtins[this._effectName];
this._effect = Effect.parseEffect(effectAsset);
let propCls = cc.js.getClassByName(Effect.getPropertyClassName(effectAsset));
this._props = propCls ? new propCls() : {};
}
}
}
/**
* @return {cc.renderer.Effect}
* @return {Effect}
*/
get effect() {
if (this._effect === null) {
this._instantiateEffect();
}
return this._effect;
}
_instantiateEffect() {
if (!cc.game || !cc.game._builtins) {
return;
}
const effectAsset = cc.game._builtins[this._effectName];
if (!effectAsset) {
return;
}
this._effect = Effect.parseEffect(effectAsset);
for (let def in this._defines) {
this.define(def, this._defines[def]);
}
for (let name in this._props) {
this.setProperty(name, this._props[name]);
}
}
/**
*
* @param {Material} mat
*/
copy(mat) {
if (this._effectAsset !== mat._effectAsset) {
this._effectAsset = mat._effectAsset;
this._effect = Effect.parseEffect(this._effectAsset);
this._effectName = mat._effectName;
for (let def in mat._defines) {
this.define(def, mat._defines[def]);
}
for (let name in mat._props) {
@@ -97,10 +131,12 @@ export default class Material extends Asset {
setProperty(name, val) {
this._props[name] = val;
if (val instanceof Texture) {
this._effect.setProperty(name, val._texture);
} else {
this._effect.setProperty(name, val);
if (this._effect) {
if (val instanceof Texture) {
this._effect.setProperty(name, val._texture);
} else {
this._effect.setProperty(name, val);
}
}
}
@@ -110,7 +146,10 @@ export default class Material extends Asset {
* @param {*} val
*/
define(name, val) {
this._effect.define(name, val);
this._defines[name] = val;
if (this._effect) {
this._effect.define(name, val);
}
}
destroy() {
@@ -118,26 +157,6 @@ export default class Material extends Asset {
return super.destroy();
}
_serialize() {
// todo: this may be refactored for it is editor only
return {
effect: (this._effectAsset && this._effectAsset._uuid) || 'unknown',
props: Editor.serialize(this._props),
};
}
_deserialize(data/*, handle*/) {
console.log(`try to deserialize material`);
if (data.effect.indexOf('builtin-effect') !== -1) {
this._effectAsset = cc.game._builtins[data.effect];
this._effect = Effect.parseEffect(this._effectAsset);
this._props = cc.deserialize(data.props);
} else {
// todo: add custom effect
console.error('Cannot support custom effect now');
}
}
static getInstantiatedMaterial(mat, rndCom) {
if (mat._owner === rndCom) {
return mat;
+158 -28
View File
@@ -27,65 +27,166 @@
import { _decorator } from "../../core/data/index";
const { ccclass, property } = _decorator;
import Asset from "../../assets/CCAsset";
import gfx from "../../renderer/gfx";
import { enums as gfxEnums } from "../../renderer/gfx/enums";
import InputAssembler from "../../renderer/core/input-assembler";
import BufferRange from "./utils/buffer-range";
/**
* @interface
* A vertex bundle describes a serials of vertex attributes.
* These vertex attributes occupy a range of the buffer and
* are interleaved, no padding bytes, in the range.
*/
@ccclass('cc.MeshResource')
export class MeshResource {
@ccclass("cc.internal.VertexBundle")
export class VertexBundle {
/**
*
* @param {Mesh} mesh
* The data range of this bundle.
* This range of data is essentially mapped to a GPU vertex buffer.
* @type {BufferRange}
*/
flush(mesh) {
@property(BufferRange)
_data = null;
}
/**
* This bundle's vertices count.
* @type {number}
*/
@property(Number)
_verticesCount = 0;
/**
* The attributes's formats.
* @type {{name: string, type: number, num: number, normalize: boolean}[]}
*/
@property
_formats = [];
}
/**
* A primitive is a geometry constituted with a list of
* same topology primitive graphic(such as points, lines or triangles).
*/
@ccclass("cc.internal.Primitive")
export class Primitive {
/**
* The vertex bundles that this primitive use.
* @type {number[]}
*/
@property([Number])
_vertexBundelIndices = [];
/**
* The indices data range of this primitive.
* @type {BufferRange}
*/
@property(BufferRange)
_indices = null;
/**
* The type of this primitive's indices.
* @type {number}
*/
@property(Number)
_indexUnit = gfxEnums.INDEX_FMT_UINT16;
/**
* This primitive's topology.
* @type {number}
*/
@property(Number)
_topology = gfxEnums.PT_TRIANGLES;
}
cc.MeshResource = MeshResource;
@ccclass('cc.Mesh')
export default class Mesh extends Asset {
/**
* @type {MeshResource}
* The vertex bundles that this mesh owns.
* @type {VertexBundle[]}
*/
@property(MeshResource)
_resource = null;
@property([VertexBundle])
_vertexBundles = [];
get resource() {
return this._resource;
}
/**
* @type {Primitive[]}
*/
@property([Primitive])
_primitives = [];
set resource(value) {
this._resource = value;
this.flush();
}
/**
* The min position of this mesh's vertices.
*/
@property(cc.v3)
_minPosition = null;
/**
* The max position of this mesh's vertices.
*/
@property(cc.v3)
_maxPosition = null;
constructor() {
super();
/**
* @type {cc.renderer.InputAssembler[]}
* @type {InputAssembler[]}
*/
this._subMeshes = null;
/**
* @type {cc.core.math.vec3}
* @type {Uint8Array}
*/
this._minPos = null;
this._data = null;
}
/**
* @type {cc.core.math.vec3}
*/
this._maxPos = null;
get _nativeAsset() {
return this._data;
}
set _nativeAsset(value) {
this._data = value;
}
/**
*
*/
flush() {
if (this._resource) {
this._resource.flush(this);
_lazyInitRenderResources() {
if (this._subMeshes != null) {
return;
}
this._subMeshes = [];
if (this._data === null) {
return;
}
const buffer = this._getBuffer();
const vertexBuffers = this._vertexBundles.map((vertexBundle) => {
return new gfx.VertexBuffer(
cc.game._renderContext,
new gfx.VertexFormat(vertexBundle._formats),
gfx.USAGE_STATIC,
new Uint8Array(buffer, vertexBundle._data._offset, vertexBundle._data._length),
vertexBundle._verticesCount);
});
this._subMeshes = this._primitives.map((primitive) => {
if (primitive._vertexBundelIndices.length === 0) {
return null;
}
// Currently, an IA only has one vertex buffer.
const vertexBuffer = vertexBuffers[primitive._vertexBundelIndices[0]];
const indexBuffer = new gfx.IndexBuffer(
cc.game._renderContext,
primitive._indexUnit,
gfx.USAGE_STATIC,
new DataView(buffer, primitive._indices._offset, primitive._indices._length),
primitive._indices._length / this._getIndexUnitSize(primitive._indexUnit)
);
return new InputAssembler(vertexBuffer, indexBuffer);
});
}
/**
@@ -112,6 +213,7 @@ export default class Mesh extends Asset {
* @property {number}
*/
get subMeshCount() {
this._lazyInitRenderResources();
return this._subMeshes.length;
}
@@ -121,9 +223,18 @@ export default class Mesh extends Asset {
* @param {number} index Index of the specified submesh.
*/
getSubMesh(index) {
this._lazyInitRenderResources();
return this._subMeshes[index];
}
get minPosition() {
return this._minPosition;
}
get maxPosition() {
return this._maxPosition;
}
// TODO
// updateData () {
// // store the data
@@ -135,5 +246,24 @@ export default class Mesh extends Asset {
// }
// }
// }
/**
* @return {ArrayBuffer}
*/
_getBuffer() {
return this._data.buffer;
}
_getIndexUnitSize(indexUnit) {
switch (indexUnit) {
case gfxEnums.INDEX_FMT_UINT8:
return 1;
case gfxEnums.INDEX_FMT_UINT16:
return 2;
case gfxEnums.INDEX_FMT_UINT32:
return 3;
}
return 1;
}
}
cc.Mesh = Mesh;
+53
View File
@@ -0,0 +1,53 @@
/****************************************************************************
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";
const { ccclass, property } = _decorator;
/**
* The class BufferRange denotes a range of the buffer.
*/
@ccclass("cc.internal.BufferRange")
export default class BufferRange {
/**
* The offset of the range.
* @type {Number}
*/
@property(Number)
_offset = 0;
/**
* The length of the range, in bytes.
* @type {Number}
*/
@property(Number)
_length = 0;
constructor(offset, length) {
this._offset = offset;
this._length = length;
}
}
File diff suppressed because it is too large Load Diff
+41 -58
View File
@@ -23,7 +23,7 @@
THE SOFTWARE.
****************************************************************************/
// @ts-check
import renderer from '../../renderer/index';
import Model from '../../renderer/scene/model';
import { ccclass, property, menu, executionOrder, executeInEditMode } from '../../core/data/class-decorator';
import Mesh from '../assets/mesh';
import Enum from '../../core/value-types/enum';
@@ -103,6 +103,11 @@ export default class ModelComponent extends RenderableComponent {
@property
_receiveShadows = false;
/**
* @type {Material}
*/
static _builtinMaterial = null;
/**
* !#en The mesh of the model
*
@@ -169,13 +174,6 @@ export default class ModelComponent extends RenderableComponent {
this._updateModels();
this._updateCastShadow();
this._updateReceiveShadow();
/** @type {import("../../../engine/cocos/3d/assets/material").default} */
if (this.material == null) {
let mtl = new cc.Material();
mtl.effectAsset = cc.game._builtins['builtin-effect-unlit'];
this.material = mtl;
}
}
onEnable() {
@@ -190,53 +188,14 @@ export default class ModelComponent extends RenderableComponent {
}
}
/**
* !#en Returns the material corresponding to the sequence number
*
* !#ch 返回相对应序号的材质
* @param {Number} idx - Look for the material list number
*/
getMaterial(idx) {
if (this._materials.length === 0) {
return null;
}
if (idx < this._materials.length) {
return this._materials[idx];
}
return this._materials[this._materials.length - 1];
}
get material() {
return this.getMaterial(0);
}
set material(val) {
if (this._materials.length === 1 && this._materials[0] === val) {
return;
}
this._materials[0] = val;
if (this._models.length > 0) {
this._models.forEach((model) => {
model.setEffect(val.effect);
});
}
}
_updateModels() {
if (this._mesh) {
this._mesh.flush();
}
let meshCount = this._mesh ? this._mesh.subMeshCount : 0;
let oldModels = this._models;
this._models = new Array(meshCount);
for (let i = 0; i < meshCount; ++i) {
let model = new renderer.Model();
model.createBoundingShape(this._mesh._minPos, this._mesh._maxPos);
let model = this._createModel();
model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition);
this._models[i] = model;
}
@@ -252,28 +211,41 @@ export default class ModelComponent extends RenderableComponent {
}
}
_createModel() {
return new Model();
}
_updateModelParams() {
for (let i = 0; i < this._models.length; ++i) {
let model = this._models[i];
let material = this._getSubMeshMaterial(i);
let material = this.getSharedMaterial(i);
let inputAssembler = this._mesh.getSubMesh(i);
model.setInputAssembler(inputAssembler);
model.setEffect(material ? material.effect : null);
model.setNode(this.node);
this._updateModelMaterial(model, material);
}
}
_getSubMeshMaterial(idx) {
let mat = this.getSharedMaterial(idx);
if (mat == null && this._materials.length > 0) {
mat = this._materials[this._materials.length - 1];
_onMaterialModified(idx, material) {
if (idx < this._models.length) {
this._updateModelMaterial(this._models[idx], material);
}
return mat;
}
_onMaterialModified(idx, mat) {
this._models[idx].setEffect(mat.effect);
_clearMaterials() {
for (let i = 0; i < this._models.length; ++i) {
this._onMaterialModified(i, null);
}
}
/**
*
* @param {Model} model
* @param {Material} material
*/
_updateModelMaterial(model, material) {
model.setEffect((material ? material.effect : null) || this._getBuiltinMaterial().effect);
}
_updateCastShadow() {
@@ -300,4 +272,15 @@ export default class ModelComponent extends RenderableComponent {
}
}
}
_getBuiltinMaterial() {
if (ModelComponent._builtinMaterial === null) {
const builtinMaterial = new cc.Material();
builtinMaterial.effectName = 'builtin-effect-unlit';
builtinMaterial.define("USE_COLOR", true);
builtinMaterial.setProperty("color", new cc.Color(123, 0, 0, 255));
ModelComponent._builtinMaterial = builtinMaterial;
}
return ModelComponent._builtinMaterial;
}
}
+1 -1
View File
@@ -38,4 +38,4 @@ export default class RenderSystemActor extends Component {
get scene() {
return this._scene;
}
};
}
+38 -13
View File
@@ -1,3 +1,4 @@
//@ts-check
import RenderSystemActor from "./renderSystemActor";
import { _decorator } from '../../core/data/index';
import Material from "../assets/material";
@@ -5,19 +6,26 @@ const { ccclass, property } = _decorator;
@ccclass('cc.RenderableComponent')
export default class RenderableComponent extends RenderSystemActor {
@property
/**
* @type {Material[]}
*/
@property([Material])
_materials = [];
constructor() {
super();
}
/**
* !#en The material of the model
*
* !#ch 模型材质
* @type {Material[]}
*/
@property
@property([Material])
get materials() {
for (let i = 0; i < this._materials.length; i++) {
this._materials[i] = this.getMaterial(i);
this._materials[i] = this.getSharedMaterial(i);
}
return this._materials;
}
@@ -27,10 +35,19 @@ export default class RenderableComponent extends RenderSystemActor {
}
set materials(val) {
this._materials = val;
for (let i = 0; i < val.length; i++) {
this._onMaterialModified(i, val[i]);
}
// const dLen = val.length - this._materials.length;
// if (dLen > 0) {
// this._materials = this._materials.concat(new Array(dLen).fill(null));
// } else if (dLen < 0) {
// for (let i = -dLen; i < this._materials.length; ++i) {
// this._setMaterial(null, i);
// }
// this._materials = this._materials.splice(-dLen);
// }
// 因为现在编辑器的做法是,当这个val传进来时,内部的materials已经被修改了。
// 我们没办法做到上面的最优化,只能先清理ModelComponent里所有Submodel的材质,再重新关联。
this._clearMaterials();
val.forEach((newMaterial, index) => this._setMaterial(newMaterial, index));
}
/**
@@ -46,8 +63,7 @@ export default class RenderableComponent extends RenderSystemActor {
let instantiated = Material.getInstantiatedMaterial(this._materials[idx], this);
if (instantiated != this) {
this._materials[idx] = instantiated;
this._onMaterialModified(idx, instantiated);
this._setMaterial(instantiated, idx);
}
return this._materials[idx];
@@ -72,10 +88,19 @@ export default class RenderableComponent extends RenderSystemActor {
if (this._materials.length === 1 && this._materials[0] === val) {
return;
}
this._setMaterial(val, 0);
}
_setMaterial(material, index) {
this._onMaterialModified(index, material);
this._materials[index] = material;
}
_onMaterialModified(index, material) {
}
_clearMaterials() {
if (val != this._materials[0]) {
this._onMaterialModified(0, val);
}
this._materials[0] = val;
}
}
+24 -38
View File
@@ -62,10 +62,6 @@ export default class SkinningModelComponent extends ModelComponent {
@property(Node)
_skinningRoot = null;
/**
* @type {Node}
*/
@property(Node)
_skeletonRoot = null;
constructor() {
@@ -102,27 +98,31 @@ export default class SkinningModelComponent extends ModelComponent {
this._skeleton = val;
}
@property(Node)
get skinningRoot() {
return this._skinningRoot;
}
set skinningRoot(value) {
this._skinningRoot = value;
//this._resetTarget();
}
onLoad() {
this._resetTarget();
this._reInitJointsData();
this._updateModels();
this._updateCastShadow();
this._updateReceiveShadow();
/** @type {import("../assets/material").default} */
let mtl = new cc.Material();
mtl.effectAsset = cc.game._builtins['builtin-effect-unlit'];
mtl.setProperty("color", new cc.vmath.color4(0, 0, 0, 1));
this.material = mtl;
}
update(dt) {
this._updateMatrices();
super.update();
}
onDestroy() {
SkinningModelComponent.system.remove(this);
}
_updateMatrices() {
@@ -146,8 +146,8 @@ export default class SkinningModelComponent extends ModelComponent {
// }
// });
const inverseSkinningRootWorldMatrix = this._skinningRoot.getWorldMatrix();
mat4.invert(inverseSkinningRootWorldMatrix, inverseSkinningRootWorldMatrix);
const cancelThisNoTransform = this.node.getWorldMatrix();
mat4.invert(cancelThisNoTransform, cancelThisNoTransform);
this._skeleton.joints.forEach((joint, index) => {
// const debugNode = nodes[this._skeleton._debugjoints[index]];
@@ -158,35 +158,21 @@ export default class SkinningModelComponent extends ModelComponent {
return;
}
const bindpose = this._skeleton.bindposes[index];
let worldMatrix = targetNode.getWorldMatrix();
mat4.multiply(worldMatrix, inverseSkinningRootWorldMatrix, worldMatrix);
mat4.multiply(_m4_tmp, worldMatrix, bindpose);
this._setJointMatrix(index, _m4_tmp);
// 1. transform mesh to joint's local space
// 2. transform from joint' local space to world space
// 3. because it has been in world space, just cancel this mesh's original local-world transform
const jointMatrix = _m4_tmp;
mat4.multiply(jointMatrix, cancelThisNoTransform, targetNode.getWorldMatrix());
mat4.multiply(jointMatrix, jointMatrix, bindpose);
this._setJointMatrix(index, jointMatrix);
});
this._commitJointsData();
}
_updateModels() {
if (this._mesh) {
this._mesh.flush();
}
let meshCount = this._mesh ? this._mesh.subMeshCount : 0;
let oldModels = this._models;
this._models = new Array(meshCount);
for (let i = 0; i < meshCount; ++i) {
let model = new renderer.SkinningModel();
model.createBoundingShape(this._mesh._minPos, this._mesh._maxPos);
this._models[i] = model;
}
this._updateModelParams();
if (this.enabled) {
this.node.emit('skinning-model-changed', this, 'mesh', oldModels);
}
_createModel() {
return new renderer.SkinningModel();
}
_updateModelParams() {
@@ -255,7 +241,7 @@ export default class SkinningModelComponent extends ModelComponent {
_resetTarget() {
this._skinningTarget = new Map();
if (!this._skeleton) {
if (!this._skeleton || !this._skinningRoot) {
return;
}
const rootNode = this._skinningRoot;
+2 -2
View File
@@ -162,7 +162,7 @@ const PixelFormat = Enum({
* The texture wrap mode
* @enum Texture2D.WrapMode
*/
const WrapMode = Enum({
export const WrapMode = Enum({
/**
* The constant variable equals gl.REPEAT for texture
* @property REPEAT
@@ -190,7 +190,7 @@ const WrapMode = Enum({
* The texture filter mode
* @enum Texture2D.Filter
*/
const Filter = Enum({
export const Filter = Enum({
/**
* The constant variable equals gl.LINEAR for texture
* @property LINEAR
+1 -1
View File
@@ -381,7 +381,7 @@ export default class ForwardRenderer extends BaseRenderer {
defines.USE_JOINTS_TEXTURE = true;
this._device.setTexture('u_jointsTexture', model._jointsTexture, this._allocTextureUnit());
this._device.setUniform('u_jointsTextureSize', model._jointsTexture._width);
} else {
} else if (model._jointsMatrixArray != null) {
defines.USE_JOINTS_TEXTURE = false;
this._device.setUniform("u_jointMatrices", model._jointsMatrixArray);
}