diff --git a/cocos/3d/assets/material.js b/cocos/3d/assets/material.js index 1709ffb6d5..f9146e8f2b 100644 --- a/cocos/3d/assets/material.js +++ b/cocos/3d/assets/material.js @@ -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; diff --git a/cocos/3d/assets/mesh.js b/cocos/3d/assets/mesh.js index 42cc22aa61..9cda47a252 100644 --- a/cocos/3d/assets/mesh.js +++ b/cocos/3d/assets/mesh.js @@ -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; \ No newline at end of file diff --git a/cocos/3d/assets/utils/buffer-range.js b/cocos/3d/assets/utils/buffer-range.js new file mode 100644 index 0000000000..9ad81808e1 --- /dev/null +++ b/cocos/3d/assets/utils/buffer-range.js @@ -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; + } +} \ No newline at end of file diff --git a/cocos/3d/assets/utils/gltf-utils.js b/cocos/3d/assets/utils/gltf-utils.js index 728f6f57a7..2ee7c7b7d0 100644 --- a/cocos/3d/assets/utils/gltf-utils.js +++ b/cocos/3d/assets/utils/gltf-utils.js @@ -1,431 +1,25 @@ // @ts-check -import { _decorator } from "../../../core/data/index"; -const { ccclass, property } = _decorator; import gfx from "../../../renderer/gfx"; -import renderer from "../../../renderer"; -import { vec3, quat, mat4 } from "../../../core/vmath"; +import { enums as gfxEnums } from "../../../renderer/gfx/enums"; +import { vec3 } from "../../../core/vmath"; import Node from "../../../scene-graph/node"; -import { MeshResource } from "../mesh"; -import GLTFAsset from "../../../assets/CCGLTFAsset"; +import Texture, { WrapMode, Filter } from "../../../assets/CCTexture2D"; +import Material from "../material"; +import Mesh, { Primitive, VertexBundle } from "../mesh"; +import BufferRange from "./buffer-range"; import Skeleton from "../skeleton"; -import { Mat4 } from "../../../core/value-types"; +import { Vec3, Mat4 } from "../../../core/value-types"; import AnimationClip, { AnimationFrame, AnimationChannel } from "../animation-clip"; /** - * @typedef {import("../../../../types/glTF/glTF").GlTf} GLTFFormat + * @typedef {import("../../../../types/glTF/glTF").GlTf} Gltf + * @typedef {import("../../../../types/glTF/glTF").Accessor} GltfAccessor + * @typedef {import("../../../../types/glTF/glTF").Buffer} GltfBuffer + * @typedef {import("../../../../types/glTF/glTF").BufferView} GltfBufferView * @typedef {import("../../../../types/glTF/glTF").Node} GLTFNode + * @typedef {import("../../../../types/glTF/glTF").Sampler} GltfSampler */ -@ccclass('cc.GltfMeshResource') -export class GltfMeshResource extends MeshResource { - /** - * @type {GLTFAsset} - */ - @property(GLTFAsset) - gltfAsset = null; - - /** - * @type {number} - */ - @property(Number) - gltfIndex = -1; - - /** - * Update mesh asset's content to the GlTf asset's specified mesh. - * The GlTf mesh is conditionally supported. - * All attributes of a GlTf primitive shall be recognized; - * they shall have same amount of elements, and - * shall be tighly interleaved, with no extra head data, in same buffer view. - * @param {cc.d3.asset.Mesh} mesh - */ - flush(mesh) { - if (!this.gltfAsset) { - return; - } - - /** @type GLTFFormat */ - const gltf = this.gltfAsset.description; - if (this.gltfIndex >= gltf.meshes.length) { - return; - } - - const gltfMesh = gltf.meshes[this.gltfIndex]; - const gltfAccessors = gltf.accessors; - - mesh.name = gltfMesh.name; - - mesh._subMeshes = new Array(gltfMesh.primitives.length); - for (let i = 0; i < gltfMesh.primitives.length; ++i) { - let primitive = gltfMesh.primitives[i]; - - let iVertexBufferView = -1; - let vertexCount = -1; - const vfmt = []; - for (const gltfAttribName in primitive.attributes) { - const gfxAttribName = _gltfAttribMap[gltfAttribName]; - if (gfxAttribName === undefined) { - console.error(`Found unacceptable GlTf attribute ${gltfAttribName}.`); - return; - } - const gltfAccessor = gltfAccessors[primitive.attributes[gltfAttribName]]; - - if (iVertexBufferView !== -1 && iVertexBufferView !== gltfAccessor.bufferView) { - console.error(`All attributes of one GlTf primitive should reference to the same buffer view.`); - return; - } else { - iVertexBufferView = gltfAccessor.bufferView; - } - - if (vertexCount !== -1 && vertexCount !== gltfAccessor.count) { - console.error(`All attributes of one GlTf primitive should have same amount of elements.`); - return; - } else { - vertexCount = gltfAccessor.count; - } - - if (gltfAttribName === "POSITION") { - mesh._minPos = vec3.create(gltfAccessor.min[0], gltfAccessor.min[1], gltfAccessor.min[2]); - mesh._maxPos = vec3.create(gltfAccessor.max[0], gltfAccessor.max[1], gltfAccessor.max[2]); - } - vfmt.push({ name: gfxAttribName, type: gltfAccessor.componentType, num: _type2size[gltfAccessor.type] }); - } - - const vertexBufferView = gltf.bufferViews[iVertexBufferView]; - const vbData = new Uint8Array(this.gltfAsset.buffers[vertexBufferView.buffer].data.buffer, vertexBufferView.byteOffset, vertexBufferView.byteLength); - const vb = new gfx.VertexBuffer( - cc.game._renderContext, - new gfx.VertexFormat(vfmt), - gfx.USAGE_STATIC, - vbData, - vertexCount - ); - - let ib = null; - if (primitive.indices !== undefined) { - let ibAcc = gltfAccessors[primitive.indices]; - let ibView = gltf.bufferViews[ibAcc.bufferView]; - let ibData = new DataView(this.gltfAsset.buffers[ibView.buffer].data.buffer, ibView.byteOffset, ibView.byteLength); - - ib = new gfx.IndexBuffer( - cc.game._renderContext, - ibAcc.componentType, - gfx.USAGE_STATIC, - ibData, - ibAcc.count - ); - } - - mesh._subMeshes[i] = new renderer.InputAssembler(vb, ib); - } - } -} -cc.GltfMeshResource = GltfMeshResource; - -const _type2size = { - SCALAR: 1, - VEC2: 2, - VEC3: 3, - VEC4: 4, - MAT2: 4, - MAT3: 9, - MAT4: 16, -}; - -const _compType2Array = { - 5120: Int8Array, - 5121: Uint8Array, - 5122: Int16Array, - 5123: Uint16Array, - 5124: Int32Array, - 5125: Uint32Array, - 5126: Float32Array, -}; - -const _gltfAttribMap = { - POSITION: gfx.ATTR_POSITION, - NORMAL: gfx.ATTR_NORMAL, - TANGENT: gfx.ATTR_TANGENT, - COLOR_0: gfx.ATTR_COLOR0, - TEXCOORD_0: gfx.ATTR_UV0, - TEXCOORD_1: gfx.ATTR_UV1, - TEXCOORD_2: gfx.ATTR_UV2, - TEXCOORD_3: gfx.ATTR_UV3, - JOINTS_0: gfx.ATTR_JOINTS, - WEIGHTS_0: gfx.ATTR_WEIGHTS -}; - -/** - * @param {GLTFFormat} gltf - * @param {ArrayBuffer} bin - * @param {number} accessorID - * @return {Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array} - */ -function _createArray(gltf, bin, accessorID) { - let acc = gltf.accessors[accessorID]; - if (acc.bufferView === undefined) { - throw "Unexpect accessor format."; - } - let bufView = gltf.bufferViews[acc.bufferView]; - - let num = _type2size[acc.type]; - let typedArray = _compType2Array[acc.componentType]; - let result = new typedArray(bin, bufView.byteOffset + acc.byteOffset, acc.count * num); - - return result; -} - -/** - * @param {GLTFNode[]} gltfNodes - */ -export function createNodes(gltfNodes) { - let nodes = new Array(gltfNodes.length); - - for (let i = 0; i < gltfNodes.length; ++i) { - let node = createNode(gltfNodes[i]); - nodes[i] = node; - } - - for (let i = 0; i < gltfNodes.length; ++i) { - let gltfNode = gltfNodes[i]; - let node = nodes[i]; - - if (gltfNode.children) { - for (let j = 0; j < gltfNode.children.length; ++j) { - let index = gltfNode.children[j]; - node.append(nodes[index]); - } - } - } - - return nodes; -} - -/** - * @param {*} app - * @param {Array} gltfNodes - */ -export function createEntities(app, gltfNodes) { - let nodes = new Array(gltfNodes.length); - - for (let i = 0; i < gltfNodes.length; ++i) { - let gltfNode = gltfNodes[i]; - /** @type Node */ - let node = app.createEntity(gltfNode.name); - - if (gltfNode.translation) { - node.setPosition( - gltfNode.translation[0], - gltfNode.translation[1], - gltfNode.translation[2] - ); - } - - if (gltfNode.rotation) { - node.setRotation( - gltfNode.rotation[0], - gltfNode.rotation[1], - gltfNode.rotation[2], - gltfNode.rotation[3] - ); - } - - if (gltfNode.scale) { - node.setScale( - gltfNode.scale[0], - gltfNode.scale[1], - gltfNode.scale[2] - ); - } - - nodes[i] = node; - } - - for (let i = 0; i < gltfNodes.length; ++i) { - let gltfNode = gltfNodes[i]; - let node = nodes[i]; - - if (gltfNode.children) { - for (let j = 0; j < gltfNode.children.length; ++j) { - let index = gltfNode.children[j]; - node.append(nodes[index]); - } - } - } - - return nodes; -} - -/** - * @param {GLTFFormat} gltf - * @param {Buffer[]} buffers - * @param {number} index - * @param {string[]} nodePathTable - */ -export function createSkeleton(gltf, buffers, nodePathTable, index) { - if (!gltf.skins || index >= gltf.skins.length) { - return; - } - - /** @type {cc.Node[]} */ - let nodes = []; - if (gltf.nodes) { - nodes = new Array(gltf.nodes.length); - gltf.nodes.forEach((gltfNode, index) => { - nodes[index] = createNode(gltfNode); - }); - gltf.nodes.forEach((gltfNode, index) => { - if (gltfNode.children) { - const node = nodes[index]; - gltfNode.children.forEach(childIndex => { - node.addChild(nodes[childIndex]); - }); - } - }); - } - - const gltfSkin = gltf.skins[index]; - const skeleton = new Skeleton(); - skeleton.name = gltfSkin.name; - skeleton._joints = gltfSkin.joints.map(nodeIndex => nodePathTable[nodeIndex]); - // extract bindposes mat4 data - let accessor = gltf.accessors[gltfSkin.inverseBindMatrices]; - let bufView = gltf.bufferViews[accessor.bufferView]; - let data = _createArray(gltf, buffers[bufView.buffer].buffer, gltfSkin.inverseBindMatrices); - skeleton._inverseBindMatrices = new Array(accessor.count); - for (let i = 0; i < accessor.count; ++i) { - skeleton._inverseBindMatrices[i] = new Mat4( - data[16 * i + 0], data[16 * i + 1], data[16 * i + 2], data[16 * i + 3], - data[16 * i + 4], data[16 * i + 5], data[16 * i + 6], data[16 * i + 7], - data[16 * i + 8], data[16 * i + 9], data[16 * i + 10], data[16 * i + 11], - data[16 * i + 12], data[16 * i + 13], data[16 * i + 14], data[16 * i + 15] - ); - } - - return skeleton; -} - -/** - * @param {GLTFFormat} gltf - * @param {Buffer[]} buffers - * @param {number} index - * @param {string[]} nodePathTable - */ -export function createAnimation(gltf, buffers, nodePathTable, index) { - if (!gltf.animations || index >= gltf.animations.length) { - return; - } - - const bin = buffers[0].buffer; - - /** @type {AnimationFrame[]} */ - let frames = []; - let maxLength = -1; - - let gltfAnimation = gltf.animations[index]; - gltfAnimation.channels.forEach(gltfChannel => { - if (gltfChannel.target.node === undefined) { - // When node isn't defined, channel should be ignored. - return; - } - - let gltfSampler = gltfAnimation.samplers[gltfChannel.sampler]; - let inputAcc = gltf.accessors[gltfSampler.input]; - - // find frame by input name - /** @type {AnimationFrame} */ - let frame = frames.find((frame) => frame._name === inputAcc.name); - - // if not found, create one - if (!frame) { - let inArray = _createArray(gltf, bin, gltfSampler.input); - /** @type {number[]} */ - let inputs = new Array(inArray.length); - for (let i = 0; i < inArray.length; ++i) { - let t = inArray[i]; - inputs[i] = t; - - if (maxLength < t) { - maxLength = t; - } - } - - frame = new AnimationFrame(); - frame._name = inputAcc.name; - frame._times = inputs; - frame._channels = []; - frames.push(frame); - } - - // find output frames by node id - /** @type {AnimationChannel} */ - let channel = frame._channels.find((channel) => channel.target === nodePathTable[gltfChannel.target.node]); - - // if not found, create one - if (!channel) { - channel = new AnimationChannel(); - channel.target = nodePathTable[gltfChannel.target.node]; - frame._channels.push(channel); - } - - let outArray = _createArray(gltf, bin, gltfSampler.output); - if (gltfChannel.target.path === 'translation') { - let cnt = outArray.length / 3; - channel.positionCurve = new Array(cnt); - for (let i = 0; i < cnt; ++i) { - channel.positionCurve[i] = new cc.Vec3( - outArray[3 * i + 0], - outArray[3 * i + 1], - outArray[3 * i + 2] - ); - } - } else if (gltfChannel.target.path === 'rotation') { - let cnt = outArray.length / 4; - channel.rotationCurve = new Array(cnt); - for (let i = 0; i < cnt; ++i) { - channel.rotationCurve[i] = new cc.Quat( - outArray[4 * i + 0], - outArray[4 * i + 1], - outArray[4 * i + 2], - outArray[4 * i + 3] - ); - } - } else if (gltfChannel.target.path === 'scale') { - let cnt = outArray.length / 3; - channel.scaleCurve = new Array(cnt); - for (let i = 0; i < cnt; ++i) { - channel.scaleCurve[i] = new cc.Vec3( - outArray[3 * i + 0], - outArray[3 * i + 1], - outArray[3 * i + 2] - ); - } - } - }); - - const animationClip = new AnimationClip(); - animationClip.name = gltfAnimation.name; - animationClip._frames = frames; - animationClip._length = maxLength; - return animationClip; -} - -/** - * - * @param {GLTFFormat} gltf - * @param {number} index - */ -function _createNodeRecursive(gltf, index) { - let gltfNode = gltf.nodes[index]; - let node = createNode(gltfNode); - if (gltfNode.children) { - gltfNode.children.forEach((childGLTFNode) => { - let childNode = _createNodeRecursive(gltf, childGLTFNode); - node.addChild(childNode); - }); - } - return node; -} - /** * * @param {GLTFNode} gltfNode @@ -460,34 +54,648 @@ export function createNode(gltfNode) { return node; } -/** - * - * @param {GLTFFormat} gltf - */ -export function createNodePathTable(gltf) { - if (!gltf.nodes) { - return []; +class BufferBlob { + constructor() { + /** + * @type {ArrayBuffer[]} + */ + this._arrayByffers = []; + + this._length = 0; } - /** @type {string[]} */ - const result = new Array(gltf.nodes.length); - result.fill(""); - gltf.nodes.forEach((gltfNode, nodeIndex) => { - const myPath = result[nodeIndex] + gltfNode.name; - result[nodeIndex] = myPath; - if (gltfNode.children) { - gltfNode.children.forEach(childNodeIndex => { - const childPath = result[childNodeIndex]; - result[childNodeIndex] = `${myPath}/${childPath}`; - }); - } - }); - // Remove root segment - result.forEach((path, index) => { - let segments = path.split('/'); - segments.shift(); - result[index] = segments.join('/'); - }); + /** + * + * @param {ArrayBuffer} arrayBuffer + * @return {number} + */ + addBuffer(arrayBuffer) { + const result = this._length; + this._arrayByffers.push(arrayBuffer); + this._length += arrayBuffer.byteLength; + return result; + } - return result; + getLength() { + return this._length; + } + + /** + * @return {ArrayBuffer} + */ + getCombined() { + let length = 0; + this._arrayByffers.forEach(arrayBuffer => length += arrayBuffer.byteLength); + const result = new Uint8Array(length); + let counter = 0; + this._arrayByffers.forEach(arrayBuffer => { + result.set(new Uint8Array(arrayBuffer), counter); + counter += arrayBuffer.byteLength; + }); + return result.buffer; + } +} + +export class GltfConverter { + /** + * + * @param {Gltf} gltf + * @param {Buffer[]} buffers + */ + constructor(gltf, buffers) { + /** + * @type {Gltf} + */ + this._gltf = gltf; + /** + * @type {Buffer[]} + */ + this._buffers = buffers; + } + + /** + * + * @param {number} index + * @return {{mesh: Mesh, buffer: ArrayBuffer}} + */ + createMesh(index) { + if (this._gltf.meshes === undefined || index >= this._gltf.meshes.length) { + return null; + } + + const gltfMesh = this._gltf.meshes[index]; + + const bufferBlob = new BufferBlob(); + + let minPosition = new Vec3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); + let maxPosition = new Vec3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); + + const vertexBundles = []; + const primitives = gltfMesh.primitives.map((gltfPrimitive, primitiveIndex) => { + const attributeNames = Object.getOwnPropertyNames(gltfPrimitive.attributes); + + let vertexBufferStride = 0; + let verticesCount = 0; + const formats = []; + + const attributeByteLengths = attributeNames.map((attributeName) => { + const attributeAccessor = this._requireGltfAccessor(gltfPrimitive.attributes[attributeName]); + const attributeByteLength = this._getBytesPerAttribute(attributeAccessor); + vertexBufferStride += attributeByteLength; + verticesCount = Math.max(verticesCount, attributeAccessor.count); + return attributeByteLength; + }); + + const vertexBuffer = new ArrayBuffer(vertexBufferStride * verticesCount); + + let currentByteOffset = 0; + attributeNames.forEach((attributeName, iAttribute) => { + const attributeAccessor = this._requireGltfAccessor(gltfPrimitive.attributes[attributeName]); + this._readAccessor(attributeAccessor, new DataView(vertexBuffer, currentByteOffset), vertexBufferStride); + currentByteOffset += attributeByteLengths[iAttribute]; + + if (attributeName === "POSITION") { + if (attributeAccessor.min) { + vec3.min(minPosition, minPosition, new vec3(attributeAccessor.min[0], attributeAccessor.min[1], attributeAccessor.min[2])); + } + if (attributeAccessor.max) { + vec3.max(maxPosition, maxPosition, new vec3(attributeAccessor.max[0], attributeAccessor.max[1], attributeAccessor.max[2])); + } + } + + formats.push({ + name: this._getGfxAttributeName(attributeName), + type: this._getGfxComponentType(attributeAccessor.componentType), + num: this._getComponentsPerAttribute(attributeAccessor.type) + }); + }); + + const vertexBundleRange = new BufferRange(bufferBlob.addBuffer(vertexBuffer), vertexBuffer.byteLength); + + const vertexBundle = new VertexBundle(); + vertexBundle._data = vertexBundleRange; + vertexBundle._verticesCount = verticesCount; + vertexBundle._formats = formats; + vertexBundles.push(vertexBundle); + + let indices = null; + let indexUnit = null; + if (gltfPrimitive.indices !== undefined) { + const indicesAccessor = this._requireGltfAccessor(gltfPrimitive.indices); + const indexStride = this._getBytesPerAttribute(indicesAccessor); + const indicesData = new ArrayBuffer(indexStride * indicesAccessor.count); + this._readAccessor(indicesAccessor, new DataView(indicesData)); + indices = new BufferRange(bufferBlob.addBuffer(indicesData), indicesData.byteLength); + indexUnit = this._getGfxIndexUnitType(indicesAccessor.componentType); + } + + const primitive = new Primitive(); + primitive._vertexBundelIndices = [primitiveIndex]; + primitive._topology = this._getTopology(gltfPrimitive.mode === undefined ? 4 : gltfPrimitive.mode); + primitive._indices = indices; + primitive._indexUnit = indexUnit; + return primitive; + }); + + const mesh = new Mesh(); + mesh.name = gltfMesh.name; + mesh._minPosition = minPosition; + mesh._maxPosition = maxPosition; + mesh._primitives = primitives; + mesh._vertexBundles = vertexBundles; + return { mesh, buffer: bufferBlob.getCombined() }; + } + + /** + * @param {number} index + * @param {string[]} nodePathTable + */ + createSkeleton(index, nodePathTable) { + if (this._gltf.skins === undefined || index >= this._gltf.skins.length) { + return null; + } + + const gltfSkin = this._gltf.skins[index]; + + const inverseBindMatrices = new Array(gltfSkin.joints.length); + if (gltfSkin.inverseBindMatrices === undefined) { + // The default is that each matrix is a 4x4 identity matrix, + // which implies that inverse-bind matrices were pre-applied. + for (let i = 0; i < inverseBindMatrices.length; ++i) { + inverseBindMatrices[i] = new Mat4( + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ); + } + } else { + const inverseBindMatricesAccessor = this._requireGltfAccessor(gltfSkin.inverseBindMatrices); + if (inverseBindMatricesAccessor.componentType !== 5126 || + inverseBindMatricesAccessor.type !== "MAT4") { + throw `The inverse bind matrix should be floating-point 4x4 matrix.`; + } + const data = new Float32Array(inverseBindMatrices.length * 16); + this._readAccessor(inverseBindMatricesAccessor, new DataView(data.buffer)); + for (let i = 0; i < inverseBindMatrices.length; ++i) { + inverseBindMatrices[i] = new Mat4( + data[16 * i + 0], data[16 * i + 1], data[16 * i + 2], data[16 * i + 3], + data[16 * i + 4], data[16 * i + 5], data[16 * i + 6], data[16 * i + 7], + data[16 * i + 8], data[16 * i + 9], data[16 * i + 10], data[16 * i + 11], + data[16 * i + 12], data[16 * i + 13], data[16 * i + 14], data[16 * i + 15] + ); + } + } + + const skeleton = new Skeleton(); + skeleton.name = gltfSkin.name; + skeleton._joints = gltfSkin.joints.map(nodeIndex => nodePathTable[nodeIndex]); + skeleton._inverseBindMatrices = inverseBindMatrices; + + return skeleton; + } + + /** + * @param {number} index + * @param {string[]} nodePathTable + */ + createAnimation(index, nodePathTable) { + if (this._gltf.animations === undefined || index >= this._gltf.animations.length) { + return; + } + + let gltfAnimation = this._gltf.animations[index]; + + /** @type {AnimationFrame[]} */ + let frames = []; + let maxLength = 0; + + gltfAnimation.channels.forEach(gltfChannel => { + if (gltfChannel.target.node === undefined) { + // When node isn't defined, channel should be ignored. + return; + } + + const gltfSampler = gltfAnimation.samplers[gltfChannel.sampler]; + const inputAccessor = this._requireGltfAccessor(gltfSampler.input); + + // find frame by input name + /** @type {AnimationFrame} */ + let frame = frames.find((frame) => frame._name === inputAccessor.name); + + // if not found, create one + if (!frame) { + if (inputAccessor.componentType !== 5126 || + inputAccessor.type !== "SCALAR") { + throw `Input of an animation channel must be floating point scalars represent times.`; + } + const inputData = new Float32Array(inputAccessor.count); + this._readAccessor(inputAccessor, new DataView(inputData.buffer)); + + const times = new Array(inputData.length); + inputData.forEach((time, index) => { + times[index] = time; + }); + if (times.length > 0) { + maxLength = Math.max(maxLength, times[times.length - 1]); + } + + frame = new AnimationFrame(); + frame._name = inputAccessor.name; + frame._times = times; + frame._channels = []; + frames.push(frame); + } + + // find output frames by node id + /** @type {AnimationChannel} */ + let channel = frame._channels.find((channel) => channel.target === nodePathTable[gltfChannel.target.node]); + + // if not found, create one + if (!channel) { + channel = new AnimationChannel(); + channel.target = nodePathTable[gltfChannel.target.node]; + frame._channels.push(channel); + } + + const outputAccessor = this._requireGltfAccessor(gltfSampler.output); + if (outputAccessor.componentType !== 5126) { + throw `Output of an animation channel must be floating point values.`; + } + const outputData = new Float32Array(this._getComponentsPerAttribute(outputAccessor.type) * outputAccessor.count); + this._readAccessor(outputAccessor, new DataView(outputData.buffer)); + if (gltfChannel.target.path === 'translation') { + if (outputAccessor.type !== "VEC3") { + throw `Output of an animation channel targetting translation must be 3d vectors.`; + } + channel.positionCurve = new Array(outputAccessor.count); + for (let i = 0; i < outputAccessor.count; ++i) { + channel.positionCurve[i] = new cc.Vec3(outputData[3 * i + 0], outputData[3 * i + 1], outputData[3 * i + 2]); + } + } else if (gltfChannel.target.path === 'rotation') { + if (outputAccessor.type !== "VEC4") { + throw `Output of an animation channel targetting translation must be 4d vectors.`; + } + channel.rotationCurve = new Array(outputAccessor.count); + for (let i = 0; i < outputAccessor.count; ++i) { + channel.rotationCurve[i] = new cc.Quat(outputData[4 * i + 0], outputData[4 * i + 1], outputData[4 * i + 2], outputData[4 * i + 3]); + } + } else if (gltfChannel.target.path === 'scale') { + if (outputAccessor.type !== "VEC3") { + throw `Output of an animation channel targetting scale must be 3d vectors.`; + } + channel.scaleCurve = new Array(outputAccessor.count); + for (let i = 0; i < outputAccessor.count; ++i) { + channel.scaleCurve[i] = new cc.Vec3(outputData[3 * i + 0], outputData[3 * i + 1], outputData[3 * i + 2]); + } + } else { + throw `Unsupported channel target path.`; + } + }); + + const animationClip = new AnimationClip(); + animationClip.name = gltfAnimation.name; + animationClip._frames = frames; + animationClip._length = maxLength; + return animationClip; + } + + /** + * + * @param {number} index + * @param {Texture} textures + */ + createMaterial(index, textures) { + if (this._gltf.materials === undefined || index >= this._gltf.materials.length) { + return null; + } + + const gltfMaterial = this._gltf.materials[index]; + + const material = new Material(); + material.name = gltfMaterial.name; + material.effectName = "builtin-effect-unlit"; + if (gltfMaterial.pbrMetallicRoughness) { + const pbrMetallicRoughness = gltfMaterial.pbrMetallicRoughness; + if (pbrMetallicRoughness.baseColorTexture) { + material.define("USE_TEXTURE", true); + material.setProperty("mainTexture", textures[pbrMetallicRoughness.baseColorTexture.index]); + } else { + material.define("USE_COLOR", true); + let color = null; + if (pbrMetallicRoughness.baseColorFactor) { + const c = pbrMetallicRoughness.baseColorFactor; + color = new cc.Color(c[0] * 255, c[1] * 255, c[2] * 255, c[3] * 255); + } else { + color = new cc.Color(255, 255, 255, 255); + } + material.setProperty("color", color); + } + } + + return material; + } + + /** + * + * @param {number} index + */ + createTexture(index) { + if (this._gltf.textures === undefined || index >= this._gltf.textures.length) { + return null; + } + + const gltfTexture = this._gltf.textures[index]; + const texture = new Texture(); + texture.name = gltfTexture.name; + if (gltfTexture.sampler === undefined) { + texture.setWrapMode(WrapMode.REPEAT, WrapMode.REPEAT); + } else { + const gltfSampler = this._requireSampler(gltfTexture.sampler); + texture.setFilters( + gltfSampler.minFilter === undefined ? undefined : this._getFilter(gltfSampler.minFilter), + gltfSampler.magFilter === undefined ? undefined : this._getFilter(gltfSampler.magFilter) + ); + texture.setWrapMode( + this._getWrapMode(gltfSampler.wrapS === undefined ? 10497 : gltfSampler.wrapS), + this._getWrapMode(gltfSampler.wrapT === undefined ? 10497 : gltfSampler.wrapT), + ); + } + + return texture; + } + + createNodePathTable() { + if (this._gltf.nodes === undefined) { + return []; + } + + /** @type {string[]} */ + const result = new Array(this._gltf.nodes.length); + result.fill(""); + this._gltf.nodes.forEach((gltfNode, nodeIndex) => { + const myPath = result[nodeIndex] + gltfNode.name; + result[nodeIndex] = myPath; + if (gltfNode.children) { + gltfNode.children.forEach(childNodeIndex => { + const childPath = result[childNodeIndex]; + result[childNodeIndex] = `${myPath}/${childPath}`; + }); + } + }); + // Remove root segment + result.forEach((path, index) => { + let segments = path.split('/'); + segments.shift(); + result[index] = segments.join('/'); + }); + + return result; + } + + /** + * + * @param {GltfAccessor} gltfAccessor + * @param {DataView} outputBuffer + * @param {number} outputStride + */ + _readAccessor(gltfAccessor, outputBuffer, outputStride = 0) { + const gltfBufferView = this._requireGltfBufferView(gltfAccessor.bufferView); + + const componentsPerAttribute = this._getComponentsPerAttribute(gltfAccessor.type); + const bytesPerElement = this._getBytesPerComponent(gltfAccessor.componentType); + + if (outputStride === 0) { + outputStride = componentsPerAttribute * bytesPerElement; + } + + const inputStartOffset = + (gltfAccessor.byteOffset !== undefined ? gltfAccessor.byteOffset : 0) + + (gltfBufferView.byteOffset !== undefined ? gltfBufferView.byteOffset : 0); + + const inputBuffer = new DataView(this._buffers[gltfBufferView.buffer].buffer, inputStartOffset); + + const inputStride = gltfBufferView.byteStride !== undefined ? gltfBufferView.byteStride : componentsPerAttribute * bytesPerElement; + + const componentReader = this._getComponentReader(gltfAccessor.componentType); + const componentWriter = this._getComponentWriter(gltfAccessor.componentType); + + for (let iAttribute = 0; iAttribute < gltfAccessor.count; ++iAttribute) { + const i = new DataView(inputBuffer.buffer, inputBuffer.byteOffset + inputStride * iAttribute); + const o = new DataView(outputBuffer.buffer, outputBuffer.byteOffset + outputStride * iAttribute); + for (let iComponent = 0; iComponent < componentsPerAttribute; ++iComponent) { + const componentBytesOffset = bytesPerElement * iComponent; + const value = componentReader(i, componentBytesOffset); + componentWriter(o, componentBytesOffset, value); + } + } + } + + /** + * + * @param {number} mode + */ + _getTopology(mode) { + switch (mode) { + case 0: return gfxEnums.PT_POINTS; + case 1: return gfxEnums.PT_LINES; + case 2: return gfxEnums.PT_LINE_LOOP; + case 3: return gfxEnums.PT_LINE_STRIP; + case 4: return gfxEnums.PT_TRIANGLES; + case 5: return gfxEnums.PT_TRIANGLE_STRIP; + case 6: return gfxEnums.PT_TRIANGLE_FAN; + default: + throw `Unrecognized primitive mode: ${mode}.`; + } + } + + /** + * + * @param {number} componentType + */ + _getGfxIndexUnitType(componentType) { + return componentType; + } + + /** + * + * @param {number} componentType + */ + _getGfxComponentType(componentType) { + return componentType; + } + + /** + * + * @param {GltfAccessor} gltfAccessor + */ + _getBytesPerAttribute(gltfAccessor) { + return this._getBytesPerComponent(gltfAccessor.componentType) * this._getComponentsPerAttribute(gltfAccessor.type); + } + + /** + * + * @param {string} type + */ + _getComponentsPerAttribute(type) { + switch (type) { + case "SCALAR": return 1; + case "VEC2": return 2; + case "VEC3": return 3; + case "VEC4": case "MAT2": return 4; + case "MAT3": return 9; + case "MAT4": return 16; + default: + throw `Unrecognized attribute type: ${type}.`; + } + } + + /** + * + * @param {number} componentType + */ + _getBytesPerComponent(componentType) { + switch (componentType) { + case 5120: case 5121: return 1; + case 5122: case 5123: return 2; + case 5125: case 5126: return 4; + default: + throw `Unrecognized component type: ${componentType}`; + } + } + + /** + * + * @param {string} name + */ + _getGfxAttributeName(name) { + switch (name) { + case "POSITION": return gfx.ATTR_POSITION; + case "NORMAL": return gfx.ATTR_NORMAL; + case "TANGENT": return gfx.ATTR_TANGENT; + case "COLOR_0": return gfx.ATTR_COLOR0; + case "TEXCOORD_0": return gfx.ATTR_UV0; + case "TEXCOORD_1": return gfx.ATTR_UV1; + case "TEXCOORD_2": return gfx.ATTR_UV2; + case "TEXCOORD_3": return gfx.ATTR_UV3; + case "JOINTS_0": return gfx.ATTR_JOINTS; + case "WEIGHTS_0": return gfx.ATTR_WEIGHTS; + default: + throw `Unrecognized attribute type: ${name}`; + } + } + + /** + * + * @param {number} componentType + * @return {(buffer: DataView, offset: number) => number} + */ + _getComponentReader(componentType) { + switch (componentType) { + case 5120: return (buffer, offset) => buffer.getInt8(offset); + case 5121: return (buffer, offset) => buffer.getUint8(offset); + case 5122: return (buffer, offset) => buffer.getInt16(offset, true); + case 5123: return (buffer, offset) => buffer.getUint16(offset, true); + case 5125: return (buffer, offset) => buffer.getUint32(offset, true); + case 5126: return (buffer, offset) => buffer.getFloat32(offset, true); + default: + throw `Unrecognized component type: ${componentType}`; + } + } + + /** + * + * @param {number} componentType + * @return {(buffer: DataView, offset: number, value: number) => void} + */ + _getComponentWriter(componentType) { + switch (componentType) { + case 5120: return (buffer, offset, value) => buffer.setInt8(offset, value); + case 5121: return (buffer, offset, value) => buffer.setUint8(offset, value); + case 5122: return (buffer, offset, value) => buffer.setInt16(offset, value, true); + case 5123: return (buffer, offset, value) => buffer.setUint16(offset, value, true); + case 5125: return (buffer, offset, value) => buffer.setUint32(offset, value, true); + case 5126: return (buffer, offset, value) => buffer.setFloat32(offset, value, true); + default: + throw `Unrecognized component type: ${componentType}`; + } + } + + /** + * + * @param {number} filter + */ + _getFilter(filter) { + switch (filter) { + case 9728: + return Filter.NEAREST; + case 9729: + return Filter.LINEAR; + default: + throw `Unrecognized filter: ${filter}.`; + } + } + + /** + * + * @param {number} wrapMode + */ + _getWrapMode(wrapMode) { + switch (wrapMode) { + case 33071: + return WrapMode.CLAMP_TO_EDGE; + case 33648: + return WrapMode.MIRRORED_REPEAT; + case 10497: + return WrapMode.REPEAT; + default: + throw `Unrecognized wrapMode: ${wrapMode}.`; + } + } + + /** + * + * @param {number} index + * @return {GltfBuffer} + */ + _requireGltfBuffer(index) { + if (this._gltf.buffers === undefined) { + throw `Buffers is require but it do not exists.`; + } + return this._gltf.buffers[index]; + } + + /** + * @return {GltfBufferView} + * @param {number} index + */ + _requireGltfBufferView(index) { + if (this._gltf.bufferViews === undefined) { + throw `BufferViews is require but it do not exists.`; + } + return this._gltf.bufferViews[index]; + } + + /** + * + * @param {number} index + * @return {GltfAccessor} + */ + _requireGltfAccessor(index) { + if (this._gltf.accessors === undefined) { + throw `Accessors is require but it do not exists.`; + } + return this._gltf.accessors[index]; + } + + /** + * @param {number} index + * @return {GltfSampler} + */ + _requireSampler(index) { + if (this._gltf.samplers === undefined) { + throw `Samplers is require but it do not exists.`; + } + return this._gltf.samplers[index]; + } } \ No newline at end of file diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index eb04139f3b..b47184ccc8 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -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; + } } diff --git a/cocos/3d/framework/renderSystemActor.js b/cocos/3d/framework/renderSystemActor.js index a02a6a730f..eaf5ed65d5 100644 --- a/cocos/3d/framework/renderSystemActor.js +++ b/cocos/3d/framework/renderSystemActor.js @@ -38,4 +38,4 @@ export default class RenderSystemActor extends Component { get scene() { return this._scene; } -}; +} diff --git a/cocos/3d/framework/renderable-component.js b/cocos/3d/framework/renderable-component.js index f1e3d94266..d0b778cd6d 100644 --- a/cocos/3d/framework/renderable-component.js +++ b/cocos/3d/framework/renderable-component.js @@ -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; } } diff --git a/cocos/3d/framework/skinning-model-component.js b/cocos/3d/framework/skinning-model-component.js index 57f3be5df6..e73e7868f8 100644 --- a/cocos/3d/framework/skinning-model-component.js +++ b/cocos/3d/framework/skinning-model-component.js @@ -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; diff --git a/cocos/assets/CCTexture2D.js b/cocos/assets/CCTexture2D.js index a57a35b339..bcd0029641 100644 --- a/cocos/assets/CCTexture2D.js +++ b/cocos/assets/CCTexture2D.js @@ -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 diff --git a/cocos/renderer/renderers/forward-renderer.js b/cocos/renderer/renderers/forward-renderer.js index 2be5ac2a6f..cccdae3510 100644 --- a/cocos/renderer/renderers/forward-renderer.js +++ b/cocos/renderer/renderers/forward-renderer.js @@ -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); }