From e0e3a9fade1cc60279811aecc01ce59d13cb0dd4 Mon Sep 17 00:00:00 2001 From: cebgcontract <99630598+cebgcontract@users.noreply.github.com> Date: Thu, 21 Jul 2022 18:25:30 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0jazzicon=E7=BB=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/comp/IconCache.ts | 13 + src/comp/JazzIcon.ts | 96 +++ src/index.ts | 46 +- src/lib/value-types/math.d.ts | 56 ++ src/lib/value-types/utils.ts | 248 +++++++ src/lib/value-types/value-type.ts | 99 +++ src/lib/value-types/vec2.ts | 1142 +++++++++++++++++++++++++++++ src/util/id-generater.js | 55 ++ src/util/js.js | 996 +++++++++++++++++++++++++ 9 files changed, 2747 insertions(+), 4 deletions(-) create mode 100644 src/comp/IconCache.ts create mode 100644 src/comp/JazzIcon.ts create mode 100644 src/lib/value-types/math.d.ts create mode 100644 src/lib/value-types/utils.ts create mode 100644 src/lib/value-types/value-type.ts create mode 100644 src/lib/value-types/vec2.ts create mode 100644 src/util/id-generater.js create mode 100644 src/util/js.js diff --git a/src/comp/IconCache.ts b/src/comp/IconCache.ts new file mode 100644 index 0000000..7892e63 --- /dev/null +++ b/src/comp/IconCache.ts @@ -0,0 +1,13 @@ +import { singleton } from "../decorator/singleton.decorator" + + +@singleton +export default class IconCache { + iconMap: Map = new Map() + add(key: string, val: any) { + this.iconMap.set(key, val) + } + get(key: string) { + return this.iconMap.get(key) + } +} \ No newline at end of file diff --git a/src/comp/JazzIcon.ts b/src/comp/JazzIcon.ts new file mode 100644 index 0000000..c68a172 --- /dev/null +++ b/src/comp/JazzIcon.ts @@ -0,0 +1,96 @@ +import MersenneTwister from "../lib/mersenne-twister"; +import Vec2 from "../lib/value-types/vec2"; +import IconCache from "./IconCache"; + + +export class JazzIcon{ + private generator: MersenneTwister + + + private shapeCount = 4 + + private colors = [] + private diameter: number; + + init(address: string, diameter: number) { + this.diameter = diameter; + this.colors = [ + '#01888C', // teal + '#FC7500', // bright orange + '#034F5D', // dark teal + '#F73F01', // orangered + '#FC1960', // magenta + '#C7144C', // raspberry + '#F3C100', // goldenrod + '#1598F2', // lightning blue + '#2465E1', // sail blue + '#F19E02', // gold + ] + let cacheData: any = new IconCache().get(address) + if (cacheData) { + return cacheData + } + let seed = Date.now() + if (address.startsWith("0x")) { + seed = parseInt(address.slice(2, 10), 16); + } + this.generator = new MersenneTwister(seed); + // let remainingColors = this.hueShift(this.colors.slice()) + this.generator.random() + let remainingColors = this.colors.slice() + let fillColor = this.genColor(this.colors) + let cache: any = { diameter, color: fillColor, paths: [] } + for(var i = 0; i < this.shapeCount - 1; i++) { + let data = this.genShape(remainingColors, diameter, i, this.shapeCount - 1) + cache.paths.push(data) + } + new IconCache().add(address, cache) + return cache; + } + + genColor(colors: string[]) { + let rand = this.generator.random() + var idx = Math.floor(colors.length * this.generator.random()) + var color = colors.splice(idx,1)[0] + return color; + } + + hueShift(colors: string[]) { + this.generator.random() + return colors + } + genShape(remainingColors: string[], diameter: number, i: number, total: number) { + let firstRot = this.generator.random() + let angle = Math.PI * 2 * firstRot + let velocity = diameter / total * this.generator.random() + (i * diameter / total) + let tx = (Math.cos(angle) * velocity) + let ty = (Math.sin(angle) * velocity) + let c1 = new Vec2(diameter / 2, diameter / 2) + let c2 = new Vec2(tx, ty) + + let secondRot = this.generator.random() + let rot = (firstRot * 360) + secondRot * 180 + let angle2 = Math.PI * 2 * rot + let p0 = this.moveAndRotate(new Vec2(0, 0), c1, c2, angle2, diameter) + let p1 = this.moveAndRotate(new Vec2(0, diameter), c1, c2, angle2, diameter) + let p2 = this.moveAndRotate(new Vec2(diameter, diameter), c1, c2, angle2, diameter) + let p3 = this.moveAndRotate(new Vec2(diameter, 0), c1, c2, angle2, diameter) + let fill = this.genColor(remainingColors) + return { + color: fill, + path: [p0, p1, p2, p3] + } + // this.ctx.stroke() + } + + moveAndRotate(p1: Vec2, c1: Vec2, c2: Vec2, radians: number, diameter: number) { + let x1 = c2.x - c1.x + let y1 = c2.y - c1.y + let tmpV2 = new Vec2(x1, y1) + let p2 = p1.add(tmpV2).sub(c2) + let r = p2.rotate(radians).add(c2) + let x = Math.min(Math.max(0, r.x), diameter) + let y = Math.min(Math.max(0, r.y), diameter) + return new Vec2(x, y) + } +} diff --git a/src/index.ts b/src/index.ts index 6fdce8b..8d68ab4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,6 +30,7 @@ import { restoreWalletByMnemonic, } from "./manage/WalletManage"; import { signLogin } from "./util/sign.util"; +import { JazzIcon } from "./comp/JazzIcon"; var global = (typeof globalThis !== "undefined" && globalThis) || @@ -149,6 +150,7 @@ export default class JCWallet { this.web3.eth.setProvider(chainData.rpc); this.mainHandlers.emit(WALLET_CHAIN_CHANGE, chainData); this.updateListType("tokens"); + return this.currentChain; } updateListType(type: string) { @@ -256,19 +258,26 @@ export default class JCWallet { } return maxIdx + 1; } - - public selectAccount(address: string) { + private getAccountByAddress(address: string) { + let account; let index = 0; for (let i = 0, l = this.wallet.length; i < l; i++) { if (this.wallet[i].address === address) { + account = this.wallet[i]; index = i; break; } } + return {account, index}; + } + + public selectAccount(address: string) { + const { index } = this.getAccountByAddress(address); if (index !== this.accountIndex && index < this.wallet.length) { this.accountIndex = index; this.mainHandlers.emit(WALLET_ACCOUNT_CHANGE, this.wallet[index].address); } + return address; } public async sendEth(to: string, amount: number | string) { @@ -305,7 +314,7 @@ export default class JCWallet { }); } - public loginSign(nonce: string, tips: string) { + public loginSign(nonce: string, tips: string, address?: string) { const account = this.currentAccount(); return signLogin(nonce, tips, account.privateKey); } @@ -317,6 +326,36 @@ export default class JCWallet { version: SignTypedDataVersion.V4, }); } + + public generateIconData(msg: string, diameter: number) { + let icon = new JazzIcon(); + return icon.init(msg, diameter); + } + + public async erc20Info(address: string) { + let symbol = await this.erc20Standard.getTokenSymbol(address); + let decimal = await this.erc20Standard.getTokenDecimals(address); + return {symbol, decimal}; + } + + public async erc20Balance(address: string, account?: string) { + if (!account) { + account = this.currentAccount().address; + } + let result = await this.erc20Standard.getBalanceOf(address, account); + return result; + } + + public async sendErc20(address: string, to: string, amount: string) { + let from = this.currentAccount().address + let result = await this.erc20Standard.transfer({ + address, + from, + to, + amount + }) + return result; + } } // window.jc = window.jc || {wallet: new JCWallet()}; @@ -327,4 +366,3 @@ export * from "./config/chain_config"; export * from "./util/number.util"; export * from "./util/wallet.util"; export * from "./data/DataModel"; -export * from "./config/chain_config"; diff --git a/src/lib/value-types/math.d.ts b/src/lib/value-types/math.d.ts new file mode 100644 index 0000000..43115fa --- /dev/null +++ b/src/lib/value-types/math.d.ts @@ -0,0 +1,56 @@ + +type FloatArray = Float64Array | Float32Array; + +interface IColorLike { + r: number; + g: number; + b: number; + a: number; + _val: number; + +} + +interface IMat3Like { + m: FloatArray +} + +interface IMat4Like { + m: FloatArray +} + +interface IQuatLike { + x: number; + y: number; + z: number; + w: number; +} + +interface IRectLike { + x: number; + y: number; + width: number; + height: number; +} + +interface ISizeLike { + width: number; + height: number; +} + +interface IVec2Like { + x: number; + y: number; +} + +interface IVec3Like { + x: number; + y: number; + z: number; +} + +interface IVec4Like { + x: number; + y: number; + z: number; + w: number; +} \ No newline at end of file diff --git a/src/lib/value-types/utils.ts b/src/lib/value-types/utils.ts new file mode 100644 index 0000000..4d32eb4 --- /dev/null +++ b/src/lib/value-types/utils.ts @@ -0,0 +1,248 @@ +/** + * @ignore + */ +const _d2r = Math.PI / 180.0; +/** + * @ignore + */ +const _r2d = 180.0 / Math.PI; + +/** + * @property {number} EPSILON + */ +export const EPSILON = 0.000001; + +// Number of bits in an integer +export const INT_BITS = 32; +export const INT_MAX = 0x7fffffff; +export const INT_MIN = -1 << (INT_BITS - 1); + +/** + * Tests whether or not the arguments have approximately the same value, within an absolute + * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less + * than or equal to 1.0, and a relative tolerance is used for larger values) + * + * @param {Number} a The first number to test. + * @param {Number} b The second number to test. + * @returns {Boolean} True if the numbers are approximately equal, false otherwise. + */ +export function equals(a, b) { + return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); +} + +/** + * Tests whether or not the arguments have approximately the same value by given maxDiff + * + * @param {Number} a The first number to test. + * @param {Number} b The second number to test. + * @param {Number} maxDiff Maximum difference. + * @returns {Boolean} True if the numbers are approximately equal, false otherwise. + */ +export function approx(a, b, maxDiff) { + maxDiff = maxDiff || EPSILON; + return Math.abs(a - b) <= maxDiff; +} + +/** + * Clamps a value between a minimum float and maximum float value. + * + * @method clamp + * @param {number} val + * @param {number} min + * @param {number} max + * @return {number} + */ +export function clamp(val, min, max) { + return val < min ? min : val > max ? max : val; +} + +/** + * Clamps a value between 0 and 1. + * + * @method clamp01 + * @param {number} val + * @return {number} + */ +export function clamp01(val) { + return val < 0 ? 0 : val > 1 ? 1 : val; +} + +/** + * @method lerp + * @param {number} from + * @param {number} to + * @param {number} ratio - the interpolation coefficient + * @return {number} + */ +export function lerp(from, to, ratio) { + return from + (to - from) * ratio; +} + +/** +* Convert Degree To Radian +* +* @param {Number} a Angle in Degrees +*/ +export function toRadian(a) { + return a * _d2r; +} + +/** +* Convert Radian To Degree +* +* @param {Number} a Angle in Radian +*/ +export function toDegree(a) { + return a * _r2d; +} + +/** +* @method random +*/ +export const random = Math.random; + +/** + * Returns a floating-point random number between min (inclusive) and max (exclusive). + * + * @method randomRange + * @param {number} min + * @param {number} max + * @return {number} the random number + */ +export function randomRange(min, max) { + return Math.random() * (max - min) + min; +} + +/** + * Returns a random integer between min (inclusive) and max (exclusive). + * + * @method randomRangeInt + * @param {number} min + * @param {number} max + * @return {number} the random integer + */ +export function randomRangeInt(min, max) { + return Math.floor(randomRange(min, max)); +} + +/** + * Linear congruential generator using Hull-Dobell Theorem. + * + * @method pseudoRandom + * @param {number} seed the random seed + * @return {number} the pseudo random + */ +export function pseudoRandom(seed) { + seed = (seed * 9301 + 49297) % 233280; + return seed / 233280.0; +} + +/** + * Returns a floating-point pseudo-random number between min (inclusive) and max (exclusive). + * + * @method pseudoRandomRange + * @param {number} seed + * @param {number} min + * @param {number} max + * @return {number} the random number + */ +export function pseudoRandomRange(seed, min, max) { + return pseudoRandom(seed) * (max - min) + min; +} + +/** + * Returns a pseudo-random integer between min (inclusive) and max (exclusive). + * + * @method pseudoRandomRangeInt + * @param {number} seed + * @param {number} min + * @param {number} max + * @return {number} the random integer + */ +export function pseudoRandomRangeInt(seed, min, max) { + return Math.floor(pseudoRandomRange(seed, min, max)); +} + +/** + * Returns the next power of two for the value + * + * @method nextPow2 + * @param {number} val + * @return {number} the the next power of two + */ +export function nextPow2(val) { + --val; + val = (val >> 1) | val; + val = (val >> 2) | val; + val = (val >> 4) | val; + val = (val >> 8) | val; + val = (val >> 16) | val; + ++val; + + return val; +} + +/** + * Returns float remainder for t / length + * + * @method repeat + * @param {number} t time start at 0 + * @param {number} length time of one cycle + * @return {number} the time wrapped in the first cycle + */ +export function repeat(t, length) { + return t - Math.floor(t / length) * length; +} + +/** + * Returns time wrapped in ping-pong mode + * + * @method repeat + * @param {number} t time start at 0 + * @param {number} length time of one cycle + * @return {number} the time wrapped in the first cycle + */ +export function pingPong(t, length) { + t = repeat(t, length * 2); + t = length - Math.abs(t - length); + return t; +} + +/** + * Returns ratio of a value within a given range + * + * @method repeat + * @param {number} from start value + * @param {number} to end value + * @param {number} value given value + * @return {number} the ratio between [from,to] + */ +export function inverseLerp(from, to, value) { + return (value - from) / (to - from); +} + +/** + * !#en Clamp a value between from and to. + * !#zh + * 限定浮点数的最大最小值。
+ * 数值大于 max_inclusive 则返回 max_inclusive。
+ * 数值小于 min_inclusive 则返回 min_inclusive。
+ * 否则返回自身。 + * @method clampf + * @param {Number} value + * @param {Number} min_inclusive + * @param {Number} max_inclusive + * @return {Number} + * @example + * var v1 = cc.misc.clampf(20, 0, 20); // 20; + * var v2 = cc.misc.clampf(-1, 0, 20); // 0; + * var v3 = cc.misc.clampf(10, 0, 20); // 10; + */ +export function mclampf(value, min_inclusive, max_inclusive) { + if (min_inclusive > max_inclusive) { + var temp = min_inclusive; + min_inclusive = max_inclusive; + max_inclusive = temp; + } + return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive; +} \ No newline at end of file diff --git a/src/lib/value-types/value-type.ts b/src/lib/value-types/value-type.ts new file mode 100644 index 0000000..a2a7ab2 --- /dev/null +++ b/src/lib/value-types/value-type.ts @@ -0,0 +1,99 @@ +/**************************************************************************** + 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 The base class of all value types. + * !#zh 所有值类型的基类。 + * @class ValueType + * + */ +export default class ValueType { + /** + * !#en This method returns an exact copy of current value. + * !#zh 克隆当前值,该方法返回一个新对象,新对象的值和原对象相等。 + * @method clone + * @return {ValueType} + */ + clone () : ValueType { + // cc.errorID('0100', js.getClassName(this) + '.clone'); + // @ts-ignore + return null; + } + + /** + * !#en Compares this object with the other one. + * !#zh 当前对象是否等于指定对象。 + * @method equals + * @param {ValueType} other + * @return {Boolean} + */ + equals (other) { + // cc.errorID('0100', js.getClassName(this) + '.equals'); + return false; + } + + /** + * !#en + * Linearly interpolates between this value to to value by ratio which is in the range [0, 1]. + * When ratio = 0 returns this. When ratio = 1 return to. When ratio = 0.5 returns the average of this and to. + * !#zh + * 线性插值。
+ * 当 ratio = 0 时返回自身,ratio = 1 时返回目标,ratio = 0.5 返回自身和目标的平均值。。 + * @method lerp + * @param {ValueType} to - the to value + * @param {number} ratio - the interpolation coefficient + * @return {ValueType} + */ + lerp (to, ratio) { + // cc.errorID('0100', js.getClassName(this) + '.lerp'); + return this.clone(); + } + + /** + * !#en + * Copys all the properties from another given object to this value. + * !#zh + * 从其它对象把所有属性复制到当前对象。 + * @method set + * @param {ValueType} source - the source to copy + */ + set (source) { + // cc.errorID('0100', js.getClassName(this) + '.set'); + } + + /** + * !#en Convert to a readable string. + * !#zh 转换为方便阅读的字符串。 + * @method toString + * @return {string} + */ + toString () { + return '' + {}; + } +} + diff --git a/src/lib/value-types/vec2.ts b/src/lib/value-types/vec2.ts new file mode 100644 index 0000000..fc1060d --- /dev/null +++ b/src/lib/value-types/vec2.ts @@ -0,0 +1,1142 @@ +/**************************************************************************** + 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 ValueType from './value-type'; +import { EPSILON, mclampf, random } from './utils'; + +let _x: number = 0.0; +let _y: number = 0.0; + +/** + * !#en Representation of 2D vectors and points. + * !#zh 表示 2D 向量和坐标 + * + * @class Vec2 + * @extends ValueType + */ + +export default class Vec2 extends ValueType { + // deprecated + static sub = Vec2.subtract; + static mul = Vec2.multiply; + static scale = Vec2.multiplyScalar; + static mag = Vec2.len; + static squaredMagnitude = Vec2.lengthSqr; + static div = Vec2.divide; + /** + * !#en Returns the length of this vector. + * !#zh 返回该向量的长度。 + * @method mag + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.mag(); // return 14.142135623730951; + */ + mag = Vec2.prototype.len; + /** + * !#en Returns the squared length of this vector. + * !#zh 返回该向量的长度平方。 + * @method magSqr + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.magSqr(); // return 200; + */ + magSqr = Vec2.prototype.lengthSqr; + /** + * !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead. + * !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。 + * @method subSelf + * @param {Vec2} vector + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.subSelf(cc.v2(5, 5));// return Vec2 {x: 5, y: 5}; + */ + subSelf = Vec2.prototype.subtract; + /** + * !#en Subtracts one vector from this, and returns the new result. + * !#zh 向量减法,并返回新结果。 + * @method sub + * @param {Vec2} vector + * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * v.sub(cc.v2(5, 5)); // return Vec2 {x: 5, y: 5}; + * var v1 = new Vec2; + * v.sub(cc.v2(5, 5), v1); // return Vec2 {x: 5, y: 5}; + */ + sub (vector: Vec2, out?: Vec2): Vec2 { + return Vec2.subtract(out || new Vec2(), this, vector); + } + /** + * !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead. + * !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。 + * @method mulSelf + * @param {number} num + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.mulSelf(5);// return Vec2 {x: 50, y: 50}; + */ + mulSelf = Vec2.prototype.multiplyScalar; + /** + * !#en Multiplies by a number, and returns the new result. + * !#zh 缩放向量,并返回新结果。 + * @method mul + * @param {number} num + * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * v.mul(5); // return Vec2 {x: 50, y: 50}; + * var v1 = new Vec2; + * v.mul(5, v1); // return Vec2 {x: 50, y: 50}; + */ + mul (num: number, out?: Vec2): Vec2 { + return Vec2.multiplyScalar(out || new Vec2(), this, num); + } + /** + * !#en Divides by a number. If you want to save result to another vector, use div() instead. + * !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。 + * @method divSelf + * @param {number} num + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.divSelf(5); // return Vec2 {x: 2, y: 2}; + */ + divSelf = Vec2.prototype.divide; + /** + * !#en Divides by a number, and returns the new result. + * !#zh 向量除法,并返回新的结果。 + * @method div + * @param {number} num + * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * v.div(5); // return Vec2 {x: 2, y: 2}; + * var v1 = new Vec2; + * v.div(5, v1); // return Vec2 {x: 2, y: 2}; + */ + div (num: number, out?: Vec2): Vec2 { + return Vec2.multiplyScalar(out || new Vec2(), this, 1/num); + } + /** + * !#en Multiplies two vectors. + * !#zh 分量相乘。 + * @method scaleSelf + * @param {Vec2} vector + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.scaleSelf(cc.v2(5, 5));// return Vec2 {x: 50, y: 50}; + */ + scaleSelf = Vec2.prototype.multiply; + /** + * !#en Multiplies two vectors, and returns the new result. + * !#zh 分量相乘,并返回新的结果。 + * @method scale + * @param {Vec2} vector + * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * v.scale(cc.v2(5, 5)); // return Vec2 {x: 50, y: 50}; + * var v1 = new Vec2; + * v.scale(cc.v2(5, 5), v1); // return Vec2 {x: 50, y: 50}; + */ + scale (vector: Vec2, out?: Vec2): Vec2 { + return Vec2.multiply(out || new Vec2(), this, vector); + } + /** + * !#en Negates the components. If you want to save result to another vector, use neg() instead. + * !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。 + * @method negSelf + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.negSelf(); // return Vec2 {x: -10, y: -10}; + */ + negSelf = Vec2.prototype.negate; + /** + * !#en Negates the components, and returns the new result. + * !#zh 返回取反后的新向量。 + * @method neg + * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * var v1 = new Vec2; + * v.neg(v1); // return Vec2 {x: -10, y: -10}; + */ + neg (out?: Vec2): Vec2 { + return Vec2.negate(out || new Vec2(), this); + } + + /** + * !#en return a Vec2 object with x = 1 and y = 1. + * !#zh 新 Vec2 对象。 + * @property ONE + * @type Vec2 + * @static + */ + static get ONE () { return new Vec2(1, 1) }; + static readonly ONE_R = Vec2.ONE; + + /** + * !#en return a Vec2 object with x = 0 and y = 0. + * !#zh 返回 x = 0 和 y = 0 的 Vec2 对象。 + * @property {Vec2} ZERO + * @static + */ + static get ZERO () { return new Vec2(0, 0) }; + /** + * !#en return a readonly Vec2 object with x = 0 and y = 0. + * !#zh 返回一个 x = 0 和 y = 0 的 Vec2 只读对象。 + * @property {Vec2} ZERO_R + * @readonly + * @static + */ + static readonly ZERO_R = Vec2.ZERO; + + /** + * !#en return a Vec2 object with x = 0 and y = 1. + * !#zh 返回 x = 0 和 y = 1 的 Vec2 对象。 + * @property {Vec2} UP + * @static + */ + static get UP () { return new Vec2(0, 1) }; + /** + * !#en return a readonly Vec2 object with x = 0 and y = 1. + * !#zh 返回 x = 0 和 y = 1 的 Vec2 只读对象。 + * @property {Vec2} UP_R + * @static + * @readonly + */ + static readonly UP_R = Vec2.UP; + + /** + * !#en return a readonly Vec2 object with x = 1 and y = 0. + * !#zh 返回 x = 1 和 y = 0 的 Vec2 只读对象。 + * @property {Vec2} RIGHT + * @static + */ + static get RIGHT () { return new Vec2(1, 0) }; + /** + * !#en return a Vec2 object with x = 1 and y = 0. + * !#zh 返回 x = 1 和 y = 0 的 Vec2 对象。 + * @property {Vec2} RIGHT_R + * @static + * @readonly + */ + static readonly RIGHT_R = Vec2.RIGHT; + + /** + * !#zh 获得指定向量的拷贝 + * @method clone + * @typescript + * clone (a: Out): Vec2 + * @static + */ + static clone (a: Out) { + return new Vec2(a.x, a.y); + } + + /** + * !#zh 复制指定向量的值 + * @method copy + * @typescript + * copy (out: Out, a: Out): Out + * @static + */ + static copy (out: Out, a: Out) { + out.x = a.x; + out.y = a.y; + return out; + } + + /** + * !#zh 设置向量值 + * @method set + * @typescript + * set (out: Out, x: number, y: number): Out + * @static + */ + static set (out: Out, x: number, y: number) { + out.x = x; + out.y = y; + return out; + } + + /** + * !#zh 逐元素向量加法 + * @method add + * @typescript + * add (out: Out, a: Out, b: Out): Out + * @static + */ + static add (out: Out, a: Out, b: Out) { + out.x = a.x + b.x; + out.y = a.y + b.y; + return out; + } + + /** + * !#zh 逐元素向量减法 + * @method subtract + * @typescript + * subtract (out: Out, a: Out, b: Out): Out + * @static + */ + static subtract (out: Out, a: Out, b: Out) { + out.x = a.x - b.x; + out.y = a.y - b.y; + return out; + } + + /** + * !#zh 逐元素向量乘法 + * @method multiply + * @typescript + * multiply (out: Out, a: Out, b: Out): Out + * @static + */ + static multiply (out: Out, a: Out, b: Out) { + out.x = a.x * b.x; + out.y = a.y * b.y; + return out; + } + + /** + * !#zh 逐元素向量除法 + * @method divide + * @typescript + * divide (out: Out, a: Out, b: Out): Out + * @static + */ + static divide (out: Out, a: Out, b: Out) { + out.x = a.x / b.x; + out.y = a.y / b.y; + return out; + } + + /** + * !#zh 逐元素向量向上取整 + * @method ceil + * @typescript + * ceil (out: Out, a: Out): Out + * @static + */ + static ceil (out: Out, a: Out) { + out.x = Math.ceil(a.x); + out.y = Math.ceil(a.y); + return out; + } + + /** + * !#zh 逐元素向量向下取整 + * @method floor + * @typescript + * floor (out: Out, a: Out): Out + * @static + */ + static floor (out: Out, a: Out) { + out.x = Math.floor(a.x); + out.y = Math.floor(a.y); + return out; + } + + /** + * !#zh 逐元素向量最小值 + * @method min + * @typescript + * min (out: Out, a: Out, b: Out): Out + * @static + */ + static min (out: Out, a: Out, b: Out) { + out.x = Math.min(a.x, b.x); + out.y = Math.min(a.y, b.y); + return out; + } + + + /** + * !#zh 逐元素向量最大值 + * @method max + * @typescript + * max (out: Out, a: Out, b: Out): Out + * @static + */ + static max (out: Out, a: Out, b: Out) { + out.x = Math.max(a.x, b.x); + out.y = Math.max(a.y, b.y); + return out; + } + + /** + * !#zh 逐元素向量四舍五入取整 + * @method round + * @typescript + * round (out: Out, a: Out): Out + * @static + */ + static round (out: Out, a: Out) { + out.x = Math.round(a.x); + out.y = Math.round(a.y); + return out; + } + + /** + * !#zh 向量标量乘法 + * @method multiplyScalar + * @typescript + * multiplyScalar (out: Out, a: Out, b: number): Out + * @static + */ + static multiplyScalar (out: Out, a: Out, b: number) { + out.x = a.x * b; + out.y = a.y * b; + return out; + } + + /** + * !#zh 逐元素向量乘加: A + B * scale + * @method scaleAndAdd + * @typescript + * scaleAndAdd (out: Out, a: Out, b: Out, scale: number): Out + * @static + */ + static scaleAndAdd (out: Out, a: Out, b: Out, scale: number) { + out.x = a.x + (b.x * scale); + out.y = a.y + (b.y * scale); + return out; + } + + /** + * !#zh 求两向量的欧氏距离 + * @method distance + * @typescript + * distance (a: Out, b: Out): number + * @static + */ + static distance (a: Out, b: Out) { + _x = b.x - a.x; + _y = b.y - a.y; + return Math.sqrt(_x * _x + _y * _y); + } + + /** + * !#zh 求两向量的欧氏距离平方 + * @method squaredDistance + * @typescript + * squaredDistance (a: Out, b: Out): number + * @static + */ + static squaredDistance (a: Out, b: Out) { + _x = b.x - a.x; + _y = b.y - a.y; + return _x * _x + _y * _y; + } + + /** + * !#zh 求向量长度 + * @method len + * @typescript + * len (a: Out): number + * @static + */ + static len (a: Out) { + _x = a.x; + _y = a.y; + return Math.sqrt(_x * _x + _y * _y); + } + + /** + * !#zh 求向量长度平方 + * @method lengthSqr + * @typescript + * lengthSqr (a: Out): number + * @static + */ + static lengthSqr (a: Out) { + _x = a.x; + _y = a.y; + return _x * _x + _y * _y; + } + + /** + * !#zh 逐元素向量取负 + * @method negate + * @typescript + * negate (out: Out, a: Out): Out + * @static + */ + static negate (out: Out, a: Out) { + out.x = -a.x; + out.y = -a.y; + return out; + } + + /** + * !#zh 逐元素向量取倒数,接近 0 时返回 Infinity + * @method inverse + * @typescript + * inverse (out: Out, a: Out): Out + * @static + */ + static inverse (out: Out, a: Out) { + out.x = 1.0 / a.x; + out.y = 1.0 / a.y; + return out; + } + + /** + * !#zh 逐元素向量取倒数,接近 0 时返回 0 + * @method inverseSafe + * @typescript + * inverseSafe (out: Out, a: Out): Out + * @static + */ + static inverseSafe (out: Out, a: Out) { + _x = a.x; + _y = a.y; + + if (Math.abs(_x) < EPSILON) { + out.x = 0; + } else { + out.x = 1.0 / _x; + } + + if (Math.abs(_y) < EPSILON) { + out.y = 0; + } else { + out.y = 1.0 / _y; + } + + return out; + } + + /** + * !#zh 归一化向量 + * @method normalize + * @typescript + * normalize (out: Out, a: Vec2Like): Out + * @static + */ + static normalize (out: Out, a: Vec2Like) { + _x = a.x; + _y = a.y; + let len = _x * _x + _y * _y; + if (len > 0) { + len = 1 / Math.sqrt(len); + out.x = _x * len; + out.y = _y * len; + } + return out; + } + + /** + * !#zh 向量点积(数量积) + * @method dot + * @typescript + * dot (a: Out, b: Out): number + * @static + */ + static dot (a: Out, b: Out) { + return a.x * b.x + a.y * b.y; + } + + /** + * !#zh 向量叉积(向量积),注意二维向量的叉积为与 Z 轴平行的三维向量 + * @method cross + * @typescript + * cross (out: Vec2, a: Out, b: Out): Vec2 + * @static + */ + static cross (out: Vec2, a: Out, b: Out) { + out.x = out.y = 0; + out.z = a.x * b.y - a.y * b.x; + return out; + } + + /** + * !#zh 逐元素向量线性插值: A + t * (B - A) + * @method lerp + * @typescript + * lerp (out: Out, a: Out, b: Out, t: number): Out + * @static + */ + static lerp (out: Out, a: Out, b: Out, t: number) { + _x = a.x; + _y = a.y; + out.x = _x + t * (b.x - _x); + out.y = _y + t * (b.y - _y); + return out; + } + + /** + * !#zh 生成一个在单位圆上均匀分布的随机向量 + * @method random + * @typescript + * random (out: Out, scale?: number): Out + * @static + */ + static random (out: Out, scale?: number) { + scale = scale || 1.0; + const r = random() * 2.0 * Math.PI; + out.x = Math.cos(r) * scale; + out.y = Math.sin(r) * scale; + return out; + } + + /** + * !#zh 向量与三维矩阵乘法,默认向量第三位为 1。 + * @method transformMat3 + * @typescript + * transformMat3 (out: Out, a: Out, mat: IMat3Like): Out + * @static + */ + static transformMat3 (out: Out, a: Out, mat: MatLike) { + _x = a.x; + _y = a.y; + let m = mat.m; + out.x = m[0] * _x + m[3] * _y + m[6]; + out.y = m[1] * _x + m[4] * _y + m[7]; + return out; + } + + /** + * !#zh 向量与四维矩阵乘法,默认向量第三位为 0,第四位为 1。 + * @method transformMat4 + * @typescript + * transformMat4 (out: Out, a: Out, mat: MatLike): Out + * @static + */ + static transformMat4 (out: Out, a: Out, mat: MatLike) { + _x = a.x; + _y = a.y; + let m = mat.m; + out.x = m[0] * _x + m[4] * _y + m[12]; + out.y = m[1] * _x + m[5] * _y + m[13]; + return out; + } + + /** + * !#zh 向量等价判断 + * @method strictEquals + * @typescript + * strictEquals (a: Out, b: Out): boolean + * @static + */ + static strictEquals (a: Out, b: Out) { + return a.x === b.x && a.y === b.y; + } + + /** + * !#zh 排除浮点数误差的向量近似等价判断 + * @method equals + * @typescript + * equals (a: Out, b: Out, epsilon?: number): boolean + * @static + */ + static equals (a: Out, b: Out, epsilon = EPSILON) { + return ( + Math.abs(a.x - b.x) <= + epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && + Math.abs(a.y - b.y) <= + epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) + ); + } + + /** + * !#zh 排除浮点数误差的向量近似等价判断 + * @method angle + * @typescript + * angle (a: Out, b: Out): number + * @static + */ + static angle (a: Out, b: Out) { + Vec2.normalize(v2_1, a); + Vec2.normalize(v2_2, b); + const cosine = Vec2.dot(v2_1, v2_2); + if (cosine > 1.0) { + return 0; + } + if (cosine < -1.0) { + return Math.PI; + } + return Math.acos(cosine); + } + + + + + + /** + * @property {Number} x + */ + x: number; + + /** + * @property {Number} y + */ + y: number; + + // compatible with vec3 + z: number = 0; + + /** + * !#en + * Constructor + * see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} + * @method constructor + * @param {Number} [x=0] + * @param {Number} [y=0] + */ + constructor (x: number | Vec2 = 0, y: number = 0) { + super(); + + if (x && typeof x === 'object') { + this.x = x.x || 0; + this.y = x.y || 0; + } else { + this.x = x as number || 0; + this.y = y || 0; + } + } + + /** + * !#en clone a Vec2 object + * !#zh 克隆一个 Vec2 对象 + * @method clone + * @return {Vec2} + */ + clone (): Vec2 { + return new Vec2(this.x, this.y); + } + + /** + * !#en Sets vector with another's value + * !#zh 设置向量值。 + * @method set + * @param {Vec2} newValue - !#en new value to set. !#zh 要设置的新值 + * @return {Vec2} returns this + * @chainable + */ + set (newValue: Vec2): this { + this.x = newValue.x; + this.y = newValue.y; + return this; + } + + /** + * !#en Check whether two vector equal + * !#zh 当前的向量是否与指定的向量相等。 + * @method equals + * @param {Vec2} other + * @return {Boolean} + */ + equals (other: Vec2): boolean { + return other && this.x === other.x && this.y === other.y; + } + + /** + * !#en Check whether two vector equal with some degree of variance. + * !#zh + * 近似判断两个点是否相等。
+ * 判断 2 个向量是否在指定数值的范围之内,如果在则返回 true,反之则返回 false。 + * @method fuzzyEquals + * @param {Vec2} other + * @param {Number} variance + * @return {Boolean} + */ + fuzzyEquals (other: Vec2, variance): boolean { + if (this.x - variance <= other.x && other.x <= this.x + variance) { + if (this.y - variance <= other.y && other.y <= this.y + variance) + return true; + } + return false; + } + + /** + * !#en Transform to string with vector informations + * !#zh 转换为方便阅读的字符串。 + * @method toString + * @return {string} + */ + toString (): string { + return "(" + + this.x.toFixed(2) + ", " + + this.y.toFixed(2) + ")" + ; + } + + /** + * !#en Calculate linear interpolation result between this vector and another one with given ratio + * !#zh 线性插值。 + * @method lerp + * @param {Vec2} to + * @param {Number} ratio - the interpolation coefficient + * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created + * @return {Vec2} + */ + lerp (to: Vec2, ratio: number, out?: Vec2): Vec2 { + out = out || new Vec2(); + var x = this.x; + var y = this.y; + out.x = x + (to.x - x) * ratio; + out.y = y + (to.y - y) * ratio; + return out; + } + + + /** + * !#en Adds this vector. + * !#zh 向量加法。 + * @method add + * @param {Vec2} vector + * @param {Vec2} [out] + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.add(cc.v2(5, 5));// return Vec2 {x: 15, y: 15}; + */ + add (vector: Vec2, out?: Vec2): Vec2 { + out = out || new Vec2(); + out.x = this.x + vector.x; + out.y = this.y + vector.y; + return out; + } + + /** + * !#en Adds this vector. If you want to save result to another vector, use add() instead. + * !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。 + * @method addSelf + * @param {Vec2} vector + * @return {Vec2} returns this + * @chainable + */ + addSelf (vector: Vec2): this { + this.x += vector.x; + this.y += vector.y; + return this; + } + + /** + * !#en Subtracts one vector from this. + * !#zh 向量减法。 + * @method subtract + * @param {Vec2} vector + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.subSelf(cc.v2(5, 5));// return Vec2 {x: 5, y: 5}; + */ + subtract (vector: Vec2): this { + this.x -= vector.x; + this.y -= vector.y; + return this; + } + + /** + * !#en Multiplies this by a number. + * !#zh 缩放当前向量。 + * @method multiplyScalar + * @param {number} num + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.multiply(5);// return Vec2 {x: 50, y: 50}; + */ + multiplyScalar (num: number): this { + this.x *= num; + this.y *= num; + return this; + } + + /** + * !#en Multiplies two vectors. + * !#zh 分量相乘。 + * @method multiply + * @param {Vec2} vector + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.multiply(cc.v2(5, 5));// return Vec2 {x: 50, y: 50}; + */ + multiply (vector: Vec2): this { + this.x *= vector.x; + this.y *= vector.y; + return this; + } + + /** + * !#en Divides by a number. + * !#zh 向量除法。 + * @method divide + * @param {number} num + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.divide(5); // return Vec2 {x: 2, y: 2}; + */ + divide (num: number): this { + this.x /= num; + this.y /= num; + return this; + } + + /** + * !#en Negates the components. + * !#zh 向量取反。 + * @method negate + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.negate(); // return Vec2 {x: -10, y: -10}; + */ + negate (): this { + this.x = -this.x; + this.y = -this.y; + return this; + } + + /** + * !#en Dot product + * !#zh 当前向量与指定向量进行点乘。 + * @method dot + * @param {Vec2} [vector] + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.dot(cc.v2(5, 5)); // return 100; + */ + dot (vector: Vec2): number { + return this.x * vector.x + this.y * vector.y; + } + + /** + * !#en Cross product + * !#zh 当前向量与指定向量进行叉乘。 + * @method cross + * @param {Vec2} [vector] + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.cross(cc.v2(5, 5)); // return 0; + */ + cross (vector: Vec2): number { + return this.x * vector.y - this.y * vector.x; + } + + /** + * !#en Returns the length of this vector. + * !#zh 返回该向量的长度。 + * @method len + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.len(); // return 14.142135623730951; + */ + len (): number { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + + /** + * !#en Returns the squared length of this vector. + * !#zh 返回该向量的长度平方。 + * @method lengthSqr + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.lengthSqr(); // return 200; + */ + lengthSqr (): number { + return this.x * this.x + this.y * this.y; + } + + /** + * !#en Make the length of this vector to 1. + * !#zh 向量归一化,让这个向量的长度为 1。 + * @method normalizeSelf + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.normalizeSelf(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; + */ + normalizeSelf (): Vec2 { + var magSqr = this.x * this.x + this.y * this.y; + if (magSqr === 1.0) + return this; + + if (magSqr === 0.0) { + return this; + } + + var invsqrt = 1.0 / Math.sqrt(magSqr); + this.x *= invsqrt; + this.y *= invsqrt; + + return this; + } + + /** + * !#en + * Returns this vector with a magnitude of 1.
+ *
+ * Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function. + * !#zh + * 返回归一化后的向量。
+ *
+ * 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。 + * @method normalize + * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created + * @return {Vec2} result + * var v = cc.v2(10, 10); + * v.normalize(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; + */ + normalize (out?: Vec2): Vec2 { + out = out || new Vec2(); + out.x = this.x; + out.y = this.y; + out.normalizeSelf(); + return out; + } + + /** + * !#en Get angle in radian between this and vector. + * !#zh 夹角的弧度。 + * @method angle + * @param {Vec2} vector + * @return {number} from 0 to Math.PI + */ + angle (vector: Vec2): number { + var magSqr1 = this.magSqr(); + var magSqr2 = vector.magSqr(); + + if (magSqr1 === 0 || magSqr2 === 0) { + console.warn("Can't get angle between zero vector"); + return 0.0; + } + + var dot = this.dot(vector); + var theta = dot / (Math.sqrt(magSqr1 * magSqr2)); + theta = mclampf(theta, -1.0, 1.0); + return Math.acos(theta); + } + + /** + * !#en Get angle in radian between this and vector with direction. + * !#zh 带方向的夹角的弧度。 + * @method signAngle + * @param {Vec2} vector + * @return {number} from -MathPI to Math.PI + */ + signAngle (vector: Vec2): number { + let angle = this.angle(vector); + return this.cross(vector) < 0 ? -angle : angle; + } + + /** + * !#en rotate + * !#zh 返回旋转给定弧度后的新向量。 + * @method rotate + * @param {number} radians + * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created + * @return {Vec2} the result + */ + rotate (radians: number, out?: Vec2): Vec2 { + out = out || new Vec2(); + out.x = this.x; + out.y = this.y; + return out.rotateSelf(radians); + } + + /** + * !#en rotate self + * !#zh 按指定弧度旋转向量。 + * @method rotateSelf + * @param {number} radians + * @return {Vec2} returns this + * @chainable + */ + rotateSelf (radians: number): Vec2 { + var sin = Math.sin(radians); + var cos = Math.cos(radians); + var x = this.x; + this.x = cos * x - sin * this.y; + this.y = sin * x + cos * this.y; + return this; + } + + /** + * !#en Calculates the projection of the current vector over the given vector. + * !#zh 返回当前向量在指定 vector 向量上的投影向量。 + * @method project + * @param {Vec2} vector + * @return {Vec2} + * @example + * var v1 = cc.v2(20, 20); + * var v2 = cc.v2(5, 5); + * v1.project(v2); // Vec2 {x: 20, y: 20}; + */ + project (vector: Vec2): Vec2 { + return vector.multiplyScalar(this.dot(vector) / vector.dot(vector)); + } + + + + /** + * Returns the maximum value in x, y. + * @method maxAxis + * @returns {number} + */ + maxAxis (): number { + return Math.max(this.x, this.y); + } +} + +const v2_1 = new Vec2(); +const v2_2 = new Vec2(); + + diff --git a/src/util/id-generater.js b/src/util/id-generater.js new file mode 100644 index 0000000..c08a3c0 --- /dev/null +++ b/src/util/id-generater.js @@ -0,0 +1,55 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +// ID generater for runtime + +var NonUuidMark = '.'; + +/* + * @param {string} [category] - You can specify a unique category to avoid id collision with other instance of IdGenerater + */ +function IdGenerater (category) { + // init with a random id to emphasize that the returns id should not be stored in persistence data + this.id = 0 | (Math.random() * 998); + + this.prefix = category ? (category + NonUuidMark) : ''; +} + +/* + * @method getNewId + * @return {string} + */ +IdGenerater.prototype.getNewId = function () { + return this.prefix + (++this.id); +}; + +/* + * The global id generater might have a conflict problem once every 365 days, + * if the game runs at 60 FPS and each frame 4760273 counts of new id are requested. + */ +IdGenerater.global = new IdGenerater('global'); + +module.exports = IdGenerater; diff --git a/src/util/js.js b/src/util/js.js new file mode 100644 index 0000000..3363184 --- /dev/null +++ b/src/util/js.js @@ -0,0 +1,996 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + 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. + ****************************************************************************/ + +const tempCIDGenerater = new (require('./id-generater'))('TmpCId.'); + + +function _getPropertyDescriptor (obj, name) { + while (obj) { + var pd = Object.getOwnPropertyDescriptor(obj, name); + if (pd) { + return pd; + } + obj = Object.getPrototypeOf(obj); + } + return null; +} + +function _copyprop(name, source, target) { + var pd = _getPropertyDescriptor(source, name); + Object.defineProperty(target, name, pd); +} + +/** + * !#en This module provides some JavaScript utilities. All members can be accessed with `cc.js`. + * !#zh 这个模块封装了 JavaScript 相关的一些实用函数,你可以通过 `cc.js` 来访问这个模块。 + * @submodule js + * @module js + */ +var js = { + + /** + * Check the obj whether is number or not + * If a number is created by using 'new Number(10086)', the typeof it will be "object"... + * Then you can use this function if you care about this case. + * @method isNumber + * @param {*} obj + * @returns {Boolean} + */ + isNumber: function(obj) { + return typeof obj === 'number' || obj instanceof Number; + }, + + /** + * Check the obj whether is string or not. + * If a string is created by using 'new String("blabla")', the typeof it will be "object"... + * Then you can use this function if you care about this case. + * @method isString + * @param {*} obj + * @returns {Boolean} + */ + isString: function(obj) { + return typeof obj === 'string' || obj instanceof String; + }, + + /** + * Copy all properties not defined in obj from arguments[1...n] + * @method addon + * @param {Object} obj object to extend its properties + * @param {Object} ...sourceObj source object to copy properties from + * @return {Object} the result obj + */ + addon: function (obj) { + 'use strict'; + obj = obj || {}; + for (var i = 1, length = arguments.length; i < length; i++) { + var source = arguments[i]; + if (source) { + if (typeof source !== 'object') { + cc.errorID(5402, source); + continue; + } + for ( var name in source) { + if ( !(name in obj) ) { + _copyprop( name, source, obj); + } + } + } + } + return obj; + }, + + /** + * copy all properties from arguments[1...n] to obj + * @method mixin + * @param {Object} obj + * @param {Object} ...sourceObj + * @return {Object} the result obj + */ + mixin: function (obj) { + 'use strict'; + obj = obj || {}; + for (var i = 1, length = arguments.length; i < length; i++) { + var source = arguments[i]; + if (source) { + if (typeof source !== 'object') { + cc.errorID(5403, source); + continue; + } + for ( var name in source) { + _copyprop( name, source, obj); + } + } + } + return obj; + }, + + /** + * Derive the class from the supplied base class. + * Both classes are just native javascript constructors, not created by cc.Class, so + * usually you will want to inherit using {{#crossLink "cc/Class:method"}}cc.Class {{/crossLink}} instead. + * @method extend + * @param {Function} cls + * @param {Function} base - the baseclass to inherit + * @return {Function} the result class + */ + extend: function (cls, base) { + if (CC_DEV) { + if (!base) { + cc.errorID(5404); + return; + } + if (!cls) { + cc.errorID(5405); + return; + } + if (Object.keys(cls.prototype).length > 0) { + cc.errorID(5406); + } + } + for (var p in base) if (base.hasOwnProperty(p)) cls[p] = base[p]; + cls.prototype = Object.create(base.prototype, { + constructor: { + value: cls, + writable: true, + configurable: true + } + }); + return cls; + }, + + /** + * Get super class + * @method getSuper + * @param {Function} ctor - the constructor of subclass + * @return {Function} + */ + getSuper (ctor) { + var proto = ctor.prototype; // binded function do not have prototype + var dunderProto = proto && Object.getPrototypeOf(proto); + return dunderProto && dunderProto.constructor; + }, + + /** + * Checks whether subclass is child of superclass or equals to superclass + * + * @method isChildClassOf + * @param {Function} subclass + * @param {Function} superclass + * @return {Boolean} + */ + isChildClassOf (subclass, superclass) { + if (subclass && superclass) { + if (typeof subclass !== 'function') { + return false; + } + if (typeof superclass !== 'function') { + if (CC_DEV) { + cc.warnID(3625, superclass); + } + return false; + } + if (subclass === superclass) { + return true; + } + for (;;) { + subclass = js.getSuper(subclass); + if (!subclass) { + return false; + } + if (subclass === superclass) { + return true; + } + } + } + return false; + }, + + /** + * Removes all enumerable properties from object + * @method clear + * @param {any} obj + */ + clear: function (obj) { + var keys = Object.keys(obj); + for (var i = 0; i < keys.length; i++) { + delete obj[keys[i]]; + } + }, + + /** + * Checks whether obj is an empty object + * @method isEmptyObject + * @param {any} obj + * @returns {Boolean} + */ + isEmptyObject: function (obj) { + for (var key in obj) { + return false; + } + return true; + }, + + /** + * Get property descriptor in object and all its ancestors + * @method getPropertyDescriptor + * @param {Object} obj + * @param {String} name + * @return {Object} + */ + getPropertyDescriptor: _getPropertyDescriptor +}; + + +var tmpValueDesc = { + value: undefined, + enumerable: false, + writable: false, + configurable: true +}; + +/** + * Define value, just help to call Object.defineProperty.
+ * The configurable will be true. + * @method value + * @param {Object} obj + * @param {String} prop + * @param {any} value + * @param {Boolean} [writable=false] + * @param {Boolean} [enumerable=false] + */ +js.value = function (obj, prop, value, writable, enumerable) { + tmpValueDesc.value = value; + tmpValueDesc.writable = writable; + tmpValueDesc.enumerable = enumerable; + Object.defineProperty(obj, prop, tmpValueDesc); + tmpValueDesc.value = undefined; +}; + +var tmpGetSetDesc = { + get: null, + set: null, + enumerable: false, +}; + +/** + * Define get set accessor, just help to call Object.defineProperty(...) + * @method getset + * @param {Object} obj + * @param {String} prop + * @param {Function} getter + * @param {Function} [setter=null] + * @param {Boolean} [enumerable=false] + * @param {Boolean} [configurable=false] + */ +js.getset = function (obj, prop, getter, setter, enumerable, configurable) { + if (typeof setter !== 'function') { + enumerable = setter; + setter = undefined; + } + tmpGetSetDesc.get = getter; + tmpGetSetDesc.set = setter; + tmpGetSetDesc.enumerable = enumerable; + tmpGetSetDesc.configurable = configurable; + Object.defineProperty(obj, prop, tmpGetSetDesc); + tmpGetSetDesc.get = null; + tmpGetSetDesc.set = null; +}; + +var tmpGetDesc = { + get: null, + enumerable: false, + configurable: false +}; + +/** + * Define get accessor, just help to call Object.defineProperty(...) + * @method get + * @param {Object} obj + * @param {String} prop + * @param {Function} getter + * @param {Boolean} [enumerable=false] + * @param {Boolean} [configurable=false] + */ +js.get = function (obj, prop, getter, enumerable, configurable) { + tmpGetDesc.get = getter; + tmpGetDesc.enumerable = enumerable; + tmpGetDesc.configurable = configurable; + Object.defineProperty(obj, prop, tmpGetDesc); + tmpGetDesc.get = null; +}; + +var tmpSetDesc = { + set: null, + enumerable: false, + configurable: false +}; + +/** + * Define set accessor, just help to call Object.defineProperty(...) + * @method set + * @param {Object} obj + * @param {String} prop + * @param {Function} setter + * @param {Boolean} [enumerable=false] + * @param {Boolean} [configurable=false] + */ +js.set = function (obj, prop, setter, enumerable, configurable) { + tmpSetDesc.set = setter; + tmpSetDesc.enumerable = enumerable; + tmpSetDesc.configurable = configurable; + Object.defineProperty(obj, prop, tmpSetDesc); + tmpSetDesc.set = null; +}; + +/** + * Get class name of the object, if object is just a {} (and which class named 'Object'), it will return "". + * (modified from the code from this stackoverflow post) + * @method getClassName + * @param {Object|Function} objOrCtor - instance or constructor + * @return {String} + */ +js.getClassName = function (objOrCtor) { + if (typeof objOrCtor === 'function') { + var prototype = objOrCtor.prototype; + if (prototype && prototype.hasOwnProperty('__classname__') && prototype.__classname__) { + return prototype.__classname__; + } + var retval = ''; + // for browsers which have name property in the constructor of the object, such as chrome + if (objOrCtor.name) { + retval = objOrCtor.name; + } + if (objOrCtor.toString) { + var arr, str = objOrCtor.toString(); + if (str.charAt(0) === '[') { + // str is "[object objectClass]" + arr = str.match(/\[\w+\s*(\w+)\]/); + } + else { + // str is function objectClass () {} for IE Firefox + arr = str.match(/function\s*(\w+)/); + } + if (arr && arr.length === 2) { + retval = arr[1]; + } + } + return retval !== 'Object' ? retval : ''; + } + else if (objOrCtor && objOrCtor.constructor) { + return js.getClassName(objOrCtor.constructor); + } + return ''; +}; + +function isTempClassId (id) { + return typeof id !== 'string' || id.startsWith(tempCIDGenerater.prefix); +} + +// id 注册 +(function () { + var _idToClass = {}; + var _nameToClass = {}; + + function setup (key, publicName, table) { + js.getset(js, publicName, + function () { + return Object.assign({}, table); + }, + function (value) { + js.clear(table); + Object.assign(table, value); + } + ); + return function (id, constructor) { + // deregister old + if (constructor.prototype.hasOwnProperty(key)) { + delete table[constructor.prototype[key]]; + } + js.value(constructor.prototype, key, id); + // register class + if (id) { + var registered = table[id]; + if (registered && registered !== constructor) { + var error = 'A Class already exists with the same ' + key + ' : "' + id + '".'; + if (CC_TEST) { + error += ' (This may be caused by error of unit test.) \ +If you dont need serialization, you can set class id to "". You can also call \ +cc.js.unregisterClass to remove the id of unused class'; + } + cc.error(error); + } + else { + table[id] = constructor; + } + //if (id === "") { + // console.trace("", table === _nameToClass); + //} + } + }; + } + + /** + * Register the class by specified id, if its classname is not defined, the class name will also be set. + * @method _setClassId + * @param {String} classId + * @param {Function} constructor + * @private + */ + /** + * !#en All classes registered in the engine, indexed by ID. + * !#zh 引擎中已注册的所有类型,通过 ID 进行索引。 + * @property _registeredClassIds + * @example + * // save all registered classes before loading scripts + * let builtinClassIds = cc.js._registeredClassIds; + * let builtinClassNames = cc.js._registeredClassNames; + * // load some scripts that contain CCClass + * ... + * // clear all loaded classes + * cc.js._registeredClassIds = builtinClassIds; + * cc.js._registeredClassNames = builtinClassNames; + */ + js._setClassId = setup('__cid__', '_registeredClassIds', _idToClass); + + /** + * !#en All classes registered in the engine, indexed by name. + * !#zh 引擎中已注册的所有类型,通过名称进行索引。 + * @property _registeredClassNames + * @example + * // save all registered classes before loading scripts + * let builtinClassIds = cc.js._registeredClassIds; + * let builtinClassNames = cc.js._registeredClassNames; + * // load some scripts that contain CCClass + * ... + * // clear all loaded classes + * cc.js._registeredClassIds = builtinClassIds; + * cc.js._registeredClassNames = builtinClassNames; + */ + var doSetClassName = setup('__classname__', '_registeredClassNames', _nameToClass); + + /** + * Register the class by specified name manually + * @method setClassName + * @param {String} className + * @param {Function} constructor + */ + js.setClassName = function (className, constructor) { + doSetClassName(className, constructor); + // auto set class id + if (!constructor.prototype.hasOwnProperty('__cid__')) { + var id = className || tempCIDGenerater.getNewId(); + if (id) { + js._setClassId(id, constructor); + } + } + }; + + /** + * Unregister a class from fireball. + * + * If you dont need a registered class anymore, you should unregister the class so that Fireball will not keep its reference anymore. + * Please note that its still your responsibility to free other references to the class. + * + * @method unregisterClass + * @param {Function} ...constructor - the class you will want to unregister, any number of classes can be added + */ + js.unregisterClass = function () { + for (var i = 0; i < arguments.length; i++) { + var p = arguments[i].prototype; + var classId = p.__cid__; + if (classId) { + delete _idToClass[classId]; + } + var classname = p.__classname__; + if (classname) { + delete _nameToClass[classname]; + } + } + }; + + /** + * Get the registered class by id + * @method _getClassById + * @param {String} classId + * @return {Function} constructor + * @private + */ + js._getClassById = function (classId) { + return _idToClass[classId]; + }; + + /** + * Get the registered class by name + * @method getClassByName + * @param {String} classname + * @return {Function} constructor + */ + js.getClassByName = function (classname) { + return _nameToClass[classname]; + }; + + /** + * Get class id of the object + * @method _getClassId + * @param {Object|Function} obj - instance or constructor + * @param {Boolean} [allowTempId=true] - can return temp id in editor + * @return {String} + * @private + */ + js._getClassId = function (obj, allowTempId) { + allowTempId = (typeof allowTempId !== 'undefined' ? allowTempId: true); + + var res; + if (typeof obj === 'function' && obj.prototype.hasOwnProperty('__cid__')) { + res = obj.prototype.__cid__; + if (!allowTempId && (CC_DEV || CC_EDITOR) && isTempClassId(res)) { + return ''; + } + return res; + } + if (obj && obj.constructor) { + var prototype = obj.constructor.prototype; + if (prototype && prototype.hasOwnProperty('__cid__')) { + res = obj.__cid__; + if (!allowTempId && (CC_DEV || CC_EDITOR) && isTempClassId(res)) { + return ''; + } + return res; + } + } + return ''; + }; +})(); + +/** + * Defines a polyfill field for deprecated codes. + * @method obsolete + * @param {any} obj - YourObject or YourClass.prototype + * @param {String} obsoleted - "OldParam" or "YourClass.OldParam" + * @param {String} newExpr - "NewParam" or "YourClass.NewParam" + * @param {Boolean} [writable=false] + */ +js.obsolete = function (obj, obsoleted, newExpr, writable) { + var extractPropName = /([^.]+)$/; + var oldProp = extractPropName.exec(obsoleted)[0]; + var newProp = extractPropName.exec(newExpr)[0]; + function get () { + if (CC_DEV) { + cc.warnID(1400, obsoleted, newExpr); + } + return this[newProp]; + } + if (writable) { + js.getset(obj, oldProp, + get, + function (value) { + if (CC_DEV) { + cc.warnID(1400, obsoleted, newExpr); + } + this[newProp] = value; + } + ); + } + else { + js.get(obj, oldProp, get); + } +}; + +/** + * Defines all polyfill fields for obsoleted codes corresponding to the enumerable properties of props. + * @method obsoletes + * @param {any} obj - YourObject or YourClass.prototype + * @param {any} objName - "YourObject" or "YourClass" + * @param {Object} props + * @param {Boolean} [writable=false] + */ +js.obsoletes = function (obj, objName, props, writable) { + for (var obsoleted in props) { + var newName = props[obsoleted]; + js.obsolete(obj, objName + '.' + obsoleted, newName, writable); + } +}; + +var REGEXP_NUM_OR_STR = /(%d)|(%s)/; +var REGEXP_STR = /%s/; + +/** + * A string tool to construct a string with format string. + * @method formatStr + * @param {String|any} msg - A JavaScript string containing zero or more substitution strings (%s). + * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. + * @returns {String} + * @example + * cc.js.formatStr("a: %s, b: %s", a, b); + * cc.js.formatStr(a, b, c); + */ +js.formatStr = function () { + var argLen = arguments.length; + if (argLen === 0) { + return ''; + } + var msg = arguments[0]; + if (argLen === 1) { + return '' + msg; + } + + var hasSubstitution = typeof msg === 'string' && REGEXP_NUM_OR_STR.test(msg); + if (hasSubstitution) { + for (let i = 1; i < argLen; ++i) { + var arg = arguments[i]; + var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR; + if (regExpToTest.test(msg)) { + const notReplaceFunction = '' + arg; + msg = msg.replace(regExpToTest, notReplaceFunction); + } + else + msg += ' ' + arg; + } + } + else { + for (let i = 1; i < argLen; ++i) { + msg += ' ' + arguments[i]; + } + } + return msg; +}; + +// see https://github.com/petkaantonov/bluebird/issues/1389 +js.shiftArguments = function () { + var len = arguments.length - 1; + var args = new Array(len); + for(var i = 0; i < len; ++i) { + args[i] = arguments[i + 1]; + } + return args; +}; + +/** + * !#en + * A simple wrapper of `Object.create(null)` which ensures the return object have no prototype (and thus no inherited members). So we can skip `hasOwnProperty` calls on property lookups. It is a worthwhile optimization than the `{}` literal when `hasOwnProperty` calls are necessary. + * !#zh + * 该方法是对 `Object.create(null)` 的简单封装。`Object.create(null)` 用于创建无 prototype (也就无继承)的空对象。这样我们在该对象上查找属性时,就不用进行 `hasOwnProperty` 判断。在需要频繁判断 `hasOwnProperty` 时,使用这个方法性能会比 `{}` 更高。 + * + * @method createMap + * @param {Boolean} [forceDictMode=false] - Apply the delete operator to newly created map object. This causes V8 to put the object in "dictionary mode" and disables creation of hidden classes which are very expensive for objects that are constantly changing shape. + * @return {Object} + */ +js.createMap = function (forceDictMode) { + var map = Object.create(null); + if (forceDictMode) { + const INVALID_IDENTIFIER_1 = '.'; + const INVALID_IDENTIFIER_2 = '/'; + map[INVALID_IDENTIFIER_1] = true; + map[INVALID_IDENTIFIER_2] = true; + delete map[INVALID_IDENTIFIER_1]; + delete map[INVALID_IDENTIFIER_2]; + } + return map; +}; + +/** + * @class array + * @static + */ + +/** + * Removes the array item at the specified index. + * @method removeAt + * @param {any[]} array + * @param {Number} index + */ +function removeAt (array, index) { + array.splice(index, 1); +} + +/** + * Removes the array item at the specified index. + * It's faster but the order of the array will be changed. + * @method fastRemoveAt + * @param {any[]} array + * @param {Number} index + */ +function fastRemoveAt (array, index) { + var length = array.length; + if (index < 0 || index >= length) { + return; + } + array[index] = array[length - 1]; + array.length = length - 1; +} + +/** + * Removes the first occurrence of a specific object from the array. + * @method remove + * @param {any[]} array + * @param {any} value + * @return {Boolean} + */ +function remove (array, value) { + var index = array.indexOf(value); + if (index >= 0) { + removeAt(array, index); + return true; + } + else { + return false; + } +} + +/** + * Removes the first occurrence of a specific object from the array. + * It's faster but the order of the array will be changed. + * @method fastRemove + * @param {any[]} array + * @param {Number} value + */ +function fastRemove (array, value) { + var index = array.indexOf(value); + if (index >= 0) { + array[index] = array[array.length - 1]; + --array.length; + } +} + +/** + * Verify array's Type + * @method verifyType + * @param {array} array + * @param {Function} type + * @return {Boolean} + */ +function verifyType (array, type) { + if (array && array.length > 0) { + for (var i = 0; i < array.length; i++) { + if (!(array[i] instanceof type)) { + cc.logID(1300); + return false; + } + } + } + return true; +} + +/** + * Removes from array all values in minusArr. For each Value in minusArr, the first matching instance in array will be removed. + * @method removeArray + * @param {Array} array Source Array + * @param {Array} minusArr minus Array + */ +function removeArray (array, minusArr) { + for (var i = 0, l = minusArr.length; i < l; i++) { + remove(array, minusArr[i]); + } +} + +/** + * Inserts some objects at index + * @method appendObjectsAt + * @param {Array} array + * @param {Array} addObjs + * @param {Number} index + * @return {Array} + */ +function appendObjectsAt (array, addObjs, index) { + array.splice.apply(array, [index, 0].concat(addObjs)); + return array; +} + +/** + * Determines whether the array contains a specific value. + * @method contains + * @param {any[]} array + * @param {any} value + * @return {Boolean} + */ +function contains (array, value) { + return array.indexOf(value) >= 0; +} + +/** + * Copy an array's item to a new array (its performance is better than Array.slice) + * @method copy + * @param {Array} array + * @return {Array} + */ +function copy (array) { + var i, len = array.length, arr_clone = new Array(len); + for (i = 0; i < len; i += 1) + arr_clone[i] = array[i]; + return arr_clone; +} + +js.array = { + remove, + fastRemove, + removeAt, + fastRemoveAt, + contains, + verifyType, + removeArray, + appendObjectsAt, + copy, + MutableForwardIterator: require('../utils/mutable-forward-iterator') +}; + +// OBJECT POOL + +/** + * !#en + * A fixed-length object pool designed for general type.
+ * The implementation of this object pool is very simple, + * it can helps you to improve your game performance for objects which need frequent release and recreate operations
+ * !#zh + * 长度固定的对象缓存池,可以用来缓存各种对象类型。
+ * 这个对象池的实现非常精简,它可以帮助您提高游戏性能,适用于优化对象的反复创建和销毁。 + * @class Pool + * @example + * + *Example 1: + * + *function Details () { + * this.uuidList = []; + *}; + *Details.prototype.reset = function () { + * this.uuidList.length = 0; + *}; + *Details.pool = new js.Pool(function (obj) { + * obj.reset(); + *}, 5); + *Details.pool.get = function () { + * return this._get() || new Details(); + *}; + * + *var detail = Details.pool.get(); + *... + *Details.pool.put(detail); + * + *Example 2: + * + *function Details (buffer) { + * this.uuidList = buffer; + *}; + *... + *Details.pool.get = function (buffer) { + * var cached = this._get(); + * if (cached) { + * cached.uuidList = buffer; + * return cached; + * } + * else { + * return new Details(buffer); + * } + *}; + * + *var detail = Details.pool.get( [] ); + *... + */ +/** + * !#en + * Constructor for creating an object pool for the specific object type. + * You can pass a callback argument for process the cleanup logic when the object is recycled. + * !#zh + * 使用构造函数来创建一个指定对象类型的对象池,您可以传递一个回调函数,用于处理对象回收时的清理逻辑。 + * @method constructor + * @param {Function} [cleanupFunc] - the callback method used to process the cleanup logic when the object is recycled. + * @param {Object} cleanupFunc.obj + * @param {Number} size - initializes the length of the array + * @typescript + * constructor(cleanupFunc: (obj: any) => void, size: number) + * constructor(size: number) + */ +function Pool (cleanupFunc, size) { + if (size === undefined) { + size = cleanupFunc; + cleanupFunc = null; + } + this.get = null; + this.count = 0; + this._pool = new Array(size); + this._cleanup = cleanupFunc; +} + +/** + * !#en + * Get and initialize an object from pool. This method defaults to null and requires the user to implement it. + * !#zh + * 获取并初始化对象池中的对象。这个方法默认为空,需要用户自己实现。 + * @method get + * @param {any} ...params - parameters to used to initialize the object + * @returns {Object} + */ + +/** + * !#en + * The current number of available objects, the default is 0, it will gradually increase with the recycle of the object, + * the maximum will not exceed the size specified when the constructor is called. + * !#zh + * 当前可用对象数量,一开始默认是 0,随着对象的回收会逐渐增大,最大不会超过调用构造函数时指定的 size。 + * @property {Number} count + * @default 0 + */ + +/** + * !#en + * Get an object from pool, if no available object in the pool, null will be returned. + * !#zh + * 获取对象池中的对象,如果对象池没有可用对象,则返回空。 + * @method _get + * @returns {Object|null} + */ +Pool.prototype._get = function () { + if (this.count > 0) { + --this.count; + var cache = this._pool[this.count]; + this._pool[this.count] = null; + return cache; + } + return null; +}; + +/** + * !#en Put an object into the pool. + * !#zh 向对象池返还一个不再需要的对象。 + * @method put + */ +Pool.prototype.put = function (obj) { + var pool = this._pool; + if (this.count < pool.length) { + if (this._cleanup && this._cleanup(obj) === false) { + return; + } + pool[this.count] = obj; + ++this.count; + } +}; + +/** + * !#en Resize the pool. + * !#zh 设置对象池容量。 + * @method resize + */ +Pool.prototype.resize = function (length) { + if (length >= 0) { + this._pool.length = length; + if (this.count > length) { + this.count = length; + } + } +}; + +js.Pool = Pool; + +// + +cc.js = js; + +module.exports = js; + +// fix submodule pollute ... +/** + * @submodule cc + */