This commit is contained in:
jerrywwl
2019-01-08 20:02:39 +08:00
13 changed files with 1575 additions and 1594 deletions
-285
View File
@@ -1,285 +0,0 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import GFXTextureCube from '../../renderer/gfx/texture-cube';
import TextureBase from '../../assets/texture-base';
import { ccclass, property } from '../../core/data/class-decorator';
import ImageAsset from '../../assets/image-asset';
/**
* @typedef {import("../../assets/texture-2d")} Texture2D
* @typedef {import("../../assets/texture-base").ImageSource} ImageSource
* @typedef {import("../../assets/texture-base").TextureUpdateOpts} TextureUpdateOpts
* @typedef {import("../../assets/texture-base").HTMLImageSource} HTMLImageSource
* @typedef {{front: HTMLImageSource, back: HTMLImageSource, left: HTMLImageSource, right: HTMLImageSource, top: HTMLImageSource, bottom: HTMLImageSource}} MipmapHTMLImageSource
* @typedef {{front: ImageAsset, back: ImageAsset, left: ImageAsset, right: ImageAsset, top: ImageAsset, bottom: ImageAsset}} Mipmap
*/
/**
* @enum {number}
*/
const FaceIndex = cc.Enum({
right: 0,
left: 1,
top: 2,
bottom: 3,
front: 4,
back: 5
});
@ccclass('cc.TextureCube')
export default class TextureCube extends TextureBase {
/**
* @type {Mipmap[]}
*/
@property
_mipmaps = [];
constructor() {
super();
/**
* @type {GFXTextureCube}
*/
this._texture = null;
}
/**
* Gets the mipmap images.
* Note that the result do not contains the auto generated mipmaps.
* @type {Mipmap[]}
*/
get mipmaps() {
return this._mipmaps;
}
/**
* Sets the mipmaps images.
* @type {Mipmap[]}
*/
set mipmaps(value) {
this._setMipmaps(value);
}
/**
* Gets the mipmap image at level 0.
* @type {Mipmap}
*/
get image() {
return this._mipmaps.length === 0 ? null : this._mipmaps[0];
}
/**
* Sets the mipmap images as a single mipmap image.
* @type {Mipmap}
*/
set image(value) {
this.mipmaps = [value];
}
/**
* Gets the underlying texture object.
*/
getImpl () {
return this._texture;
}
/**
* !#en
* Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)<br>
* After destroy, this object is not usable any more.
* You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
* !#zh
* 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)<br/>
* 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
* @method destroy
* @return {Boolean} inherit from the CCObject
*/
destroy () {
this.releaseTexture();
// TODO cc.textureUtil ?
// cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url
return super.destroy();
}
/**
* !#en
* Release texture, please use destroy instead.
* !#zh 释放纹理,请使用 destroy 替代。
* @method releaseTexture
* @deprecated since v2.0
*/
releaseTexture () {
this._setMipmaps([]);
this._texture && this._texture.destroy();
}
/**
* Sets the _mipmaps to specified value, and updates the width and height accordingly.
* If available, synchronize the mipmap data to underlying texture.
* @param {Mipmap[]} mipmaps
*/
_setMipmaps(mipmaps) {
this._mipmaps = mipmaps;
if (mipmaps.length === 0) {
super.update({
width: 0,
height: 0
});
} else {
super.update({
width: this._mipmaps[0].front.width,
height: this._mipmaps[0].front.height,
format: this._mipmaps[0].front._format
});
}
let counter = 0;
const inc = () => {
++counter;
if (counter === this._mipmaps.length * 6) {
this._updateMipmaps(this._mipmaps.map(mipmap => TextureCube._toMipmapArray(mipmap)));
}
};
mipmaps.forEach(mipmap => {
TextureCube._forEachFace(mipmap, face => {
if (face.loaded) {
inc();
} else {
face.addEventListener("load", () => inc());
}
});
});
}
/**
* Updates mipmaps of the underlying texture.
* @param {ImageSource[][]} mipmapSources
*/
_updateMipmaps(mipmapSources) {
const opts = this._getOpts();
opts.images = mipmapSources;
if (!this._texture) {
this._texture = new GFXTextureCube(cc.game._renderContext, opts);
} else {
this._texture.update(opts);
}
}
/**
* Update texture options, not available in Canvas render mode.
* image, format, premultiplyAlpha can not be updated in native.
* @method update
*/
update (options) {
if (!options) return;
super.update(options);
// TODO: options.image
if (this._texture) {
this._texture.update(options);
}
}
/**
* @param {Mipmap} mipmap
* @return {ImageSource[]}
*/
static _toMipmapArray(mipmap) {
/** @type {ImageSource[]} */
const result = new Array();
result[FaceIndex.front] = mipmap.front.data;
result[FaceIndex.back] = mipmap.back.data;
result[FaceIndex.left] = mipmap.left.data;
result[FaceIndex.right] = mipmap.right.data;
result[FaceIndex.top] = mipmap.top.data;
result[FaceIndex.bottom] = mipmap.bottom.data;
return result;
}
/**
* @param {Mipmap} mipmap
* @param {(face: ImageAsset) => void} callback
*/
static _forEachFace(mipmap, callback) {
for (let face in mipmap) {
callback(mipmap[face]);
}
}
/**
* @param {Texture2D[]} textures
*/
static fromTexture2DArray(textures, out) {
let res = [], mips = textures.length / 6;
for (let i = 0; i < mips; i++) {
res.push(textures.splice(0, 6).reduce((acc, img, i) => {
acc[FaceIndex[i]] = img.image;
return acc;
}, {}));
}
if (!out) out = new TextureCube();
out.mipmaps = res;
return out;
}
_serialize() {
return {
base: super._serialize(),
mipmaps: this._mipmaps.map(mipmap => {return {
front: mipmap.front._uuid,
back: mipmap.back._uuid,
left: mipmap.left._uuid,
right: mipmap.right._uuid,
top: mipmap.top._uuid,
bottom: mipmap.bottom._uuid,
};})
};
}
_deserialize (data, handle) {
super._deserialize(data.base);
this._mipmaps = new Array(data.mipmaps.length);
this._mipmaps.fill({});
for (let i = 0; i < data.mipmaps.length; ++i) {
const mipmap = data.mipmaps[i];
handle.result.push(this._mipmaps[i], `front`, mipmap.front);
handle.result.push(this._mipmaps[i], `back`, mipmap.back);
handle.result.push(this._mipmaps[i], `left`, mipmap.left);
handle.result.push(this._mipmaps[i], `right`, mipmap.right);
handle.result.push(this._mipmaps[i], `top`, mipmap.top);
handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom);
}
}
onLoaded() {
this.mipmaps = this._mipmaps;
}
}
cc.TextureCube = TextureCube;
+248
View File
@@ -0,0 +1,248 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { Texture2D } from '../../assets';
import ImageAsset from '../../assets/image-asset';
import TextureBase from '../../assets/texture-base';
import { ccclass, property } from '../../core/data/class-decorator';
import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define';
interface ITextureCubeMipmap {
front: ImageAsset;
back: ImageAsset;
left: ImageAsset;
right: ImageAsset;
top: ImageAsset;
bottom: ImageAsset;
}
@ccclass('cc.TextureCube')
export default class TextureCube extends TextureBase {
/**
* Gets the mipmap images.
* Note that the result do not contains the auto generated mipmaps.
*/
get mipmaps () {
return this._mipmaps;
}
/**
* Sets the mipmaps images.
*/
set mipmaps (value) {
this._mipmaps = value;
this._recreateTexture();
}
/**
* Gets the mipmap image at level 0.
*/
get image () {
return this._mipmaps.length === 0 ? null : this._mipmaps[0];
}
/**
* Sets the mipmap images as a single mipmap image.
*/
set image (value) {
this.mipmaps = value ? [value] : [];
}
/**
* @param textures
* @deprecated Manually assign to mipmaps property instead.
*/
public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube) {
const mipmaps: ITextureCubeMipmap[] = [];
const nMipmaps = textures.length / 6;
for (let i = 0; i < nMipmaps; i++) {
const x = i * 6;
mipmaps.push({
front: textures[x + FaceIndex.front].image!,
back: textures[x + FaceIndex.back].image!,
left: textures[x + FaceIndex.left].image!,
right: textures[x + FaceIndex.right].image!,
top: textures[x + FaceIndex.top].image!,
bottom: textures[x + FaceIndex.bottom].image!,
});
}
if (!out) { out = new TextureCube(); }
out.mipmaps = mipmaps;
return out;
}
@property
public _mipmaps: ITextureCubeMipmap[] = [];
constructor () {
super();
}
/**
* !#en
* Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)<br>
* After destroy, this object is not usable any more.
* You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
* !#zh
* 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)<br/>
* 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
*/
public destroy () {
this._mipmaps = [];
return super.destroy();
}
/**
* !#en
* Release texture, please use destroy instead.
* !#zh 释放纹理,请使用 destroy 替代。
* @deprecated Since v2.0.
*/
public releaseTexture () {
this.mipmaps = [];
}
public _serialize () {
return {
base: super._serialize(),
mipmaps: this._mipmaps.map((mipmap) => {return {
front: mipmap.front._uuid,
back: mipmap.back._uuid,
left: mipmap.left._uuid,
right: mipmap.right._uuid,
top: mipmap.top._uuid,
bottom: mipmap.bottom._uuid,
}; }),
};
}
public _deserialize (serializedData: ITextureCubeSerializeData, handle: any) {
const data = serializedData as ITextureCubeSerializeData;
super._deserialize(data.base, handle);
this._mipmaps = new Array(data.mipmaps.length);
for (let i = 0; i < data.mipmaps.length; ++i) {
// Prevent resource load failed
this._mipmaps[i] = {
front: new ImageAsset(),
back: new ImageAsset(),
left: new ImageAsset(),
right: new ImageAsset(),
top: new ImageAsset(),
bottom: new ImageAsset(),
};
const mipmap = data.mipmaps[i];
handle.result.push(this._mipmaps[i], `front`, mipmap.front);
handle.result.push(this._mipmaps[i], `back`, mipmap.back);
handle.result.push(this._mipmaps[i], `left`, mipmap.left);
handle.result.push(this._mipmaps[i], `right`, mipmap.right);
handle.result.push(this._mipmaps[i], `top`, mipmap.top);
handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom);
}
}
protected _createTexture () {
if (this._mipmaps.length === 0) {
return;
}
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) {
return;
}
this._texture = gfxDevice.createTexture({
type: GFXTextureType.TEX2D,
/* tslint:disable:no-bitwise */
usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST,
/* tslint:enable:no-bitwise */
format: this._getGfxFormat(),
width: this.width,
height: this.height,
mipLevel: this._mipmaps.length,
arrayLayer: 6,
});
this._mipmaps.forEach((mipmap, level) => {
_forEachFace(mipmap, (face, faceIndex) => {
this._assignImage(face, level, faceIndex);
});
});
}
protected _createTextureView () {
if (!this._texture) {
return;
}
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) {
return;
}
this._textureView = gfxDevice.createTextureView({
texture: this._texture,
type: GFXTextureViewType.TV2D_ARRAY,
format: this._getGfxFormat(),
});
}
}
/* tslint:disable:no-string-literal */
cc['TextureCube'] = TextureCube;
interface ITextureCubeSerializeData {
base: string;
mipmaps: Array<{
front: string;
back: string;
left: string;
right: string;
top: string;
bottom: string;
}>;
}
enum FaceIndex {
right = 0,
left = 1,
top = 2,
bottom = 3,
front = 4,
back = 5,
}
/**
* @param {Mipmap} mipmap
* @param {(face: ImageAsset) => void} callback
*/
function _forEachFace (mipmap: ITextureCubeMipmap, callback: (face: ImageAsset, faceIndex: number) => void) {
callback(mipmap.front, FaceIndex.front);
callback(mipmap.back, FaceIndex.back);
callback(mipmap.left, FaceIndex.left);
callback(mipmap.right, FaceIndex.right);
callback(mipmap.top, FaceIndex.top);
callback(mipmap.bottom, FaceIndex.bottom);
}
-243
View File
@@ -1,243 +0,0 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
//@ts-check
import {ccclass, property} from "../core/data/class-decorator";
import EventTarget from '../core/event/event-target';
import {addon} from '../core/utils/js';
/**
* @typedef {{ _data: ArrayBufferView, _compressed: boolean, width: number, height: number, format: number}} RawImageData
*/
const CHAR_CODE_0 = 48; // '0'
/**
* Class ImageAsset.
*/
@ccclass('cc.ImageAsset')
export default class ImageAsset extends cc.Asset {
static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc'];
/**
* @param {HTMLCanvasElement | HTMLImageElement | RawImageData} nativeAsset
*/
constructor(nativeAsset = undefined) {
super();
EventTarget.call(this);
/**
* !#en
* The url of the texture, this could be empty if the texture wasn't created via a file.
* !#zh
* 图像文件的 url,当图像不是由文件创建时值可能为空
* @property url
* @type {String}
* @readonly
*/
// TODO - use nativeUrl directly
this.url = "";
/**
* @type {HTMLCanvasElement | HTMLImageElement | RawImageData}
*/
this._nativeData = {
_data: null,
width: 0,
height: 0,
format: 0,
_compressed: false
};
if (CC_EDITOR) {
this._exportedExts = null;
}
if (nativeAsset !== undefined) {
this._nativeAsset = nativeAsset;
}
}
/**
* @type {HTMLCanvasElement | HTMLImageElement | RawImageData}
*/
@property({
override: true
})
get _nativeAsset () {
// maybe returned to pool in webgl
return this._nativeData;
}
/**
* @param {HTMLCanvasElement | HTMLImageElement | RawImageData} value
*/
set _nativeAsset (value) {
this.reset(value);
}
/**
* @type {HTMLCanvasElement | HTMLImageElement | ArrayBufferView}
*/
get data() {
return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data;
}
/**
* @param {HTMLCanvasElement | HTMLImageElement | RawImageData} data
*/
reset(data) {
if (!(data instanceof HTMLElement)) {
this._nativeData = Object.create(data);
this._onDataComplete();
} else {
this._nativeData = data;
if (CC_WECHATGAME || CC_QQPLAY || data.complete || data instanceof HTMLCanvasElement) {
this._onDataComplete();
} else {
this.loaded = false;
data.addEventListener('load', () => {
this._onDataComplete();
});
data.addEventListener('error', (err) => {
cc.warnID(3119, err.message);
});
}
}
}
get width() {
return this._nativeData.width;
}
get height() {
return this._nativeData.height;
}
get format() {
if (this._nativeData instanceof HTMLElement) {
return undefined;
}
return this._nativeData.format;
}
// destroy() {
// if (cc.macro.CLEANUP_IMAGE_CACHE) {
// if (this._data instanceof HTMLImageElement) {
// this._data.src = "";
// cc.loader.removeItem(this._data.id);
// }
// }
// }
// SERIALIZATION
_serialize () {
let extId = "";
let exportedExts = this._exportedExts;
if (!exportedExts && this._native) {
exportedExts = [this._native];
}
if (exportedExts) {
let exts = [];
for (let i = 0; i < exportedExts.length; i++) {
let extId = "";
let ext = exportedExts[i];
if (ext) {
// ext@format
let extFormat = ext.split('@');
extId = ImageAsset.extnames.indexOf(extFormat[0]);
if (extId < 0) {
extId = ext;
}
if (extFormat[1]) {
extId += '@' + extFormat[1];
}
}
exts.push(extId);
}
extId = exts.join('_');
}
return "" + extId;
}
_deserialize (data, handle) {
let fields = data.split(',');
// decode extname
var extIdStr = fields[0];
if (extIdStr) {
let extIds = extIdStr.split('_');
let extId = 999;
let ext = '';
let format = this._format;
let SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS;
for (let i = 0; i < extIds.length; i++) {
let extFormat = extIds[i].split('@');
let tmpExt = extFormat[0];
tmpExt = tmpExt.charCodeAt(0) - CHAR_CODE_0;
tmpExt = ImageAsset.extnames[tmpExt] || extFormat;
let index = SupportTextureFormats.indexOf(tmpExt);
if (index !== -1 && index < extId) {
extId = index;
ext = tmpExt;
format = extFormat[1] ? parseInt(extFormat[1]) : this._format;
}
}
if (ext) {
this._setRawAsset(ext);
this._format = format;
}
// preset uuid to get correct nativeUrl
let loadingItem = handle.customEnv;
let uuid = loadingItem && loadingItem.uuid;
if (uuid) {
this._uuid = uuid;
var url = this.nativeUrl;
this.url = url;
}
}
}
_onDataComplete() {
this.loaded = true;
this.emit("load");
}
}
/**
* !#zh
* 当该资源加载成功后触发该事件
* !#en
* This event is emitted when the asset is loaded
*
* @event load
*/
addon(ImageAsset.prototype, EventTarget.prototype);
cc.ImageAsset = ImageAsset;
+231
View File
@@ -0,0 +1,231 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import {ccclass, property} from '../core/data/class-decorator';
import EventTarget from '../core/event/event-target';
import {addon} from '../core/utils/js';
import { Asset } from './asset';
export interface IMemoryImageSource {
_data: ArrayBufferView | null;
_compressed: boolean;
width: number;
height: number;
format: number;
}
type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource;
/**
* Class ImageAsset.
*/
@ccclass('cc.ImageAsset')
export default class ImageAsset extends Asset {
@property({override: true})
get _nativeAsset () {
// Maybe returned to pool in webgl.
return this._nativeData;
}
set _nativeAsset (value: ImageSource) {
this.reset(value);
}
get data () {
return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data;
}
get width () {
return this._nativeData.width;
}
get height () {
return this._nativeData.height;
}
get format () {
if (this._nativeData instanceof HTMLElement) {
return undefined;
}
return this._nativeData.format;
}
/**
* !#en
* The url of the texture, this could be empty if the texture wasn't created via a file.
* !#zh
* 图像文件的 url,当图像不是由文件创建时值可能为空
*/
// TODO - use nativeUrl directly
get url () {
return this._url;
}
private static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc'];
private _nativeData: ImageSource;
private _url: string;
private _exportedExts: string[] | null | undefined = undefined;
private _format: string = '';
/**
* @param nativeAsset
*/
constructor (nativeAsset?: ImageSource) {
super();
// @ts-ignore
EventTarget.call(this);
this._url = '';
this._nativeData = {
_data: null,
width: 0,
height: 0,
format: 0,
_compressed: false,
};
if (CC_EDITOR) {
this._exportedExts = null;
}
if (nativeAsset !== undefined) {
this._nativeAsset = nativeAsset;
}
}
public reset (data: ImageSource) {
if (!(data instanceof HTMLElement)) {
this._nativeData = Object.create(data);
this._onDataComplete();
} else {
this._nativeData = data;
if (CC_WECHATGAME || CC_QQPLAY || (data as any).complete || data instanceof HTMLCanvasElement) {
this._onDataComplete();
} else {
this.loaded = false;
data.addEventListener('load', () => {
this._onDataComplete();
});
data.addEventListener('error', (err) => {
cc.warnID(3119, err.message);
});
}
}
}
// destroy() {
// if (cc.macro.CLEANUP_IMAGE_CACHE) {
// if (this._data instanceof HTMLImageElement) {
// this._data.src = "";
// cc.loader.removeItem(this._data.id);
// }
// }
// }
// SERIALIZATION
public _serialize () {
let targetExtensions = this._exportedExts;
if (!targetExtensions && this._native) {
targetExtensions = [this._native];
}
if (!targetExtensions) {
return '';
}
const extensionIndices: string[] = [];
for (const targetExtension of targetExtensions) {
const extensionFormat = targetExtension.split('@');
const i = ImageAsset.extnames.indexOf(extensionFormat[0]);
let exportedExtensionID = i < 0 ? targetExtension : `${i}`;
if (extensionFormat[1]) {
exportedExtensionID += '@' + extensionFormat[1];
}
extensionIndices.push(exportedExtensionID);
}
return extensionIndices.join('_');
}
public _deserialize (data: string, handle: any) {
const extensionIDs = data.split('_');
let preferedExtensionIndex = Number.MAX_VALUE;
let format = this._format;
let ext = '';
const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS as string[];
for (const extensionID of extensionIDs) {
const extFormat = extensionID.split('@');
const i = parseInt(extFormat[0], undefined);
const tmpExt = ImageAsset.extnames[i] || extFormat.join();
const index = SupportTextureFormats.indexOf(tmpExt);
if (index !== -1 && index < preferedExtensionIndex) {
preferedExtensionIndex = index;
ext = tmpExt;
format = extFormat[1] ? extFormat[1] : this._format;
}
}
if (ext) {
// @ts-ignore
this._setRawAsset(ext);
this._format = format;
}
// preset uuid to get correct nativeUrl
const loadingItem = handle.customEnv;
const uuid = loadingItem && loadingItem.uuid;
if (uuid) {
this._uuid = uuid;
this._url = this.nativeUrl;
}
}
public _onDataComplete () {
this.loaded = true;
// @ts-ignore
this.emit('load');
}
}
/**
* !#zh
* 当该资源加载成功后触发该事件
* !#en
* This event is emitted when the asset is loaded
*
* @event load
*/
addon(ImageAsset.prototype, EventTarget.prototype);
cc.ImageAsset = ImageAsset;
-135
View File
@@ -1,135 +0,0 @@
import gfx from '../renderer/gfx';
import Texture2D from './texture-2d';
import { ccclass } from '../core/data/class-decorator';
/**
* Render textures are textures that can be rendered to.
* @class RenderTexture
* @extends Texture2D
*/
@ccclass('cc.RenderTexture')
export default class RenderTexture extends Texture2D {
constructor () {
super();
this._framebuffer = null;
}
/**
* !#en
* Init the render texture with size.
* !#zh
* 初始化 render texture
* @param {Number} [width]
* @param {Number} [height]
* @param {Number} [depthStencilFormat]
* @method initWithSize
*/
initWithSize (width, height, depthStencilFormat) {
this.width = Math.floor(width || cc.visibleRect.width);
this.height = Math.floor(height || cc.visibleRect.height);
this._resetUnderlyingMipmaps();
let opts = {
colors: [ this._texture ],
};
if (depthStencilFormat) {
if (this.depthStencilBuffer) this.depthStencilBuffer.destroy();
let depthStencilBuffer = new gfx.RenderBuffer(cc.game._renderContext, depthStencilFormat, this.width, this.height);
if (depthStencilFormat === gfx.RB_FMT_D24S8) {
opts.depthStencil = depthStencilBuffer;
}
else if (depthStencilFormat === gfx.RB_FMT_S8) {
opts.stencil = depthStencilBuffer;
}
else if (depthStencilFormat === gfx.RB_FMT_D16) {
opts.depth = depthStencilBuffer;
}
this.depthStencilBuffer = depthStencilBuffer;
this.depthStencilFormat = depthStencilFormat;
}
if (this._framebuffer) this._framebuffer.destroy();
this._framebuffer = new gfx.FrameBuffer(cc.game._renderContext, this.width, this.height, opts);
this.loaded = true;
this.emit("load");
}
updateSize(width, height) {
this.width = Math.floor(width || cc.visibleRect.width);
this.height = Math.floor(height || cc.visibleRect.height);
this._resetUnderlyingMipmaps();
let rbo = this.depthStencilBuffer;
if (rbo) rbo.update(this.width, this.height);
this._framebuffer._width = width;
this._framebuffer._height = height;
}
/**
* !#en Draw a texture to the specified position
* !#zh 将指定的图片渲染到指定的位置上
* @param {Texture2D} texture
* @param {Number} x
* @param {Number} y
*/
drawTextureAt (texture, x, y) {
if (!texture._image) return;
this._texture.updateSubImage({
x, y,
image: texture._image,
width: texture.width,
height: texture.height,
level: 0,
flipY: false,
premultiplyAlpha: texture._premultiplyAlpha
})
}
/**
* !#en
* Get pixels from render texture, the pixels data stores in a RGBA Uint8Array.
* It will return a new (width * height * 4) length Uint8Array by default。
* You can specify a data to store the pixels to reuse the data,
* you and can specify other params to specify the texture region to read.
* !#zh
* 从 render texture 读取像素数据,数据类型为 RGBA 格式的 Uint8Array 数组。
* 默认每次调用此函数会生成一个大小为 (长 x 高 x 4) 的 Uint8Array。
* 你可以通过传入 data 来接收像素数据,也可以通过传参来指定需要读取的区域的像素。
* @method readPixels
* @param {Uint8Array} [data]
* @param {Number} [x]
* @param {Number} [y]
* @param {Number} [w]
* @param {Number} [h]
* @return {Uint8Array}
*/
readPixels (data, x, y, w, h) {
if (!this._framebuffer || !this._texture) return data;
x = x || 0;
y = y || 0;
let width = w || this.width;
let height = h || this.height;
data = data || new Uint8Array(width * height * 4);
let gl = cc.game._renderContext._gl;
let oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer._glID);
gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);
gl.bindFramebuffer(gl.FRAMEBUFFER, oldFBO);
return data;
}
destroy () {
super.destroy();
if (this._framebuffer) {
this._framebuffer.destroy();
}
}
}
cc.RenderTexture = RenderTexture;
+220
View File
@@ -0,0 +1,220 @@
import { ccclass } from '../core/data/class-decorator';
import { IRect2D, normalizeRect2D } from '../core/vmath/rect';
import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define';
import { GFXFramebuffer } from '../gfx/framebuffer';
import { GFXTexture } from '../gfx/texture';
import { GFXTextureView } from '../gfx/texture-view';
import { RenderPassStage } from '../pipeline/render-pipeline';
import ImageAsset from './image-asset';
import Texture2D from './texture-2d';
enum DepthStencilFormat {
D24S8 = GFXFormat.D24S8,
S8 = GFXFormat.R8UI,
D16 = GFXFormat.D16,
}
function toGfxDepthStencilFormat (depthStencilFormat: DepthStencilFormat): GFXFormat {
return depthStencilFormat as unknown as GFXFormat;
}
/**
* Render textures are textures that can be rendered to.
* @class RenderTexture
* @extends Texture2D
*/
@ccclass('cc.RenderTexture')
export default class RenderTexture extends Texture2D {
private _framebuffer: GFXFramebuffer | null = null;
private _depthStencilTexture: GFXTexture | null = null;
private _depthStencilTextureView: GFXTextureView | null = null;
constructor () {
super();
}
/**
* !#en
* Init the render texture with size.
* !#zh
* 初始化 render texture
* @param [width]
* @param [height]
* @param [depthStencilFormat]
* @method initWithSize
*/
public initWithSize (width?: number, height?: number, depthStencilFormat?: DepthStencilFormat) {
this.destroy();
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) {
return;
}
const w = Math.floor(width || cc.visibleRect.width);
const h = Math.floor(height || cc.visibleRect.height);
const image = new ImageAsset({
width: w,
height: h,
format: GFXFormat.RGBA8UI,
_data: new Uint8Array(w * h * 4),
_compressed: false,
});
this.image = image;
if (!this._texture) {
return;
}
const colorView = gfxDevice.createTextureView({
texture: this._texture,
type: GFXTextureViewType.TV2D,
format: this._getGfxFormat(),
});
if (!colorView) {
return;
}
if (depthStencilFormat !== undefined) {
this._depthStencilTexture = gfxDevice.createTexture({
type: GFXTextureType.TEX2D,
usage: GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT,
format: toGfxDepthStencilFormat(depthStencilFormat),
width: w,
height: h,
});
if (!this._depthStencilTexture) {
return;
}
this._depthStencilTextureView = gfxDevice.createTextureView({
texture: this._depthStencilTexture,
type: GFXTextureViewType.TV2D,
format: toGfxDepthStencilFormat(depthStencilFormat),
});
}
if (this._depthStencilTextureView === null) {
return;
}
this._framebuffer = gfxDevice.createFramebuffer({
renderPass: cc.director.root.pipeline.getRenderPass(RenderPassStage.DEFAULT),
colorViews: [ colorView ],
depthStencilView: this._depthStencilTextureView === null ? undefined : this._depthStencilTextureView,
isOffscreen: true,
});
this.loaded = true;
// @ts-ignore
this.emit('load');
}
public destroy () {
if (this._framebuffer) {
this._framebuffer.destroy();
this._framebuffer = null;
}
if (this._depthStencilTextureView) {
this._depthStencilTextureView.destroy();
this._depthStencilTextureView = null;
}
if (this._depthStencilTexture) {
this._depthStencilTexture.destroy();
this._depthStencilTexture = null;
}
return super.destroy();
}
// TODO:
// public updateSize (width, height) {
// this.width = Math.floor(width || cc.visibleRect.width);
// this.height = Math.floor(height || cc.visibleRect.height);
// this._resetUnderlyingMipmaps();
// const rbo = this.depthStencilBuffer;
// if (rbo) { rbo.update(this.width, this.height); }
// this._framebuffer._width = width;
// this._framebuffer._height = height;
// }
/**
* !#en Draw a texture to the specified position
* !#zh 将指定的图片渲染到指定的位置上
* @param texture
* @param x
* @param y
*/
public drawTextureAt (texture: Texture2D, x: number, y: number) {
if (!this._texture) {
return;
}
const image = texture.image;
if (!image) {
return;
}
this._assignImage(image, 0);
}
/**
* !#en
* Get pixels from render texture, the pixels data stores in a RGBA Uint8Array.
* It will return a new (width * height * 4) length Uint8Array by default。
* You can specify a data to store the pixels to reuse the data,
* you and can specify other params to specify the texture region to read.
* !#zh
* 从 render texture 读取像素数据,数据类型为 RGBA 格式的 Uint8Array 数组。
* 默认每次调用此函数会生成一个大小为 (长 x 高 x 4) 的 Uint8Array。
* 你可以通过传入 data 来接收像素数据,也可以通过传参来指定需要读取的区域的像素。
* @param [data]
* @param [rect]
*/
public readPixels (data?: Uint8Array, rect: IRect2D = {}) {
if (!this._framebuffer || !this._texture) {
return undefined;
}
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) {
return;
}
const normalizedRect = normalizeRect2D(rect, this.width, this.height);
data = data || new Uint8Array(normalizedRect.width * normalizedRect.height * 4);
gfxDevice.copyFramebufferToBuffer(this._framebuffer, data.buffer, [{
buffOffset: 0,
buffStride: 0,
buffTexHeight: 0,
texOffset: {
x: normalizedRect.x,
y: normalizedRect.y,
z: 0,
},
texExtent: {
width: normalizedRect.width,
height: normalizedRect.height,
depth: 1,
},
texSubres: {
baseMipLevel: 0,
levelCount: 1,
baseArrayLayer: 0,
layerCount: 1,
},
}]);
return data;
}
}
cc.RenderTexture = RenderTexture;
-327
View File
@@ -1,327 +0,0 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import GFXTexture2D from '../renderer/gfx/texture-2d';
import {ccclass, property} from '../core/data/class-decorator';
import TextureBase from './texture-base';
import ImageAsset from './image-asset';
/**
* @typedef {import("./texture-base").ImageSource} ImageSource
* @typedef {import("./texture-base").TextureUpdateOpts} TextureUpdateOpts
*/
/**
* <p>
* This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data. <br/>
* The created cc.Texture2D object will always have power-of-two dimensions. <br/>
* Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions <br/>
* i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0). <br/>
* Be aware that the content of the generated textures will be upside-down! </p>
* @class Texture2D
* @extends TextureBase
*/
@ccclass('cc.Texture2D')
export default class Texture2D extends TextureBase {
@property({
override: true
})
_flipY = true;
/**
* @type {ImageAsset[]}
*/
@property([ImageAsset])
_mipmaps = [];
constructor () {
super();
/**
* @type {GFXTexture2D}
*/
this._texture = null;
}
/**
* Gets the mipmap images.
* Note that the result do not contains the auto generated mipmaps.
* @return {ImageAsset[]}
*/
get mipmaps() {
return this._mipmaps;
}
/**
* Sets the mipmaps images.
* @param {ImageAsset[]} value
*/
set mipmaps(value) {
this._setMipmaps(value);
}
/**
* Gets the mipmap image at level 0.
* @return {ImageAsset}
*/
get image() {
return this._mipmaps.length === 0 ? null : this._mipmaps[0];
}
/**
* Sets the mipmap images as a single mipmap image.
* @param {ImageAsset} value
*/
set image(value) {
this.mipmaps = [value];
}
/**
* Gets the underlying texture object.
*/
getImpl () {
return this._texture;
}
/**
* Returns the string representation of this texture.
*/
toString () {
return this._mipmaps.length !== 0 ? this._mipmaps[0].url : "";
}
/**
* Update texture options, not available in Canvas render mode.
* image, format, premultiplyAlpha can not be updated in native.
* @method update
* @param {TextureUpdateOpts} options
*/
update (options) {
if (!options) {
return;
}
super.update(options);
if (options.image) {
options.images = [options.image];
}
if (options.images !== undefined && options.images.length !== 0) {
this._setMipmaps(options.images.map(image => {
const mipmap = new ImageAsset();
mipmap.reset(image instanceof HTMLElement ? image : {
_data: image,
width: this.width,
height: this.height,
format: this._format,
_compressed: false
});
return mipmap;
}));
}
if (this._texture) {
this._texture.update(options);
}
}
/**
*
* @param {ImageSource} source
*/
updateImage(source) {
this.updateMipmaps([source]);
}
/**
* Updates mipmaps at specified range of levels.
* @param {ImageSource[]} sources The image sources.
* @param {number} firstLevel The first level from which the sources update.
* @description
* If the range specified by [firstLevel, firstLevel + sources.length) exceeds
* the actually range of mipmaps this texture contains, only overlaped mipmaps are updated.
*/
updateMipmaps(sources, firstLevel = 0) {
if (firstLevel >= sources.length) {
return;
}
const nUpdate = Math.min(sources.length, this._mipmaps.length - firstLevel);
for (let i = 0; i < nUpdate; ++i) {
const level = firstLevel + i;
const mipmap = this._mipmaps[level];
const source = sources[i];
mipmap.reset(source instanceof HTMLElement ? source : {
_data: source,
width: mipmap.width,
height: mipmap.height,
format: mipmap._format,
_compressed: false
});
this._texture.updateImage({
width: this.width,
height: this.height,
level: level,
image: sources[i],
flipY: false,
premultiplyAlpha: false
});
}
}
/**
* !#en
* HTMLElement Object getter, available only on web.
* !#zh 获取当前贴图对应的 HTML Image 或 Canvas 对象,只在 Web 平台下有效。
* @method getHtmlElementObj
* @return {HTMLImageElement|HTMLCanvasElement}
* @deprecated Use this.image.data instead.
*/
getHtmlElementObj () {
return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data: null;
}
/**
* !#en
* Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)<br>
* After destroy, this object is not usable any more.
* You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
* !#zh
* 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)<br/>
* 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
* @method destroy
* @return {Boolean} inherit from the CCObject
*/
destroy () {
this.releaseTexture();
// TODO cc.textureUtil ?
// cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url
return super.destroy();
}
/**
* !#en
* Description of cc.Texture2D.
* !#zh cc.Texture2D 描述。
* @method description
* @returns {String}
*/
description () {
return "<cc.Texture2D | Name = " + (this._mipmaps[0] ? this._mipmaps[0].url : "") + " | Dimensions = " + this.width + " x " + this.height + ">";
}
/**
* !#en
* Release texture, please use destroy instead.
* !#zh 释放纹理,请使用 destroy 替代。
* @method releaseTexture
* @deprecated since v2.0, use destroy instead.
*/
releaseTexture () {
this._setMipmaps([]);
this._texture && this._texture.destroy();
}
/**
* Sets the _mipmaps to specified value, and updates the width and height accordingly.
* If available, synchronize the mipmap data to underlying texture.
* @param {ImageAsset[]} mipmaps
*/
_setMipmaps(mipmaps) {
this._mipmaps = mipmaps;
if (mipmaps.length === 0) {
super.update({
width: 0,
height: 0
});
} else {
const level0 = this._mipmaps[0];
super.update({
width: level0.width,
height: level0.height,
format: level0._format
});
}
let counter = 0;
const inc = () => {
++counter;
if (counter === mipmaps.length) {
this._resetUnderlyingMipmaps(mipmaps.map(mipmap => mipmap.data));
}
};
mipmaps.forEach(mipmap => {
if (mipmap.loaded) {
inc();
} else {
mipmap.addEventListener("load", () => {
inc();
});
}
});
}
/**
* Resets sources and amount of the underlying texture's the mipmaps.
* @param {ImageSource[]} mipmapSources
*/
_resetUnderlyingMipmaps(mipmapSources = [null]) {
const opts = this._getOpts();
opts.images = mipmapSources;
if (!this._texture) {
this._texture = new GFXTexture2D(cc.game._renderContext, opts);
} else {
this._texture.update(opts);
}
}
_serialize() {
return {
base: super._serialize(),
mipmaps: this._mipmaps.map(mipmap => mipmap._uuid)
};
}
_deserialize (data, handle) {
super._deserialize(data.base);
this._mipmaps = new Array(data.mipmaps.length);
for (let i = 0; i < data.mipmaps.length; ++i) {
// Prevent resource load failed
this._mipmaps[i] = new ImageAsset();
const mipmapUUID = data.mipmaps[i];
handle.result.push(this._mipmaps, `${i}`, mipmapUUID);
}
}
onLoaded() {
this.mipmaps = this._mipmaps;
}
}
cc.Texture2D = Texture2D;
+228
View File
@@ -0,0 +1,228 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { ccclass, property } from '../core/data/class-decorator';
import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define';
import ImageAsset from './image-asset';
import TextureBase from './texture-base';
/**
* Represents a 2-dimension texture.
*/
@ccclass('cc.Texture2D')
export default class Texture2D extends TextureBase {
/**
* Gets the mipmap images.
* Note that the result do not contains the auto generated mipmaps.
*/
get mipmaps () {
return this._mipmaps;
}
/**
* Sets the mipmaps images.
*/
set mipmaps (value) {
this._mipmaps = value;
this._recreateTexture();
}
/**
* Gets the mipmap image at level 0.
*/
get image () {
return this._mipmaps.length === 0 ? null : this._mipmaps[0];
}
/**
* Sets the mipmap images as a single mipmap image.
*/
set image (value) {
this.mipmaps = value ? [value] : [];
}
@property([ImageAsset])
public _mipmaps: ImageAsset[] = [];
constructor () {
super(true);
}
/**
* Returns the string representation of this texture.
*/
public toString () {
return this._mipmaps.length !== 0 ? this._mipmaps[0].url : '';
}
/**
* Updates mipmaps at level 0.
*/
public updateImage () {
this.updateMipmaps(0);
}
/**
* Updates mipmaps at specified range of levels.
* @param sources The image sources.
* @param firstLevel The first level from which the sources update.
* @description
* If the range specified by [firstLevel, firstLevel + sources.length) exceeds
* the actually range of mipmaps this texture contains, only overlaped mipmaps are updated.
* Use this method if your mipmap data are modified.
*/
public updateMipmaps (firstLevel: number, count?: number) {
if (firstLevel >= this._mipmaps.length) {
return;
}
const nUpdate = Math.min(
count === undefined ? this._mipmaps.length : count,
this._mipmaps.length - firstLevel);
for (let i = 0; i < nUpdate; ++i) {
const level = firstLevel + i;
this._uploadImage(this._mipmaps[level], level);
}
}
/**
* !#en
* HTMLElement Object getter, available only on web.
* !#zh 获取当前贴图对应的 HTML Image 或 Canvas 对象,只在 Web 平台下有效。
* @method getHtmlElementObj
* @return {HTMLImageElement|HTMLCanvasElement}
* @deprecated Use this.image.data instead.
*/
public getHtmlElementObj () {
return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data : null;
}
/**
* !#en
* Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)<br>
* After destroy, this object is not usable any more.
* You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
* !#zh
* 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)<br/>
* 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
*/
public destroy () {
this._mipmaps = [];
return super.destroy();
}
/**
* !#en
* Description of cc.Texture2D.
* !#zh cc.Texture2D 描述。
*/
public description () {
const url = this._mipmaps[0] ? this._mipmaps[0].url : '';
return `<cc.Texture2D | Name = ${url} | Dimension = ${this.width} x ${this.height}>`;
}
/**
* !#en
* Release texture, please use destroy instead.
* !#zh 释放纹理,请使用 destroy 替代。
* @deprecated Since v2.0, use destroy instead.
*/
public releaseTexture () {
this.mipmaps = [];
}
public _serialize () {
return {
base: super._serialize(),
mipmaps: this._mipmaps.map((mipmap) => mipmap._uuid),
};
}
public _deserialize (serializedData: any, handle: any) {
const data = serializedData as ITexture2DSerializeData;
super._deserialize(data.base, handle);
this._mipmaps = new Array(data.mipmaps.length);
for (let i = 0; i < data.mipmaps.length; ++i) {
// Prevent resource load failed
this._mipmaps[i] = new ImageAsset();
const mipmapUUID = data.mipmaps[i];
handle.result.push(this._mipmaps, `${i}`, mipmapUUID);
}
}
protected _createTexture () {
if (this._mipmaps.length === 0) {
return;
}
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) {
return;
}
this._texture = gfxDevice.createTexture({
type: GFXTextureType.TEX2D,
/* tslint:disable:no-bitwise */
usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST,
/* tslint:enable:no-bitwise */
format: this._getGfxFormat(),
width: this.width,
height: this.height,
mipLevel: this._mipmaps.length,
});
this._mipmaps.forEach((mipmap, level) => {
this._assignImage(mipmap, level);
});
}
protected _createTextureView () {
if (!this._texture) {
return;
}
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) {
return;
}
this._textureView = gfxDevice.createTextureView({
texture: this._texture,
type: GFXTextureViewType.TV2D,
format: this._getGfxFormat(),
});
}
}
/* tslint:disable:no-string-literal */
cc['Texture2D'] = Texture2D;
interface ITexture2DSerializeData {
base: string;
mipmaps: string[];
}
-602
View File
@@ -1,602 +0,0 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import EventTarget from '../core/event/event-target';
import IDGenerator from '../core/utils/id-generator';
import Enum from '../core/value-types/enum';
import {addon} from '../core/utils/js';
import {enums} from '../renderer/gfx/enums';
import { Asset } from './asset';
import {ccclass, property} from '../core/data/class-decorator';
/**
* @typedef {import("../renderer/gfx/texture-2d").HTMLImageSource} HTMLImageSource
* @typedef {import("../renderer/gfx/texture-2d").ImageSource} ImageSource
* @typedef {import("../renderer/gfx/texture-2d").TextureUpdateOpts} TextureUpdateOpts
*
* @exports HTMLImageSource
* @exports ImageSource
* @exports TextureUpdateOpts
*/
let _images = [];
const CHAR_CODE_1 = 49; // '1'
const GL_NEAREST = 9728; // gl.NEAREST
const GL_LINEAR = 9729; // gl.LINEAR
const GL_REPEAT = 10497; // gl.REPEAT
const GL_CLAMP_TO_EDGE = 33071; // gl.CLAMP_TO_EDGE
const GL_MIRRORED_REPEAT = 33648; // gl.MIRRORED_REPEAT
var idGenerator = new IDGenerator('Tex');
/**
* The texture pixel format, default value is RGBA8888,
* you should note that textures loaded by normal image files (png, jpg) can only support RGBA8888 format,
* other formats are supported by compressed file types or raw data.
* @enum {number}
*/
const PixelFormat = Enum({
/**
* 16-bit texture without Alpha channel
* @property RGB565
* @readonly
* @type {Number}
*/
RGB565: enums.TEXTURE_FMT_R5_G6_B5,
/**
* 16-bit textures: RGB5A1
* @property RGB5A1
* @readonly
* @type {Number}
*/
RGB5A1: enums.TEXTURE_FMT_R5_G5_B5_A1,
/**
* 16-bit textures: RGBA4444
* @property RGBA4444
* @readonly
* @type {Number}
*/
RGBA4444: enums.TEXTURE_FMT_R4_G4_B4_A4,
/**
* 24-bit texture: RGB888
* @property RGB888
* @readonly
* @type {Number}
*/
RGB888: enums.TEXTURE_FMT_RGB8,
/**
* 32-bit texture: RGBA8888
* @property RGBA8888
* @readonly
* @type {Number}
*/
RGBA8888: enums.TEXTURE_FMT_RGBA8,
/**
* 32-bit float texture: RGBA32F
* @property RGBA32F
* @readonly
* @type {Number}
*/
RGBA32F: enums.TEXTURE_FMT_RGBA32F,
/**
* 8-bit textures used as masks
* @property A8
* @readonly
* @type {Number}
*/
A8: enums.TEXTURE_FMT_A8,
/**
* 8-bit intensity texture
* @property I8
* @readonly
* @type {Number}
*/
I8: enums.TEXTURE_FMT_L8,
/**
* 16-bit textures used as masks
* @property AI88
* @readonly
* @type {Number}
*/
AI8: enums.TEXTURE_FMT_L8_A8,
/**
* rgb 2 bpp pvrtc
* @property RGB_PVRTC_2BPPV1
* @readonly
* @type {Number}
*/
RGB_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_2BPPV1,
/**
* rgba 2 bpp pvrtc
* @property RGBA_PVRTC_2BPPV1
* @readonly
* @type {Number}
*/
RGBA_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_2BPPV1,
/**
* rgb 4 bpp pvrtc
* @property RGB_PVRTC_4BPPV1
* @readonly
* @type {Number}
*/
RGB_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_4BPPV1,
/**
* rgba 4 bpp pvrtc
* @property RGBA_PVRTC_4BPPV1
* @readonly
* @type {Number}
*/
RGBA_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1,
});
/**
* The texture wrap mode
* @enum {number}
*/
export const WrapMode = Enum({
/**
* The constant variable equals gl.REPEAT for texture
* @property REPEAT
* @type {Number}
* @readonly
*/
REPEAT: GL_REPEAT,
/**
* The constant variable equals gl.CLAMP_TO_EDGE for texture
* @property CLAMP_TO_EDGE
* @type {Number}
* @readonly
*/
CLAMP_TO_EDGE: GL_CLAMP_TO_EDGE,
/**
* The constant variable equals gl.MIRRORED_REPEAT for texture
* @property MIRRORED_REPEAT
* @type {Number}
* @readonly
*/
MIRRORED_REPEAT: GL_MIRRORED_REPEAT
});
/**
* The texture filter mode
* @enum {number}
*/
export const Filter = Enum({
/**
* The constant variable equals gl.LINEAR for texture
* @property LINEAR
* @type {Number}
* @readonly
*/
LINEAR: GL_LINEAR,
/**
* The constant variable equals gl.NEAREST for texture
* @property NEAREST
* @type {Number}
* @readonly
*/
NEAREST: GL_NEAREST
});
const FilterIndex = {
9728: 0, // GL_NEAREST
9729: 1, // GL_LINEAR
};
/**
* @type TextureUpdateOpts
*/
let _sharedOpts = {
width: undefined,
height: undefined,
minFilter: undefined,
magFilter: undefined,
mipFilter: undefined,
wrapS: undefined,
wrapT: undefined,
format: undefined,
mipmap: undefined,
images: undefined,
image: undefined,
flipY: undefined,
premultiplyAlpha: undefined,
anisotropy: undefined
};
function _getSharedOptions () {
for (var key in _sharedOpts) {
_sharedOpts[key] = undefined;
}
_images.length = 0;
_sharedOpts.images = _images;
_sharedOpts.flipY = false;
return _sharedOpts;
}
@ccclass('cc.TextureBase')
export default class TextureBase extends Asset {
@property
_genMipmap = false;
@property
_format = PixelFormat.RGBA8888;
@property
_premultiplyAlpha = false;
@property
_flipY = false;
@property
_minFilter = Filter.LINEAR;
@property
_magFilter = Filter.LINEAR;
@property
_mipFilter = Filter.LINEAR;
@property
_wrapS = WrapMode.CLAMP_TO_EDGE;
@property
_wrapT = WrapMode.CLAMP_TO_EDGE;
@property
_anisotropy = 1;
static PixelFormat = PixelFormat;
static WrapMode = WrapMode;
static Filter = Filter;
/**
*
* @param {TextureBase} texture
*/
static _isCompressed (texture) {
return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1;
}
constructor () {
super();
EventTarget.call(this);
// Id for generate hash in material
this._id = idGenerator.getNewId();
/**
* !#en
* Whether the texture is loaded or not
* !#zh
* 贴图是否已经成功加载
* @property loaded
* @type {Boolean}
*/
this.loaded = false;
/**
* !#en
* Texture width, in pixels.
* For 2D texture, the width of texture is equal to its very first mipmap's width;
* For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width.
* !#zh
* 贴图像素宽度
* @property width
* @type {Number}
*/
this.width = 0;
/**
* !#en
* Texture height, in pixels.
* For 2D texture, the height of texture is equal to its very first mipmap's height;
* For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height.
* !#zh
* 贴图像素高度
* @property height
* @type {Number}
*/
this.height = 0;
}
getId () {
return this._id;
}
/**
* Update texture sampler options.
* @method update
* @param {TextureUpdateOpts} options
*/
update (options) {
if (!options) {
return;
}
if (options.width !== undefined) {
this.width = options.width;
}
if (options.height !== undefined) {
this.height = options.height;
}
if (options.minFilter !== undefined) {
this._minFilter = options.minFilter;
options.minFilter = FilterIndex[options.minFilter];
}
if (options.magFilter !== undefined) {
this._magFilter = options.magFilter;
options.magFilter = FilterIndex[options.magFilter];
}
if (options.mipFilter !== undefined) {
this._mipFilter = options.mipFilter;
options.mipFilter = FilterIndex[options.mipFilter];
}
if (options.wrapS !== undefined) {
this._wrapS = options.wrapS;
}
if (options.wrapT !== undefined) {
this._wrapT = options.wrapT;
}
if (options.format !== undefined) {
this._format = options.format;
}
if (options.flipY !== undefined) {
this._flipY = options.flipY;
}
if (options.premultiplyAlpha !== undefined) {
this._premultiplyAlpha = options.premultiplyAlpha;
}
if (options.anisotropy !== undefined) {
this._anisotropy = options.anisotropy;
}
if (options.mipmap !== undefined) {
this._genMipmap = options.mipmap;
}
}
_getOpts() {
let opts = _getSharedOptions();
opts.width = this.width;
opts.height = this.height;
opts.mipmap = this._genMipmap;
opts.format = this._format;
opts.premultiplyAlpha = this._premultiplyAlpha;
opts.anisotropy = this._anisotropy;
opts.flipY = this._flipY;
opts.minFilter = FilterIndex[this._minFilter];
opts.magFilter = FilterIndex[this._magFilter];
opts.mipFilter = FilterIndex[this._mipFilter];
opts.wrapS = this._wrapS;
opts.wrapT = this._wrapT;
return opts;
}
/**
* !#en
* Pixel format of the texture.
* !#zh 获取纹理的像素格式。
* @method getPixelFormat
* @return {Number}
*/
getPixelFormat () {
//support only in WebGl rendering mode
return this._format;
}
/**
* !#en
* Whether or not the texture has their Alpha premultiplied.
* !#zh 检查纹理在上传 GPU 时预乘选项是否开启。
* @method hasPremultipliedAlpha
* @return {Boolean}
*/
hasPremultipliedAlpha () {
return this._premultiplyAlpha || false;
}
/**
* !#en Anisotropy of the texture.
* !#zh 获取纹理的各向异性。
* @method getAnisotropy
* @return {Number}
*/
getAnisotropy() {
return this._anisotropy;
}
/**
* !#en
* Whether or not to generate mipmap.
* !#zh 检查纹理在上传 GPU 时是否生成 mipmap。
* @method hasMipmap
* @return {Boolean}
*/
genMipmap () {
return this._genMipmap || false;
}
/**
* !#en Sets the wrap s and wrap t options. <br/>
* If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}.
* !#zh 设置纹理包装模式。
* 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。
* @method setTexParameters
* @param {WrapMode} wrapS
* @param {WrapMode} wrapT
*/
setWrapMode (wrapS, wrapT) {
if (this._wrapS !== wrapS || this._wrapT !== wrapT) {
var opts = _getSharedOptions();
opts.wrapS = wrapS;
opts.wrapT = wrapT;
this.update(opts);
}
}
/**
* !#en Sets the minFilter and magFilter options
* !#zh 设置纹理贴图缩小和放大过滤器算法选项。
* @method setFilters
* @param {Filter} minFilter
* @param {Filter} magFilter
*/
setFilters (minFilter, magFilter) {
if (this._minFilter !== minFilter || this._magFilter !== magFilter) {
var opts = _getSharedOptions();
opts.minFilter = minFilter;
opts.magFilter = magFilter;
this.update(opts);
}
}
/**
* !#en Sets the mipFilter options
* !#zh 设置纹理Mipmap过滤算法选项。
* @method setMipFilter
* @param {Filter} mipFilter
*/
setMipFilter (mipFilter) {
if (this._mipFilter !== mipFilter) {
var opts = _getSharedOptions();
opts.mipFilter = mipFilter;
this.update(opts);
}
}
/**
* !#en
* Sets the flipY options
* !#zh 设置贴图的纵向翻转选项。
* @method setFlipY
* @param {Boolean} flipY
*/
setFlipY (flipY) {
if (this._flipY !== flipY) {
var opts = _getSharedOptions();
opts.flipY = flipY;
this.update(opts);
}
}
/**
* !#en
* Sets the premultiply alpha options
* !#zh 设置贴图的预乘选项。
* @method setPremultiplyAlpha
* @param {Boolean} premultiply
*/
setPremultiplyAlpha (premultiply) {
if (this._premultiplyAlpha !== premultiply) {
var opts = _getSharedOptions();
opts.premultiplyAlpha = premultiply;
this.update(opts);
}
}
/**
* !#en Sets the anisotropy of the texture
* !#zh 设置贴图的各向异性。
* @method setAnisotropy
* @param {number} anisotropy
*/
setAnisotropy(anisotropy) {
if (this._anisotropy != anisotropy) {
var opts = _getSharedOptions();
opts.anisotropy = anisotropy;
this.update(opts);
}
}
/**
* !#en
* Sets whether generate mipmaps for the texture
* !#zh 是否为纹理设置生成 mipmaps。
* @method setGenerateMipmap
* @param {Boolean} mipmap
*/
setGenMipmap (mipmap) {
if (this._genMipmap !== mipmap) {
var opts = _getSharedOptions();
opts.mipmap = mipmap;
this.update(opts);
}
}
// SERIALIZATION
/**
* @return {any}
*/
_serialize () {
return this._minFilter + "," + this._magFilter + "," +
this._wrapS + "," + this._wrapT + "," +
(this._premultiplyAlpha ? 1 : 0) + "," +
this._mipFilter + "," + this._anisotropy + "," +
(this._flipY ? 1 : 0) + "," +
(this._genMipmap ? 1 : 0);
}
/**
*
* @param {string} data
*/
_deserialize (data) {
let fields = data.split(',');
fields.unshift("");
if (fields.length >= 6) {
// decode filters
this._minFilter = parseInt(fields[1]);
this._magFilter = parseInt(fields[2]);
// decode wraps
this._wrapS = parseInt(fields[3]);
this._wrapT = parseInt(fields[4]);
// decode premultiply alpha
this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1;
}
if (fields.length >= 8) {
this._mipFilter = parseInt(fields[6]);
this._anisotropy = parseInt(fields[7]);
}
if (fields.length >= 10) {
this._flipY = fields[8].charCodeAt(0) === CHAR_CODE_1;
this._genMipmap = fields[9].charCodeAt(0) === CHAR_CODE_1;
}
}
}
/**
* !#zh
* 当该资源加载成功后触发该事件
* !#en
* This event is emitted when the asset is loaded
*
* @event load
*/
addon(TextureBase.prototype, EventTarget.prototype);
cc.TextureBase = TextureBase;
+613
View File
@@ -0,0 +1,613 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import {ccclass, property} from '../core/data/class-decorator';
import EventTarget from '../core/event/event-target';
import IDGenerator from '../core/utils/id-generator';
import {addon} from '../core/utils/js';
import { ccenum } from '../core/value-types/enum';
import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat } from '../gfx/define';
import { GFXDevice } from '../gfx/device';
import { GFXSampler } from '../gfx/sampler';
import { GFXTexture } from '../gfx/texture';
import { GFXTextureView } from '../gfx/texture-view';
import { Asset } from './asset';
import ImageAsset from './image-asset';
const CHAR_CODE_1 = 49; // '1'
const idGenerator = new IDGenerator('Tex');
/**
* The texture pixel format, default value is RGBA8888,
* you should note that textures loaded by normal image files (png, jpg) can only support RGBA8888 format,
* other formats are supported by compressed file types or raw data.
* @enum {number}
*/
export enum PixelFormat {
/**
* 16-bit texture without Alpha channel
*/
RGB565 = GFXFormat.R5G6B5,
/**
* 16-bit textures: RGB5A1
*/
RGB5A1 = GFXFormat.RGB5A1,
/**
* 16-bit textures: RGBA4444
*/
RGBA4444 = GFXFormat.RGBA4,
/**
* 24-bit texture: RGB888
*/
RGB888 = GFXFormat.RGB8UI,
/**
* 32-bit texture: RGBA8888
*/
RGBA8888 = GFXFormat.RGBA8UI,
/**
* 32-bit float texture: RGBA32F
*/
RGBA32F = GFXFormat.RGBA32F,
/**
* 8-bit textures used as masks
*/
A8 = GFXFormat.R8UI,
/**
* 8-bit intensity texture
*/
I8 = GFXFormat.R8UI,
/**
* 16-bit textures used as masks
*/
AI8 = GFXFormat.RG8UI,
/**
* rgb 2 bpp pvrtc
*/
RGB_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGB2,
/**
* rgba 2 bpp pvrtc
*/
RGBA_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGBA2,
/**
* rgb 4 bpp pvrtc
*/
RGB_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGB4,
/**
* rgba 4 bpp pvrtc
*/
RGBA_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGBA4,
}
ccenum(PixelFormat);
function toGfxFormat (pixelFormat: PixelFormat) {
return pixelFormat as unknown as GFXFormat;
}
/**
* The texture wrap mode.
* @enum {number}
*/
export enum WrapMode {
/**
* Specifies that the repeat warp mode will be used.
*/
REPEAT = GFXAddress.WRAP,
/**
* Specifies that the clamp to edge warp mode will be used.
*/
CLAMP_TO_EDGE = GFXAddress.CLAMP,
/**
* Specifies that the mirrored repeat warp mode will be used.
*/
MIRRORED_REPEAT = GFXAddress.MIRROR,
/**
* Specifies that the clamp to border wrap mode will be used.
*/
CLAMP_TO_BORDER = GFXAddress.BORDER,
}
ccenum(WrapMode);
function toGfxAddressMode (wrapMode: WrapMode) {
return wrapMode as unknown as GFXAddress;
}
/**
* The texture filter mode
* @enum {number}
*/
export enum Filter {
/**
* Specifies linear filtering.
*/
LINEAR = GFXFilter.LINEAR,
/**
* Specifies nearest filtering.
*/
NEAREST = GFXFilter.POINT,
}
ccenum(Filter);
function toGfxFilterMode (filter: Filter) {
return filter as unknown as GFXFilter;
}
@ccclass('cc.TextureBase')
export default class TextureBase extends Asset {
/**
* !#en
* Texture width, in pixels.
* For 2D texture, the width of texture is equal to its very first mipmap's width;
* For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width.
* !#zh
* 贴图像素宽度
* @property width
* @type {Number}
*/
public get width (): number {
return this._width;
}
/**
* !#en
* Texture height, in pixels.
* For 2D texture, the height of texture is equal to its very first mipmap's height;
* For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height.
* !#zh
* 贴图像素高度
* @property height
* @type {Number}
*/
public get height (): number {
return this._height;
}
public static PixelFormat = PixelFormat;
public static WrapMode = WrapMode;
public static Filter = Filter;
/**
*
* @param texture
*/
public static _isCompressed (texture: TextureBase) {
return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1;
}
protected _texture: GFXTexture | null = null;
protected _textureView: GFXTextureView | null = null;
@property
private _genMipmap = false;
@property
private _format: PixelFormat = PixelFormat.RGBA8888;
@property
private _premultiplyAlpha = false;
@property
private _flipY = false;
@property
private _minFilter = Filter.LINEAR;
@property
private _magFilter = Filter.LINEAR;
@property
private _mipFilter = Filter.LINEAR;
@property
private _wrapS: WrapMode = WrapMode.CLAMP_TO_EDGE;
@property
private _wrapT: WrapMode = WrapMode.CLAMP_TO_EDGE;
@property
private _anisotropy = 1;
private _width: number = 0;
private _height: number = 0;
private _sampler: GFXSampler | null = null;
private _id: string;
protected constructor (flipY: boolean = false) {
super();
// @ts-ignore
EventTarget.call(this);
this._flipY = flipY;
// Id for generate hash in material
this._id = idGenerator.getNewId();
/**
* !#en
* Whether the texture is loaded or not
* !#zh
* 贴图是否已经成功加载
* @property loaded
* @type {Boolean}
*/
// @ts-ignore
this.loaded = false;
}
/**
* Gets the underlying texture object.
* @deprecated Use getGfxTexture() instead.
*/
public getImpl () {
return this._texture;
}
public getId () {
return this._id;
}
/**
* !#en
* Pixel format of the texture.
* !#zh 获取纹理的像素格式。
* @return
*/
public getPixelFormat () {
// support only in WebGl rendering mode
return this._format;
}
/**
* !#en
* Whether or not the texture has their Alpha premultiplied.
* !#zh 检查纹理在上传 GPU 时预乘选项是否开启。
* @return
*/
public hasPremultipliedAlpha () {
return this._premultiplyAlpha || false;
}
/**
* !#en Anisotropy of the texture.
* !#zh 获取纹理的各向异性。
* @return
*/
public getAnisotropy () {
return this._anisotropy;
}
/**
* !#en
* Whether or not to generate mipmap.
* !#zh 检查纹理在上传 GPU 时是否生成 mipmap。
* @return
*/
public genMipmap () {
return this._genMipmap || false;
}
/**
* !#en Sets the wrap s and wrap t options. <br/>
* If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}.
* !#zh 设置纹理包装模式。
* 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。
* @param wrapS
* @param wrapT
*/
public setWrapMode (wrapS: WrapMode, wrapT: WrapMode) {
if (this._wrapS !== wrapS || this._wrapT !== wrapT) {
this._wrapS = wrapS;
this._wrapT = wrapT;
this._updateSampler();
}
}
/**
* !#en Sets the minFilter and magFilter options
* !#zh 设置纹理贴图缩小和放大过滤器算法选项。
* @param minFilter
* @param magFilter
*/
public setFilters (minFilter: Filter, magFilter: Filter) {
if (this._minFilter !== minFilter || this._magFilter !== magFilter) {
this._minFilter = minFilter;
this._magFilter = magFilter;
this._updateSampler();
}
}
/**
* !#en Sets the mipFilter options
* !#zh 设置纹理Mipmap过滤算法选项。
* @param mipFilter
*/
public setMipFilter (mipFilter: Filter) {
if (this._mipFilter !== mipFilter) {
this._mipFilter = mipFilter;
this._updateSampler();
}
}
/**
* !#en
* Sets the flipY options
* !#zh 设置贴图的纵向翻转选项。
* @param flipY
*/
public setFlipY (flipY: boolean) {
if (this._flipY !== flipY) {
this._flipY = flipY;
this._updateSampler();
}
}
/**
* !#en
* Sets the premultiply alpha options
* !#zh 设置贴图的预乘选项。
* @param premultiply
*/
public setPremultiplyAlpha (premultiply: boolean) {
if (this._premultiplyAlpha !== premultiply) {
this._premultiplyAlpha = premultiply;
this._updateSampler();
}
}
/**
* !#en Sets the anisotropy of the texture
* !#zh 设置贴图的各向异性。
* @param anisotropy
*/
public setAnisotropy (anisotropy: number) {
if (this._anisotropy !== anisotropy) {
this._anisotropy = anisotropy;
this._updateSampler();
}
}
/**
* !#en
* Sets whether generate mipmaps for the texture
* !#zh 是否为纹理设置生成 mipmaps。
* @param mipmap
*/
public setGenMipmap (mipmap: boolean) {
if (this._genMipmap !== mipmap) {
this._genMipmap = mipmap;
this._updateSampler();
}
}
public destroy () {
this._destroyTexture();
if (this._sampler) {
this._sampler.destroy();
}
return true;
}
public getGFXTexture () {
return this._texture;
}
public getGFXTextureView () {
return this._textureView;
}
public getGFXSampler () {
return this._sampler;
}
// SERIALIZATION
/**
* @return
*/
public _serialize (): any {
return this._minFilter + ',' + this._magFilter + ',' +
this._wrapS + ',' + this._wrapT + ',' +
(this._premultiplyAlpha ? 1 : 0) + ',' +
this._mipFilter + ',' + this._anisotropy + ',' +
(this._flipY ? 1 : 0) + ',' +
(this._genMipmap ? 1 : 0);
}
/**
*
* @param data
*/
public _deserialize (serializedData: any, handle: any) {
const data = serializedData as string;
const fields = data.split(',');
fields.unshift('');
if (fields.length >= 6) {
// decode filters
this._minFilter = parseInt(fields[1], undefined);
this._magFilter = parseInt(fields[2], undefined);
// decode wraps
this._wrapS = parseInt(fields[3], undefined);
this._wrapT = parseInt(fields[4], undefined);
// decode premultiply alpha
this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1;
}
if (fields.length >= 8) {
this._mipFilter = parseInt(fields[6], undefined);
this._anisotropy = parseInt(fields[7], undefined);
}
if (fields.length >= 10) {
this._flipY = fields[8].charCodeAt(0) === CHAR_CODE_1;
this._genMipmap = fields[9].charCodeAt(0) === CHAR_CODE_1;
}
}
public onLoaded () {
this._updateSampler();
this._recreateTexture();
}
protected _getGlobalDevice (): GFXDevice | null {
return cc.director.root.device;
}
protected _getGfxFormat () {
return toGfxFormat(this._format);
}
protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) {
const upload = () => { this._uploadImage(image, level, arrayIndex); };
// @ts-ignore
if (image.loaded) {
upload();
} else {
// @ts-ignore
image.addEventListener('load', () => {
upload();
});
}
}
protected _uploadImage (image: ImageAsset, level: number, arrayIndex?: number) {
if (!this._texture) {
return;
}
if (level >= this._texture.mipLevel) {
return;
}
const data = image.data;
if (!data) {
return;
}
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) {
return;
}
const region: GFXBufferTextureCopy = {
buffOffset: 0,
buffStride: 0,
buffTexHeight: 0,
texOffset: {
x: 0,
y: 0,
z: 0,
},
texExtent: {
width: this._texture.width,
height: this._texture.height,
depth: 1,
},
texSubres: {
baseMipLevel: level,
levelCount: 1,
baseArrayLayer: arrayIndex || 0,
layerCount: 1,
},
};
if (data instanceof HTMLElement) {
gfxDevice.copyImageSourceToTexture(data, this._texture, [region]);
} else {
gfxDevice.copyBufferToTexture(data.buffer, this._texture, [region]);
}
}
protected _recreateTexture () {
this._destroyTexture();
this._createTexture();
if (this._texture) {
this._width = this._texture.width;
this._height = this._texture.height;
}
this._createTextureView();
}
protected _createTexture () {
return;
}
protected _createTextureView () {
return;
}
private _destroyTexture () {
if (this._textureView) {
this._textureView.destroy();
this._textureView = null;
}
if (this._texture) {
this._texture.destroy();
this._texture = null;
}
}
private _updateSampler () {
if (this._sampler) {
this._sampler.destroy();
}
const gfxDevice = this._getGlobalDevice();
if (!gfxDevice) {
return;
}
this._sampler = gfxDevice.createSampler({
name: `Sampler of ${this.name}`,
minFilter: toGfxFilterMode(this._minFilter),
magFilter: toGfxFilterMode(this._magFilter),
addressU: toGfxAddressMode(this._wrapS),
addressV: toGfxAddressMode(this._wrapT),
maxAnisotropy: this._anisotropy,
});
}
}
/* tslint:disable:no-string-literal */
cc['TextureBase'] = TextureBase;
/**
* !#zh
* 当该资源加载成功后触发该事件
* !#en
* This event is emitted when the asset is loaded
*
* @event load
*/
addon(TextureBase.prototype, EventTarget.prototype);
+2 -2
View File
@@ -40,8 +40,8 @@ export class CCObject {
protected _destruct(): void;
protected _destroyImmediate(): void;
protected _serialize: (exporting: boolean) => object | null;
protected _deserialize: (data: object, ctx: object) => object | null;
protected _serialize?(): any;
protected _deserialize?(data: any, ctx: any): any;
protected _onPreDestroy: () => void | null;
protected Flags: object;
}
+11
View File
@@ -118,4 +118,15 @@ if (CC_DEV) {
}
}
/**
*
* @param {Object} enumx
*/
export function ccenum(enumx) {
if ('__enums__' in enumx) {
return;
}
js.value(enumx, '__enums__', null, true);
}
cc.Enum = Enum;
+22
View File
@@ -0,0 +1,22 @@
export interface IRect2D {
x?: number;
y?: number;
width?: number;
height?: number;
}
export interface INormalizedRect2D {
x: number;
y: number;
width: number;
height: number;
}
export function normalizeRect2D (rect: IRect2D, fullWidth: number, fullHeight: number): INormalizedRect2D {
rect.x = rect.x || 0;
rect.y = rect.y || 0;
rect.width = rect.width || fullWidth;
rect.height = rect.height || fullHeight;
return rect as INormalizedRect2D;
}