diff --git a/cocos/core/assets/index.ts b/cocos/core/assets/index.ts index c6f4f66d62..ab01623256 100644 --- a/cocos/core/assets/index.ts +++ b/cocos/core/assets/index.ts @@ -31,14 +31,14 @@ import { legacyCC } from '../global-exports'; export { RawAsset } from './raw-asset'; export { Asset } from './asset'; -export {default as Prefab} from './prefab'; +export { default as Prefab } from './prefab'; export * from './scripts'; -export {default as SceneAsset} from './scene-asset'; +export { default as SceneAsset } from './scene-asset'; export * from './sprite-frame'; export { SpriteAtlas } from './sprite-atlas'; -export {default as TextAsset} from './text-asset'; -export {default as JsonAsset} from './json-asset'; -export {default as AssetLibrary} from './asset-library'; +export { default as TextAsset } from './text-asset'; +export { default as JsonAsset } from './json-asset'; +export { default as AssetLibrary } from './asset-library'; export { ImageAsset } from './image-asset'; export { Texture2D } from './texture-2d'; export { TextureCube } from './texture-cube'; diff --git a/cocos/core/assets/sprite-frame.ts b/cocos/core/assets/sprite-frame.ts index fe27094dfa..9d5cec44d1 100644 --- a/cocos/core/assets/sprite-frame.ts +++ b/cocos/core/assets/sprite-frame.ts @@ -458,6 +458,8 @@ export class SpriteFrame extends Asset { public uv: number[] = []; public uvHash: number = 0; + public unbiasUV:number[] = []; + /** * @en UV for sliced 9 vertices * @zh 九宫格的顶点 UV。 @@ -805,6 +807,7 @@ export class SpriteFrame extends Asset { public _calculateUV () { const rect = this._rect; const uv = this.uv; + const unbiasUV = this.unbiasUV; const tex = this.texture; const texw = tex.width; const texh = tex.height; @@ -835,6 +838,30 @@ export class SpriteFrame extends Asset { uv[6] = r; uv[7] = b; } + + const ul = texw === 0 ? 0 : (rect.x) / texw; + const ur = texw === 0 ? 0 : (rect.x + rect.height) / texw; + const ut = texh === 0 ? 0 : (rect.y) / texh; + const ub = texh === 0 ? 0 : (rect.y + rect.width) / texh; + if (this._flipUv) { + unbiasUV[0] = ul; + unbiasUV[1] = ut; + unbiasUV[2] = ul; + unbiasUV[3] = ub; + unbiasUV[4] = ur; + unbiasUV[5] = ut; + unbiasUV[6] = ur; + unbiasUV[7] = ub; + } else { + unbiasUV[0] = ul; + unbiasUV[1] = ut; + unbiasUV[2] = ul; + unbiasUV[3] = ub; + unbiasUV[4] = ur; + unbiasUV[5] = ut; + unbiasUV[6] = ur; + unbiasUV[7] = ub; + } } else { // Canceling out the floating-point rounding errors by slightly nudging the UV coordinates const l = texw === 0 ? 0 : (rect.x + 0.5) / texw; @@ -860,6 +887,29 @@ export class SpriteFrame extends Asset { uv[6] = r; uv[7] = t; } + const ul = texw === 0 ? 0 : (rect.x ) / texw; + const ur = texw === 0 ? 0 : (rect.x + rect.width) / texw; + const ub = texh === 0 ? 0 : (rect.y + rect.height) / texh; + const ut = texh === 0 ? 0 : (rect.y) / texh; + if (this._flipUv) { + unbiasUV[0] = ul; + unbiasUV[1] = ut; + unbiasUV[2] = ur; + unbiasUV[3] = ut; + unbiasUV[4] = ul; + unbiasUV[5] = ub; + unbiasUV[6] = ur; + unbiasUV[7] = ub; + } else { + unbiasUV[0] = ul; + unbiasUV[1] = ub; + unbiasUV[2] = ur; + unbiasUV[3] = ub; + unbiasUV[4] = ul; + unbiasUV[5] = ut; + unbiasUV[6] = ur; + unbiasUV[7] = ut; + } } let uvHashStr = ''; diff --git a/cocos/core/load-pipeline/plist-parser.ts b/cocos/core/load-pipeline/plist-parser.ts index fb17bf061d..91d1a75909 100644 --- a/cocos/core/load-pipeline/plist-parser.ts +++ b/cocos/core/load-pipeline/plist-parser.ts @@ -37,7 +37,7 @@ import { warnID } from '../platform/debug'; * A SAX Parser * @class saxParser */ -class SAXParser { +export class SAXParser { private _isSupportDOMParser; private _parser; constructor () { diff --git a/cocos/core/renderer/ui/render-data.ts b/cocos/core/renderer/ui/render-data.ts index 5ee580a8e7..c6e70456d5 100644 --- a/cocos/core/renderer/ui/render-data.ts +++ b/cocos/core/renderer/ui/render-data.ts @@ -152,7 +152,16 @@ export class MeshRenderData extends BaseRenderData { public request (vertexCount: number, indicesCount: number) { const byteOffset = this.byteCount + vertexCount * this._formatByte; - const indicesOffset = this.indicesCount + indicesCount; + this.reserve(vertexCount, vertexCount); + this.vertexCount += vertexCount; // vertexOffset + this.indicesCount += indicesCount; // indicesOffset + this.byteCount = byteOffset; // byteOffset + return true; + } + + public reserve(vertexCount: number, indicesCount: number) { + const newVBytes = this.byteCount + vertexCount * this._formatByte; + const newICount = this.indicesCount + indicesCount; if (vertexCount + this.vertexCount > 65535) { return false; @@ -162,8 +171,8 @@ export class MeshRenderData extends BaseRenderData { let indicesLength = this.iData!.length; let vCount = this.vData.length; let iCount = this.iData.length; - if (byteOffset > byteLength || indicesOffset > indicesLength) { - while (byteLength < byteOffset || indicesLength < indicesOffset) { + if (newVBytes > byteLength || newICount > indicesLength) { + while (byteLength < newVBytes || indicesLength < newICount) { vCount *= 2; iCount *= 2; @@ -173,11 +182,12 @@ export class MeshRenderData extends BaseRenderData { this._reallocBuffer(vCount, iCount); } + } + public advance(vertexCount: number, indicesCount: number) { this.vertexCount += vertexCount; // vertexOffset this.indicesCount += indicesCount; // indicesOffset - this.byteCount = byteOffset; // byteOffset - return true; + this.byteCount += vertexCount * this._formatByte; } public reset () { diff --git a/cocos/core/renderer/ui/ui.ts b/cocos/core/renderer/ui/ui.ts index 9fbf5e5c80..35cf2f773d 100644 --- a/cocos/core/renderer/ui/ui.ts +++ b/cocos/core/renderer/ui/ui.ts @@ -106,7 +106,6 @@ export class UI { private _currTextureHash: number = 0; private _currSamplerHash: number = 0; private _parentOpacity = 1; - // DescriptorSet Cache Map private _descriptorSetCacheMap: Map> = new Map>(); @@ -139,7 +138,7 @@ export class UI { } public destroy () { - for (let i = 0; i < this._batches.length; i++ ) { + for (let i = 0; i < this._batches.length; i++) { if (this._batches.array[i]) { this._batches.array[i].destroy(this); } @@ -342,7 +341,7 @@ export class UI { } } else { const descriptorSetTextureMap = this._descriptorSetCacheMap.get(batch.textureHash); - if(descriptorSetTextureMap && descriptorSetTextureMap.has(batch.samplerHash)) { + if (descriptorSetTextureMap && descriptorSetTextureMap.has(batch.samplerHash)) { batch.hDescriptorSet = descriptorSetTextureMap.get(batch.samplerHash)!; } else { this._initDescriptorSet(batch); @@ -356,7 +355,7 @@ export class UI { if (descriptorSetTextureMap) { this._descriptorSetCacheMap.get(batch.textureHash)!.set(batch.samplerHash, batch.hDescriptorSet); } else { - this._descriptorSetCacheMap.set(batch.textureHash,new Map([[batch.samplerHash, batch.hDescriptorSet]])); + this._descriptorSetCacheMap.set(batch.textureHash, new Map([[batch.samplerHash, batch.hDescriptorSet]])); } } @@ -423,7 +422,7 @@ export class UI { * @param frame - 当前执行组件贴图。 * @param assembler - 当前组件渲染数据组装器。 */ - public commitComp (comp: UIRenderable, frame: TextureBase | SpriteFrame| RenderTexture | null, assembler: any) { + public commitComp (comp: UIRenderable, frame: TextureBase | SpriteFrame | RenderTexture | null, assembler: any) { const renderComp = comp; let texture; let samp; @@ -645,17 +644,18 @@ export class UI { this._uiMaterials.clear(); } - private _walk (node: Node, level = 0) { + public walk (node: Node, level = 0) { const len = node.children.length; const parentOpacity = this._parentOpacity; this._parentOpacity *= node._uiProps.opacity; + this._preprocess(node); if (len > 0 && !node._static) { const children = node.children; for (let i = 0; i < children.length; ++i) { const child = children[i]; - this._walk(child, level); + this.walk(child, level); } } @@ -686,8 +686,7 @@ export class UI { } private _recursiveScreenNode (screen: Node) { - this._walk(screen); - + this.walk(screen); this.autoMergeBatches(this._currComponent!); } @@ -738,7 +737,7 @@ export class UI { } private _releaseDescriptorSetCache (textureHash: number) { - if(this._descriptorSetCacheMap.has(textureHash)) { + if (this._descriptorSetCacheMap.has(textureHash)) { this._descriptorSetCacheMap.get(textureHash)!.forEach((value) => { DSPool.free(value); }); diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index 21e01fbbe3..db1d4641ae 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -562,11 +562,23 @@ export class Node extends BaseNode { */ public setPosition (x: number, y: number, z: number): void; - public setPosition (val: Vec3 | number, y?: number, z?: number) { - if (y === undefined || z === undefined) { + + /** + * @en Set position in local coordinate system + * @zh 设置本地坐标 + * @param x X axis position + * @param y Y axis position + */ + public setPosition (x: number, y: number): void; + + + public setPosition (val: Vec3 | number, y?: number, z?: number): void { + if (y === undefined && z === undefined) { Vec3.copy(this._lpos, val as Vec3); + } else if( z === undefined) { + Vec3.set(this._lpos, val as number, y!, this._lpos.z); } else { - Vec3.set(this._lpos, val as number, y, z); + Vec3.set(this._lpos, val as number, y!, z); } this.invalidateChildren(TransformBit.POSITION); @@ -627,7 +639,8 @@ export class Node extends BaseNode { * @param y Y axis rotation * @param z Z axis rotation */ - public setRotationFromEuler (x: number, y: number, z: number): void { + public setRotationFromEuler (x: number, y: number, z?: number): void { + if(z === undefined) z = this._euler.z; Vec3.set(this._euler, x, y, z); Quat.fromEuler(this._lrot, x, y, z); this._eulerDirty = false; @@ -666,11 +679,13 @@ export class Node extends BaseNode { * @param y Y axis scale * @param z Z axis scale */ - public setScale (x: number, y: number, z: number): void; + public setScale (x: number, y: number, z?: number): void; public setScale (val: Vec3 | number, y?: number, z?: number) { if (y === undefined || z === undefined) { Vec3.copy(this._lscale, val as Vec3); + } else if( z === undefined) { + Vec3.set(this._lscale, val as number, y, this._lscale.z); } else { Vec3.set(this._lscale, val as number, y, z); } diff --git a/cocos/core/utils/misc.ts b/cocos/core/utils/misc.ts index cdc86db7c9..1132bb6c7f 100644 --- a/cocos/core/utils/misc.ts +++ b/cocos/core/utils/misc.ts @@ -40,7 +40,7 @@ import { macro } from '../platform/macro'; export const BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/; const BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -const values = new Array(123); // max char code in base64Keys +const values:number[] = new Array(123); // max char code in base64Keys for (let i = 0; i < 123; ++i) { values[i] = 64; } // fill with placeholder('=') index for (let i = 0; i < 64; ++i) { values[BASE64_KEYS.charCodeAt(i)] = i; } diff --git a/cocos/tiledmap/assembler/index.ts b/cocos/tiledmap/assembler/index.ts new file mode 100644 index 0000000000..8370be79c4 --- /dev/null +++ b/cocos/tiledmap/assembler/index.ts @@ -0,0 +1,48 @@ +/* + 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. +*/ + +/** + * @packageDocumentation + * @hidden + */ + +import { IAssemblerManager } from '../../core/renderer/ui/base'; +import { TiledLayer } from '../tiled-layer'; +import { simple } from './simple'; + + +// Inline all type switch to avoid jit deoptimization during inlined function change + +const tiledLayerAssembler: IAssemblerManager = { + getAssembler () { + return simple; + }, +}; + +TiledLayer.Assembler = tiledLayerAssembler; + +export { + tiledLayerAssembler +}; diff --git a/cocos/tiledmap/assembler/simple.ts b/cocos/tiledmap/assembler/simple.ts new file mode 100644 index 0000000000..bdd4a1252e --- /dev/null +++ b/cocos/tiledmap/assembler/simple.ts @@ -0,0 +1,641 @@ +/* + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + https://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. +*/ + +/** + * @packageDocumentation + * @module ui-assembler + */ + +import { Mat4, Size, Vec3 } from '../../core/math'; +import { IAssembler } from '../../core/renderer/ui/base'; +import { MeshRenderData } from '../../core/renderer/ui/render-data'; +import { UI } from '../../core/renderer/ui/ui'; +import { TiledLayer, TiledMeshData, TiledTile } from '..'; +import { GID, MixedGID, RenderOrder, TiledGrid, TileFlag } from '../../tiledmap/tiled-types'; +import { Texture2D, Node } from '../../core'; + + +const MaxGridsLimit = Math.ceil(65535 / 6); + +const vec3_temps: Vec3[] = []; +for (let i = 0; i < 4; i++) { + vec3_temps.push(new Vec3()); +} + +const _mat4_temp = new Mat4(); +const _vec3u_temp = new Vec3(); +const _leftDown = { row: 0, col: 0 }; +let _uva = { x: 0, y: 0 }; +let _uvb = { x: 0, y: 0 }; +let _uvc = { x: 0, y: 0 }; +let _uvd = { x: 0, y: 0 }; + +let _renderData: { renderData: MeshRenderData, texture: Texture2D | null } | null; +let _fillGrids = 0; +let _vfOffset = 0; +let _moveX = 0; +let _moveY = 0; + + +let flipTexture: (grid: TiledGrid, gid: MixedGID) => void; + +/** + * simple 组装器 + * 可通过 `UI.simple` 获取该组装器。 + */ +export const simple: IAssembler = { + createData (layer: TiledLayer) { + + const renderData = layer.requestMeshRenderData(); + const maxGrids = layer.rightTop.col * layer.rightTop.row; + if (maxGrids * 4 > 65535) { + console.error(`Vertex count exceeds 65535`); + } + return renderData; + }, + + updateRenderData (comp: TiledLayer, ui: UI) { + + comp.updateCulling(); + const renderData = comp.meshRenderDataArray![0]; + + _moveX = comp.leftDownToCenterX; + _moveY = comp.leftDownToCenterY; + _renderData = renderData as TiledMeshData; + + if (comp.colorChanged || comp.isCullingDirty() || comp.isUserNodeDirty() || comp.hasAnimation() || comp.hasTiledNode()) { + comp.colorChanged = false; + + comp.resetRenderData(); + + let leftDown: { col: number, row: number }; + let rightTop: { col: number, row: number }; + if (comp.enableCulling) { + const cullingRect = comp.cullingRect; + leftDown = cullingRect.leftDown; + rightTop = cullingRect.rightTop; + } else { + leftDown = _leftDown; + rightTop = comp.rightTop; + } + + switch (comp.renderOrder) { + // left top to right down, col add, row sub, + case RenderOrder.RightDown: + traverseGrids(leftDown, rightTop, -1, 1, comp); + break; + // right top to left down, col sub, row sub + case RenderOrder.LeftDown: + traverseGrids(leftDown, rightTop, -1, -1, comp); + break; + // left down to right up, col add, row add + case RenderOrder.RightUp: + traverseGrids(leftDown, rightTop, 1, 1, comp); + break; + // right down to left up, col sub, row add + case RenderOrder.LeftUp: + traverseGrids(leftDown, rightTop, 1, -1, comp); + break; + } + comp.setCullingDirty(false); + comp.setUserNodeDirty(false); + + } + + _renderData = null; + + }, + + updateColor (tiled: TiledLayer) { + + const color = tiled.color; + const colorV = new Float32Array(4); + colorV[0] = color.r / 255; + colorV[1] = color.g / 255; + colorV[2] = color.b / 255; + colorV[0] = color.a / 255; + const rs = tiled.meshRenderDataArray; + if (rs) { + for (const r of rs) { + if(!(r as any).renderData) continue; + const renderData = (r as any).renderData; + const vs = renderData.vData; + for (let i = renderData.vertexStart, l = renderData.vertexCount; i < l; i++) { + vs.set(colorV, i * 9 + 5); + } + } + } + }, + + fillBuffers (layer: TiledLayer, renderer: UI) { + if (!layer || !layer.meshRenderDataArray) return; + + const dataArray = layer.meshRenderDataArray!; + const node = layer.node; + + let buffer = renderer.currBufferBatch!; + let vertexOffset = buffer.byteOffset >> 2; + let indicesOffset = buffer.indicesOffset; + let vertexId = buffer.vertexOffset; + + // 当前渲染的数据 + const data = dataArray[layer._meshRenderDataArrayIdx] as TiledMeshData; + const renderData = data.renderData; + + const isRecreate = buffer.request(renderData.vertexCount, renderData.indicesCount); + if (!isRecreate) { + buffer = renderer.currBufferBatch!; + vertexOffset = 0; + indicesOffset = 0; + vertexId = 0; + } + + const vBuf = buffer.vData!; + const iBuf = buffer.iData!; + const matrix = node.worldMatrix; + + const srcVBuf = renderData.vData; + const srcVIdx = renderData.vertexStart; + + // copy all vertexData + vBuf.set(srcVBuf.slice(srcVIdx, srcVIdx + renderData.vertexCount * 9), vertexOffset); + for (let i = 0; i < renderData.vertexCount; i++) { + const pOffset = vertexOffset + i * 9; + _vec3u_temp.set(vBuf[pOffset], vBuf[pOffset + 1], vBuf[pOffset + 2]); + _vec3u_temp.transformMat4(matrix); + vBuf[pOffset] = _vec3u_temp.x; + vBuf[pOffset + 1] = _vec3u_temp.y; + vBuf[pOffset + 2] = _vec3u_temp.z; + } + + const quadCount = renderData.vertexCount / 4; + for (let i = 0; i < quadCount; i += 1) { + iBuf[indicesOffset] = vertexId; + iBuf[indicesOffset + 1] = vertexId + 1; + iBuf[indicesOffset + 2] = vertexId + 2; + iBuf[indicesOffset + 3] = vertexId + 2; + iBuf[indicesOffset + 4] = vertexId + 1; + iBuf[indicesOffset + 5] = vertexId + 3; + indicesOffset += 6; + vertexId += 4; + } + } +}; + + +/* +texture coordinate +a c +b d +*/ +function _flipTexture (inGrid: TiledGrid, gid: MixedGID) { + if (inGrid._rotated) { + // 2:b 1:a + // 4:d 3:c + _uva.x = inGrid.r; + _uva.y = inGrid.t; + _uvb.x = inGrid.l; + _uvb.y = inGrid.t; + _uvc.x = inGrid.r; + _uvc.y = inGrid.b; + _uvd.x = inGrid.l; + _uvd.y = inGrid.b; + } else { + // 1:a 3:c + // 2:b 4:d + _uva.x = inGrid.l; + _uva.y = inGrid.t; + _uvb.x = inGrid.l; + _uvb.y = inGrid.b; + _uvc.x = inGrid.r; + _uvc.y = inGrid.t; + _uvd.x = inGrid.r; + _uvd.y = inGrid.b; + } + + let tempVal; + + // vice + if (((gid as unknown as number) & TileFlag.DIAGONAL) >>> 0) { + tempVal = _uvb; + _uvb = _uvc; + _uvc = tempVal; + } + + // flip x + if (((gid as unknown as number) & TileFlag.HORIZONTAL) >>> 0) { + tempVal = _uva; + _uva = _uvc; + _uvc = tempVal; + + tempVal = _uvb; + _uvb = _uvd; + _uvd = tempVal; + } + + // flip y + if (((gid as unknown as number) & TileFlag.VERTICAL) >>> 0) { + tempVal = _uva; + _uva = _uvb; + _uvb = tempVal; + + tempVal = _uvc; + _uvc = _uvd; + _uvd = tempVal; + } +} + +/* +texture coordinate + a +b c + d +*/ +function _flipDiamondTileTexture (inGrid: TiledGrid, gid: MixedGID) { + if (inGrid._rotated) { + // 2:b + // 4:d 1:a + // 3:c + _uva.x = inGrid.r; + _uva.y = inGrid.cy; + _uvb.x = inGrid.cx; + _uvb.y = inGrid.t; + _uvc.x = inGrid.cx; + _uvc.y = inGrid.b; + _uvd.x = inGrid.l; + _uvd.y = inGrid.cy; + } else { + // 1:a + // 2:b 3:c + // 4:d + _uva.x = inGrid.cx; + _uva.y = inGrid.t; + _uvb.x = inGrid.l; + _uvb.y = inGrid.cy; + _uvc.x = inGrid.r; + _uvc.y = inGrid.cy; + _uvd.x = inGrid.cx; + _uvd.y = inGrid.b; + } + + let tempVal; + + // vice + if (((gid as unknown as number) & TileFlag.DIAGONAL) >>> 0) { + tempVal = _uva; + _uva = _uvb; + _uvb = tempVal; + + tempVal = _uvc; + _uvc = _uvd; + _uvd = tempVal; + } + + // flip x + if (((gid as unknown as number) & TileFlag.HORIZONTAL) >>> 0) { + tempVal = _uvb; + _uvb = _uvc; + _uvc = tempVal; + } + + // flip y + if (((gid as unknown as number) & TileFlag.VERTICAL) >>> 0) { + tempVal = _uva; + _uva = _uvd; + _uvd = tempVal; + } +} + +function switchRenderData (curTexIdx: Texture2D | null, grid: TiledGrid, comp: TiledLayer) { + // need flush + if (!curTexIdx) curTexIdx = grid.texture; + if (!_renderData!.texture) { + _renderData!.texture = curTexIdx; + } + // update material + _renderData = comp.requestMeshRenderData(); + _renderData.texture = grid.texture; +} + +function _renderNodes (row: number, col: number, comp: TiledLayer) { + const nodesInfo = comp.getNodesByRowCol(row, col); + if (!nodesInfo || nodesInfo.count === 0) return; + + +} + + +// rowMoveDir is -1 or 1, -1 means decrease, 1 means increase +// colMoveDir is -1 or 1, -1 means decrease, 1 means increase +function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: number, row: number }, + rowMoveDir: number, colMoveDir: number, comp: TiledLayer) { + + // show nothing + if (rightTop.row < 0 || rightTop.col < 0) return; + + let vertexBuf: Float32Array = _renderData!.renderData.vData; + // let idxBuf: Uint16Array = _renderData!.renderData.iData; + + _fillGrids = 0; + _vfOffset = 0; + + const tiledTiles = comp.tiledTiles; + + + const texGrids = comp.texGrids!; + const tiles = comp.tiles; + + const vertStep = 9; + const vertStep2 = vertStep * 2; + const vertStep3 = vertStep * 3; + + const vertices = comp.vertices; + let rowData: { [key: number]: { left: number, bottom: number; index: number }, maxCol: number, minCol: number }; + let col: number; + let cols: number; + let row: number; + let rows: number; + let colData: { left: number, bottom: number, index: number }; + let tileSize: Size; + let grid: TiledGrid | undefined; + let gid: MixedGID = 0 as unknown as any; + let left = 0; + let bottom = 0; + let right = 0; + let top = 0; // x, y + let tiledNode: TiledTile | null; + let curTexIdx: Texture2D | null = null; + let colNodesCount = 0; + let checkColRange = true; + + const diamondTile = false; // TODO:comp._diamondTile; + + flipTexture = diamondTile ? _flipDiamondTileTexture : _flipTexture; + + const color: Float32Array = new Float32Array(4); + color[0] = comp.color.r / 255; + color[1] = comp.color.g / 255; + color[2] = comp.color.b / 255; + color[3] = comp.color.a / 255; + + if (rowMoveDir === -1) { + row = rightTop.row; + rows = leftDown.row; + } else { + row = leftDown.row; + rows = rightTop.row; + } + + // traverse row + for (; (rows - row) * rowMoveDir >= 0; row += rowMoveDir) { + rowData = vertices[row]; + colNodesCount = comp.getNodesCountByRow(row); + checkColRange = rowData && colNodesCount === 0; + + // limit min col and max col + if (colMoveDir === 1) { + col = checkColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col; + cols = checkColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col; + } else { + col = checkColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col; + cols = checkColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col; + } + + // traverse col + for (; (cols - col) * colMoveDir >= 0; col += colMoveDir) { + + colData = rowData && rowData[col]; + if (!colData) { + // only render users nodes because map data is empty + if (colNodesCount > 0) { + const nodes = comp.requestSubNodesData(); + const celData = comp.getNodesByRowCol(row, col); + if(celData) { + nodes.subNodes = comp.getNodesByRowCol(row, col)!.list; + curTexIdx = null; + _renderData = comp.requestMeshRenderData(); + } + } + continue; + } + + gid = tiles[colData.index]; + grid = texGrids.get((((gid as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0) as unknown as GID); + if (!grid) continue; + + // check init or new material + if (curTexIdx !== grid.texture) { + switchRenderData(curTexIdx, grid, comp); + curTexIdx = grid.texture; + } + + tileSize = grid.tileset._tileSize; + + // calc rect vertex + left = colData.left - _moveX; + bottom = colData.bottom - _moveY; + right = left + tileSize.width; + top = bottom + tileSize.height; + + // begin to fill vertex buffer + tiledNode = tiledTiles[colData.index]; + + _renderData!.renderData.reserve(4, 0); + _vfOffset = _renderData!.renderData.vertexCount * 9; + vertexBuf = _renderData!.renderData.vData; + if (!tiledNode) { + if (diamondTile) { + const centerX = (left + right) / 2; + const centerY = (top + bottom) / 2; + // ct + vertexBuf[_vfOffset] = centerX; + vertexBuf[_vfOffset + 1] = top; + + // lc + vertexBuf[_vfOffset + vertStep] = left; + vertexBuf[_vfOffset + vertStep + 1] = centerY; + + // rc + vertexBuf[_vfOffset + vertStep2] = right; + vertexBuf[_vfOffset + vertStep2 + 1] = centerY; + + // cb + vertexBuf[_vfOffset + vertStep3] = centerX; + vertexBuf[_vfOffset + vertStep3 + 1] = bottom; + } else { + // lt + vertexBuf[_vfOffset] = left; + vertexBuf[_vfOffset + 1] = top; + + // lb + vertexBuf[_vfOffset + vertStep] = left; + vertexBuf[_vfOffset + vertStep + 1] = bottom; + + // rt + vertexBuf[_vfOffset + vertStep2] = right; + vertexBuf[_vfOffset + vertStep2 + 1] = top; + + // rb + vertexBuf[_vfOffset + vertStep3] = right; + vertexBuf[_vfOffset + vertStep3 + 1] = bottom; + } + + vertexBuf.set(color, _vfOffset + 5); + vertexBuf.set(color, _vfOffset + vertStep + 5); + vertexBuf.set(color, _vfOffset + vertStep2 + 5); + vertexBuf.set(color, _vfOffset + vertStep3 + 5); + } else { + fillByTiledNode(tiledNode.node, color, vertexBuf, left, right, top, bottom, diamondTile); + } + + flipTexture(grid, gid); + + // lt/ct -> a + vertexBuf[_vfOffset + 3] = _uva.x; + vertexBuf[_vfOffset + 4] = _uva.y; + + // lb/lc -> b + vertexBuf[_vfOffset + vertStep + 3] = _uvb.x; + vertexBuf[_vfOffset + vertStep + 4] = _uvb.y; + + // rt/rc -> c + vertexBuf[_vfOffset + vertStep2 + 3] = _uvc.x; + vertexBuf[_vfOffset + vertStep2 + 4] = _uvc.y; + + // rt/cb -> d + vertexBuf[_vfOffset + vertStep3 + 3] = _uvd.x; + vertexBuf[_vfOffset + vertStep3 + 4] = _uvd.y; + + _fillGrids++; + + _renderData!.renderData.advance(4, 6); + + + // check render users node + // if (colNodesCount > 0) _renderNodes(row, col); + + // vertices count exceed 66635, buffer must be switched + if (_fillGrids >= MaxGridsLimit) { + switchRenderData(curTexIdx, grid, comp); + curTexIdx = grid.texture; + } + } + } +} + + +function fillByTiledNode (tiledNode: Node, color: Float32Array, vbuf: Float32Array, + left: number, right: number, top: number, bottom: number, diamondTile: boolean) { + const vertStep = 9; + const vertStep2 = vertStep * 2; + const vertStep3 = vertStep * 3; + + tiledNode.updateWorldTransform(); + + Mat4.copy(_mat4_temp, tiledNode.matrix); + Vec3.set(_vec3u_temp, -(left + _moveX), -(bottom + _moveY), 0); + Mat4.transform(_mat4_temp, _mat4_temp, _vec3u_temp); + const m = _mat4_temp; + const tx = m.m12; + const ty = m.m13; + + const a = m.m00; + const b = m.m01; + const c = m.m04; + const d = m.m05; + + const justTranslate = a === 1 && b === 0 && c === 0 && d === 1; + + if (diamondTile) { + const centerX = (left + right) / 2; + const centerY = (top + bottom) / 2; + if (justTranslate) { + // ct + vbuf[_vfOffset] = centerX + tx; + vbuf[_vfOffset + 1] = top + ty; + + // lc + vbuf[_vfOffset + vertStep] = left + tx; + vbuf[_vfOffset + vertStep + 1] = centerY + ty; + + // rc + vbuf[_vfOffset + vertStep2] = right + tx; + vbuf[_vfOffset + vertStep2 + 1] = centerY + ty; + + // cb + vbuf[_vfOffset + vertStep3] = centerX + tx; + vbuf[_vfOffset + vertStep3 + 1] = bottom + ty; + } else { + // ct + vbuf[_vfOffset] = centerX * a + top * c + tx; + vbuf[_vfOffset + 1] = centerX * b + top * d + ty; + + // lc + vbuf[_vfOffset + vertStep] = left * a + centerY * c + tx; + vbuf[_vfOffset + vertStep + 1] = left * b + centerY * d + ty; + + // rc + vbuf[_vfOffset + vertStep2] = right * a + centerY * c + tx; + vbuf[_vfOffset + vertStep2 + 1] = right * b + centerY * d + ty; + + // cb + vbuf[_vfOffset + vertStep3] = centerX * a + bottom * c + tx; + vbuf[_vfOffset + vertStep3 + 1] = centerX * b + bottom * d + ty; + } + } else if (justTranslate) { + vbuf[_vfOffset] = left + tx; + vbuf[_vfOffset + 1] = top + ty; + + vbuf[_vfOffset + vertStep] = left + tx; + vbuf[_vfOffset + vertStep + 1] = bottom + ty; + + vbuf[_vfOffset + vertStep2] = right + tx; + vbuf[_vfOffset + vertStep2 + 1] = top + ty; + + vbuf[_vfOffset + vertStep3] = right + tx; + vbuf[_vfOffset + vertStep3 + 1] = bottom + ty; + } else { + // lt + vbuf[_vfOffset] = left * a + top * c + tx; + vbuf[_vfOffset + 1] = left * b + top * d + ty; + + // lb + vbuf[_vfOffset + vertStep] = left * a + bottom * c + tx; + vbuf[_vfOffset + vertStep + 1] = left * b + bottom * d + ty; + + // rt + vbuf[_vfOffset + vertStep2] = right * a + top * c + tx; + vbuf[_vfOffset + vertStep2 + 1] = right * b + top * d + ty; + + // rb + vbuf[_vfOffset + vertStep3] = right * a + bottom * c + tx; + vbuf[_vfOffset + vertStep3 + 1] = right * b + bottom * d + ty; + } + + vbuf.set(color, _vfOffset + 5); + vbuf.set(color, _vfOffset + vertStep + 5); + vbuf.set(color, _vfOffset + vertStep2 + 5); + vbuf.set(color, _vfOffset + vertStep3 + 5); +} diff --git a/cocos/tiledmap/index.ts b/cocos/tiledmap/index.ts new file mode 100644 index 0000000000..0ecd8dd1b4 --- /dev/null +++ b/cocos/tiledmap/index.ts @@ -0,0 +1,31 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + +export * from './tiled-map'; +export * from './tiled-map-asset'; +export * from './tiled-layer'; +export * from './tiled-object-group'; +export * from './tiled-tile'; +export * from './assembler'; \ No newline at end of file diff --git a/cocos/tiledmap/tiled-layer.ts b/cocos/tiledmap/tiled-layer.ts new file mode 100644 index 0000000000..70863bf002 --- /dev/null +++ b/cocos/tiledmap/tiled-layer.ts @@ -0,0 +1,1449 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + +/** + * @packageDocumentation + * @module ui + */ + +import { ccclass } from 'cc.decorator'; + +import { UIRenderable } from '../core/components/ui-base/ui-renderable'; +import { Component } from '../core/components'; +import visibleRect from '../core/platform/visible-rect'; +import { TMXMapInfo } from './tmx-xml-parser'; +import { Color, IVec2Like, Mat4, Size, SpriteFrame, SystemEventType, Texture2D, Vec2, Vec3, Node, warn, logID, CCBoolean } from '../core'; +import { TiledTile } from './tiled-tile'; +import { EDITOR } from 'internal:constants'; +import { MeshRenderData } from '../core/renderer/ui/render-data'; +import { UI } from '../core/renderer/ui/ui'; +import { + MixedGID, GID, Orientation, TiledTextureGrids, TMXTilesetInfo, RenderOrder, StaggerAxis, StaggerIndex, TileFlag, + GIDFlags, TiledGrid, TiledAnimationType, PropertiesInfo, TMXLayerInfo +} from './tiled-types'; +import { fillTextureGrids, loadAllTextures } from './tiled-utils'; + +const _mat4_temp = new Mat4(); +const _vec2_temp = new Vec2(); +const _vec3_temp = new Vec3(); +const _vec3_temp2 = new Vec3(); +const _tempRowCol = { row: 0, col: 0 }; + +@ccclass('cc.TiledUserNodeData') +export class TiledUserNodeData extends Component { + _index = -1; + _row = -1; + _col = -1; + _tiledLayer: TiledLayer | null = null; + constructor () { + super(); + } +} + +export interface TiledMeshData { + renderData: MeshRenderData; + texture: Texture2D | null; +} + +interface TiledSubNodeData { + subNodes: (null|TiledUserNodeData)[] ; +} + +type TiledMeshDataArray = (TiledMeshData |TiledSubNodeData)[]; + +/** + * !#en Render the TMX layer. + * !#zh 渲染 TMX layer。 + * @class TiledLayer + * @extends Component + */ +@ccclass('cc.TiledLayer') +export class TiledLayer extends UIRenderable { + + // [row][col] = {count: 0, nodesList: []}; + protected _userNodeGrid: { [key: number]: { count: number;[key: number]: { count: number, list: (TiledUserNodeData | null)[] } } } = {}; + protected _userNodeMap: { [key: string]: TiledUserNodeData } = {};// [id] = node; + protected _userNodeDirty = false; + + // store the layer tiles node, index is caculated by 'x + width * y', format likes '[0]=tileNode0,[1]=tileNode1, ...' + public tiledTiles: (TiledTile | null)[] = []; + + // // store the layer tilesets index array + // _tilesetIndexArr: number[] = []; + // // tileset index to array index + // _tilesetIndexToArrIndex: { [key: number]: number } = {}; + + protected _viewPort = { x: -1, y: -1, width: -1, height: -1 }; + protected _cullingRect = { + leftDown: { row: -1, col: -1 }, + rightTop: { row: -1, col: -1 } + }; + get cullingRect () { return this._cullingRect; } + + protected _cullingDirty = true; + protected _rightTop = { row: -1, col: -1 }; + get rightTop () { return this._rightTop; } + + protected _layerInfo: TMXLayerInfo | null = null; + protected _mapInfo: TMXMapInfo | null = null; + + // record max or min tile texture offset, + // it will make culling rect more large, which insure culling rect correct. + protected _topOffset = 0; + protected _downOffset = 0; + protected _leftOffset = 0; + protected _rightOffset = 0; + + // store the layer tiles, index is caculated by 'x + width * y', format likes '[0]=gid0,[1]=gid1, ...' + public tiles: MixedGID[] = []; + + // vertex array + public vertices: { minCol: number, maxCol: number, [key: number]: { left: number, bottom: number, index: number } }[] = []; + // vertices dirty + protected _verticesDirty = true; + + protected _layerName = ''; + protected _layerSize?: Size; + + get layerSize () { return this._layerSize!; } + + protected _minGID?: GID; + protected _maxGID?: GID; + protected _layerOrientation: null | Orientation = null; + + protected _opacity?: number; + protected _tintColor?: Color; + + // store all layer gid corresponding texture info, index is gid, format likes '[gid0]=tex-info,[gid1]=tex-info, ...' + public texGrids: TiledTextureGrids | null = null; + // store all tileset texture, index is tileset index, format likes '[0]=texture0, [1]=texture1, ...' + protected _textures: SpriteFrame[] = []; + protected _tilesets: TMXTilesetInfo[] = []; + + protected _leftDownToCenterX = 0; + protected _leftDownToCenterY = 0; + + protected _hasTiledNodeGrid = false; + protected _hasAniGrid = false; + protected _animations: TiledAnimationType | null = null; + + // switch of culling + protected _enableCulling?: boolean; + + public colorChanged = false; + + protected _properties?: PropertiesInfo; + public renderOrder?: RenderOrder; + protected _staggerAxis?: StaggerAxis; + protected _staggerIndex?: StaggerIndex; + protected _hexSideLength?: number; + + protected _mapTileSize?: Size; + protected _odd_even?: number; + protected _diffX1?: number; + protected _diffY1?: number; + protected _useAutomaticVertexZ?: boolean; + protected _vertexZvalue?: number; + protected _offset?: Vec2; + + protected _meshRenderDataArray: TiledMeshDataArray | null = null; + + get meshRenderDataArray () { return this._meshRenderDataArray; }; + get leftDownToCenterX () { return this._leftDownToCenterX; } + get leftDownToCenterY () { return this._leftDownToCenterY; } + + constructor () { + super(); + } + + public hasTiledNode () { + return this._hasTiledNodeGrid; + } + + public hasAnimation () { + return this._hasAniGrid; + } + + /** + * !#en enable or disable culling + * !#zh 开启或关闭裁剪。 + * @method enableCulling + * @param value + */ + set enableCulling (value: boolean) { + if (this._enableCulling !== value) { + this._enableCulling = value; + this._cullingDirty = true; + } + } + get enableCulling () { return this._enableCulling!; } + + /** + * !#en Adds user's node into layer. + * !#zh 添加用户节点。 + * @method addUserNode + * @param {cc.Node} node + * @return {Boolean} + */ + public addUserNode (node: Node) { + let dataComp = node.getComponent(TiledUserNodeData); + if (dataComp) { + warn('CCTiledLayer:addUserNode node has been added'); + return false; + } + + dataComp = node.addComponent(TiledUserNodeData); + node.parent = this.node; + // node._renderFlag |= RenderFlow.FLAG_BREAK_FLOW; + this._userNodeMap[node.uuid] = dataComp; + + dataComp._row = -1; + dataComp._col = -1; + dataComp._tiledLayer = this; + + this._nodeLocalPosToLayerPos(node.getPosition(), _vec2_temp); + this._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol); + this._addUserNodeToGrid(dataComp, _tempRowCol); + this._updateCullingOffsetByUserNode(node); + node.on(SystemEventType.TRANSFORM_CHANGED, this._userNodePosChange, dataComp); + node.on(SystemEventType.SIZE_CHANGED, this._userNodeSizeChange, dataComp); + return true; + } + + /** + * !#en Removes user's node. + * !#zh 移除用户节点。 + * @method removeUserNode + * @param {cc.Node} node + * @return {Boolean} + */ + public removeUserNode (node: Node) { + const dataComp = node.getComponent(TiledUserNodeData); + if (!dataComp) { + warn('CCTiledLayer:removeUserNode node is not exist'); + return false; + } + node.off(SystemEventType.TRANSFORM_CHANGED, this._userNodePosChange, dataComp); + node.off(SystemEventType.SIZE_CHANGED, this._userNodeSizeChange, dataComp); + this._removeUserNodeFromGrid(dataComp); + delete this._userNodeMap[node.uuid]; + node._removeComponent(dataComp); + dataComp.destroy(); + node.removeFromParent(); + // node._renderFlag &= ~RenderFlow.FLAG_BREAK_FLOW; + return true; + } + + /** + * !#en Destroy user's node. + * !#zh 销毁用户节点。 + * @method destroyUserNode + * @param {cc.Node} node + */ + public destroyUserNode (node: Node) { + this.removeUserNode(node); + node.destroy(); + } + + // acording layer anchor point to calculate node layer pos + protected _nodeLocalPosToLayerPos (nodePos: IVec2Like, out: IVec2Like) { + out.x = nodePos.x + this._leftDownToCenterX; + out.y = nodePos.y + this._leftDownToCenterY; + } + + public getNodesByRowCol (row: number, col: number) { + const rowData = this._userNodeGrid[row]; + if (!rowData) return null; + return rowData[col]; + } + + public getNodesCountByRow (row) { + const rowData = this._userNodeGrid[row]; + if (!rowData) return 0; + return rowData.count; + } + + protected _updateAllUserNode () { + this._userNodeGrid = {}; + for (const dataId in this._userNodeMap) { + const dataComp = this._userNodeMap[dataId]; + this._nodeLocalPosToLayerPos(dataComp.node.getPosition(), _vec2_temp); + this._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol); + this._addUserNodeToGrid(dataComp, _tempRowCol); + this._updateCullingOffsetByUserNode(dataComp.node); + } + } + + protected _updateCullingOffsetByUserNode (node_: Node) { + const node = node_._uiProps.uiTransformComp!.contentSize; + if (this._topOffset < node.height) { + this._topOffset = node.height; + } + if (this._downOffset < node.height) { + this._downOffset = node.height; + } + if (this._leftOffset < node.width) { + this._leftOffset = node.width; + } + if (this._rightOffset < node.width) { + this._rightOffset = node.width; + } + } + + protected _userNodeSizeChange () { + const dataComp: TiledUserNodeData = this as unknown as any; + const node = dataComp.node; + const self = dataComp._tiledLayer!; + self._updateCullingOffsetByUserNode(node); + } + + protected _userNodePosChange () { + const dataComp: TiledUserNodeData = this as unknown as any; + const node = dataComp.node; + const self = dataComp._tiledLayer!; + self._nodeLocalPosToLayerPos(node.getPosition(), _vec2_temp); + self._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol); + self._limitInLayer(_tempRowCol); + // users pos not change + if (_tempRowCol.row === dataComp._row && _tempRowCol.col === dataComp._col) return; + + self._removeUserNodeFromGrid(dataComp); + self._addUserNodeToGrid(dataComp, _tempRowCol); + } + + protected _removeUserNodeFromGrid (dataComp: TiledUserNodeData) { + const row = dataComp._row; + const col = dataComp._col; + const index = dataComp._index; + + const rowData = this._userNodeGrid[row]; + const colData = rowData && rowData[col]; + if (colData) { + rowData.count--; + colData.count--; + colData.list[index] = null; + if (colData.count <= 0) { + colData.list.length = 0; + colData.count = 0; + } + } + + dataComp._row = -1; + dataComp._col = -1; + dataComp._index = -1; + this._userNodeDirty = true; + } + + protected _limitInLayer (rowCol: { row: number, col: number }) { + const row = rowCol.row; + const col = rowCol.col; + if (row < 0) rowCol.row = 0; + if (row > this._rightTop.row) rowCol.row = this._rightTop.row; + if (col < 0) rowCol.col = 0; + if (col > this._rightTop.col) rowCol.col = this._rightTop.col; + } + + protected _addUserNodeToGrid (dataComp: TiledUserNodeData, tempRowCol: { col: number, row: number }) { + const row = tempRowCol.row; + const col = tempRowCol.col; + const rowData = this._userNodeGrid[row] = this._userNodeGrid[row] || { count: 0 }; + const colData = rowData[col] = rowData[col] || { count: 0, list: [] }; + dataComp._row = row; + dataComp._col = col; + dataComp._index = colData.list.length; + rowData.count++; + colData.count++; + colData.list.push(dataComp); + this._userNodeDirty = true; + } + + public isUserNodeDirty () { + return this._userNodeDirty; + } + + public setUserNodeDirty (value) { + this._userNodeDirty = value; + } + + onEnable () { + super.onEnable() + this.node.on(SystemEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this); + this.markForUpdateRenderData(); + } + + onDisable () { + super.onDisable(); + this.node.off(SystemEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this); + } + + protected _syncAnchorPoint () { + const node = this.node; + const trans = node._uiProps.uiTransformComp!; + const scale = node.getScale(); + this._leftDownToCenterX = trans.width * trans.anchorX * scale.x; + this._leftDownToCenterY = trans.height * trans.anchorY * scale.y; + this._cullingDirty = true; + this.markForUpdateRenderData(); + } + + onDestroy () { + super.onDestroy(); + } + + /** + * !#en Gets the layer name. + * !#zh 获取层的名称。 + * @method getLayerName + * @return {String} + * @example + * let layerName = tiledLayer.getLayerName(); + * cc.log(layerName); + */ + public getLayerName (): string { + return this._layerName; + } + + /** + * !#en Set the layer name. + * !#zh 设置层的名称 + * @method SetLayerName + * @param {String} layerName + * @example + * tiledLayer.setLayerName("New Layer"); + */ + public setLayerName (layerName: string) { + this._layerName = layerName; + } + + /** + * !#en Return the value for the specific property name. + * !#zh 获取指定属性名的值。 + * @method getProperty + * @param {String} propertyName + * @return {*} + * @example + * let property = tiledLayer.getProperty("info"); + * cc.log(property); + */ + public getProperty (propertyName: string) { + return this._properties![propertyName]; + } + + /** + * !#en Returns the position in pixels of a given tile coordinate. + * !#zh 获取指定 tile 的像素坐标。 + * @method getPositionAt + * @param {Vec2|Number} pos position or x + * @param {Number} [y] + * @return {Vec2} + * @example + * let pos = tiledLayer.getPositionAt(cc.v2(0, 0)); + * cc.log("Pos: " + pos); + * let pos = tiledLayer.getPositionAt(0, 0); + * cc.log("Pos: " + pos); + */ + public getPositionAt (pos: IVec2Like | number, y?: number): Vec2 | null { + let x; + if (y !== undefined) { + x = Math.floor(pos as number); + y = Math.floor(y); + } + else { + x = Math.floor((pos as IVec2Like).x); + y = Math.floor((pos as IVec2Like).y); + } + + switch (this._layerOrientation) { + case Orientation.ORTHO: + return this._positionForOrthoAt(x, y); + case Orientation.ISO: + return this._positionForIsoAt(x, y); + case Orientation.HEX: + return this._positionForHexAt(x, y); + } + return null; + } + + public isInvalidPosition (x: number, y: number) { + return x >= this._layerSize!.width || y >= this._layerSize!.height || x < 0 || y < 0; + } + + protected _positionForIsoAt (x: number, y: number): Vec2 { + let offsetX = 0; + let offsetY = 0; + const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width; + const gidAndFlags = this.tiles[index]; + if (gidAndFlags) { + const gid = (((gidAndFlags as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0); + const tileset = this.texGrids!.get(gid as unknown as GID)!.tileset; + const offset = tileset.tileOffset; + offsetX = offset.x; + offsetY = offset.y; + } + + return new Vec2( + this._mapTileSize!.width * 0.5 * (this._layerSize!.height + x - y - 1) + offsetX, + this._mapTileSize!.height * 0.5 * (this._layerSize!.width - x + this._layerSize!.height - y - 2) - offsetY + ); + } + + protected _positionForOrthoAt (x: number, y: number): Vec2 { + let offsetX = 0; + let offsetY = 0; + const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width; + const gidAndFlags = this.tiles[index]; + if (gidAndFlags) { + const gid = (((gidAndFlags as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0) as unknown as GID; + const tileset = this.texGrids!.get(gid)!.tileset; + const offset = tileset.tileOffset; + offsetX = offset.x; + offsetY = offset.y; + } + + return new Vec2( + x * this._mapTileSize!.width + offsetX, + (this._layerSize!.height - y - 1) * this._mapTileSize!.height - offsetY + ); + } + + protected _positionForHexAt (col: number, row: number): Vec2 { + const tileWidth = this._mapTileSize!.width; + const tileHeight = this._mapTileSize!.height; + const rows = this._layerSize!.height; + + const index = Math.floor(col) + Math.floor(row) * this._layerSize!.width; + const gid = ((this.tiles[index] as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0; + let offset; + if (this.texGrids!.get(gid as unknown as GID)) { + offset = this.texGrids!.get(gid as unknown as GID)!.tileset.tileOffset; + } else { + offset = { x: 0, y: 0 } + } + + const odd_even = (this._staggerIndex === StaggerIndex.STAGGERINDEX_ODD) ? 1 : -1; + let x = 0; + let y = 0; + let diffX = 0; + let diffY = 0; + switch (this._staggerAxis) { + case StaggerAxis.STAGGERAXIS_Y: + diffX = 0; + if (row % 2 === 1) { + diffX = tileWidth / 2 * odd_even; + } + x = col * tileWidth + diffX + offset.x; + y = (rows - row - 1) * (tileHeight - (tileHeight - this._hexSideLength!) / 2) - offset.y; + break; + case StaggerAxis.STAGGERAXIS_X: + diffY = 0; + if (col % 2 === 1) { + diffY = tileHeight / 2 * -odd_even; + } + x = col * (tileWidth - (tileWidth - this._hexSideLength!) / 2) + offset.x; + y = (rows - row - 1) * tileHeight + diffY - offset.y; + break; + } + return new Vec2(x, y); + } + + /** + * !#en + * Sets the tiles gid (gid = tile global id) at a given tiles rect. + * !#zh + * 设置给定区域的 tile 的 gid (gid = tile 全局 id), + * @method setTilesGIDAt + * @param {Array} gids an array contains gid + * @param {Number} beginCol begin col number + * @param {Number} beginRow begin row number + * @param {Number} totalCols count of column + * @example + * tiledLayer.setTilesGIDAt([1, 1, 1, 1], 10, 10, 2) + */ + public setTilesGIDAt (gids: number[], beginCol: number, beginRow: number, totalCols: number) { + if (!gids || gids.length === 0 || totalCols <= 0) return; + if (beginRow < 0) beginRow = 0; + if (beginCol < 0) beginCol = 0; + let gidsIdx = 0; + const endCol = beginCol + totalCols; + for (let row = beginRow; ; row++) { + for (let col = beginCol; col < endCol; col++) { + if (gidsIdx >= gids.length) return; + this._updateTileForGID(gids[gidsIdx] as unknown as MixedGID, col, row); + gidsIdx++; + } + } + } + + /** + * !#en + * Sets the tile gid (gid = tile global id) at a given tile coordinate.
+ * The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.
+ * If a tile is already placed at that position, then it will be removed. + * !#zh + * 设置给定坐标的 tile 的 gid (gid = tile 全局 id), + * tile 的 GID 可以使用方法 “tileGIDAt” 来获得。
+ * 如果一个 tile 已经放在那个位置,那么它将被删除。 + * @method setTileGIDAt + * @param {Number} gid + * @param {Vec2|Number} posOrX position or x + * @param {Number} flagsOrY flags or y + * @param {Number} [flags] + * @example + * tiledLayer.setTileGIDAt(1001, 10, 10, 1) + */ + public setTileGIDAt (gid: MixedGID, x: number, y: number, flags?: number) { + + const ugid = ((gid as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0; + + x = Math.floor(x); + y = Math.floor(y); + if (this.isInvalidPosition(x, y)) { + throw new Error('cc.TiledLayer.setTileGIDAt(): invalid position'); + } + if (!this.tiles || !this._tilesets || this._tilesets.length === 0) { + logID(7238); + return; + } + if (ugid !== 0 && ugid < (this._tilesets[0].firstGid as unknown as number)) { + logID(7239, gid); + return; + } + + flags = flags || 0; + this._updateTileForGID(((ugid | flags) >>> 0) as unknown as MixedGID, x, y); + } + + protected _updateTileForGID (gidAndFlags: MixedGID, x: number, y: number): void { + const idx = 0 | (x + y * this._layerSize!.width); + if (idx >= this.tiles.length) return; + + const oldGIDAndFlags = this.tiles[idx]; + if (gidAndFlags === oldGIDAndFlags) return; + + const gid = (((gidAndFlags as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0); + const grid = this.texGrids!.get(gid as unknown as GID); + + if (grid) { + this.tiles[idx] = gidAndFlags; + this._updateVertex(x, y); + } else { + this.tiles[idx] = 0 as unknown as MixedGID; + } + this._cullingDirty = true; + } + + /** + * !#en + * Returns the tile gid at a given tile coordinate.
+ * if it returns 0, it means that the tile is empty.
+ * !#zh + * 通过给定的 tile 坐标、flags(可选)返回 tile 的 GID.
+ * 如果它返回 0,则表示该 tile 为空。
+ * @method getTileGIDAt + * @param {Vec2} pos + * @return {Number} + * @example + * let tileGid = tiledLayer.getTileGIDAt(0, 0); + */ + public getTileGIDAt (x: number, y: number): number | null { + if (this.isInvalidPosition(x, y)) { + throw new Error('cc.TiledLayer.getTileGIDAt(): invalid position'); + } + if (!this.tiles) { + logID(7237); + return null; + } + + const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width; + // Bits on the far end of the 32-bit global tile ID are used for tile flags + const tile = this.tiles[index] as unknown as number; + + return ((tile & TileFlag.FLIPPED_MASK) >>> 0); + } + /** + * !#en + * Returns the tile flags at a given tile coordinate.
+ * !#zh + * 通过给定的 tile 坐标, 返回 tile 的 flags.
+ * 如果它返回 null,则表示该 tile 为空。
+ * @method getTileGIDAt + * @param {number}} x + * @param {number}} y + * @return {Number} + * @example + * let tileGid = tiledLayer.getTileGIDAt(0, 0); + */ + public getTileFlagsAt (x:number, y:number) { + + if (this.isInvalidPosition(x, y)) { + throw new Error('TiledLayer.getTileFlagsAt: invalid position'); + } + if (!this.tiles) { + logID(7240); + return null; + } + + const idx = Math.floor(x) + Math.floor(y) * this._layerSize!.width; + // Bits on the far end of the 32-bit global tile ID are used for tile flags + const tile = this.tiles[idx] as unknown as number; + + return ((tile & TileFlag.FLIPPED_ALL) >>> 0) as unknown as GIDFlags; + } + + public setCullingDirty (value: boolean) { + this._cullingDirty = value; + } + + public isCullingDirty (): boolean { + return this._cullingDirty; + } + + // 'x, y' is the position of viewPort, which's anchor point is at the center of rect. + // 'width, height' is the size of viewPort. + public updateViewPort (x: number, y: number, width: number, height: number): void { + if (this._viewPort.width === width && + this._viewPort.height === height && + this._viewPort.x === x && + this._viewPort.y === y) { + return; + } + this._viewPort.x = x; + this._viewPort.y = y; + this._viewPort.width = width; + this._viewPort.height = height; + + // if map's type is iso, reserve bottom line is 2 to avoid show empty grid because of iso grid arithmetic + let reserveLine = 1; + if (this._layerOrientation === Orientation.ISO) { + reserveLine = 2; + } + + const vpx = this._viewPort.x - this._offset!.x + this._leftDownToCenterX; + const vpy = this._viewPort.y - this._offset!.y + this._leftDownToCenterY; + + let leftDownX = vpx - this._leftOffset; + let leftDownY = vpy - this._downOffset; + const rightTopX = vpx + width + this._rightOffset; + const rightTopY = vpy + height + this._topOffset; + + const leftDown = this._cullingRect.leftDown; + const rightTop = this._cullingRect.rightTop; + + if (leftDownX < 0) leftDownX = 0; + if (leftDownY < 0) leftDownY = 0; + + // calc left down + this._positionToRowCol(leftDownX, leftDownY, _tempRowCol); + // make range large + _tempRowCol.row -= reserveLine; + _tempRowCol.col -= reserveLine; + // insure left down row col greater than 0 + _tempRowCol.row = _tempRowCol.row > 0 ? _tempRowCol.row : 0; + _tempRowCol.col = _tempRowCol.col > 0 ? _tempRowCol.col : 0; + + if (_tempRowCol.row !== leftDown.row || _tempRowCol.col !== leftDown.col) { + leftDown.row = _tempRowCol.row; + leftDown.col = _tempRowCol.col; + this._cullingDirty = true; + } + + // show nothing + if (rightTopX < 0 || rightTopY < 0) { + _tempRowCol.row = -1; + _tempRowCol.col = -1; + } else { + // calc right top + this._positionToRowCol(rightTopX, rightTopY, _tempRowCol); + // make range large + _tempRowCol.row++; + _tempRowCol.col++; + } + + // avoid range out of max rect + if (_tempRowCol.row > this._rightTop.row) _tempRowCol.row = this._rightTop.row; + if (_tempRowCol.col > this._rightTop.col) _tempRowCol.col = this._rightTop.col; + + if (_tempRowCol.row !== rightTop.row || _tempRowCol.col !== rightTop.col) { + rightTop.row = _tempRowCol.row; + rightTop.col = _tempRowCol.col; + this._cullingDirty = true; + } + } + + // the result may not precise, but it dose't matter, it just uses to be got range + protected _positionToRowCol (x: number, y: number, result: { col: number, row: number }): { col: number, row: number } { + + const maptw = this._mapTileSize!.width; + const mapth = this._mapTileSize!.height; + const maptw2 = maptw * 0.5; + const mapth2 = mapth * 0.5; + let row = 0; + let col = 0; + let diffX2 = 0; + let diffY2 = 0; + const axis = this._staggerAxis; + + switch (this._layerOrientation) { + // left top to right dowm + case Orientation.ORTHO: + col = Math.floor(x / maptw); + row = Math.floor(y / mapth); + break; + // right top to left down + // iso can be treat as special hex whose hex side length is 0 + case Orientation.ISO: + col = Math.floor(x / maptw2); + row = Math.floor(y / mapth2); + break; + // left top to right dowm + case Orientation.HEX: + if (axis === StaggerAxis.STAGGERAXIS_Y) { + row = Math.floor(y / (mapth - this._diffY1!)); + diffX2 = row % 2 === 1 ? maptw2 * this._odd_even! : 0; + col = Math.floor((x - diffX2) / maptw); + } else { + col = Math.floor(x / (maptw - this._diffX1!)); + diffY2 = col % 2 === 1 ? mapth2 * -this._odd_even! : 0; + row = Math.floor((y - diffY2) / mapth); + } + break; + } + result.row = row; + result.col = col; + return result; + } + + public updateCulling () { + if (EDITOR) { + this.enableCulling = false; + } else if (this._enableCulling) { + this.node.updateWorldTransform(); + Mat4.invert(_mat4_temp, this.node.getWorldMatrix()); + const rect = visibleRect; + const camera = this.node._uiProps.uiTransformComp!._canvas!.camera; + if (camera) { + _vec3_temp.x = 0; + _vec3_temp.y = 0; + _vec3_temp.z = 0; + _vec3_temp2.x = _vec3_temp2.x + rect.width; + _vec3_temp2.y = _vec3_temp2.y + rect.height; + _vec3_temp2.z = 0; + camera.screenToWorld(_vec3_temp, _vec3_temp); + camera.screenToWorld(_vec3_temp2, _vec3_temp2); + // camera.getScreenToWorldPoint(_vec2_temp, _vec2_temp); + // camera.getScreenToWorldPoint(_vec2_temp2, _vec2_temp2); + Vec2.transformMat4(_vec3_temp, _vec3_temp, _mat4_temp); + Vec2.transformMat4(_vec3_temp2, _vec3_temp2, _mat4_temp); + this.updateViewPort(_vec3_temp.x, _vec3_temp.y, _vec3_temp2.x - _vec3_temp.x, _vec3_temp2.y - _vec3_temp.y); + } + } + } + + /** + * !#en Layer orientation, which is the same as the map orientation. + * !#zh 获取 Layer 方向(同地图方向)。 + * @method getLayerOrientation + * @return {Number} + * @example + * let orientation = tiledLayer.getLayerOrientation(); + * cc.log("Layer Orientation: " + orientation); + */ + public getLayerOrientation () { + return this._layerOrientation; + } + + /** + * !#en properties from the layer. They can be added using Tiled. + * !#zh 获取 layer 的属性,可以使用 Tiled 编辑器添加属性。 + * @method getProperties + * @return {Object} + * @example + * let properties = tiledLayer.getProperties(); + * cc.log("Properties: " + properties); + */ + public getProperties () { + return this._properties; + } + + protected _updateVertex (col: number, row: number) { + const FLIPPED_MASK = TileFlag.FLIPPED_MASK; + + const vertices = this.vertices; + + const layerOrientation = this._layerOrientation; + const tiles = this.tiles; + + if (!tiles) { + return; + } + + const rightTop = this._rightTop; + const maptw = this._mapTileSize!.width; + const mapth = this._mapTileSize!.height; + const maptw2 = maptw * 0.5; + const mapth2 = mapth * 0.5; + const rows = this._layerSize!.height; + const cols = this._layerSize!.width; + const grids = this.texGrids!; + + let gid: MixedGID; + let left: number = 0; + let bottom: number = 0; + let axis: StaggerAxis; + let diffX1: number; + let diffY1: number; + let odd_even: number; + let diffX2: number; + let diffY2: number; + let grid: TiledGrid; + + if (layerOrientation === Orientation.HEX) { + axis = this._staggerAxis!; + diffX1 = this._diffX1!; + diffY1 = this._diffY1!; + odd_even = this._odd_even!; + } + + let cullingCol = 0; + let cullingRow = 0; + let tileOffset: Vec2; + let gridGID: GID = 0 as unknown as GID; + + // grid border + let topBorder = 0; + let downBorder = 0; let leftBorder = 0; + let rightBorder = 0; + const index = row * cols + col; + gid = tiles[index]; + gridGID = (((gid as unknown as number) & FLIPPED_MASK) >>> 0) as unknown as GID; + grid = grids.get(gridGID)!; + if (!grid) { + return; + } + + // if has animation, grid must be updated per frame + if (this._animations!.get(gridGID)) { + this._hasAniGrid = this._hasAniGrid || true; + } + + switch (layerOrientation) { + // left top to right dowm + case Orientation.ORTHO: + cullingCol = col; + cullingRow = rows - row - 1; + left = cullingCol * maptw; + bottom = cullingRow * mapth; + break; + // right top to left down + case Orientation.ISO: + // if not consider about col, then left is 'w/2 * (rows - row - 1)' + // if consider about col then left must add 'w/2 * col' + // so left is 'w/2 * (rows - row - 1) + w/2 * col' + // combine expression is 'w/2 * (rows - row + col -1)' + cullingCol = rows + col - row - 1; + // if not consider about row, then bottom is 'h/2 * (cols - col -1)' + // if consider about row then bottom must add 'h/2 * (rows - row - 1)' + // so bottom is 'h/2 * (cols - col -1) + h/2 * (rows - row - 1)' + // combine expressionn is 'h/2 * (rows + cols - col - row - 2)' + cullingRow = rows + cols - col - row - 2; + left = maptw2 * cullingCol; + bottom = mapth2 * cullingRow; + break; + // left top to right dowm + case Orientation.HEX: + diffX2 = (axis! === StaggerAxis.STAGGERAXIS_Y && row % 2 === 1) ? maptw2 * odd_even! : 0; + diffY2 = (axis! === StaggerAxis.STAGGERAXIS_X && col % 2 === 1) ? mapth2 * -odd_even! : 0; + + left = col * (maptw - diffX1!) + diffX2; + bottom = (rows - row - 1) * (mapth - diffY1!) + diffY2; + cullingCol = col; + cullingRow = rows - row - 1; + break; + } + + const rowData = vertices[cullingRow] = vertices[cullingRow] || { minCol: 0, maxCol: 0 }; + const colData = rowData[cullingCol] = rowData[cullingCol] || {}; + + // record each row range, it will faster when culling grid + if (rowData.minCol > cullingCol) { + rowData.minCol = cullingCol; + } + + if (rowData.maxCol < cullingCol) { + rowData.maxCol = cullingCol; + } + + // record max rect, when viewPort is bigger than layer, can make it smaller + if (rightTop.row < cullingRow) { + rightTop.row = cullingRow; + } + + if (rightTop.col < cullingCol) { + rightTop.col = cullingCol; + } + + // _offset is whole layer offset + // tileOffset is tileset offset which is related to each grid + // tileOffset coordinate system's y axis is opposite with engine's y axis. + tileOffset = grid.tileset.tileOffset!; + left += this._offset!.x + tileOffset!.x + grid.offsetX; + bottom += this._offset!.y - tileOffset!.y - grid.offsetY; + + topBorder = -tileOffset.y + grid.tileset._tileSize.height - mapth; + topBorder = topBorder < 0 ? 0 : topBorder; + downBorder = tileOffset.y < 0 ? 0 : tileOffset.y; + leftBorder = -tileOffset.x < 0 ? 0 : -tileOffset.x; + rightBorder = tileOffset.x + grid.tileset._tileSize.width - maptw; + rightBorder = rightBorder < 0 ? 0 : rightBorder; + + if (this._rightOffset < leftBorder) { + this._rightOffset = leftBorder; + } + + if (this._leftOffset < rightBorder) { + this._leftOffset = rightBorder; + } + + if (this._topOffset < downBorder) { + this._topOffset = downBorder; + } + + if (this._downOffset < topBorder) { + this._downOffset = topBorder; + } + + colData.left = left; + colData.bottom = bottom; + // this index is tiledmap grid index + colData.index = index; + + this._cullingDirty = true; + } + + protected _updateVertices () { + const vertices = this.vertices; + vertices.length = 0; + + const tiles = this.tiles; + if (!tiles) { + return; + } + + const rightTop = this._rightTop; + rightTop.row = -1; + rightTop.col = -1; + + const rows = this._layerSize!.height; + const cols = this._layerSize!.width; + + this._topOffset = 0; + this._downOffset = 0; + this._leftOffset = 0; + this._rightOffset = 0; + this._hasAniGrid = false; + + for (let row = 0; row < rows; ++row) { + for (let col = 0; col < cols; ++col) { + this._updateVertex(col, row); + } + } + this._verticesDirty = false; + } + + /** + * !#en + * Get the TiledTile with the tile coordinate.
+ * If there is no tile in the specified coordinate and forceCreate parameter is true,
+ * then will create a new TiledTile at the coordinate. + * The renderer will render the tile with the rotation, scale, position and color property of the TiledTile. + * !#zh + * 通过指定的 tile 坐标获取对应的 TiledTile。
+ * 如果指定的坐标没有 tile,并且设置了 forceCreate 那么将会在指定的坐标创建一个新的 TiledTile 。
+ * 在渲染这个 tile 的时候,将会使用 TiledTile 的节点的旋转、缩放、位移、颜色属性。
+ * @method getTiledTileAt + * @param {Integer} x + * @param {Integer} y + * @param {Boolean} forceCreate + * @return {cc.TiledTile} + * @example + * let tile = tiledLayer.getTiledTileAt(100, 100, true); + * cc.log(tile); + */ + public getTiledTileAt (x: number, y: number, forceCreate?: boolean) { + if (this.isInvalidPosition(x, y)) { + throw new Error('TiledLayer.getTiledTileAt: invalid position'); + } + if (!this.tiles) { + logID(7236); + return null; + } + + const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width; + let tile = this.tiledTiles[index]; + if (!tile && forceCreate) { + const node = new Node(); + tile = node.addComponent(TiledTile); + tile._x = x; + tile._y = y; + tile._layer = this; + tile.updateInfo(); + node.parent = this.node; + return tile; + } + return tile; + } + + /** + * !#en + * Change tile to TiledTile at the specified coordinate. + * !#zh + * 将指定的 tile 坐标替换为指定的 TiledTile。 + * @method setTiledTileAt + * @param {Integer} x + * @param {Integer} y + * @param {cc.TiledTile} tiledTile + * @return {cc.TiledTile} + */ + public setTiledTileAt (x: number, y: number, tiledTile: TiledTile | null): TiledTile | null { + if (this.isInvalidPosition(x, y)) { + throw new Error('TiledLayer.setTiledTileAt: invalid position'); + } + if (!this.tiles) { + logID(7236); + return null; + } + + const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width; + this.tiledTiles[index] = tiledTile; + this._cullingDirty = true; + + if (tiledTile) { + this._hasTiledNodeGrid = true; + } else { + this._hasTiledNodeGrid = this.tiledTiles.some((tiledNode) => { + return !!tiledNode; + }); + } + + return tiledTile; + } + + /** + * !#en Return texture. + * !#zh 获取纹理。 + * @method getTexture + * @param index The index of textures + * @return {Texture2D} + */ + public getTexture (index?: number): SpriteFrame | null { + index = index || 0; + if (this._textures && index >= 0 && this._textures.length > index) { + return this._textures[index]; + } + return null; + } + + /** + * !#en Return texture. + * !#zh 获取纹理。 + * @method getTextures + * @return {Texture2D} + */ + public getTextures () { + return this._textures; + } + + /** + * !#en Set the texture. + * !#zh 设置纹理。 + * @method setTexture + * @param {SpriteFrame} texture + */ + public setTexture (texture: SpriteFrame) { + this.setTextures([texture]); + } + + /** + * !#en Set the texture. + * !#zh 设置纹理。 + * @method setTexture + * @param {SpriteFrame} textures + */ + public setTextures (textures: SpriteFrame[]) { + this._textures = textures; + this.markForUpdateRenderData(); + } + + /** + * !#en Gets layer size. + * !#zh 获得层大小。 + * @method getLayerSize + * @return {Size} + * @example + * let size = tiledLayer.getLayerSize(); + * cc.log("layer size: " + size); + */ + public getLayerSize (): Size { + return this._layerSize!; + } + + /** + * !#en Size of the map's tile (could be different from the tile's size). + * !#zh 获取 tile 的大小( tile 的大小可能会有所不同)。 + * @method getMapTileSize + * @return {Size} + * @example + * let mapTileSize = tiledLayer.getMapTileSize(); + * cc.log("MapTile size: " + mapTileSize); + */ + public getMapTileSize (): Size { + return this._mapTileSize!; + } + + /** + * !#en Gets Tile set first information for the layer. + * !#zh 获取 layer 索引位置为0的 Tileset 信息。 + * @method getTileSet + * @param index The index of tilesets + * @return {TMXTilesetInfo} + */ + public getTileSet (index: number): TMXTilesetInfo | null { + index = index || 0; + if (this._tilesets && index >= 0 && this._tilesets.length > index) { + return this._tilesets[index]; + } + return null; + } + + /** + * !#en Gets tile set all information for the layer. + * !#zh 获取 layer 所有的 Tileset 信息。 + * @method getTileSet + * @return {TMXTilesetInfo} + */ + public getTileSets (): TMXTilesetInfo[] { + return this._tilesets; + } + + /** + * !#en Sets tile set information for the layer. + * !#zh 设置 layer 的 tileset 信息。 + * @method setTileSet + * @param {TMXTilesetInfo} tileset + */ + public setTileSet (tileset: TMXTilesetInfo) { + this.setTileSets([tileset]); + } + + /** + * !#en Sets Tile set information for the layer. + * !#zh 设置 layer 的 Tileset 信息。 + * @method setTileSets + * @param {TMXTilesetInfo} tilesets + */ + public setTileSets (tilesets: TMXTilesetInfo[]) { + this._tilesets = tilesets; + const textures: SpriteFrame[] = this._textures = []; + const texGrids = this.texGrids!; + texGrids.clear(); + for (let i = 0; i < tilesets.length; i++) { + const tileset = tilesets[i]; + if (tileset) { + textures[i] = tileset.sourceImage!; + } + } + + const self = this; + loadAllTextures(textures, () => { + for (let i = 0, l = tilesets.length; i < l; ++i) { + const tilesetInfo = tilesets[i]; + if (!tilesetInfo) continue; + fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage); + } + self._prepareToRender(); + }); + } + + public init (layerInfo: TMXLayerInfo, mapInfo: TMXMapInfo, tilesets: TMXTilesetInfo[], textures: SpriteFrame[], texGrids: TiledTextureGrids) { + + this._cullingDirty = true; + this._layerInfo = layerInfo; + this._mapInfo = mapInfo; + + const size = layerInfo.layerSize!; + + // layerInfo + this._layerName = layerInfo.name; + this.tiles = layerInfo.tiles as unknown as any; + this._properties = layerInfo.properties; + this._layerSize = size; + this._minGID = layerInfo.minGID; + this._maxGID = layerInfo.maxGID; + this._opacity = layerInfo.opacity; + + if (layerInfo.tintColor) { + this._tintColor = layerInfo.tintColor; + // this.node.color = this._tintColor; + } + + this.renderOrder = mapInfo.renderOrder; + this._staggerAxis = mapInfo.getStaggerAxis()!; + this._staggerIndex = mapInfo.getStaggerIndex()!; + this._hexSideLength = mapInfo.getHexSideLength(); + this._animations = mapInfo.getTileAnimations(); + + // tilesets + this._tilesets = tilesets; + // textures + this._textures = textures; + // grid texture + this.texGrids = texGrids; + + // mapInfo + this._layerOrientation = mapInfo.orientation; + this._mapTileSize = mapInfo.getTileSize(); + + const maptw = this._mapTileSize.width; + const mapth = this._mapTileSize.height; + const layerW = this._layerSize.width; + const layerH = this._layerSize.height; + + if (this._layerOrientation === Orientation.HEX) { + + let width = 0; + let height = 0; + + this._odd_even = (this._staggerIndex === StaggerIndex.STAGGERINDEX_ODD) ? 1 : -1; + if (this._staggerAxis === StaggerAxis.STAGGERAXIS_X) { + this._diffX1 = (maptw - this._hexSideLength) / 2; + this._diffY1 = 0; + height = mapth * (layerH + 0.5); + width = (maptw + this._hexSideLength) * Math.floor(layerW / 2) + maptw * (layerW % 2); + } else { + this._diffX1 = 0; + this._diffY1 = (mapth - this._hexSideLength) / 2; + width = maptw * (layerW + 0.5); + height = (mapth + this._hexSideLength) * Math.floor(layerH / 2) + mapth * (layerH % 2); + } + this.node._uiProps.uiTransformComp!.setContentSize(width, height); + } else if (this._layerOrientation === Orientation.ISO) { + const wh = layerW + layerH; + this.node._uiProps.uiTransformComp!.setContentSize(maptw * 0.5 * wh, mapth * 0.5 * wh); + } else { + this.node._uiProps.uiTransformComp!.setContentSize(layerW * maptw, layerH * mapth); + } + + // offset (after layer orientation is set); + this._offset = new Vec2(layerInfo.offset.x, -layerInfo.offset.y); + this._useAutomaticVertexZ = false; + this._vertexZvalue = 0; + this._syncAnchorPoint(); + this._prepareToRender(); + } + + protected _prepareToRender () { + this._updateVertices(); + this._updateAllUserNode(); + } + + public requestMeshRenderData () { + if (!this._meshRenderDataArray) { + this._meshRenderDataArray = new Array(); + } + const renderData = new MeshRenderData(); + const comb = { renderData, texture: null }; + Object.defineProperty(renderData, 'material', { get: () => { return this.getRenderMaterial(0); } }); + this._meshRenderDataArray.push(comb); + return comb; + } + + public requestSubNodesData () { + if (!this._meshRenderDataArray) { + this._meshRenderDataArray = new Array(); + } + const renderData:(TiledUserNodeData|null)[] = []; + const comb = {subNodes: renderData}; + this._meshRenderDataArray.push(comb); + return comb; + } + + public destroyRenderData () { + if (this._meshRenderDataArray) { + this._meshRenderDataArray.forEach((rd) => { if ((rd as TiledMeshData).renderData) (rd as TiledMeshData).renderData.reset(); }); + this._meshRenderDataArray = null; + } + } + + public resetRenderData () { + if (this._meshRenderDataArray) { + this._meshRenderDataArray.forEach((rd) => { if ((rd as TiledMeshData).renderData) (rd as TiledMeshData).renderData.reset(); }); + } + } + + public markForUpdateRenderData (enable: boolean = true) { + this._renderFlag = this._canRender(); + if (enable && this._renderFlag) { + this._renderDataFlag = enable; + } else if (!enable) { + this._renderDataFlag = enable; + } + } + + protected _flushAssembler () { + const assembler = TiledLayer.Assembler!.getAssembler(this); + if (this._assembler !== assembler) { + this._assembler = assembler; + } + if (!this._meshRenderDataArray) { + if (this._assembler && this._assembler.createData) { + this._assembler.createData(this); + this.markForUpdateRenderData(); + this._updateColor(); + } + } + } + + // 当前的 _meshRenderDataArray 的索引, 以便 fillBuffers 选取 RenderData + public _meshRenderDataArrayIdx: number = 0; + protected _render (ui: UI) { + if (this._meshRenderDataArray) { + for (let i = 0; i < this._meshRenderDataArray.length; i++) { + this._meshRenderDataArrayIdx = i; + const m = this._meshRenderDataArray[i]; + if ((m as TiledSubNodeData).subNodes!) { + // 提前处理 User Nodes + (m as TiledSubNodeData).subNodes.forEach((c) => { + if(c) ui.walk(c.node); + }); + } else if ((m as TiledMeshData).texture) { + // NOTE: 由于 commitComp 只支持单张纹理, 故分多次提交 + ui.commitComp(this, (m as TiledMeshData).texture, this._assembler); + } + } + this.node._static = true; + } + } +} diff --git a/cocos/tiledmap/tiled-map-asset.ts b/cocos/tiledmap/tiled-map-asset.ts new file mode 100644 index 0000000000..d85bdab6d5 --- /dev/null +++ b/cocos/tiledmap/tiled-map-asset.ts @@ -0,0 +1,87 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + + +import { Asset } from '../core/assets/asset'; +import { ccclass, type, serializable } from 'cc.decorator'; +import { CCString, Size, SpriteFrame, TextAsset } from '../core'; +/** + * Class for tiled map asset handling. + * @class TiledMapAsset + * @extends Asset + * + */ +@ccclass('cc.TiledMapAsset') +export class TiledMapAsset extends Asset { + + @serializable + tmxXmlStr: string = ''; + + @serializable + @type([TextAsset]) + tsxFiles: TextAsset[] = []; + + @serializable + @type([CCString]) + tsxFileNames: string[] = []; + + /** + * @zh s + */ + @serializable + @type([SpriteFrame]) + spriteFrames: SpriteFrame[] = []; + + /** + * @property {SpriteFrame[]} imageLayerSpriteFrame + */ + @serializable + @type([SpriteFrame]) + imageLayerSpriteFrame: SpriteFrame[] = [] + + /** + * @property {String[]} imageLayerTextureNames + */ + @serializable + @type([CCString]) + imageLayerSpriteFrameNames: string[] = []; + + /** + * @property {String[]} spriteFrameNames + */ + @serializable + @type([CCString]) + spriteFrameNames: string[] = []; + + /** + * @property {Size[]} spriteFrameSizes + */ + @serializable + @type([Size]) + spriteFrameSizes: Size[] = []; + + static preventDeferredLoadDependents: boolean = true; +} diff --git a/cocos/tiledmap/tiled-map.ts b/cocos/tiledmap/tiled-map.ts new file mode 100644 index 0000000000..f17c3c6485 --- /dev/null +++ b/cocos/tiledmap/tiled-map.ts @@ -0,0 +1,646 @@ +/**************************************************************************** + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + +/** + * @packageDocumentation + * @module ui + */ + +import { Component } from '../core/components'; +import { UITransform } from '../core/components/ui-base'; +import { ccclass, displayOrder, executeInEditMode, help, menu, requireComponent, type, serializable } from 'cc.decorator'; +import { GID, Orientation, PropertiesInfo, Property, RenderOrder, StaggerAxis, StaggerIndex, TiledAnimationType, TiledTextureGrids, TileFlag, + TMXImageLayerInfo, TMXLayerInfo, TMXObjectGroupInfo, TMXObjectType, TMXTilesetInfo } from './tiled-types' +import { TMXMapInfo } from './tmx-xml-parser'; +import { TiledLayer } from './tiled-layer'; +import { TiledObjectGroup } from './tiled-object-group'; +import { TiledMapAsset } from './tiled-map-asset'; +import { Sprite } from '../ui/components/sprite'; +import { EDITOR } from 'internal:constants'; +import { fillTextureGrids, loadAllTextures } from './tiled-utils'; +import { Size, SpriteFrame, SystemEventType, Vec2, Node, logID, Color, sys } from '../core'; + + +interface ImageExtendedNode extends Node { + layerInfo: TMXImageLayerInfo; + _offset: Vec2; +} + +/** + * !#en Renders a TMX Tile Map in the scene. + * !#zh 在场景中渲染一个 tmx 格式的 Tile Map。 + * @class TiledMap + * @extends Component + */ +@ccclass('cc.TiledMap') +@help('i18n:cc.TiledMap') +@menu('Components/TiledMap') +@requireComponent(UITransform) +@executeInEditMode +export class TiledMap extends Component { + + // store all layer gid corresponding texture info, index is gid, format likes '[gid0]=tex-info,[gid1]=tex-info, ...' + _texGrids: TiledTextureGrids = new Map(); + // store all tileset texture, index is tileset index, format likes '[0]=texture0, [1]=texture1, ...' + _textures: SpriteFrame[] = []; + _tilesets: TMXTilesetInfo[] = []; + + _animations: TiledAnimationType = new Map(); + _imageLayers: TMXImageLayerInfo[] = []; + _layers: TiledLayer[] = []; + _groups: TiledObjectGroup[] = []; + _images: ImageExtendedNode[] = []; + _properties: PropertiesInfo = {} as any; + _tileProperties: Map = new Map(); + + _mapInfo: TMXMapInfo | null = null; + _mapSize: Size = new Size(0, 0); + _tileSize: Size = new Size(0, 0); + + _preloaded: boolean = false; + + _mapOrientation = Orientation.ORTHO; + + + static Orientation = Orientation; + static Property = Property; + static TileFlag = TileFlag; + static StaggerAxis = StaggerAxis; + static StaggerIndex = StaggerIndex; + static TMXObjectType = TMXObjectType; + static RenderOrder = RenderOrder; + + @serializable + _tmxFile: TiledMapAsset | null = null; + /** + * !#en The TiledMap Asset. + * !#zh TiledMap 资源。 + * @property {TiledMapAsset} tmxAsset + * @default "" + */ + + @type(TiledMapAsset) + @displayOrder(7) + get tmxAsset (): TiledMapAsset { + return this._tmxFile!; + } + + set tmxAsset (value: TiledMapAsset) { + if (this._tmxFile !== value || EDITOR) { + this._tmxFile = value; + if (this._preloaded || EDITOR) { + this._applyFile(); + } + } + } + + + /** + * !#en + * Whether or not enabled tiled map auto culling. If you set the TiledMap skew or rotation, then need to manually + * disable this, otherwise, the rendering will be wrong. + * !#zh + * 是否开启瓦片地图的自动裁减功能。瓦片地图如果设置了 skew, rotation 或者采用了摄像机的话,需要手动关闭,否则渲染会出错。 + */ + @serializable + protected _enableCulling: boolean = true; + get enableCulling () { + return this._enableCulling; + } + set enableCulling (value) { + this._enableCulling = value; + const layers = this._layers; + for (let i = 0; i < layers.length; ++i) { + layers[i].enableCulling = value; + } + } + + @serializable + protected cleanupImageCache: boolean = true; + + + /** + * !#en Gets the map size. + * !#zh 获取地图大小。 + * @method getMapSize + * @return {Size} + * @example + * let mapSize = tiledMap.getMapSize(); + * cc.log("Map Size: " + mapSize); + */ + getMapSize () { + return this._mapSize; + } + + /** + * !#en Gets the tile size. + * !#zh 获取地图背景中 tile 元素的大小。 + * @method getTileSize + * @return {Size} + * @example + * let tileSize = tiledMap.getTileSize(); + * cc.log("Tile Size: " + tileSize); + */ + getTileSize () { + return this._tileSize; + } + + /** + * !#en map orientation. + * !#zh 获取地图方向。 + * @method getMapOrientation + * @return {Number} + * @example + * let mapOrientation = tiledMap.getMapOrientation(); + * cc.log("Map Orientation: " + mapOrientation); + */ + getMapOrientation () { + return this._mapOrientation; + } + + /** + * !#en object groups. + * !#zh 获取所有的对象层。 + * @method getObjectGroups + * @return {TiledObjectGroup[]} + * @example + * let objGroups = titledMap.getObjectGroups(); + * for (let i = 0; i < objGroups.length; ++i) { + * cc.log("obj: " + objGroups[i]); + * } + */ + getObjectGroups () { + return this._groups; + } + + /** + * !#en Return the TMXObjectGroup for the specific group. + * !#zh 获取指定的 TMXObjectGroup。 + * @method getObjectGroup + * @param {String} groupName + * @return {TiledObjectGroup} + * @example + * let group = titledMap.getObjectGroup("Players"); + * cc.log("ObjectGroup: " + group); + */ + getObjectGroup (groupName: string) { + const groups = this._groups; + for (let i = 0, l = groups.length; i < l; i++) { + const group = groups[i]; + if (group && group.getGroupName() === groupName) { + return group; + } + } + + return null; + } + + /** + * !#en Gets the map properties. + * !#zh 获取地图的属性。 + * @method getProperties + * @return {Object[]} + * @example + * let properties = titledMap.getProperties(); + * for (let i = 0; i < properties.length; ++i) { + * cc.log("Properties: " + properties[i]); + * } + */ + getProperties () { + return this._properties; + } + + /** + * !#en Return All layers array. + * !#zh 返回包含所有 layer 的数组。 + * @method getLayers + * @returns {TiledLayer[]} + * @example + * let layers = titledMap.getLayers(); + * for (let i = 0; i < layers.length; ++i) { + * cc.log("Layers: " + layers[i]); + * } + */ + getLayers () { + return this._layers; + } + + /** + * !#en return the cc.TiledLayer for the specific layer. + * !#zh 获取指定名称的 layer。 + * @method getLayer + * @param {String} layerName + * @return {TiledLayer} + * @example + * let layer = titledMap.getLayer("Player"); + * cc.log(layer); + */ + getLayer (layerName) { + const layers = this._layers; + for (let i = 0, l = layers.length; i < l; i++) { + const layer = layers[i]; + if (layer && layer.getLayerName() === layerName) { + return layer; + } + } + return null; + } + + protected _changeLayer (layerName, replaceLayer) { + const layers = this._layers; + for (let i = 0, l = layers.length; i < l; i++) { + const layer = layers[i]; + if (layer && layer.getLayerName() === layerName) { + layers[i] = replaceLayer; + return; + } + } + } + + /** + * !#en Return the value for the specific property name. + * !#zh 通过属性名称,获取指定的属性。 + * @method getProperty + * @param {String} propertyName + * @return {String} + * @example + * let property = titledMap.getProperty("info"); + * cc.log("Property: " + property); + */ + getProperty (propertyName: string) { + return this._properties[propertyName.toString()]; + } + + /** + * !#en Return properties dictionary for tile GID. + * !#zh 通过 GID ,获取指定的属性。 + * @method getPropertiesForGID + * @param {Number} GID + * @return {Object} + * @example + * let properties = titledMap.getPropertiesForGID(GID); + * cc.log("Properties: " + properties); + */ + getPropertiesForGID (gid: GID) { + return this._tileProperties.get(gid); + } + + __preload () { + this._preloaded = true; + + if (!this._tmxFile) { + return; + } + + this._applyFile(); + } + + onEnable () { + this.node.on(SystemEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this); + } + + onDisable () { + this.node.off(SystemEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this); + } + + _applyFile () { + + const spriteFrames: SpriteFrame[] = []; + const spriteFramesCache = {}; + + const file = this._tmxFile; + + if (file) { + // let texValues = file.textures; + let spfNames: string[] = file.spriteFrameNames; + const spfSizes: Size[] = file.spriteFrameSizes; + const fSpriteFrames: SpriteFrame[] = file.spriteFrames; + const spfTexturesMap: { [key: string]: SpriteFrame } = {}; + const spfTextureSizeMap: { [key: string]: Size } = {}; + + for (let i = 0; i < spfNames.length; ++i) { + const texName = spfNames[i]; + // textures[texName] = texValues[i]; + spfTextureSizeMap[texName] = spfSizes[i]; + spriteFrames[i] = fSpriteFrames[i]; + const frame = spriteFrames[i]; + if (frame) { + spriteFramesCache[frame.name] = frame; + spfTexturesMap[texName] = frame; + } + } + + + const imageLayerTextures: { [key: string]: SpriteFrame } = {}; + const texValues = file.imageLayerSpriteFrame; + spfNames = file.imageLayerSpriteFrameNames; + for (let i = 0; i < texValues.length; ++i) { + imageLayerTextures[spfNames[i]] = texValues[i]; + } + + const tsxFileNames = file.tsxFileNames; + const tsxFiles = file.tsxFiles; + const tsxContentMap: { [key: string]: string } = {}; + for (let i = 0; i < tsxFileNames.length; ++i) { + if (tsxFileNames[i].length > 0) { + tsxContentMap[tsxFileNames[i]] = tsxFiles[i].text; + } + } + + const mapInfo = new TMXMapInfo(file.tmxXmlStr!, tsxContentMap, spfTexturesMap, spfTextureSizeMap, imageLayerTextures); + const tilesets = mapInfo.getTilesets(); + if (!tilesets || tilesets.length === 0) { + logID(7241); + } + + this._buildWithMapInfo(mapInfo); + + } + else { + this._releaseMapInfo(); + } + } + + _releaseMapInfo () { + // remove the layers & object groups added before + const layers = this._layers; + for (let i = 0, l = layers.length; i < l; i++) { + layers[i].node.removeFromParent(); + layers[i].node.destroy(); + } + layers.length = 0; + + const groups = this._groups; + for (let i = 0, l = groups.length; i < l; i++) { + groups[i].node.removeFromParent(); + groups[i].node.destroy(); + } + groups.length = 0; + + const images = this._images; + for (let i = 0, l = images.length; i < l; i++) { + images[i].removeFromParent(); + images[i].destroy(); + } + images.length = 0; + } + + _syncAnchorPoint () { + const anchor = this.node._uiProps.uiTransformComp!.anchorPoint; + const leftTopX = this.node._uiProps.uiTransformComp!.width * anchor.x; + const leftTopY = this.node._uiProps.uiTransformComp!.height * (1 - anchor.y); + let i: number; + let l: number; + for (i = 0, l = this._layers.length; i < l; i++) { + const layerInfo = this._layers[i]; + const layerNode = layerInfo.node; + // Tiled layer sync anchor to map because it's old behavior, + // do not change the behavior avoid influence user's existed logic. + layerNode!._uiProps!.uiTransformComp!.setAnchorPoint(anchor); + } + + for (i = 0, l = this._groups.length; i < l; i++) { + const groupInfo = this._groups[i]; + const groupNode = groupInfo.node._uiProps.uiTransformComp!; + // Group layer not sync anchor to map because it's old behavior, + // do not change the behavior avoid influence user's existing logic. + groupNode.anchorX = 0.5; + groupNode.anchorY = 0.5; + const x = groupInfo.offset!.x - leftTopX + groupNode.width * groupNode.anchorX; + const y = groupInfo.offset!.y + leftTopY - groupNode.height * groupNode.anchorY; + groupInfo.node.setPosition(x, y); + } + + for (i = 0, l = this._images.length; i < l; i++) { + const image = this._images[i]._uiProps.uiTransformComp!; + image.anchorX = 0.5; + image.anchorY = 0.5; + const x = this._images[i]._offset.x - leftTopX + image.width * image.anchorX; + const y = this._images[i]._offset.y + leftTopY - image.height * image.anchorY; + this._images[i].setPosition(x, y); + } + } + + _fillAniGrids (texGrids: TiledTextureGrids, animations: TiledAnimationType) { + for (const i of animations.keys()) { + const animation = animations.get(i); + if (!animation) continue; + const frames = animation.frames; + for (let j = 0; j < frames.length; j++) { + const frame = frames[j]; + frame.grid = texGrids.get(frame.tileid)!; + } + } + } + + _buildLayerAndGroup () { + const tilesets = this._tilesets; + const texGrids = this._texGrids!; + const animations = this._animations; + texGrids.clear(); + + for (let i = 0, l = tilesets.length; i < l; ++i) { + const tilesetInfo = tilesets[i]; + if (!tilesetInfo) continue; + if (!tilesetInfo.sourceImage) { + console.warn('Can\'t find the spriteFrame of tilesets ' + i); + continue; + } + fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage); + } + this._fillAniGrids(texGrids, animations); + + let layers = this._layers; + let groups = this._groups; + let images = this._images; + const oldNodeNames: { [key: string]: boolean } = {}; + for (let i = 0, n = layers.length; i < n; i++) { + oldNodeNames[layers[i].node.name] = true; + } + for (let i = 0, n = groups.length; i < n; i++) { + oldNodeNames[groups[i].node.name] = true; + } + for (let i = 0, n = images.length; i < n; i++) { + oldNodeNames[images[i].name] = true; + } + + layers = this._layers = []; + groups = this._groups = []; + images = this._images = []; + + const mapInfo = this._mapInfo!; + const node = this.node; + const layerInfos = mapInfo.getAllChildren(); + const textures = this._textures; + let maxWidth = 0; + let maxHeight = 0; + + if (layerInfos && layerInfos.length > 0) { + for (let i = 0, len = layerInfos.length; i < len; i++) { + const layerInfo = layerInfos[i]; + const name = layerInfo.name; + + let child: ImageExtendedNode = this.node.getChildByName(name) as any; + oldNodeNames[name] = false; + + if (!child) { + child = (new Node()) as unknown as any; + child.name = name; + node.addChild(child); + } + + child.setSiblingIndex(i); + child.active = layerInfo.visible; + + if (layerInfo instanceof TMXLayerInfo) { + let layer = child!.getComponent(TiledLayer); + if (!layer) { + layer = child!.addComponent(TiledLayer); + } + + layer.init(layerInfo, mapInfo, tilesets, textures, texGrids); + layer.enableCulling = this._enableCulling; + + // tell the layerinfo to release the ownership of the tiles map. + layerInfo.ownTiles = false; + layers.push(layer); + } + else if (layerInfo instanceof TMXObjectGroupInfo) { + let group = child.getComponent(TiledObjectGroup); + if (!group) { + group = child.addComponent(TiledObjectGroup); + } + group._init(layerInfo, mapInfo, texGrids); + groups.push(group); + } + else if (layerInfo instanceof TMXImageLayerInfo) { + const texture = layerInfo.sourceImage; + + child.layerInfo = layerInfo; + child._offset = new Vec2(layerInfo.offset.x, -layerInfo.offset.y); + + let image = child.getComponent(Sprite); + if (!image) { + image = child.addComponent(Sprite); + } + + const color = image.color as Color; + color.a *= layerInfo.opacity; + + image.spriteFrame = texture!; + + child._uiProps.uiTransformComp!.setContentSize(texture!.width, texture!.height); + images.push(child); + } + + maxWidth = Math.max(maxWidth, child._uiProps.uiTransformComp!.width); + maxHeight = Math.max(maxHeight, child._uiProps.uiTransformComp!.height); + } + } + + const children = node.children; + for (let i = 0, n = children.length; i < n; i++) { + const c = children[i]; + if (oldNodeNames[c.name]) { + c.destroy(); + } + } + + this.node._uiProps.uiTransformComp!.setContentSize(maxWidth, maxHeight); + this._syncAnchorPoint(); + } + + protected _buildWithMapInfo (mapInfo: TMXMapInfo) { + this._mapInfo = mapInfo; + this._mapSize = mapInfo.getMapSize(); + this._tileSize = mapInfo.getTileSize(); + this._mapOrientation = mapInfo.orientation!; + this._properties = mapInfo.properties!; + this._tileProperties = mapInfo.getTileProperties(); + this._imageLayers = mapInfo.getImageLayers(); + this._animations = mapInfo.getTileAnimations(); + this._tilesets = mapInfo.getTilesets(); + + const tilesets = this._tilesets; + this._textures.length = 0; + + const totalTextures: SpriteFrame[] = []; + for (let i = 0, l = tilesets.length; i < l; ++i) { + const tilesetInfo = tilesets[i]; + if (!tilesetInfo || !tilesetInfo.sourceImage) continue; + this._textures[i] = tilesetInfo.sourceImage; + totalTextures.push(tilesetInfo.sourceImage!); + } + + for (let i = 0; i < this._imageLayers.length; i++) { + const imageLayer = this._imageLayers[i]; + if (!imageLayer || !imageLayer.sourceImage) continue; + totalTextures.push(imageLayer.sourceImage); + } + + const self = this; + loadAllTextures(totalTextures, () => { + self._buildLayerAndGroup(); + if (self.cleanupImageCache) { + const tiledMap = self; + self._textures.forEach((tex) => { + tiledMap.doCleanupImageCache(tex) + }); + } + }); + } + + doCleanupImageCache (texture) { + if (texture._image instanceof HTMLImageElement) { + texture._image.src = ''; + } + else if (sys.capabilities.imageBitmap && texture._image instanceof ImageBitmap) { + // tslint:disable-next-line: no-unused-expression + texture._image.close && texture._image.close(); + } + texture._image = null; + } + + update (dt: number) { + const animations = this._animations; + const texGrids = this._texGrids!; + for (const aniGID of animations.keys()) { + const animation = animations.get(aniGID)!; + const frames = animation.frames; + let frame = frames[animation.frameIdx]; + animation.dt += dt; + if (frame.duration < animation.dt) { + animation.dt = 0; + animation.frameIdx++; + if (animation.frameIdx >= frames.length) { + animation.frameIdx = 0; + } + frame = frames[animation.frameIdx]; + } + texGrids.set(aniGID, frame.grid!); + } + } + +} diff --git a/cocos/tiledmap/tiled-object-group.ts b/cocos/tiledmap/tiled-object-group.ts new file mode 100644 index 0000000000..5ab2038547 --- /dev/null +++ b/cocos/tiledmap/tiled-object-group.ts @@ -0,0 +1,435 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + +import { Component } from '../core/components'; +import { ccclass, help, type, requireComponent } from 'cc.decorator'; +import { Sprite } from '../ui/components/sprite'; +import { Label } from '../ui/components/label'; +import * as gfx from '../core/gfx'; + +import { TMXMapInfo } from './tmx-xml-parser'; +import { TiledTextureGrids, GID, TileFlag, Orientation, StaggerAxis, TMXObjectType, PropertiesInfo, TiledAnimationType, TMXObject, TMXObjectGroupInfo } from './tiled-types'; +import { UITransform } from '../core/components/ui-base/ui-transform'; +import { CCBoolean, Node, Vec2, SpriteFrame, Color, PrivateNode } from '../core'; + +/** + * !#en Renders the TMX object group. + * !#zh 渲染 tmx object group。 + * @class TiledObjectGroup + * @extends Component + */ +@ccclass('cc.TiledObjectGroup') +@help('i18n:cc.TiledObjectGroup') +@requireComponent(UITransform) +export class TiledObjectGroup extends Component { + + protected _premultiplyAlpha: boolean = false; + + @type(CCBoolean) + get premultiplyAlpha () { + return this._premultiplyAlpha; + } + set premultiplyAlpha (value:boolean) { + this._premultiplyAlpha = value; + } + + + /** + * !#en Offset position of child objects. + * !#zh 获取子对象的偏移位置。 + * @method getPositionOffset + * @return {Vec2} + * @example + * let offset = tMXObjectGroup.getPositionOffset(); + */ + public getPositionOffset () { + return this._positionOffset; + } + + /** + * !#en List of properties stored in a dictionary. + * !#zh 以映射的形式获取属性列表。 + * @method getProperties + * @return {Object} + * @example + * let offset = tMXObjectGroup.getProperties(); + */ + public getProperties () { + return this._properties; + } + + /** + * !#en Gets the Group name. + * !#zh 获取组名称。 + * @method getGroupName + * @return {String} + * @example + * let groupName = tMXObjectGroup.getGroupName; + */ + public getGroupName () { + return this._groupName; + } + + /** + * Return the value for the specific property name + * @param {String} propertyName + * @return {Object} + */ + public getProperty (propertyName: { toString (): string } | string) { + return this._properties![propertyName.toString()]; + } + + /** + * !#en + * Return the object for the specific object name.
+ * It will return the 1st object found on the array for the given name. + * !#zh 获取指定的对象。 + * @method getObject + * @param {String} objectName + * @return {Object|Null} + * @example + * let object = tMXObjectGroup.getObject("Group"); + */ + public getObject (objectName:string) { + for (let i = 0, len = this._objects!.length; i < len; i++) { + const obj = this._objects[i]; + if (obj && obj.name === objectName) { + return obj; + } + } + // object not found + return null; + } + + /** + * !#en Gets the objects. + * !#zh 获取对象数组。 + * @method getObjects + * @return {Array} + * @example + * let objects = tMXObjectGroup.getObjects(); + */ + public getObjects () { + return this._objects; + } + + protected _groupName?: string; + protected _positionOffset?: Vec2; + protected _mapInfo?: TMXMapInfo; + protected _properties?: PropertiesInfo; + protected _offset?: Vec2; + get offset () { return this._offset!; } + protected _opacity?: number; + protected _tintColor: Color | null = null; + + protected _animations?: TiledAnimationType; + protected _hasAniObj?: boolean; + protected _texGrids?: TiledTextureGrids; + protected aniObjects?: { + object: TMXObject, + imgNode: Node, + gridGID: GID + }[]; + protected _objects: TMXObject[] = []; + + + public _init (groupInfo: TMXObjectGroupInfo, mapInfo: TMXMapInfo, texGrids: TiledTextureGrids) { + + const FLIPPED_MASK = TileFlag.FLIPPED_MASK; + const FLAG_HORIZONTAL = TileFlag.HORIZONTAL; + const FLAG_VERTICAL = TileFlag.VERTICAL; + + this._groupName = groupInfo.name; + this._positionOffset = groupInfo.offset; + this._mapInfo = mapInfo; + this._properties = groupInfo.getProperties(); + this._offset = new Vec2(groupInfo.offset.x, -groupInfo.offset.y); + this._opacity = groupInfo.opacity; + + if (groupInfo.tintColor) { + this._tintColor = groupInfo.tintColor; + } + + this._texGrids = texGrids; + this._animations = mapInfo.getTileAnimations(); + this.aniObjects = []; + this._hasAniObj = false; + + const mapSize = mapInfo.mapSize; + const tileSize = mapInfo.tileSize; + let width = 0; + let height = 0; + const colorVal = new Color(); + + const iso = Orientation.ISO === mapInfo.orientation; + + if (mapInfo.orientation === Orientation.HEX) { + if (mapInfo.getStaggerAxis() === StaggerAxis.STAGGERAXIS_X) { + height = tileSize.height * (mapSize.height + 0.5); + width = (tileSize.width + mapInfo.getHexSideLength()) * Math.floor(mapSize.width / 2) + tileSize.width * (mapSize.width % 2); + } else { + width = tileSize.width * (mapSize.width + 0.5); + height = (tileSize.height + mapInfo.getHexSideLength()) * Math.floor(mapSize.height / 2) + tileSize.height * (mapSize.height % 2); + } + } else if (iso) { + const wh = mapSize.width + mapSize.height; + width = tileSize.width * 0.5 * wh; + height = tileSize.height * 0.5 * wh; + } else { + width = mapSize.width * tileSize.width; + height = mapSize.height * tileSize.height; + } + + const transComp = this.node._uiProps.uiTransformComp!; + transComp.setContentSize(width, height); + + const leftTopX = width * transComp.anchorX; + const leftTopY = height * (1 - transComp.anchorY); + + const objects = groupInfo.objects; + const aliveNodes = {}; + for (let i = 0, l = objects.length; i < l; i++) { + const object = objects[i]; + const objType = object.type; + object.offset = new Vec2(object.x, object.y); + + const points = object.points || object.polylinePoints; + if (points) { + for (let pi = 0; pi < points.length; pi++) { + points[pi].y *= -1; + } + } + + if (iso) { + const posIdxX = object.x / tileSize.height; + const posIdxY = object.y / tileSize.height; + object.x = tileSize.width * 0.5 * (mapSize.height + posIdxX - posIdxY); + object.y = tileSize.height * 0.5 * (mapSize.width + mapSize.height - posIdxX - posIdxY); + } else { + object.y = height - object.y; + } + + if (objType === TMXObjectType.TEXT) { + const textName = 'text' + object.id; + aliveNodes[textName] = true; + + let textNode = this.node.getChildByName(textName); + if (!textNode) { + textNode = new Node(); + } + + textNode.setRotationFromEuler(0, 0, -object.rotation); + textNode.setPosition(object.x - leftTopX, object.y - leftTopY); + textNode.name = textName; + textNode.parent = this.node; + textNode.setSiblingIndex(i); + + + let label = textNode.getComponent(Label); + if (!label) { + label = textNode.addComponent(Label); + } + + const textTransComp = textNode._uiProps.uiTransformComp!; + textNode.active = object.visible; + textTransComp.anchorX = 0; + textTransComp.anchorY = 1; + + if (this._tintColor) { + colorVal.set(this._tintColor); + colorVal.a *= this._opacity / 255; + label.color.set(colorVal); + } else { + const c = label.color as Color; + c.a *= this._opacity / 255; + } + + + label.overflow = Label.Overflow.SHRINK; + label.lineHeight = object.height; + label.string = object.text; + label.horizontalAlign = object.halign; + label.verticalAlign = object.valign; + label.fontSize = object.pixelsize; + + textTransComp.setContentSize(object.width, object.height); + + } else if (objType === TMXObjectType.IMAGE) { + const gid = object.gid; + const gridGID: GID = (((gid as unknown as number) & FLIPPED_MASK) >>> 0) as any; + const grid = texGrids.get(gridGID); + if (!grid) continue; + const tileset = grid.tileset; + const imgName = 'img' + object.id; + aliveNodes[imgName] = true; + let imgNode = this.node.getChildByName(imgName); + object.width = object.width || grid.width; + object.height = object.height || grid.height; + + // Delete image nodes implemented as private nodes + // Use cc.Node to implement node-level requirements + if (imgNode instanceof PrivateNode) { + imgNode.removeFromParent(); + imgNode.destroy(); + imgNode = null; + } + + if (!imgNode) { + imgNode = new Node(); + } + + if (this._animations!.get(gridGID)) { + this.aniObjects.push({ + object, + imgNode, + gridGID, + }) + this._hasAniObj = true; + } + + const tileOffsetX = tileset.tileOffset.x; + const tileOffsetY = tileset.tileOffset.y; + imgNode.active = object.visible; + imgNode.setRotationFromEuler(0, 0, -object.rotation); + imgNode.setPosition(object.x - leftTopX, object.y - leftTopY); + imgNode.name = imgName; + imgNode.parent = this.node; + imgNode.setSiblingIndex(i); + + let sprite = imgNode.getComponent(Sprite); + if (!sprite) { + sprite = imgNode.addComponent(Sprite); + } + + const imgTrans = imgNode._uiProps.uiTransformComp!; + if (iso) { + imgTrans.anchorX = 0.5 + tileOffsetX / object.width; + imgTrans.anchorY = tileOffsetY / object.height; + } else { + imgTrans.anchorX = tileOffsetX / object.width; + imgTrans.anchorY = tileOffsetY / object.height; + } + + + if (this._tintColor) { + colorVal.set(this._tintColor); + colorVal.a *= this._opacity / 255; + sprite.color.set(colorVal); + } else { + const c = sprite.color as Color; + c.a *= this._opacity / 255; + } + + + sprite.sizeMode = Sprite.SizeMode.CUSTOM; + + sprite.srcBlendFactor = this._premultiplyAlpha ? gfx.GFXBlendFactor.ONE : gfx.GFXBlendFactor.SRC_ALPHA; + sprite.dstBlendFactor = gfx.GFXBlendFactor.ONE_MINUS_SRC_ALPHA; + sprite._updateBlendFunc(); + + + let spf = grid.spriteFrame!; + if (!spf) { + spf = new SpriteFrame(); + } + const scale = imgNode.getScale(); + let scaleX = scale.x; + let scaleY = scale.y; + if (((gid as unknown as number) & FLAG_HORIZONTAL) >>> 0) { + scaleX *= -1; + } + + if (((gid as unknown as number) & FLAG_VERTICAL) >>> 0) { + scaleY *= -1; + } + imgNode.setScale(scaleX, scaleY, scale.z); + + spf.rotated = grid._rotated!; + spf.rect = grid._rect!; + sprite.spriteFrame = spf; + + imgTrans.setContentSize(object.width, object.height); + + sprite.markForUpdateRenderData(); + } + } + this._objects = objects; + + // destroy useless node + const children = this.node.children; + const uselessExp = /^(?:img|text)\d+$/; + for (let i = 0, n = children.length; i < n; i++) { + const c = children[i]; + const cName = c.name; + const isUseless = uselessExp.test(cName); + if (isUseless && !aliveNodes[cName]) c.destroy(); + } + } + + public update (dt: number) { + if (!this._hasAniObj) { + return; + } + + const aniObjects = this.aniObjects!; + const _texGrids = this._texGrids!; + const iso = Orientation.ISO === this._mapInfo!.orientation + + for (let i = 0, len = aniObjects.length; i < len; i++) { + const aniObj = aniObjects[i]; + const gridGID = aniObj.gridGID; + const grid = _texGrids.get(gridGID); + if (!grid) { + continue; + } + + const tileset = grid.tileset; + const object = aniObj.object; + const imgNode: Node = aniObj.imgNode; + + const tileOffsetX = tileset.tileOffset.x; + const tileOffsetY = tileset.tileOffset.y; + const imgTrans = imgNode._uiProps.uiTransformComp!; + if (iso) { + imgTrans.anchorX = 0.5 + tileOffsetX / object.width; + imgTrans.anchorY = tileOffsetY / object.height; + } else { + imgTrans.anchorX = tileOffsetX / object.width; + imgTrans.anchorY = tileOffsetY / object.height; + } + + const sp = imgNode.getComponent(Sprite)!; + const spf = sp.spriteFrame!; + + spf.rotated = grid._rotated!; + spf.rect = grid._rect!; + + sp.spriteFrame = spf; + sp.markForUpdateRenderData(); + } + } + +} diff --git a/cocos/tiledmap/tiled-tile.ts b/cocos/tiledmap/tiled-tile.ts new file mode 100644 index 0000000000..bb87b52bbf --- /dev/null +++ b/cocos/tiledmap/tiled-tile.ts @@ -0,0 +1,148 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + +/** + * !#en TiledTile can control the specified map tile. + * It will apply the node rotation, scale, translate to the map tile. + * You can change the TiledTile's gid to change the map tile's style. + * !#zh TiledTile 可以单独对某一个地图块进行操作。 + * 他会将节点的旋转,缩放,平移操作应用在这个地图块上,并可以通过更换当前地图块的 gid 来更换地图块的显示样式。 + * @class TiledTile + * @extends Component + */ + +import { Component } from '../core/components'; +import { ccclass, help, type } from 'cc.decorator'; +import { TiledLayer } from './tiled-layer'; +import { CCInteger, warn } from '../core'; + +@ccclass('cc.TiledTile') +@help('i18n:cc.TiledTile') +export class TiledTile extends Component { + + _layer: TiledLayer | null = null; + + constructor () { + super(); + } + + @type(CCInteger) + _x = 0; + @type(CCInteger) + _y = 0; + + /** + * !#en Specify the TiledTile horizontal coordinate,use map tile as the unit. + * !#zh 指定 TiledTile 的横向坐标,以地图块为单位 + * @property {Number} x + * @default 0 + */ + + @type(CCInteger) + get x (): number { + return this._x; + } + set x (value) { + if (value === this._x) return; + if (this._layer && this._layer.isInvalidPosition(value, this._y)) { + warn(`Invalid x, the valid value is between [%s] ~ [%s]`, 0, this._layer!.layerSize!.width); + return; + } + this._resetTile(); + this._x = value; + this.updateInfo(); + } + + /** + * !#en Specify the TiledTile vertical coordinate,use map tile as the unit. + * !#zh 指定 TiledTile 的纵向坐标,以地图块为单位 + * @property {Number} y + * @default 0 + */ + @type(CCInteger) + get y () { + return this._y; + } + set y (value: number) { + if (value === this._y) return; + if (this._layer && this._layer.isInvalidPosition(this._x, value)) { + warn(`Invalid y, the valid value is between [%s] ~ [%s]`, 0, this._layer!.layerSize.height); + return; + } + this._resetTile(); + this._y = value; + this.updateInfo(); + } + /** + * !#en Specify the TiledTile gid. + * !#zh 指定 TiledTile 的 gid 值 + * @property {Number} gid + * @default 0 + */ + @type(CCInteger) + get grid (): number { + if (this._layer) { + return this._layer.getTileGIDAt(this._x, this._y) as unknown as number; + } + return 0; + } + set grid (value: number) { + if (this._layer) { + this._layer.setTileGIDAt(value as unknown as any, this._x, this._y); + } + } + + onEnable () { + const parent = this.node.parent!; + this._layer = parent.getComponent('cc.TiledLayer') as TiledLayer; + this._resetTile(); + this.updateInfo(); + } + + onDisable () { + this._resetTile(); + } + + private _resetTile () { + if (this._layer && this._layer.getTiledTileAt(this._x, this._y) === this) { + this._layer.setTiledTileAt(this._x, this._y, null); + } + } + + public updateInfo () { + if (!this._layer) return; + + const x = this._x; + const y = this._y; + if (this._layer.getTiledTileAt(x, y)) { + warn('There is already a TiledTile at [%s, %s]', x, y); + return; + } + const p = this._layer.getPositionAt(x, y); + this.node.setPosition(p!.x, p!.y); + this._layer.setTiledTileAt(x, y, this); + } +} \ No newline at end of file diff --git a/cocos/tiledmap/tiled-types.ts b/cocos/tiledmap/tiled-types.ts new file mode 100644 index 0000000000..dcddf4e6d1 --- /dev/null +++ b/cocos/tiledmap/tiled-types.ts @@ -0,0 +1,594 @@ +/**************************************************************************** + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + + +import { Color, Rect, Size, SpriteFrame, Texture2D, Vec2 } from '../core'; +import { ccenum } from '../core/value-types/enum'; +import { HorizontalTextAlignment, VerticalTextAlignment } from '../ui/components/label'; + + +export type PropertiesInfo = { [key: string]: number | string }; +export type TiledAnimationType = Map; + + +export interface TiledAnimation { + frames: { grid: TiledGrid | null, tileid: GID, duration: number }[]; + dt: number; + frameIdx: number; +} + +/** + * !#en The orientation of tiled map. + * !#zh Tiled Map 地图方向。 + * @enum TiledMap.Orientation + * @static + */ +export enum Orientation { + /** + * !#en Orthogonal orientation. + * !#zh 直角鸟瞰地图(90°地图)。 + * @property ORTHO + * @type {Number} + * @static + */ + ORTHO = 0, + + /** + * !#en Hexagonal orientation. + * !#zh 六边形地图 + * @property HEX + * @type {Number} + * @static + */ + HEX = 1, + + /** + * Isometric orientation. + * 等距斜视地图(斜45°地图)。 + * @property ISO + * @type {Number} + * @static + */ + ISO = 2 +} + +ccenum(Orientation); + +/** + * The property type of tiled map. + * @enum TiledMap.Property + * @static + */ +export enum Property { + /** + * @property NONE + * @type {Number} + * @static + */ + NONE = 0, + + /** + * @property MAP + * @type {Number} + * @static + */ + MAP = 1, + + /** + * @property LAYER + * @type {Number} + * @static + */ + LAYER = 2, + + /** + * @property OBJECTGROUP + * @type {Number} + * @static + */ + OBJECTGROUP = 3, + + /** + * @property OBJECT + * @type {Number} + * @static + */ + OBJECT = 4, + + /** + * @property TILE + * @type {Number} + * @static + */ + TILE = 5 +} + +ccenum(Property); + +/** + * The tile flags of tiled map. + * @enum TiledMap.TileFlag + * @static + */ +export enum TileFlag { + /** + * @property HORIZONTAL + * @type {Number} + * @static + */ + HORIZONTAL = 0x80000000, + + /** + * @property VERTICAL + * @type {Number} + * @static + */ + VERTICAL = 0x40000000, + + /** + * @property DIAGONAL + * @type {Number} + * @static + */ + DIAGONAL = 0x20000000, + + /** + * @property FLIPPED_ALL + * @type {Number} + * @static + */ + FLIPPED_ALL = (0x80000000 | 0x40000000 | 0x20000000 | 0x10000000) >>> 0, + + /** + * @property FLIPPED_MASK + * @type {Number} + * @static + */ + FLIPPED_MASK = (~(0x80000000 | 0x40000000 | 0x20000000 | 0x10000000)) >>> 0 +} + +ccenum(TileFlag); + +/** + * !#en The stagger axis of Hex tiled map. + * !#zh 六边形地图的 stagger axis 值 + * @enum TiledMap.StaggerAxis + * @static + */ +export enum StaggerAxis { + /** + * @property STAGGERAXIS_X + * @type {Number} + * @static + */ + STAGGERAXIS_X = 0, + + /** + * @property STAGGERAXIS_Y + * @type {Number} + * @static + */ + STAGGERAXIS_Y = 1 +} + +ccenum(StaggerAxis); + +/** + * !#en The stagger index of Hex tiled map. + * !#zh 六边形地图的 stagger index 值 + * @enum TiledMap.RenderOrder + * @static + */ +export enum StaggerIndex { + /** + * @property STAGGERINDEX_ODD + * @type {Number} + * @static + */ + STAGGERINDEX_ODD = 0, + + /** + * @property STAGGERINDEX_EVEN + * @type {Number} + * @static + */ + STAGGERINDEX_EVEN = 1 +} +ccenum(StaggerIndex); + +/** + * !#en The render order of tiled map. + * !#zh 地图的渲染顺序 + * @enum TiledMap.RenderOrder + * @static + */ +export enum RenderOrder { + /** + * @property RightDown + * @type {Number} + * @static + */ + RightDown = 0, + /** + * @property RightUp + * @type {Number} + * @static + */ + RightUp = 1, + /** + * @property LeftDown + * @type {Number} + * @static + */ + LeftDown = 2, + /** + * @property LeftUp + * @type {Number} + * @static + */ + LeftUp = 3, +} + +ccenum(RenderOrder); + +/** + * !#en TiledMap Object Type + * !#zh 地图物体类型 + * @enum TiledMap.TMXObjectType + * @static + */ +export enum TMXObjectType { + /** + * @property RECT + * @type {Number} + * @static + */ + RECT = 0, + + /** + * @property ELLIPSE + * @type {Number} + * @static + */ + ELLIPSE = 1, + + /** + * @property POLYGON + * @type {Number} + * @static + */ + POLYGON = 2, + + /** + * @property POLYLINE + * @type {Number} + * @static + */ + POLYLINE = 3, + + /** + * @property IMAGE + * @type {Number} + * @static + */ + IMAGE = 4, + + /** + * @property TEXT + * @type {Number} + * @static + */ + TEXT = 5, +} + +ccenum(TMXObjectType); + +// --- DEBUG types +// export interface MixedGID extends Number { +// _mixed: string +// } +// export interface GID extends Number { +// _gid: string; +// } +// export interface GIDFlags extends Number { +// _flags: number; +// } + +export type MixedGID = number; +export type GID = number; +export type GIDFlags = number; + +/** + * Size in pixels of the image + * @property {cc.Size} imageSize + */ + +/** + *

cc.TMXTilesetInfo contains the information about the tilesets like:
+ * - Tileset name
+ * - Tileset spacing
+ * - Tileset margin
+ * - size of the tiles
+ * - Image used for the tiles
+ * - Image size
+ * + * This information is obtained from the TMX file.

+ * @class TMXTilesetInfo + */ +export class TMXTilesetInfo { + /** + * Tileset name + * @property {string} name + */ + name = ''; + /** + * First grid + * @property {number} firstGid + */ + firstGid: GID = 0 as any; + + /** + * Spacing + * @property {number} spacing + */ + spacing = 0; + + /** + * Margin + * @property {number} margin + */ + + margin = 0; + /** + * Texture containing the tiles (should be sprite sheet / texture atlas) + * @property {cc.SpriteFrame} sourceImage + */ + sourceImage?: SpriteFrame; + // Size in pixels of the image + + imageName: string | null = null; + + imageSize = new Size(0, 0); + + tileOffset = new Vec2(0, 0); + + _tileSize = new Size(0, 0); + + collection = false; + + rectForGID (gid_: MixedGID | GID, result?: TiledGrid) { + const rect = result || new Rect(0, 0, 0, 0); + rect.width = this._tileSize.width; + rect.height = this._tileSize.height; + let gid = gid_ as unknown as number; + gid &= TileFlag.FLIPPED_MASK; + gid = gid - (this.firstGid as unknown as number); + const max_x = Math.floor((this.imageSize.width - this.margin * 2 + this.spacing) / (this._tileSize.width + this.spacing)); + rect.x = Math.round((gid % max_x) * (this._tileSize.width + this.spacing) + this.margin); + rect.y = Math.round(Math.floor(gid / max_x) * (this._tileSize.height + this.spacing) + this.margin); + return rect; + } +}; + + +/** + *

cc.TMXObjectGroupInfo contains the information about the object group like: + * - group name + * - group size + * - group opacity at creation time (it can be modified at runtime) + * - Whether the group is visible + * + * This information is obtained from the TMX file.

+ * @class TMXObjectGroupInfo + */ + +export class TMXObjectGroupInfo { + + /** + * Properties of the ObjectGroup info. + * @property {Array} properties + */ + properties: PropertiesInfo = {} as any; + name: string = ''; + objects: TMXObject[] = []; + visible = true; + opacity = 0; + color: Color = new Color(255, 255, 255, 255); + offset: Vec2 = new Vec2(0, 0); + draworder: DrawOrder = 'topdown'; + + tintColor: Color | null = null; + /** + * Gets the Properties. + * @return {Array} + */ + getProperties () { + return this.properties; + } + + /** + * Set the Properties. + * @param {object} value + */ + setProperties (value: PropertiesInfo) { + this.properties = value; + } +}; + + +export interface TMXObject { + id: number | string; + name: string; + width: number; + height: number; + x: number; + y: number; + rotation: number; + type: TMXObjectType; + visible: boolean; + wrap: boolean; + color: Color; + halign: HorizontalTextAlignment; + valign: VerticalTextAlignment; + pixelsize: number; + text: string; + gid: MixedGID; + points: { x: number, y: number }[]; + polylinePoints: { x: number, y: number }[] | null; + + offset?: Vec2; +} + + +/** + * cc.TMXLayerInfo contains the information about the layers like: + * - Layer name + * - Layer size + * - Layer opacity at creation time (it can be modified at runtime) + * - Whether the layer is visible (if it's not visible, then the CocosNode won't be created) + * This information is obtained from the TMX file. + * @class TMXLayerInfo + */ +export class TMXLayerInfo { + + /** + * Properties of the layer info. + * @property {Object} properties + */ + properties: PropertiesInfo = {} as any; + name = ''; + layerSize: Size | null = null; + tiles: number[] | Uint32Array = []; + visible = true; + opacity = 0; + ownTiles = true; + minGID: GID = 100000 as unknown as GID; + maxGID: GID = 0 as unknown as GID; + offset: Vec2 = new Vec2(0, 0); + tintColor: Color | null = null; + + /** + * Gets the Properties. + * @return {Object} + */ + getProperties () { + return this.properties; + } + + /** + * Set the Properties. + * @param {object} value + */ + setProperties (value: PropertiesInfo) { + this.properties = value; + } + + + /** + * @property ATTRIB_NONE + * @constant + * @static + * @type {Number} + * @default 1 + */ + static ATTRIB_NONE = 1 << 0; + /** + * @property ATTRIB_BASE64 + * @constant + * @static + * @type {Number} + * @default 2 + */ + static ATTRIB_BASE64 = 1 << 1; + /** + * @property ATTRIB_GZIP + * @constant + * @static + * @type {Number} + * @default 4 + */ + static ATTRIB_GZIP = 1 << 2; + /** + * @property ATTRIB_ZLIB + * @constant + * @static + * @type {Number} + * @default 8 + */ + static ATTRIB_ZLIB = 1 << 3; +} + + +/** + * cc.TMXImageLayerInfo contains the information about the image layers. + * This information is obtained from the TMX file. + * @class TMXImageLayerInfo + */ +export class TMXImageLayerInfo { + name = ''; + visible = true; + width = 0; + height = 0; + offset: Vec2 = new Vec2(0, 0); + opacity = 0; + trans = new Color(255, 255, 255, 255); + sourceImage?: SpriteFrame; + + tintColor: Color | null = null; +} + +type DrawOrder = 'topdown' | 'bottomup'; + + +export interface TiledGrid { + + // record texture id + // texId: TexID; + // record belong to which tileset + tileset: TMXTilesetInfo; + x: number; + y: number; + width: number; + height: number; + t: number; + l: number; + r: number; + b: number; + cx: number; + cy: number; + offsetX: number; + offsetY: number; + rotated: boolean; + gid: GID; + spriteFrame: SpriteFrame; + texture: Texture2D; + + _name?: string; + _rect?: Rect; + _rotated?: boolean; +} + + +export type TiledTextureGrids = Map; \ No newline at end of file diff --git a/cocos/tiledmap/tiled-utils.ts b/cocos/tiledmap/tiled-utils.ts new file mode 100644 index 0000000000..f67a1dd84e --- /dev/null +++ b/cocos/tiledmap/tiled-utils.ts @@ -0,0 +1,157 @@ +/**************************************************************************** + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + +import { Rect, SpriteFrame, Texture2D } from '../core'; +import { GID, TiledGrid, TiledTextureGrids, TMXTilesetInfo } from './tiled-types'; + +export function fillTextureGrids (tileset: TMXTilesetInfo, texGrids: TiledTextureGrids, spFrame?: SpriteFrame) { + + const spf: SpriteFrame = spFrame ? spFrame : tileset.sourceImage!; + const tex: Texture2D = spf.texture as Texture2D; + + const collection = tileset.collection; + + if (!tileset.imageSize.width || !tileset.imageSize.height) { + const sourceImage = tileset.sourceImage!; + tileset.imageSize.width = sourceImage.width; + tileset.imageSize.height = sourceImage.height; + } + + const imageWidth = tileset.imageSize.width; + const imageHeight = tileset.imageSize.height; + + const tw = tileset._tileSize.width; + const th = tileset._tileSize.height; + const texWidth = spf.width; + const texHeight = spf.height; + const spacing = tileset.spacing; + const margin = tileset.margin; + + let count = 1; + if (!collection) { + const cols = Math.floor((imageWidth - margin * 2 + spacing) / (tw + spacing)); + const rows = Math.floor((imageHeight - margin * 2 + spacing) / (th + spacing)); + count = Math.max(1, rows * cols); + } + + const firstGid = tileset.firstGid; + let grid: TiledGrid | null = null; + let override = texGrids.get(firstGid) ? true : false; + + // Tiledmap may not be partitioned into blocks, resulting in a count value of 0 + + const maxGid = (tileset.firstGid as unknown as number) + count; + let gid = firstGid as unknown as number; + for (; gid < maxGid; ++gid) { + // Avoid overlapping + if (override && !texGrids.get(gid as unknown as GID)) { + override = false; + } + if (!override && texGrids.get(gid as unknown as GID)) { + break; + } + + grid = { + tileset, + x: 0, y: 0, width: tw, height: th, + t: 0, l: 0, r: 0, b: 0, + cx: 0, cy: 0, + offsetX: 0, + offsetY: 0, + rotated: false, + gid: gid as unknown as GID, + spriteFrame: spf, + texture: tex, + }; + + tileset.rectForGID(gid as unknown as GID, grid); + + if (!spFrame || count > 1) { + if (spFrame) { + grid._name = spFrame.name; + const lm = spFrame.unbiasUV[0]; + const bm = spFrame.rotated ? spFrame.unbiasUV[1] : spFrame.unbiasUV[5]; + grid.l = lm + (grid.x + 0.5) / texWidth; + grid.t = bm + (grid.y + 0.5) / texHeight; + grid.r = lm + (grid.x + grid.width - 0.5) / texWidth; + grid.b = bm + (grid.y + grid.height - 0.5) / texHeight; + grid._rect = new Rect(grid.x, grid.y, grid.width, grid.height); + } else { + grid.l = grid.x / texWidth; + grid.t = grid.y / texHeight; + grid.r = (grid.x + grid.width) / texWidth; + grid.b = (grid.y + grid.height) / texHeight; + grid._rect = new Rect(grid.x, grid.y, grid.width, grid.height); + } + } else if (spFrame.rotated) { + grid._rotated = true; + grid._name = spFrame.name; + grid._rect = spFrame.getRect(); + grid.l = spFrame.unbiasUV[0]; + grid.t = spFrame.unbiasUV[1]; + grid.r = spFrame.unbiasUV[4]; + grid.b = spFrame.unbiasUV[3]; + } else { + grid._name = spFrame.name; + grid._rect = spFrame.getRect(); + grid.l = spFrame.unbiasUV[0]; + grid.t = spFrame.unbiasUV[5]; + grid.r = spFrame.unbiasUV[2]; + grid.b = spFrame.unbiasUV[1]; + } + grid.cx = (grid.l + grid.r) / 2; + grid.cy = (grid.t + grid.b) / 2; + + texGrids.set(gid as unknown as GID, grid); + } +} + + +export function loadAllTextures (textures: SpriteFrame[], loadedCallback: any) { + const totalNum = textures.length; + if (totalNum === 0) { + loadedCallback(); + return; + } + + let curNum = 0; + const itemCallback = () => { + curNum++; + if (curNum >= totalNum) { + loadedCallback(); + } + }; + + for (let i = 0; i < totalNum; i++) { + const tex = textures[i]; + if (!tex.loaded) { + tex.once('load', () => { + itemCallback(); + }); + } else { + itemCallback(); + } + } +} \ No newline at end of file diff --git a/cocos/tiledmap/tmx-xml-parser.ts b/cocos/tiledmap/tmx-xml-parser.ts new file mode 100644 index 0000000000..c5533eea66 --- /dev/null +++ b/cocos/tiledmap/tmx-xml-parser.ts @@ -0,0 +1,1084 @@ +/**************************************************************************** + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + +import { Label, HorizontalTextAlignment, VerticalTextAlignment } from '../ui/components/label'; +import codec from '../../external/compression/ZipUtils.js'; +import zlib from '../../external/compression/zlib.min.js'; +import { SAXParser } from '../core/load-pipeline/plist-parser'; +import { + GID, MixedGID, Orientation, PropertiesInfo, RenderOrder, StaggerAxis, StaggerIndex, TiledAnimation, TiledAnimationType, + TileFlag, TMXImageLayerInfo, TMXLayerInfo, TMXObject, TMXObjectGroupInfo, TMXObjectType, TMXTilesetInfo +} from './tiled-types'; +import { Color, errorID, logID, Size, SpriteFrame, Vec2 } from '../core'; + +function uint8ArrayToUint32Array (uint8Arr: Uint8Array): null | Uint32Array | number[] { + if (uint8Arr.length % 4 !== 0) + return null; + const arrLen = uint8Arr.length / 4; + const retArr = window.Uint32Array ? new Uint32Array(arrLen) : []; + for (let i = 0; i < arrLen; i++) { + const offset = i * 4; + retArr[i] = uint8Arr[offset] + uint8Arr[offset + 1] * (1 << 8) + uint8Arr[offset + 2] * (1 << 16) + uint8Arr[offset + 3] * (1 << 24); + } + return retArr; +} + + +function strToHAlign (value): HorizontalTextAlignment { + const hAlign = Label.HorizontalAlign; + switch (value) { + case 'center': + return hAlign.CENTER; + case 'right': + return hAlign.RIGHT; + default: + return hAlign.LEFT; + } +} + +function strToVAlign (value): VerticalTextAlignment { + const vAlign = Label.VerticalAlign; + switch (value) { + case 'center': + return vAlign.CENTER; + case 'bottom': + return vAlign.BOTTOM; + default: + return vAlign.TOP; + } +} + +function strToColor (value: string): Color { + if (!value) { + return new Color(0, 0, 0, 255); + } + value = (value.indexOf('#') !== -1) ? value.substring(1) : value; + if (value.length === 8) { + const a = parseInt(value.substr(0, 2), 16) || 255; + const r = parseInt(value.substr(2, 2), 16) || 0; + const g = parseInt(value.substr(4, 2), 16) || 0; + const b = parseInt(value.substr(6, 2), 16) || 0; + return new Color(r, g, b, a); + } else { + const r = parseInt(value.substr(0, 2), 16) || 0; + const g = parseInt(value.substr(2, 2), 16) || 0; + const b = parseInt(value.substr(4, 2), 16) || 0; + return new Color(r, g, b, 255); + } +} + +function getPropertyList (node: Element, map?: PropertiesInfo): PropertiesInfo { + const res: any[] = []; + const properties = node.getElementsByTagName('properties'); + for (let i = 0; i < properties.length; ++i) { + const property = properties[i].getElementsByTagName('property'); + for (let j = 0; j < property.length; ++j) { + res.push(property[j]); + } + } + + map = map || ({} as any); + for (let i = 0; i < res.length; i++) { + const element = res[i]; + const name = element.getAttribute('name'); + const type = element.getAttribute('type') || 'string'; + + let value = element.getAttribute('value'); + if (type === 'int') { + value = parseInt(value); + } + else if (type === 'float') { + value = parseFloat(value); + } + else if (type === 'bool') { + value = value === 'true'; + } + else if (type === 'color') { + value = strToColor(value); + } + + map![name] = value; + } + + return map!; +} + + +/** + *

cc.TMXMapInfo contains the information about the map like:
+ * - Map orientation (hexagonal, isometric or orthogonal)
+ * - Tile size
+ * - Map size

+ * + *

And it also contains:
+ * - Layers (an array of TMXLayerInfo objects)
+ * - Tilesets (an array of TMXTilesetInfo objects)
+ * - ObjectGroups (an array of TMXObjectGroupInfo objects)

+ * + *

This information is obtained from the TMX file.

+ * @class TMXMapInfo + */ + +export class TMXMapInfo { + + /** + * Properties of the map info. + * @property {Array} properties + */ + properties: PropertiesInfo = {} as any; + + /** + * Map orientation. + * @property {Number} orientation + */ + orientation: Orientation | null = null; + + /** + * Parent element. + * @property {Object} parentElement + */ + parentElement: Object | null = null; + + /** + * Parent GID. + * @property {Number} parentGID + */ + parentGID: MixedGID = 0 as unknown as any; + + /** + * Layer attributes. + * @property {Object} layerAttrs + */ + layerAttrs = 0; + + /** + * Is reading storing characters stream. + * @property {Boolean} storingCharacters + */ + storingCharacters = false; + + /** + * Current string stored from characters stream. + * @property {String} currentString + */ + currentString: string | null = null; + renderOrder: RenderOrder = RenderOrder.RightDown; + + protected _supportVersion = [1, 4, 0]; + protected _objectGroups: TMXObjectGroupInfo[] = []; + protected _allChildren: (TMXLayerInfo | TMXImageLayerInfo | TMXObjectGroupInfo)[] = []; + protected _mapSize = new Size(0, 0); + get mapSize () { return this._mapSize; } + protected _tileSize = new Size(0, 0); + get tileSize () { return this._tileSize; } + protected _layers: TMXLayerInfo[] = []; + protected _tilesets: TMXTilesetInfo[] = []; + protected _imageLayers: TMXImageLayerInfo[] = []; + protected _tileProperties: Map = new Map(); + protected _tileAnimations: TiledAnimationType = {} as any; + protected _tsxContentMap: { [key: string]: string } | null = null; + + // map of textures indexed by name + protected _spriteFrameMap: { [key: string]: SpriteFrame } | null = null; + protected _spfSizeMap: { [key: string]: Size } = {}; + + // hex map values + protected _staggerAxis: StaggerAxis | null = null; + protected _staggerIndex: StaggerIndex | null = null; + protected _hexSideLength = 0; + + protected _imageLayerSPF: { [key: string]: SpriteFrame } | null = null; + + constructor (tmxFile: string, tsxContentMap: { [key: string]: string }, spfTexturesMap: { [key: string]: SpriteFrame }, + textureSizes: { [key: string]: Size }, imageLayerTextures: { [key: string]: SpriteFrame }) { + this.initWithXML(tmxFile, tsxContentMap, spfTexturesMap, textureSizes, imageLayerTextures); + } + + /* Gets Map orientation. + * @return {Number} + */ + getOrientation () { + return this.orientation; + } + + /** + * Set the Map orientation. + * @param {Number} value + */ + setOrientation (value: Orientation) { + this.orientation = value; + } + /** + * Gets the staggerAxis of map. + * @return {TiledMap.StaggerAxis} + */ + getStaggerAxis () { + return this._staggerAxis; + } + + /** + * Set the staggerAxis of map. + * @param {TiledMap.StaggerAxis} value + */ + setStaggerAxis (value: StaggerAxis) { + this._staggerAxis = value; + } + + /** + * Gets stagger index + * @return {TiledMap.StaggerIndex} + */ + getStaggerIndex () { + return this._staggerIndex; + } + + /** + * Set the stagger index. + * @param {TiledMap.StaggerIndex} value + */ + setStaggerIndex (value) { + this._staggerIndex = value; + } + + /** + * Gets Hex side length. + * @return {Number} + */ + getHexSideLength () { + return this._hexSideLength; + } + + /** + * Set the Hex side length. + * @param {Number} value + */ + setHexSideLength (value: number) { + this._hexSideLength = value; + } + + /** + * Map width & height + * @return {Size} + */ + getMapSize () { + return new Size(this._mapSize.width, this._mapSize.height); + } + + /** + * Map width & height + * @param {Size} value + */ + setMapSize (value: Size) { + this._mapSize.width = value.width; + this._mapSize.height = value.height; + } + + get mapWidth () { + return this._mapSize.width; + } + set mapWidth (width: number) { + this._mapSize.width = width; + } + + get mapHeight () { + return this._mapSize.height; + } + set mapHeight (height: number) { + this._mapSize.height = height; + } + + /** + * Tiles width & height + * @return {Size} + */ + getTileSize () { + return new Size(this._tileSize.width, this._tileSize.height); + } + + /** + * Tiles width & height + * @param {Size} value + */ + setTileSize (value: Size) { + this._tileSize.width = value.width; + this._tileSize.height = value.height; + } + + get tileWidth () { + return this._tileSize.width; + } + + set tileWidth (width) { + this._tileSize.width = width; + } + + /** + * Height of a tile + */ + get tileHeight () { + return this._tileSize.height; + } + + set tileHeight (height: number) { + this._tileSize.height = height; + } + + /** + * Layers + * @return {Array} + */ + getLayers () { + return this._layers; + } + + /** + * Layers + * @param {cc.TMXLayerInfo} value + */ + setLayers (value: TMXLayerInfo) { + this._allChildren.push(value); + this._layers.push(value); + } + + /** + * ImageLayers + * @return {Array} + */ + getImageLayers () { + return this._imageLayers; + } + + /** + * ImageLayers + * @param {cc.TMXImageLayerInfo} value + */ + setImageLayers (value: TMXImageLayerInfo) { + this._allChildren.push(value); + this._imageLayers.push(value); + } + + /** + * tilesets + * @return {Array} + */ + getTilesets () { + return this._tilesets; + } + + /** + * tilesets + * @param {cc.TMXTilesetInfo} value + */ + setTilesets (value: TMXTilesetInfo) { + this._tilesets.push(value); + } + + /** + * ObjectGroups + * @return {Array} + */ + getObjectGroups () { + return this._objectGroups; + } + + /** + * ObjectGroups + * @param {cc.TMXObjectGroup} value + */ + setObjectGroups (value: TMXObjectGroupInfo) { + this._allChildren.push(value); + this._objectGroups.push(value); + } + + getAllChildren () { + return this._allChildren; + } + + /** + * parent element + * @return {Object} + */ + getParentElement () { + return this.parentElement; + } + + /** + * parent element + * @param {Object} value + */ + setParentElement (value) { + this.parentElement = value; + } + + /** + * parent GID + * @return {Number} + */ + getParentGID () { + return this.parentGID; + } + + /** + * parent GID + * @param {Number} value + */ + setParentGID (value) { + this.parentGID = value; + } + + /** + * Layer attribute + * @return {Object} + */ + getLayerAttribs () { + return this.layerAttrs; + } + + /** + * Layer attribute + * @param {Object} value + */ + setLayerAttribs (value) { + this.layerAttrs = value; + } + + /** + * Is reading storing characters stream + * @return {Boolean} + */ + getStoringCharacters () { + return this.storingCharacters; + } + + /** + * Is reading storing characters stream + * @param {Boolean} value + */ + setStoringCharacters (value) { + this.storingCharacters = value; + } + + /** + * Properties + * @return {Array} + */ + getProperties () { + return this.properties; + } + + /** + * Properties + * @param {object} value + */ + setProperties (value) { + this.properties = value; + } + + /** + * initializes a TMX format with an XML string and a TMX resource path + * @param {String} tmxString + * @param {Object} tsxMap + * @param {Object} spfTextureMap + * @return {Boolean} + */ + initWithXML (tmxString: string, tsxMap: { [key: string]: string }, spfTextureMap: { [key: string]: SpriteFrame }, + textureSizes: { [key: string]: Size }, imageLayerTextures: { [key: string]: SpriteFrame }) { + this._tilesets.length = 0; + this._layers.length = 0; + this._imageLayers.length = 0; + + this._tsxContentMap = tsxMap; + this._spriteFrameMap = spfTextureMap; + this._imageLayerSPF = imageLayerTextures; + this._spfSizeMap = textureSizes; + + this._objectGroups.length = 0; + this._allChildren.length = 0; + this.properties = {} as any; + this._tileProperties = new Map(); + this._tileAnimations = new Map(); + + // tmp vars + this.currentString = ''; + this.storingCharacters = false; + this.layerAttrs = TMXLayerInfo.ATTRIB_NONE; + this.parentElement = null; + + return this.parseXMLString(tmxString); + } + + /** + * Initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string + * @param {String} xmlString + * @param {Number} tilesetFirstGid + * @return {Element} + */ + parseXMLString (xmlStr: string, tilesetFirstGid?: number) { + const parser = new SAXParser(); + const mapXML: Document = parser._parseXML(xmlStr); + let i: number; + + // PARSE + const map = mapXML.documentElement; + + const orientationStr = map.getAttribute('orientation'); + const staggerAxisStr = map.getAttribute('staggeraxis'); + const staggerIndexStr = map.getAttribute('staggerindex'); + const hexSideLengthStr = map.getAttribute('hexsidelength'); + const renderorderStr = map.getAttribute('renderorder'); + const version = map.getAttribute('version') || '1.0.0'; + + if (map.nodeName === 'map') { + const versionArr = version.split('.'); + const supportVersion = this._supportVersion; + for (i = 0; i < supportVersion.length; i++) { + const v = parseInt(versionArr[i]) || 0; + const sv = supportVersion[i]; + if (sv < v) { + logID(7216, version); + break; + } + } + + if (orientationStr === 'orthogonal') + this.orientation = Orientation.ORTHO; + else if (orientationStr === 'isometric') + this.orientation = Orientation.ISO; + else if (orientationStr === 'hexagonal') + this.orientation = Orientation.HEX; + else if (orientationStr !== null) + logID(7217, orientationStr); + + if (renderorderStr === 'right-up') { + this.renderOrder = RenderOrder.RightUp; + } else if (renderorderStr === 'left-up') { + this.renderOrder = RenderOrder.LeftUp; + } else if (renderorderStr === 'left-down') { + this.renderOrder = RenderOrder.LeftDown; + } else { + this.renderOrder = RenderOrder.RightDown; + } + + if (staggerAxisStr === 'x') { + this.setStaggerAxis(StaggerAxis.STAGGERAXIS_X); + } + else if (staggerAxisStr === 'y') { + this.setStaggerAxis(StaggerAxis.STAGGERAXIS_Y); + } + + if (staggerIndexStr === 'odd') { + this.setStaggerIndex(StaggerIndex.STAGGERINDEX_ODD); + } + else if (staggerIndexStr === 'even') { + this.setStaggerIndex(StaggerIndex.STAGGERINDEX_EVEN); + } + + if (hexSideLengthStr) { + this.setHexSideLength(parseFloat(hexSideLengthStr)); + } + + let mapSize = new Size(0, 0); + mapSize.width = parseFloat(map.getAttribute('width')!); + mapSize.height = parseFloat(map.getAttribute('height')!); + this.setMapSize(mapSize); + + mapSize = new Size(0, 0); + mapSize.width = parseFloat(map.getAttribute('tilewidth')!); + mapSize.height = parseFloat(map.getAttribute('tileheight')!); + this.setTileSize(mapSize); + + // The parent element is the map + this.properties = getPropertyList(map); + } + + // PARSE + let tilesets: Element[] = map.getElementsByTagName('tileset') as unknown as Element[]; + if (map.nodeName !== 'map') { + tilesets = []; + tilesets.push(map); + } + + for (i = 0; i < tilesets.length; i++) { + const selTileset = tilesets[i]; + // If this is an external tileset then start parsing that + const tsxName = selTileset.getAttribute('source'); + if (tsxName) { + const currentFirstGID = parseInt(selTileset.getAttribute('firstgid')!); + const tsxXmlString = this._tsxContentMap![tsxName]; + if (tsxXmlString) { + this.parseXMLString(tsxXmlString, currentFirstGID); + } + } else { + const images = selTileset.getElementsByTagName('image'); + const collection = images.length > 1; + const firstImage = images[0]; + let firstImageName: string = firstImage.getAttribute('source')!; + firstImageName = firstImageName.replace(/\\/g, '\/'); + + const tiles = selTileset.getElementsByTagName('tile'); + const tileCount = tiles && tiles.length || 1; + let tile: Element | null = null; + + const tilesetName = selTileset.getAttribute('name') || ''; + const tilesetSpacing = parseInt(selTileset.getAttribute('spacing')!) || 0; + const tilesetMargin = parseInt(selTileset.getAttribute('margin')!) || 0; + const fgid = tilesetFirstGid ? tilesetFirstGid : (parseInt(selTileset.getAttribute('firstgid')!) || 0); + + const tilesetSize = new Size(0, 0); + tilesetSize.width = parseFloat(selTileset.getAttribute('tilewidth')!); + tilesetSize.height = parseFloat(selTileset.getAttribute('tileheight')!); + + // parse tile offset + const firstTileOffset = selTileset.getElementsByTagName('tileoffset')[0]; + let tileOffsetX = 0; + let tileOffsetY = 0; + if (firstTileOffset) { + tileOffsetX = parseFloat(firstTileOffset.getAttribute('x')!) || 0; + tileOffsetY = parseFloat(firstTileOffset.getAttribute('y')!) || 0; + } + + let tileset: TMXTilesetInfo | null = null; + for (let tileIdx = 0; tileIdx < tileCount; tileIdx++) { + if (!tileset || collection) { + tileset = new TMXTilesetInfo(); + tileset.name = tilesetName; + tileset.firstGid = ((fgid as unknown as number) & TileFlag.FLIPPED_MASK) as unknown as GID; + tileset.tileOffset.x = tileOffsetX; + tileset.tileOffset.y = tileOffsetY; + + tileset.collection = collection; + if (!collection) { + + tileset.imageName = firstImageName; + tileset.imageSize.width = parseFloat(firstImage.getAttribute('width')!) || 0; + tileset.imageSize.height = parseFloat(firstImage.getAttribute('height')!) || 0; + tileset.sourceImage = this._spriteFrameMap![firstImageName]; + if (!tileset.sourceImage) { + const shortName = TMXMapInfo.getShortName(firstImageName); + tileset.imageName = shortName; + tileset.sourceImage = this._spriteFrameMap![shortName]; + if (!tileset.sourceImage) { + console.error(`[error]: ${shortName} not find in [${Object.keys(this._spriteFrameMap!).join(', ')}]`); + errorID(7221, firstImageName); + console.warn(`Please try asset type of ${firstImageName} to 'sprite-frame'`); + } + } + } + + tileset.spacing = tilesetSpacing; + tileset.margin = tilesetMargin; + tileset._tileSize.width = tilesetSize.width; + tileset._tileSize.height = tilesetSize.height; + + this.setTilesets(tileset); + } + + tile = tiles && tiles[tileIdx]; + if (!tile) { + continue; + } + + this.parentGID = (fgid + (parseInt(tile.getAttribute('id')!) || 0)) as any; + const tileImages = tile.getElementsByTagName('image'); + if (tileImages && tileImages.length > 0) { + const image = tileImages[0]; + let imageName = image.getAttribute('source')!; + imageName = imageName.replace(/\\/g, '\/'); + + tileset.imageName = imageName; + tileset.imageSize.width = parseFloat(image.getAttribute('width')!) || 0; + tileset.imageSize.height = parseFloat(image.getAttribute('height')!) || 0; + + tileset._tileSize.width = tileset.imageSize.width; + tileset._tileSize.height = tileset.imageSize.height; + + tileset.sourceImage = this._spriteFrameMap![imageName]; + if (!tileset.sourceImage) { + const shortName = TMXMapInfo.getShortName(imageName); + tileset.imageName = shortName; + tileset.sourceImage = this._spriteFrameMap![shortName]; + if (!tileset.sourceImage) { + errorID(7221, imageName); + console.warn(`Please try asset type of ${imageName} to 'sprite-frame'`); + } + } + + tileset.firstGid = ((this.parentGID as unknown as number) & TileFlag.FLIPPED_MASK) as unknown as GID;; + } + const pid = ((TileFlag.FLIPPED_MASK & this.parentGID as unknown as number) >>> 0) as unknown as GID; + this._tileProperties.set(pid, getPropertyList(tile)); + const animations = tile.getElementsByTagName('animation'); + if (animations && animations.length > 0) { + const animation = animations[0]; + const framesData = animation.getElementsByTagName('frame'); + const animationProp: TiledAnimation = { frames: [], dt: 0, frameIdx: 0 }; + this._tileAnimations.set(pid, animationProp); + const frames = animationProp.frames; + for (let frameIdx = 0; frameIdx < framesData.length; frameIdx++) { + const frame = framesData[frameIdx]; + const tileid = fgid + (parseInt(frame.getAttribute('tileid')!) || 0); + const duration = parseFloat(frame.getAttribute('duration')!) || 0; + frames.push({ tileid: tileid as unknown as GID, duration: duration / 1000, grid: null }); + } + } + } + } + } + + // PARSE & in order + const childNodes = map.childNodes; + for (i = 0; i < childNodes.length; i++) { + const childNode = childNodes[i]; + if (this._shouldIgnoreNode(childNode)) { + continue; + } + + if (childNode.nodeName === 'imagelayer') { + const imageLayer = this._parseImageLayer(childNode as Element); + if (imageLayer) { + this.setImageLayers(imageLayer); + } + } + + if (childNode.nodeName === 'layer') { + const layer = this._parseLayer(childNode as Element); + this.setLayers(layer!); + } + + if (childNode.nodeName === 'objectgroup') { + const objectGroup = this._parseObjectGroup(childNode as Element); + this.setObjectGroups(objectGroup); + } + } + + return map; + } + + protected _shouldIgnoreNode (node: ChildNode): boolean { + return node.nodeType === 3 // text + || node.nodeType === 8 // comment + || node.nodeType === 4; // cdata + } + + protected _parseImageLayer (selLayer: Element) { + const datas = selLayer.getElementsByTagName('image'); + if (!datas || datas.length === 0) return null; + + const imageLayer = new TMXImageLayerInfo(); + imageLayer.name = selLayer.getAttribute('name')!; + imageLayer.offset.x = parseFloat(selLayer.getAttribute('offsetx')!) || 0; + imageLayer.offset.y = parseFloat(selLayer.getAttribute('offsety')!) || 0; + const visible = selLayer.getAttribute('visible'); + imageLayer.visible = !(visible === '0'); + + const opacity = selLayer.getAttribute('opacity'); + imageLayer.opacity = opacity ? Math.round(255 * parseFloat(opacity)) : 255; + + const tintColor = selLayer.getAttribute('tintcolor'); + imageLayer.tintColor = tintColor ? strToColor(tintColor) : null; + + const data = datas[0]; + const source = data.getAttribute('source'); + imageLayer.sourceImage = this._imageLayerSPF![source!]; + imageLayer.width = parseInt(data.getAttribute('width')!) || 0; + imageLayer.height = parseInt(data.getAttribute('height')!) || 0; + imageLayer.trans = strToColor(data.getAttribute('trans')!); + + if (!imageLayer.sourceImage) { + errorID(7221, source); + console.warn(`Please try asset type of ${source} to 'sprite-frame'`); + return null; + } + return imageLayer; + } + + protected _parseLayer (selLayer: Element) { + const data = selLayer.getElementsByTagName('data')[0]; + + const layer = new TMXLayerInfo(); + layer.name = selLayer.getAttribute('name')!; + + const layerSize = new Size(0, 0); + layerSize.width = parseFloat(selLayer.getAttribute('width')!); + layerSize.height = parseFloat(selLayer.getAttribute('height')!); + layer.layerSize = layerSize; + + const visible = selLayer.getAttribute('visible'); + layer.visible = !(visible === '0'); + + const opacity = selLayer.getAttribute('opacity'); + if (opacity) + layer.opacity = Math.round(255 * parseFloat(opacity)); + else + layer.opacity = 255; + layer.offset = new Vec2(parseFloat(selLayer.getAttribute('offsetx')!) || 0, parseFloat(selLayer.getAttribute('offsety')!) || 0); + + const tintColor = selLayer.getAttribute('tintcolor'); + layer.tintColor = tintColor ? strToColor(tintColor) : null; + + let nodeValue = ''; + for (let j = 0; j < data.childNodes.length; j++) { + nodeValue += data.childNodes[j].nodeValue + } + nodeValue = nodeValue.trim(); + + // Unpack the tilemap data + const compression = data.getAttribute('compression'); + const encoding = data.getAttribute('encoding'); + if (compression && compression !== 'gzip' && compression !== 'zlib') { + logID(7218); + return null; + } + let tiles; + switch (compression) { + case 'gzip': + tiles = codec.unzipBase64AsArray(nodeValue, 4); + break; + case 'zlib': + const inflator = new zlib.Inflate(codec.Base64.decodeAsArray(nodeValue, 1)); + tiles = uint8ArrayToUint32Array(inflator.decompress()); + break; + case null: + case '': + // Uncompressed + if (encoding === 'base64') + tiles = codec.Base64.decodeAsArray(nodeValue, 4); + else if (encoding === 'csv') { + tiles = []; + const csvTiles = nodeValue.split(','); + for (let csvIdx = 0; csvIdx < csvTiles.length; csvIdx++) + tiles.push(parseInt(csvTiles[csvIdx])); + } else { + // XML format + const selDataTiles = data.getElementsByTagName('tile'); + tiles = []; + for (let xmlIdx = 0; xmlIdx < selDataTiles.length; xmlIdx++) + tiles.push(parseInt(selDataTiles[xmlIdx].getAttribute('gid')!)); + } + break; + default: + if (this.layerAttrs === TMXLayerInfo.ATTRIB_NONE) + logID(7219); + break; + } + if (tiles) { + layer.tiles = new Uint32Array(tiles); + } + + // The parent element is the last layer + layer.properties = getPropertyList(selLayer); + + return layer; + } + + protected _parseObjectGroup (selGroup: Element) { + const objectGroup = new TMXObjectGroupInfo(); + objectGroup.name = selGroup.getAttribute('name') || ''; + objectGroup.offset = new Vec2(parseFloat(selGroup.getAttribute('offsetx')!), parseFloat(selGroup.getAttribute('offsety')!)); + + const opacity = selGroup.getAttribute('opacity'); + if (opacity) + objectGroup.opacity = Math.round(255 * parseFloat(opacity)); + else + objectGroup.opacity = 255; + + const tintColor = selGroup.getAttribute('tintcolor'); + objectGroup.tintColor = tintColor ? strToColor(tintColor) : null; + + const visible = selGroup.getAttribute('visible'); + if (visible && parseInt(visible) === 0) + objectGroup.visible = false; + + const color = selGroup.getAttribute('color'); + if (color) + objectGroup.color.fromHEX(color); + + const draworder = selGroup.getAttribute('draworder'); + if (draworder) + objectGroup.draworder = draworder as any; + + // set the properties to the group + objectGroup.setProperties(getPropertyList(selGroup)); + + const objects = selGroup.getElementsByTagName('object'); + if (objects) { + for (let j = 0; j < objects.length; j++) { + const selObj = objects[j]; + // The value for "type" was blank or not a valid class name + // Create an instance of TMXObjectInfo to store the object and its properties + const objectProp: TMXObject = {} as any; + + // Set the id of the object + objectProp.id = selObj.getAttribute('id') || j; + + // Set the name of the object to the value for "name" + objectProp.name = selObj.getAttribute('name') || ''; + + // Assign all the attributes as key/name pairs in the properties dictionary + objectProp.width = parseFloat(selObj.getAttribute('width')!) || 0; + objectProp.height = parseFloat(selObj.getAttribute('height')!) || 0; + + objectProp.x = parseFloat(selObj.getAttribute('x')!) || 0; + objectProp.y = parseFloat(selObj.getAttribute('y')!) || 0; + + objectProp.rotation = parseFloat(selObj.getAttribute('rotation')!) || 0; + + getPropertyList(selObj, objectProp as any); + + // visible + const visibleAttr = selObj.getAttribute('visible'); + objectProp.visible = !(visibleAttr && parseInt(visibleAttr) === 0); + + // text + const texts = selObj.getElementsByTagName('text'); + if (texts && texts.length > 0) { + const text = texts[0]; + objectProp.type = TMXObjectType.TEXT; + objectProp.wrap = text.getAttribute('wrap') === '1'; + objectProp.color = strToColor(text.getAttribute('color')!); + objectProp.halign = strToHAlign(text.getAttribute('halign')); + objectProp.valign = strToVAlign(text.getAttribute('valign')); + objectProp.pixelsize = parseInt(text.getAttribute('pixelsize')!) || 16; + objectProp.text = text.childNodes[0].nodeValue!; + } + + // image + const gid = selObj.getAttribute('gid'); + if (gid) { + objectProp.gid = parseInt(gid) as any; + objectProp.type = TMXObjectType.IMAGE; + } + + // ellipse + const ellipse = selObj.getElementsByTagName('ellipse'); + if (ellipse && ellipse.length > 0) { + objectProp.type = TMXObjectType.ELLIPSE; + } + + // polygon + const polygonProps = selObj.getElementsByTagName('polygon'); + if (polygonProps && polygonProps.length > 0) { + objectProp.type = TMXObjectType.POLYGON; + const selPgPointStr = polygonProps[0].getAttribute('points'); + if (selPgPointStr) + objectProp.points = this._parsePointsString(selPgPointStr)!; + } + + // polyline + const polylineProps = selObj.getElementsByTagName('polyline'); + if (polylineProps && polylineProps.length > 0) { + objectProp.type = TMXObjectType.POLYLINE; + const selPlPointStr = polylineProps[0].getAttribute('points'); + if (selPlPointStr) + objectProp.polylinePoints = this._parsePointsString(selPlPointStr)!; + } + + if (!objectProp.type) { + objectProp.type = TMXObjectType.RECT; + } + + // Add the object to the objectGroup + objectGroup.objects.push(objectProp); + } + + if (draworder !== 'index') { + objectGroup.objects.sort((a, b) => { + return a.y - b.y; + }); + } + } + return objectGroup; + } + + protected _parsePointsString (pointsString?: string) { + if (!pointsString) + return null; + + const points: { x: number, y: number }[] = []; + const pointsStr = pointsString.split(' '); + for (let i = 0; i < pointsStr.length; i++) { + const selPointStr = pointsStr[i].split(','); + points.push({ x: parseFloat(selPointStr[0]), y: parseFloat(selPointStr[1]) }); + } + return points; + } + + /** + * Sets the tile animations. + * @return {Object} + */ + setTileAnimations (animations: TiledAnimationType) { + this._tileAnimations = animations; + } + + /** + * Gets the tile animations. + * @return {Object} + */ + getTileAnimations (): TiledAnimationType { + return this._tileAnimations; + } + + /** + * Gets the tile properties. + * @return {Object} + */ + getTileProperties () { + return this._tileProperties; + } + + /** + * Set the tile properties. + * @param {Object} tileProperties + */ + setTileProperties (tileProperties: Map) { + this._tileProperties = tileProperties; + } + + /** + * Gets the currentString + * @return {String} + */ + getCurrentString () { + return this.currentString; + } + + /** + * Set the currentString + * @param {String} currentString + */ + setCurrentString (currentString: string) { + this.currentString = currentString; + } + + static getShortName (name: string) { + name = name.replace(/\\/g, '\/'); + const splashIndex = name.lastIndexOf('/') + 1; + let dotIndex = name.lastIndexOf('.'); + dotIndex = dotIndex < 0 ? name.length : dotIndex; + return name.substring(splashIndex, dotIndex); + } + +} diff --git a/cocos/ui/assembler/index.ts b/cocos/ui/assembler/index.ts index 5340914bdb..1b669bd0dd 100644 --- a/cocos/ui/assembler/index.ts +++ b/cocos/ui/assembler/index.ts @@ -33,5 +33,4 @@ export * from './graphics'; export * from './label'; export * from './mask'; export * from './sprite'; - export * from '../../core/renderer/ui/base'; diff --git a/exports/tiled-map.ts b/exports/tiled-map.ts new file mode 100644 index 0000000000..5c1cd66a78 --- /dev/null +++ b/exports/tiled-map.ts @@ -0,0 +1,2 @@ + +export * from '../cocos/tiledmap'; \ No newline at end of file diff --git a/external/compression/ZipUtils.d.ts b/external/compression/ZipUtils.d.ts index 9b603a1d6e..e7242655ef 100644 --- a/external/compression/ZipUtils.d.ts +++ b/external/compression/ZipUtils.d.ts @@ -1,6 +1,35 @@ - -declare namespace codec { - export function unzipBase64AsArray(input: string, bytes: number): Array; +import b64 from "./base64"; +import gzip from "./gzip"; +export declare module codec { + const name = "Jacob__Codec"; + export const Base64: typeof b64; + export const GZip: typeof gzip; + /** + * Unpack a gzipped byte array + * @param {Array} input Byte array + * @returns {String} Unpacked byte string + */ + export function unzip(args: string | number[]): string; + /** + * Unpack a gzipped byte string encoded as base64 + * @param {String} input Byte string encoded as base64 + * @returns {String} Unpacked byte string + */ + export function unzipBase64(arg: string): string; + /** + * Unpack a gzipped byte string encoded as base64 + * @param {String} input Byte string encoded as base64 + * @param {Number} bytes Bytes per array item + * @returns {Array} Unpacked byte array + */ + export function unzipBase64AsArray(input: string, bytes?: number): number[]; + /** + * Unpack a gzipped byte array + * @param {Array} input Byte array + * @param {Number} bytes Bytes per array item + * @returns {Array} Unpacked byte array + */ + export function unzipAsArray(input: number[], bytes?: number): number[]; } export default codec; \ No newline at end of file diff --git a/external/compression/base64.d.ts b/external/compression/base64.d.ts index a6e2b3ea2b..6ec3fd1552 100644 --- a/external/compression/base64.d.ts +++ b/external/compression/base64.d.ts @@ -1,10 +1,33 @@ - -declare namespace Base64 { - export const name: string; - - export function decode(input: string): string; - - export function decodeAsArray(input: string): number[]; +/** + * mixin cc.Codec.Base64 + */ +export declare class Base64 { + static name_: string; + /** + *

+ * cc.Codec.Base64.decode(input[, unicode=false]) -> String (http://en.wikipedia.org/wiki/Base64). + *

+ * @function + * @param {String} input The base64 encoded string to decode + * @return {String} Decodes a base64 encoded String + * @example + * //decode string + * cc.Codec.Base64.decode("U29tZSBTdHJpbmc="); // => "Some String" + */ + static decode(input: string): string; + /** + *

+ * Converts an input string encoded in base64 to an array of integers whose
+ * values represent the decoded string's characters' bytes. + *

+ * @function + * @param {String} input The String to convert to an array of Integers + * @param {Number} bytes + * @return {Array} + * @example + * //decode string to array + * var decodeArr = cc.Codec.Base64.decodeAsArray("U29tZSBTdHJpbmc="); + */ + static decodeAsArray(input: string, bytes: number): number[]; } - export default Base64; diff --git a/external/compression/gzip.d.ts b/external/compression/gzip.d.ts index 0a95480dcf..5f113c482b 100644 --- a/external/compression/gzip.d.ts +++ b/external/compression/gzip.d.ts @@ -1,6 +1,54 @@ - -declare namespace GZip { - +/** + * See cc.Codec.GZip.gunzip. + * @param {Array | String} data The bytestream to decompress + * Constructor + */ +declare class HufNode { + b0: number; + b1: number; + jump: any; + jumppos: number; +} +export declare class GZip { + constructor(data: string | number[]); + /** + * Unzips the gzipped data of the 'data' argument. + * @param string The bytestream to decompress. Either an array of Integers between 0 and 255, or a String. + * @return {String} + */ + static gunzip(string: string | number[]): string; + static HufNode: typeof HufNode; + /** + * @constant + * @type Number + */ + static LITERALS: number; + /** + * @constant + * @type Number + */ + static NAMEMAX: number; + static bitReverse: number[]; + /** + * gunzip + * @return {Array} + */ + gunzip(): string[][]; + readByte_array(): number; + readByte_string(): number; + byteAlign(): void; + readBit(): number; + readBits(a: number): number; + flushBuffer(): void; + addBuffer(a: number): void; + IsPat(): number; + Rec(): 0 | -1; + CreateTree(currentTree: any, numval: any, lengths: any, show: any): 0 | -1; + DecodeValue(currentTree: any): any; + DeflateLoop(): 1 | 0; + unzipFile(name: string): string; + nextFile(): void; + skipdir(): number; } export default GZip; \ No newline at end of file diff --git a/external/compression/zlib.min.d.ts b/external/compression/zlib.min.d.ts index 2c2db609e1..8eeee4c862 100644 --- a/external/compression/zlib.min.d.ts +++ b/external/compression/zlib.min.d.ts @@ -1,6 +1,6 @@ declare namespace zlib { - export function Inflate(data: any, info: any): void; + export function Inflate(data: any, info?: any): void; } export default zlib; diff --git a/index.ts b/index.ts index 81121e7630..9aaf05f0b9 100644 --- a/index.ts +++ b/index.ts @@ -20,3 +20,4 @@ export * from './exports/physics-ammo'; export * from './exports/physics-2d-framework'; export * from './exports/physics-2d-box2d'; export * from './exports/particle-2d'; +export * from './exports/tiled-map'; diff --git a/scripts/module-division/division-config.json b/scripts/module-division/division-config.json index a981393df8..f4a44e4ced 100644 --- a/scripts/module-division/division-config.json +++ b/scripts/module-division/division-config.json @@ -122,6 +122,12 @@ "description": "Terrain support", "entry": "terrain", "default": true + }, + { + "text": "TiledMap", + "description": "TimedMap support", + "entry": "tiled-map", + "default": true } ] }