Merge branch '3d-stable' of https://github.com/cocos-creator/engine into 3d

This commit is contained in:
jerrywwl
2019-03-20 14:25:48 +08:00
73 changed files with 3516 additions and 3316 deletions
+2
View File
@@ -44,6 +44,8 @@ declare const cc : {
[x: string]: any;
};
declare type CompareFunction<T> = (a: T, b: T) => number;
declare type RecursivePartial<T> = {
[P in keyof T]?:
T[P] extends Array<infer U> ? Array<RecursivePartial<U>> :
+7 -5
View File
@@ -10,12 +10,9 @@ export interface IPropertyInfo {
type: number; // auto-extracted if not specified
value?: number[] | string;
displayName?: string;
sampler?: IGFXSamplerInfo;
sampler?: number[];
}
export interface IPassInfo {
program: string;
// effect-writer part
switch?: string;
export interface IPassStates {
priority?: number;
primitive?: GFXPrimitiveMode;
stage?: RenderPassStage;
@@ -23,6 +20,10 @@ export interface IPassInfo {
depthStencilState?: GFXDepthStencilState;
blendState?: GFXBlendState;
dynamics?: GFXDynamicState[];
}
export interface IPassInfo extends IPassStates {
program: string; // auto-generated
switch?: string;
properties?: Record<string, IPropertyInfo>;
}
export interface ITechniqueInfo {
@@ -66,6 +67,7 @@ export interface IBuiltinInfo {
}
export interface IShaderInfo {
name: string;
hash: number;
glsl3: { vert: string, frag: string };
glsl1: { vert: string, frag: string };
builtins: { globals: IBuiltinInfo, locals: IBuiltinInfo };
+24 -16
View File
@@ -37,6 +37,7 @@ import { EffectAsset } from './effect-asset';
export interface IMaterialInfo {
technique?: number;
defines?: IDefineMap | IDefineMap[];
states?: PassOverrides | PassOverrides[];
effectAsset?: EffectAsset | null;
effectName?: string;
}
@@ -65,6 +66,8 @@ export class Material extends Asset {
@property
protected _defines: IDefineMap[] = [];
@property
protected _states: PassOverrides[] = [];
@property
protected _props: Array<Record<string, any>> = [];
protected _passes: Pass[] = [];
@@ -95,27 +98,20 @@ export class Material extends Asset {
if (info.technique) { this._techIdx = info.technique; }
if (info.effectAsset) { this._effectAsset = info.effectAsset; }
else if (info.effectName) { this._effectAsset = EffectAsset.get(info.effectName); }
if (info.defines) {
const cur = this._defines;
let patch = info.defines;
if (!Array.isArray(patch) && this._effectAsset) { // fill all the passes if not specified
const len = Effect.getPassesInfo(this._effectAsset, this._techIdx).length;
patch = Array(len).fill(info.defines);
}
for (let i = 0; i < patch.length; i++) {
Object.assign(cur[i] || (cur[i] = {}), patch[i]);
}
}
if (info.defines) { this._prepareInfo(info.defines, this._defines); }
if (info.states) { this._prepareInfo(info.states, this._states); }
this._update();
}
public destroy () {
if (!this._effectAsset) { return; }
if (this._passes) {
for (const pass of this._passes) {
pass.destroy();
}
this._passes.length = 0;
}
this._effectAsset = null;
}
/**
@@ -177,7 +173,9 @@ export class Material extends Asset {
Object.assign(this._props[i], mat._props[i]);
}
Object.assign(this._defines, mat._defines);
this._update(mat._effectAsset);
Object.assign(this._states, mat._states);
this._effectAsset = mat._effectAsset;
this._update();
}
public overridePipelineStates (overrides: PassOverrides, passIdx?: number) {
@@ -197,14 +195,24 @@ export class Material extends Asset {
this._update();
}
protected _update (asset: EffectAsset | null = this._effectAsset, keepProps: boolean = true) {
// get effect asset
this._effectAsset = asset;
asset = asset || builtinResMgr.get<Material>('default-material').effectAsset!;
protected _prepareInfo (patch: object | object[], cur: object[]) {
if (!Array.isArray(patch)) { // fill all the passes if not specified
const len = this._effectAsset ? Effect.getPassesInfo(this._effectAsset, this._techIdx).length : 1;
patch = Array(len).fill(patch);
}
for (let i = 0; i < (patch as object[]).length; i++) {
Object.assign(cur[i] || (cur[i] = {}), patch[i]);
}
}
protected _update (keepProps: boolean = true) {
const asset = this._effectAsset;
if (!asset) { this._passes = builtinResMgr.get<Material>('default-material')._passes.slice(); return; }
// create passes
this._passes = Effect.parseEffect(asset, {
techIdx: this._techIdx,
defines: this._defines,
states: this._states,
});
// handle property values
this._props.length = this._passes.length;
+53 -19
View File
File diff suppressed because one or more lines are too long
+12 -3
View File
@@ -4,7 +4,6 @@ import { ImageAsset } from '../../assets/image-asset';
import { Texture2D } from '../../assets/texture-2d';
import { Rect } from '../../core/value-types';
import { GFXDevice } from '../../gfx/device';
import { EffectAsset } from '../assets/effect-asset';
import { TextureCube } from '../assets/texture-cube';
import effects from './effects';
@@ -122,10 +121,18 @@ class BuiltinResMgr {
// builtin effects
effects.forEach((e: any) => {
const effect = Object.assign(new EffectAsset(), e);
const effect = Object.assign(new cc.EffectAsset(), e);
effect.onLoaded();
});
// tonemap material
const smaaMtl = new cc.Material();
smaaMtl._uuid = 'smaa-material';
smaaMtl.initialize({
effectName: 'builtin-smaa',
});
resources[smaaMtl._uuid] = smaaMtl;
// tonemap material
const tonemapMtl = new cc.Material();
tonemapMtl._uuid = 'tonemap-material';
@@ -146,8 +153,10 @@ class BuiltinResMgr {
const defaultMtl = new cc.Material();
defaultMtl._uuid = 'default-material';
defaultMtl.initialize({
effectName: 'builtin-standard',
effectName: 'builtin-unlit',
defines: { USE_COLOR: true },
});
defaultMtl.setProperty('color', cc.color('#ff00ff'));
resources[defaultMtl._uuid] = defaultMtl;
// sprite material
@@ -64,6 +64,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
this.angularDamping = this._angularDamping;
this.material = this._material;
this.useGravity = this._useGravity;
this.velocity = this._velocity;
}
// if (this.sharedBody) {
// this.sharedBody.body.wakeUp();
-165
View File
@@ -1,165 +0,0 @@
import { vec3, mat3 } from '../../core/vmath';
let _v3_tmp = vec3.create();
let _v3_tmp2 = vec3.create();
/**
* @access public
*/
class box {
constructor(px, py, pz, w, h, l, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
this.center = vec3.create(px, py, pz);
this.halfExtents = vec3.create(w, h, l);
this.orientation = mat3.create(ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
}
/**
* create a new box
*
* @return {plane}
*/
static create() {
return new box(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1);
}
/**
* create a new box
*
* @param {Number} px X coordinates for box's original point
* @param {Number} py Y coordinates for box's original point
* @param {Number} pz Z coordinates for box's original point
* @param {Number} w the half of box width
* @param {Number} h the half of box height
* @param {Number} l the half of box length
* @param {Number} ox_1 the orientation vector coordinates
* @param {Number} ox_2 the orientation vector coordinates
* @param {Number} ox_3 the orientation vector coordinates
* @param {Number} oy_1 the orientation vector coordinates
* @param {Number} oy_2 the orientation vector coordinates
* @param {Number} oy_3 the orientation vector coordinates
* @param {Number} oz_1 the orientation vector coordinates
* @param {Number} oz_2 the orientation vector coordinates
* @param {Number} oz_3 the orientation vector coordinates
* @return {box}
*/
static new(px, py, pz, w, h, l, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
return new box(px, py, pz, w, h, l, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
}
/**
* create a new axis-aligned box from two corner points
*
* @param {vec3} minPos lower corner position of the box
* @param {vec3} maxPos upper corner position of the box
* @return {box}
*/
static fromPoints(minPos, maxPos) {
vec3.scale(_v3_tmp, vec3.add(_v3_tmp, minPos, maxPos), 0.5);
vec3.scale(_v3_tmp2, vec3.sub(_v3_tmp2, maxPos, minPos), 0.5);
return new box(_v3_tmp.x, _v3_tmp.y, _v3_tmp.z,
_v3_tmp2.x, _v3_tmp2.y, _v3_tmp2.z,
1, 0, 0, 0, 1, 0, 0, 0, 1);
}
/**
* clone a new box
*
* @param {box} a the source box
* @return {box}
*/
static clone(a) {
return new box(a.center.x, a.center.y, a.center.z,
a.halfExtents.x, a.halfExtents.y, a.halfExtents.z,
a.orientation.m00, a.orientation.m01, a.orientation.m02,
a.orientation.m03, a.orientation.m04, a.orientation.m05,
a.orientation.m06, a.orientation.m07, a.orientation.m08);
}
/**
* copy the values from one box to another
*
* @param {box} out the receiving box
* @param {box} a the source box
* @return {box}
*/
static copy(out, a) {
out.center = a.center;
out.halfExtents = a.halfExtents;
out.orientation = a.orientation;
return out;
}
/**
* Set the components of a box to the given values
*
* @param {box} out the receiving box
* @param {Number} px X coordinates for box's original point
* @param {Number} py Y coordinates for box's original point
* @param {Number} pz Z coordinates for box's original point
* @param {Number} w the half of box width
* @param {Number} h the half of box height
* @param {Number} l the half of box length
* @param {Number} ox_1 the orientation vector coordinates
* @param {Number} ox_2 the orientation vector coordinates
* @param {Number} ox_3 the orientation vector coordinates
* @param {Number} oy_1 the orientation vector coordinates
* @param {Number} oy_2 the orientation vector coordinates
* @param {Number} oy_3 the orientation vector coordinates
* @param {Number} oz_1 the orientation vector coordinates
* @param {Number} oz_2 the orientation vector coordinates
* @param {Number} oz_3 the orientation vector coordinates
* @returns {box} out
* @function
*/
static set(out, px, py, pz, w, h, l, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
vec3.set(out.center, px, py, pz);
vec3.set(out.halfExtents, w, h, l);
mat3.set(out.orientation, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
return out;
}
/**
* Get the bounding points of this shape
* @param {vec3} minPos
* @param {vec3} maxPos
*/
getBoundary(minPos, maxPos) {
vec3.sub(minPos, this.center, this.halfExtents);
vec3.add(maxPos, this.center, this.halfExtents);
}
/**
* Translate this shape and apply the effect to a target shape
* @param {vec3} pos the translation factor
* @param {box?} out the target shape
*/
translate(pos, out) {
if (!out) out = this;
vec3.add(out.center, this.center, pos);
}
/**
* Rotate this shape and apply the effect to a target shape
* @param {quat} rot the rotation factor
* @param {box?} out the target shape
*/
rotate(rot, out) {
if (!out) out = this;
// parent box doesn't contain rotations for now
mat3.fromQuat(out.orientation, rot);
}
/**
* Scale this shape and apply the effect to a target shape
* @param {vec3} scale the scaling factor
* @param {box?} out the target shape
*/
scale(scale, out) {
if (!out) out = this;
vec3.mul(out.halfExtents, this.halfExtents, scale);
}
}
export default box;
+149
View File
@@ -0,0 +1,149 @@
import { mat3, quat, vec3 } from '../../core/vmath';
const _v3_tmp = vec3.create();
const _v3_tmp2 = vec3.create();
export default class box {
/**
* create a new box
*/
public static create () {
return new box(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1);
}
/**
* create a new axis-aligned box from two corner points
*
* @param minPos lower corner position of the box
* @param maxPos upper corner position of the box
* @return
*/
public static fromPoints (minPos: vec3, maxPos: vec3) {
vec3.scale(_v3_tmp, vec3.add(_v3_tmp, minPos, maxPos), 0.5);
vec3.scale(_v3_tmp2, vec3.sub(_v3_tmp2, maxPos, minPos), 0.5);
return new box(_v3_tmp.x, _v3_tmp.y, _v3_tmp.z,
_v3_tmp2.x, _v3_tmp2.y, _v3_tmp2.z,
1, 0, 0, 0, 1, 0, 0, 0, 1);
}
/**
* clone a new box
*
* @param a the source box
* @return
*/
public static clone (a: box) {
return new box(a.center.x, a.center.y, a.center.z,
a.halfExtents.x, a.halfExtents.y, a.halfExtents.z,
a.orientation.m00, a.orientation.m01, a.orientation.m02,
a.orientation.m03, a.orientation.m04, a.orientation.m05,
a.orientation.m06, a.orientation.m07, a.orientation.m08);
}
/**
* copy the values from one box to another
*
* @param out the receiving box
* @param a the source box
* @return
*/
public static copy (out: box, a: box) {
out.center = a.center;
out.halfExtents = a.halfExtents;
out.orientation = a.orientation;
return out;
}
/**
* Set the components of a box to the given values
*
* @param {box} out the receiving box
* @param px X coordinates for box's original point
* @param py Y coordinates for box's original point
* @param pz Z coordinates for box's original point
* @param w the half of box width
* @param h the half of box height
* @param l the half of box length
* @param ox_1 the orientation vector coordinates
* @param ox_2 the orientation vector coordinates
* @param ox_3 the orientation vector coordinates
* @param oy_1 the orientation vector coordinates
* @param oy_2 the orientation vector coordinates
* @param oy_3 the orientation vector coordinates
* @param oz_1 the orientation vector coordinates
* @param oz_2 the orientation vector coordinates
* @param oz_3 the orientation vector coordinates
* @returns out
* @function
*/
public static set (
out: box,
px: number, py: number, pz: number,
w: number, h: number, l: number,
ox_1: number, ox_2: number, ox_3: number,
oy_1: number, oy_2: number, oy_3: number,
oz_1: number, oz_2: number, oz_3: number) {
vec3.set(out.center, px, py, pz);
vec3.set(out.halfExtents, w, h, l);
mat3.set(out.orientation, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
return out;
}
public center: vec3;
public halfExtents: vec3;
public orientation: mat3;
constructor (
px: number, py: number, pz: number,
w: number, h: number, l: number,
ox_1: number, ox_2: number, ox_3: number,
oy_1: number, oy_2: number, oy_3: number,
oz_1: number, oz_2: number, oz_3: number) {
this.center = vec3.create(px, py, pz);
this.halfExtents = vec3.create(w, h, l);
this.orientation = mat3.create(ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
}
/**
* Get the bounding points of this shape
* @param minPos
* @param maxPos
*/
public getBoundary (minPos: vec3, maxPos: vec3) {
vec3.sub(minPos, this.center, this.halfExtents);
vec3.add(maxPos, this.center, this.halfExtents);
}
/**
* Translate this shape and apply the effect to a target shape
* @param pos the translation factor
* @param out the target shape
*/
public translate (pos: vec3, out?: box) {
if (!out) { out = this; }
vec3.add(out.center, this.center, pos);
}
/**
* Rotate this shape and apply the effect to a target shape
* @param rot the rotation factor
* @param out the target shape
*/
public rotate (rot: quat, out?: box) {
if (!out) { out = this; }
// parent box doesn't contain rotations for now
mat3.fromQuat(out.orientation, rot);
}
/**
* Scale this shape and apply the effect to a target shape
* @param scale the scaling factor
* @param out the target shape
*/
public scale (scale: vec3, out?: box) {
if (!out) { out = this; }
vec3.mul(out.halfExtents, this.halfExtents, scale);
}
}
-106
View File
@@ -1,106 +0,0 @@
import enums from './enums';
import { vec3 } from '../../core/vmath';
export default class line {
constructor(sx = 0, sy = 0, sz = 0, ex = 0, ey = 0, ez = -1) {
this._type = enums.SHAPE_LINE;
this.s = vec3.create(sx, sy, sz);
this.e = vec3.create(ex, ey, ez);
}
/**
* create a new line
*
* @param {number} sx start X component
* @param {number} sy start Y component
* @param {number} sz start Z component
* @param {number} ex end X component
* @param {number} ey end Y component
* @param {number} ez end Z component
* @return {line}
*/
static create(sx, sy, sz, ex, ey, ez) {
return new line(sx, sy, sz, ex, ey, ez);
}
/**
* Creates a new line initialized with values from an existing line
*
* @param {line} a line to clone
* @return {line} a new line
*/
static clone(a) {
return new line(
a.s.x, a.s.y, a.s.z,
a.e.x, a.e.y, a.e.z
);
}
/**
* Copy the values from one line to another
*
* @param {line} out the receiving line
* @param {line} a the source line
* @return {line} out
*/
static copy(out, a) {
vec3.copy(out.s, a.s);
vec3.copy(out.e, a.e);
return out;
}
/**
* create a line from two points
*
* @param {line} out the receiving line
* @param {vec3} start line start
* @param {vec3} end target position
* @return {line} out
*/
static fromPoints(out, start, end) {
vec3.copy(out.s, start);
vec3.copy(out.e, end);
return out;
}
/**
* Set the components of a vec3 to the given values
*
* @param {vec3} out the receiving vector
* @param {number} sx start X component
* @param {number} sy start Y component
* @param {number} sz start Z component
* @param {number} ex end X component
* @param {number} ey end Y component
* @param {number} ez end Z component
* @return {vec3} out
*/
static set(out, sx, sy, sz, ex, ey, ez) {
out.s.x = sx;
out.s.y = sy;
out.s.z = sz;
out.e.x = ex;
out.e.y = ey;
out.e.z = ez;
return out;
}
/**
* create line from 2 points
*
* @param {line} line
* @return {number}
*/
static magnitude(line) {
return vec3.distance(line.s, line.e);
}
/**
*Alias of {@link line.magnitude}.
*/
static mag(line) {
return line.magnitude(line);
}
}
+112
View File
@@ -0,0 +1,112 @@
import { vec3 } from '../../core/vmath';
import enums from './enums';
export default class line {
/**
* create a new line
*
* @param sx start X component
* @param sy start Y component
* @param sz start Z component
* @param ex end X component
* @param ey end Y component
* @param ez end Z component
* @return
*/
public static create (sx: number, sy: number, sz: number, ex: number, ey: number, ez: number) {
return new line(sx, sy, sz, ex, ey, ez);
}
/**
* Creates a new line initialized with values from an existing line
*
* @param a line to clone
* @return a new line
*/
public static clone (a: line) {
return new line(
a.s.x, a.s.y, a.s.z,
a.e.x, a.e.y, a.e.z,
);
}
/**
* Copy the values from one line to another
*
* @param out the receiving line
* @param a the source line
* @return out
*/
public static copy (out: line, a: line) {
vec3.copy(out.s, a.s);
vec3.copy(out.e, a.e);
return out;
}
/**
* create a line from two points
*
* @param out the receiving line
* @param start line start
* @param end target position
* @return out
*/
public static fromPoints (out: line, start: vec3, end: vec3) {
vec3.copy(out.s, start);
vec3.copy(out.e, end);
return out;
}
/**
* Set the components of a vec3 to the given values
*
* @param out the receiving vector
* @param sx start X component
* @param sy start Y component
* @param sz start Z component
* @param ex end X component
* @param ey end Y component
* @param ez end Z component
* @return out
*/
public static set (out: line, sx: number, sy: number, sz: number, ex: number, ey: number, ez: number) {
out.s.x = sx;
out.s.y = sy;
out.s.z = sz;
out.e.x = ex;
out.e.y = ey;
out.e.z = ez;
return out;
}
/**
* create line from 2 points
*
* @param a
* @return
*/
public static magnitude (a: line) {
return vec3.distance(a.s, a.e);
}
/**
* Alias of {@link line.magnitude}.
*/
public static mag (a: line) {
return line.magnitude(a);
}
public s: vec3;
public e: vec3;
private _type: number;
constructor (sx = 0, sy = 0, sz = 0, ex = 0, ey = 0, ez = -1) {
this._type = enums.SHAPE_LINE;
this.s = vec3.create(sx, sy, sz);
this.e = vec3.create(ex, ey, ez);
}
}
-228
View File
@@ -1,228 +0,0 @@
import aabb from './aabb';
import intersect from './intersect';
import { vec3 } from '../../core/vmath';
import { FixedArray } from '../memop';
let mul = function(out, v, x, y, z) {
return vec3.set(out, v.x * x, v.y * y, v.z * z);
};
class OctreeBlock {
constructor(minPos, maxPos, capacity, depth, maxDepth, getBoundingShape) {
this.minPos = minPos;
this.maxPos = maxPos;
this.boundingBox = aabb.fromPoints(aabb.create(), minPos, maxPos);
this.capacity = capacity;
this.depth = depth;
this.maxDepth = maxDepth;
this._getBoundingShape = getBoundingShape;
this.blocks = null;
this.entries = new FixedArray(this.capacity);
}
addEntry(entry) {
if (this.blocks) {
for (let i = 0; i < this.blocks.length; i++) {
this.blocks[i].addEntry(entry);
}
} else {
let shape = this._getBoundingShape(entry);
if (!intersect.resolve(this.boundingBox, shape)) return;
this.entries.push(entry);
if (this.entries.length >= this.capacity && this.depth < this.maxDepth) {
this.blocks = Octree.createBlocks(this.minPos, this.maxPos, this.entries,
this.capacity, this.depth, this.maxDepth, this._getBoundingShape);
this.entries = null;
}
}
}
removeEntry(entry) {
if (this.blocks) {
for (let i = 0; i < this.blocks.length; i++) {
this.blocks[i].removeEntry(entry);
}
} else {
this.entries.fastRemove(this.entries.indexOf(entry));
}
}
select(out, shape) {
if (!intersect.resolve(this.boundingBox, shape)) return;
if (this.blocks) {
for (let i = 0; i < this.blocks.length; i++) {
this.blocks[i].select(out, shape);
}
} else {
for (let i = 0; i < this.entries.length; i++) {
out.add(this.entries.data[i]);
}
}
}
frustumSelect(out, frustum) {
if (!intersect.box_frustum(this.boundingBox, frustum)) return;
if (this.blocks) {
for (let i = 0; i < this.blocks.length; i++) {
this.blocks[i].frustumSelect(out, frustum);
}
} else {
for (let i = 0; i < this.entries.length; i++) {
out.add(this.entries.data[i]);
}
}
}
}
/**
* An octree acceleration data structure
* @example
* let octree = new Octree();
* octree.build(models, model => {
* return model._boundingShape;
* });
* octree.select(enums.SHAPE_FRUSTUM, view._frustum);
*/
export default class Octree {
/**
* Create a octree structure
* @param {number} blockCapacity - maximum capacity for each block node
before it's been subdivided, might be exceeded if `maxDepth` is reached
* @param {number} maxDepth - maximum depth of this tree
*/
constructor(blockCapacity = 32, maxDepth = 5) {
this.blockCapacity = blockCapacity;
this.maxDepth = maxDepth;
this.blocks = [];
this.dynamics = [];
this._selection = new Set();
this._getBoundingShape = () => { return this._getBoundingShape; };
}
/**
* Build this octree from given entries.
* Root Boundary is the bounding box of all the entries.
* @param {Array<Object>} entries - a collection of entries to be queried later
* @param {function(entry: Object): Object} getBoundingShape
* - a function takes an entry and returns its primitive info
*/
build(entries, getBoundingShape) {
// calc world min & max
let worldMin = vec3.create(Infinity, Infinity, Infinity);
let worldMax = vec3.create(-Infinity, -Infinity, -Infinity);
let minPos = vec3.create();
let maxPos = vec3.create();
let staticEntries = []; this.dynamics = [];
for (let i = 0; i < entries.length; i++) {
let entry = (entries.data || entries)[i];
let shape = getBoundingShape(entry);
if (!shape) {
this.dynamics.push(entry);
} else {
shape.getBoundary(minPos, maxPos);
vec3.min(worldMin, worldMin, minPos);
vec3.max(worldMax, worldMax, maxPos);
staticEntries.push(entry);
}
}
this.blocks = Octree.createBlocks(worldMin, worldMax, staticEntries,
this.blockCapacity, 0, this.maxDepth, getBoundingShape);
this._getBoundingShape = getBoundingShape;
}
/**
* Add an entry to this tree. Should be called after `build`.
* @param {Object} entry - the new entry
*/
addEntry(entry) {
if (!this._getBoundingShape(entry).shape) {
this.dynamics.push(entry);
return;
}
for (let i = 0; i < this.blocks.length; i++) {
this.blocks[i].addEntry(entry);
}
}
/**
* Remove an entry from this tree. Should be called after `build`.
* @param {Object} entry - the entry to be removed
*/
removeEntry(entry) {
if (!this._getBoundingShape(entry).shape) {
this.dynamics.splice(this.dynamics.indexOf(entry), 1);
return;
}
for (let i = 0; i < this.blocks.length; i++) {
this.blocks[i].removeEntry(entry);
}
}
/**
* Select all the entries overlapping the given primitive
* @param {Object} shape - the selecting primitive
* @return {Set<Object>} the resulting set of entries
*/
select(shape) {
this._selection.clear();
for (let i = 0; i < this.blocks.length; i++) {
this.blocks[i].select(this._selection, shape);
}
for (let i = 0; i < this.dynamics.length; i++) {
this._selection.add(this.dynamics[i]);
}
return this._selection;
}
/**
* Specialized selection for frustums
* @param {Object} frustum - the selecting frustum
* @return {Set<Object>} the resulting set of entries
*/
frustumSelect(frustum) {
this._selection.clear();
for (let i = 0; i < this.blocks.length; i++) {
this.blocks[i].frustumSelect(this._selection, frustum);
}
for (let i = 0; i < this.dynamics.length; i++) {
this._selection.add(this.dynamics[i]);
}
return this._selection;
}
/**
* Create sub blocks and populate them with given entries
* @param {vec3} worldMin - min position of the parent bounding box
* @param {vec3} worldMax - max position of the parent bounding box
* @param {Array<Object>} entries - the entries to be inserted
* @param {number} blockCapacity - maximum capacity for each block node
before it's been subdivided, might be exceeded if `maxDepth` is reached
* @param {number} curDepth - depth before subdivided
* @param {number} maxDepth - maximum depth of this tree
* @param {function(entry: Object): Object} getBoundingShape
- a function takes an entry and returns its primitive info
* @return {OctreeBlock[]} the sub blocks
*/
static createBlocks(worldMin, worldMax, entries, blockCapacity, curDepth, maxDepth, getBoundingShape) {
let blocks = [];
let blockSize = vec3.create();
vec3.scale(blockSize, vec3.sub(blockSize, worldMax, worldMin), 0.5);
for (let x = 0; x < 2; x++) {
for (let y = 0; y < 2; y++) {
for (let z = 0; z < 2; z++) {
let localMin = vec3.create(), localMax = vec3.create();
vec3.add(localMin, worldMin, mul(localMin, blockSize, x, y, z));
vec3.add(localMax, worldMin, mul(localMax, blockSize, x + 1, y + 1, z + 1));
let block = new OctreeBlock(localMin, localMax,
blockCapacity, curDepth + 1, maxDepth, getBoundingShape);
for (let i = 0; i < entries.length; i++) {
let entry = (entries.data || entries)[i];
block.addEntry(entry);
}
blocks.push(block);
}
}
}
return blocks;
}
}
+248
View File
@@ -0,0 +1,248 @@
import { vec3 } from '../../core/vmath';
import { FixedArray } from '../memop';
import aabb from './aabb';
import intersect from './intersect';
const mul = (out, v, x, y, z) => {
return vec3.set(out, v.x * x, v.y * y, v.z * z);
};
class OctreeBlock {
public minPos: vec3;
public maxPos: vec3;
public boundingBox: aabb;
public capacity: number;
public depth: number;
public maxDepth: number;
public blocks: null | OctreeBlock[];
public entries: FixedArray;
private _getBoundingShape: Function;
constructor (minPos, maxPos, capacity, depth, maxDepth, getBoundingShape) {
this.minPos = minPos;
this.maxPos = maxPos;
this.boundingBox = aabb.fromPoints(aabb.create(), minPos, maxPos);
this.capacity = capacity;
this.depth = depth;
this.maxDepth = maxDepth;
this._getBoundingShape = getBoundingShape;
this.blocks = null;
this.entries = new FixedArray(this.capacity);
}
public addEntry (entry) {
if (this.blocks) {
for (const block of this.blocks) {
block.addEntry(entry);
}
} else {
const shape = this._getBoundingShape(entry);
if (!intersect.resolve(this.boundingBox, shape)) { return; }
this.entries.push(entry);
if (this.entries.length >= this.capacity && this.depth < this.maxDepth) {
this.blocks = Octree.createBlocks(this.minPos, this.maxPos, this.entries,
this.capacity, this.depth, this.maxDepth, this._getBoundingShape);
this.entries = null;
}
}
}
public removeEntry (entry) {
if (this.blocks) {
for (const block of this.blocks) {
block.removeEntry(entry);
}
} else {
this.entries.fastRemove(this.entries.indexOf(entry));
}
}
public select (out, shape) {
if (!intersect.resolve(this.boundingBox, shape)) { return; }
if (this.blocks) {
for (const block of this.blocks) {
block.select(out, shape);
}
} else {
for (let i = 0; i < this.entries.length; i++) {
out.add(this.entries.data[i]);
}
}
}
public frustumSelect (out, frustum) {
if (!intersect.box_frustum(this.boundingBox, frustum)) { return; }
if (this.blocks) {
for (const block of this.blocks) {
block.frustumSelect(out, frustum);
}
} else {
for (let i = 0; i < this.entries.length; i++) {
out.add(this.entries.data[i]);
}
}
}
}
/**
* An octree acceleration data structure
* @example
* let octree = new Octree();
* octree.build(models, model => {
* return model._boundingShape;
* });
* octree.select(enums.SHAPE_FRUSTUM, view._frustum);
*/
export default class Octree {
/**
* Create sub blocks and populate them with given entries
* @param {vec3} worldMin - min position of the parent bounding box
* @param {vec3} worldMax - max position of the parent bounding box
* @param {Array<Object>} entries - the entries to be inserted
* @param {number} blockCapacity - maximum capacity for each block node
* before it's been subdivided, might be exceeded if `maxDepth` is reached
* @param {number} curDepth - depth before subdivided
* @param {number} maxDepth - maximum depth of this tree
* @param {function(entry: Object): Object} getBoundingShape - a function takes an entry and returns its primitive info
* @return {OctreeBlock[]} the sub blocks
*/
public static createBlocks (worldMin, worldMax, entries, blockCapacity, curDepth, maxDepth, getBoundingShape) {
const blocks: OctreeBlock[] = [];
const blockSize = vec3.create();
vec3.scale(blockSize, vec3.sub(blockSize, worldMax, worldMin), 0.5);
for (let x = 0; x < 2; x++) {
for (let y = 0; y < 2; y++) {
for (let z = 0; z < 2; z++) {
const localMin = vec3.create();
const localMax = vec3.create();
vec3.add(localMin, worldMin, mul(localMin, blockSize, x, y, z));
vec3.add(localMax, worldMin, mul(localMax, blockSize, x + 1, y + 1, z + 1));
const block = new OctreeBlock(localMin, localMax,
blockCapacity, curDepth + 1, maxDepth, getBoundingShape);
for (let i = 0; i < entries.length; i++) {
const entry = (entries.data || entries)[i];
block.addEntry(entry);
}
blocks.push(block);
}
}
}
return blocks;
}
public blockCapacity: number;
public maxDepth: number;
public blocks: OctreeBlock[];
public dynamics: any[];
private _selection: Set<any>;
private _getBoundingShape: Function;
/**
* Create a octree structure
* @param {number} blockCapacity - maximum capacity for each block node
* before it's been subdivided, might be exceeded if `maxDepth` is reached
* @param {number} maxDepth - maximum depth of this tree
*/
constructor (blockCapacity = 32, maxDepth = 5) {
this.blockCapacity = blockCapacity;
this.maxDepth = maxDepth;
this.blocks = [];
this.dynamics = [];
this._selection = new Set();
this._getBoundingShape = () => this._getBoundingShape;
}
/**
* Build this octree from given entries.
* Root Boundary is the bounding box of all the entries.
* @param {Array<Object>} entries - a collection of entries to be queried later
* @param {function(entry: Object): Object} getBoundingShape
* - a function takes an entry and returns its primitive info
*/
public build (entries, getBoundingShape) {
// calc world min & max
const worldMin = vec3.create(Infinity, Infinity, Infinity);
const worldMax = vec3.create(-Infinity, -Infinity, -Infinity);
const minPos = vec3.create();
const maxPos = vec3.create();
const staticEntries: any[] = []; this.dynamics = [];
for (let i = 0; i < entries.length; i++) {
const entry = (entries.data || entries)[i];
const shape = getBoundingShape(entry);
if (!shape) {
this.dynamics.push(entry);
} else {
shape.getBoundary(minPos, maxPos);
vec3.min(worldMin, worldMin, minPos);
vec3.max(worldMax, worldMax, maxPos);
staticEntries.push(entry);
}
}
this.blocks = Octree.createBlocks(worldMin, worldMax, staticEntries,
this.blockCapacity, 0, this.maxDepth, getBoundingShape);
this._getBoundingShape = getBoundingShape;
}
/**
* Add an entry to this tree. Should be called after `build`.
* @param {Object} entry - the new entry
*/
public addEntry (entry) {
if (!this._getBoundingShape(entry).shape) {
this.dynamics.push(entry);
return;
}
for (const block of this.blocks) {
block.addEntry(entry);
}
}
/**
* Remove an entry from this tree. Should be called after `build`.
* @param {Object} entry - the entry to be removed
*/
public removeEntry (entry) {
if (!this._getBoundingShape(entry).shape) {
this.dynamics.splice(this.dynamics.indexOf(entry), 1);
return;
}
for (const block of this.blocks) {
block.removeEntry(entry);
}
}
/**
* Select all the entries overlapping the given primitive
* @param {Object} shape - the selecting primitive
* @return {Set<Object>} the resulting set of entries
*/
public select (shape) {
this._selection.clear();
for (const block of this.blocks) {
block.select(this._selection, shape);
}
for (const dynamic of this.dynamics) {
this._selection.add(dynamic);
}
return this._selection;
}
/**
* Specialized selection for frustums
* @param {Object} frustum - the selecting frustum
* @return {Set<Object>} the resulting set of entries
*/
public frustumSelect (frustum) {
this._selection.clear();
for (const block of this.blocks) {
block.frustumSelect(this._selection, frustum);
}
for (const dynamic of this.dynamics) {
this._selection.add(dynamic);
}
return this._selection;
}
}
-89
View File
@@ -1,89 +0,0 @@
import enums from './enums';
import { vec3 } from '../../core/vmath';
export default class ray {
constructor(ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = -1) {
this._type = enums.SHAPE_RAY;
this.o = vec3.create(ox, oy, oz);
this.d = vec3.create(dx, dy, dz);
}
/**
* create a new ray
*
* @param {number} ox origin X component
* @param {number} oy origin Y component
* @param {number} oz origin Z component
* @param {number} dx dir X component
* @param {number} dy dir Y component
* @param {number} dz dir Z component
* @return {ray}
*/
static create(ox, oy, oz, dx, dy, dz) {
return new ray(ox, oy, oz, dx, dy, dz);
}
/**
* Creates a new ray initialized with values from an existing ray
*
* @param {ray} a ray to clone
* @return {ray} a new ray
*/
static clone(a) {
return new ray(
a.o.x, a.o.y, a.o.z,
a.d.x, a.d.y, a.d.z
);
}
/**
* Copy the values from one ray to another
*
* @param {ray} out the receiving ray
* @param {ray} a the source ray
* @return {ray} out
*/
static copy(out, a) {
vec3.copy(out.o, a.o);
vec3.copy(out.d, a.d);
return out;
}
/**
* create a ray from two points
*
* @param {ray} out the receiving ray
* @param {vec3} origin ray origin
* @param {vec3} target target position
* @return {ray} out
*/
static fromPoints(out, origin, target) {
vec3.copy(out.o, origin);
vec3.normalize(out.d, vec3.sub(out.d, target, origin));
return out;
}
/**
* Set the components of a ray to the given values
*
* @param {ray} out the receiving ray
* @param {number} ox origin X component
* @param {number} oy origin Y component
* @param {number} oz origin Z component
* @param {number} dx dir X component
* @param {number} dy dir Y component
* @param {number} dz dir Z component
* @return {ray} out
*/
static set(out, ox, oy, oz, dx, dy, dz) {
out.o.x = ox;
out.o.y = oy;
out.o.z = oz;
out.d.x = dx;
out.d.y = dy;
out.d.z = dz;
return out;
}
}
+94
View File
@@ -0,0 +1,94 @@
import { vec3 } from '../../core/vmath';
import enums from './enums';
export default class ray {
/**
* create a new ray
*
* @param {number} ox origin X component
* @param {number} oy origin Y component
* @param {number} oz origin Z component
* @param {number} dx dir X component
* @param {number} dy dir Y component
* @param {number} dz dir Z component
* @return {ray}
*/
public static create (ox, oy, oz, dx, dy, dz) {
return new ray(ox, oy, oz, dx, dy, dz);
}
/**
* Creates a new ray initialized with values from an existing ray
*
* @param {ray} a ray to clone
* @return {ray} a new ray
*/
public static clone (a) {
return new ray(
a.o.x, a.o.y, a.o.z,
a.d.x, a.d.y, a.d.z,
);
}
/**
* Copy the values from one ray to another
*
* @param {ray} out the receiving ray
* @param {ray} a the source ray
* @return {ray} out
*/
public static copy (out, a) {
vec3.copy(out.o, a.o);
vec3.copy(out.d, a.d);
return out;
}
/**
* create a ray from two points
*
* @param {ray} out the receiving ray
* @param {vec3} origin ray origin
* @param {vec3} target target position
* @return {ray} out
*/
public static fromPoints (out, origin, target) {
vec3.copy(out.o, origin);
vec3.normalize(out.d, vec3.sub(out.d, target, origin));
return out;
}
/**
* Set the components of a ray to the given values
*
* @param {ray} out the receiving ray
* @param {number} ox origin X component
* @param {number} oy origin Y component
* @param {number} oz origin Z component
* @param {number} dx dir X component
* @param {number} dy dir Y component
* @param {number} dz dir Z component
* @return {ray} out
*/
public static set (out, ox, oy, oz, dx, dy, dz) {
out.o.x = ox;
out.o.y = oy;
out.o.z = oz;
out.d.x = dx;
out.d.y = dy;
out.d.z = dz;
return out;
}
public o: vec3;
public d: vec3;
private _type: number;
constructor (ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = -1) {
this._type = enums.SHAPE_RAY;
this.o = vec3.create(ox, oy, oz);
this.d = vec3.create(dx, dy, dz);
}
}
-104
View File
@@ -1,104 +0,0 @@
import enums from './enums';
import { vec3 } from '../../core/vmath';
let _v3_tmp = vec3.create();
function maxComponent(v) { return Math.max(Math.max(v.x, v.y), v.z); }
export default class sphere {
constructor(cx = 0, cy = 0, cz = 0, r = 1) {
this._type = enums.SHAPE_SPHERE;
this.c = vec3.create(cx, cy, cz);
this.r = r;
}
/**
* create a new sphere
*
* @return {plane}
*/
static create(cx, cy, cz, r) {
return new sphere(cx, cy, cz, r);
}
/**
* clone a new sphere
*
* @param {sphere} p the source sphere
* @return {sphere}
*/
static clone (p) {
return new sphere(p.c.x, p.c.y, p.c.z, p.r);
}
/**
* copy the values from one sphere to another
*
* @param {sphere} out the receiving sphere
* @param {sphere} p the source sphere
* @return {sphere}
*/
static copy (out, p) {
vec3.copy(out, p.c);
out.r = p.r;
return out;
}
/**
* create a new bounding sphere from two corner points
*
* @param {sphere} out the receiving sphere
* @param {vec3} minPos lower corner of the original shape
* @param {vec3} maxPos upper corner of the original shape
* @return {sphere}
*/
static fromPoints(out, minPos, maxPos) {
vec3.scale(out.c, vec3.add(_v3_tmp, minPos, maxPos), 0.5);
out.r = vec3.mag(vec3.sub(_v3_tmp, maxPos, minPos)) * 0.5;
return out;
}
/**
* Set the components of a sphere to the given values
*
* @param {sphere} out the receiving sphere
* @param {number} cx X component of c
* @param {number} cy Y component of c
* @param {number} cz Z component of c
* @param {number} r
* @return {sphere} out
* @function
*/
static set (out, cx, cy, cz, r) {
out.c.x = cx;
out.c.y = cy;
out.c.z = cz;
out.r = r;
return out;
}
/**
* Get the bounding points of this shape
* @param {vec3} minPos
* @param {vec3} maxPos
*/
getBoundary(minPos, maxPos) {
vec3.set(minPos, this.c.x - this.r, this.c.y - this.r, this.c.z - this.r);
vec3.set(maxPos, this.c.x + this.r, this.c.y + this.r, this.c.z + this.r);
}
/**
* Transform this shape
* @param {mat4} m the transform matrix
* @param {vec3} pos the position part of the transform
* @param {quat} rot the rotation part of the transform
* @param {vec3} scale the scale part of the transform
* @param {sphere} [out] the target shape
*/
transform(m, pos, rot, scale, out) {
if (!out) out = this;
vec3.transformMat4(out.c, this.c, m);
out.r = this.r * maxComponent(scale);
}
}
+110
View File
@@ -0,0 +1,110 @@
import { vec3 } from '../../core/vmath';
import enums from './enums';
const _v3_tmp = vec3.create();
function maxComponent (v) { return Math.max(Math.max(v.x, v.y), v.z); }
export default class sphere {
/**
* create a new sphere
*
* @return {plane}
*/
public static create (cx, cy, cz, r) {
return new sphere(cx, cy, cz, r);
}
/**
* clone a new sphere
*
* @param {sphere} p the source sphere
* @return {sphere}
*/
public static clone (p) {
return new sphere(p.c.x, p.c.y, p.c.z, p.r);
}
/**
* copy the values from one sphere to another
*
* @param {sphere} out the receiving sphere
* @param {sphere} p the source sphere
* @return {sphere}
*/
public static copy (out, p) {
vec3.copy(out, p.c);
out.r = p.r;
return out;
}
/**
* create a new bounding sphere from two corner points
*
* @param {sphere} out the receiving sphere
* @param {vec3} minPos lower corner of the original shape
* @param {vec3} maxPos upper corner of the original shape
* @return {sphere}
*/
public static fromPoints (out, minPos, maxPos) {
vec3.scale(out.c, vec3.add(_v3_tmp, minPos, maxPos), 0.5);
out.r = vec3.mag(vec3.sub(_v3_tmp, maxPos, minPos)) * 0.5;
return out;
}
/**
* Set the components of a sphere to the given values
*
* @param {sphere} out the receiving sphere
* @param {number} cx X component of c
* @param {number} cy Y component of c
* @param {number} cz Z component of c
* @param {number} r
* @return {sphere} out
* @function
*/
public static set (out, cx, cy, cz, r) {
out.c.x = cx;
out.c.y = cy;
out.c.z = cz;
out.r = r;
return out;
}
public c: vec3;
public r: number;
private _type: number;
constructor (cx = 0, cy = 0, cz = 0, r = 1) {
this._type = enums.SHAPE_SPHERE;
this.c = vec3.create(cx, cy, cz);
this.r = r;
}
/**
* Get the bounding points of this shape
* @param {vec3} minPos
* @param {vec3} maxPos
*/
public getBoundary (minPos, maxPos) {
vec3.set(minPos, this.c.x - this.r, this.c.y - this.r, this.c.z - this.r);
vec3.set(maxPos, this.c.x + this.r, this.c.y + this.r, this.c.z + this.r);
}
/**
* Transform this shape
* @param {mat4} m the transform matrix
* @param {vec3} pos the position part of the transform
* @param {quat} rot the rotation part of the transform
* @param {vec3} scale the scale part of the transform
* @param {sphere} [out] the target shape
*/
public transform (m, pos, rot, scale, out) {
if (!out) { out = this; }
vec3.transformMat4(out.c, this.c, m);
out.r = this.r * maxComponent(scale);
}
}
-106
View File
@@ -1,106 +0,0 @@
import enums from './enums';
import { vec3 } from '../../core/vmath';
export default class triangle {
constructor(ax = 0, ay = 0, az = 0, bx = 1, by = 0, bz = 0, cx = 0, cy = 1, cz = 0) {
this._type = enums.SHAPE_TRIANGLE;
this.a = vec3.create(ax, ay, az);
this.b = vec3.create(bx, by, bz);
this.c = vec3.create(cx, cy, cz);
}
/**
* create a new triangle
*
* @param {number} ax
* @param {number} ay
* @param {number} az
* @param {number} bx
* @param {number} by
* @param {number} bz
* @param {number} cx
* @param {number} cy
* @param {number} cz
* @return {triangle}
*/
static create(ax, ay, az, bx, by, bz, cx, cy, cz) {
return new triangle(ax, ay, az, bx, by, bz, cx, cy, cz);
}
/**
* clone a new triangle
*
* @param {triangle} t the source plane
* @return {triangle}
*/
static clone (t) {
return new triangle(
t.a.x, t.a.y, t.a.z,
t.b.x, t.b.y, t.b.z,
t.c.x, t.c.y, t.c.z
);
}
/**
* copy the values from one triangle to another
*
* @param {triangle} out the receiving triangle
* @param {triangle} t the source triangle
* @return {triangle}
*/
static copy (out, t) {
vec3.copy(out.a, t.a);
vec3.copy(out.b, t.b);
vec3.copy(out.c, t.c);
return out;
}
/**
* Create a triangle from three points
*
* @param {triangle} out the receiving triangle
* @param {vec3} a
* @param {vec3} b
* @param {vec3} c
* @return {triangle}
*/
static fromPoints(out, a, b, c) {
vec3.copy(out.a, a);
vec3.copy(out.b, b);
vec3.copy(out.c, c);
return out;
}
/**
* Set the components of a triangle to the given values
*
* @param {triangle} out the receiving plane
* @param {number} ax X component of a
* @param {number} ay Y component of a
* @param {number} az Z component of a
* @param {number} bx X component of b
* @param {number} by Y component of b
* @param {number} bz Z component of b
* @param {number} cx X component of c
* @param {number} cy Y component of c
* @param {number} cz Z component of c
* @return {plane}
* @function
*/
static set (out, ax, ay, az, bx, by, bz, cx, cy, cz) {
out.a.x = ax;
out.a.y = ay;
out.a.z = az;
out.b.x = bx;
out.b.y = by;
out.b.z = bz;
out.c.x = cx;
out.c.y = cy;
out.c.z = cz;
return out;
}
}
+113
View File
@@ -0,0 +1,113 @@
import { vec3 } from '../../core/vmath';
import enums from './enums';
export default class triangle {
/**
* create a new triangle
*
* @param {number} ax
* @param {number} ay
* @param {number} az
* @param {number} bx
* @param {number} by
* @param {number} bz
* @param {number} cx
* @param {number} cy
* @param {number} cz
* @return {triangle}
*/
public static create (ax, ay, az, bx, by, bz, cx, cy, cz) {
return new triangle(ax, ay, az, bx, by, bz, cx, cy, cz);
}
/**
* clone a new triangle
*
* @param {triangle} t the source plane
* @return {triangle}
*/
public static clone (t) {
return new triangle(
t.a.x, t.a.y, t.a.z,
t.b.x, t.b.y, t.b.z,
t.c.x, t.c.y, t.c.z,
);
}
/**
* copy the values from one triangle to another
*
* @param {triangle} out the receiving triangle
* @param {triangle} t the source triangle
* @return {triangle}
*/
public static copy (out, t) {
vec3.copy(out.a, t.a);
vec3.copy(out.b, t.b);
vec3.copy(out.c, t.c);
return out;
}
/**
* Create a triangle from three points
*
* @param {triangle} out the receiving triangle
* @param {vec3} a
* @param {vec3} b
* @param {vec3} c
* @return {triangle}
*/
public static fromPoints (out, a, b, c) {
vec3.copy(out.a, a);
vec3.copy(out.b, b);
vec3.copy(out.c, c);
return out;
}
/**
* Set the components of a triangle to the given values
*
* @param {triangle} out the receiving plane
* @param {number} ax X component of a
* @param {number} ay Y component of a
* @param {number} az Z component of a
* @param {number} bx X component of b
* @param {number} by Y component of b
* @param {number} bz Z component of b
* @param {number} cx X component of c
* @param {number} cy Y component of c
* @param {number} cz Z component of c
* @return {plane}
* @function
*/
public static set (out, ax, ay, az, bx, by, bz, cx, cy, cz) {
out.a.x = ax;
out.a.y = ay;
out.a.z = az;
out.b.x = bx;
out.b.y = by;
out.b.z = bz;
out.c.x = cx;
out.c.y = cy;
out.c.z = cz;
return out;
}
public a: vec3;
public b: vec3;
public c: vec3;
private _type: number;
constructor (ax = 0, ay = 0, az = 0, bx = 1, by = 0, bz = 0, cx = 0, cy = 1, cz = 0) {
this._type = enums.SHAPE_TRIANGLE;
this.a = vec3.create(ax, ay, az);
this.b = vec3.create(bx, by, bz);
this.c = vec3.create(cx, cy, cz);
}
}
-17
View File
@@ -1,17 +0,0 @@
export default class CircularPool {
constructor(fn, size) {
this._cursor = 0;
this._data = new Array(size);
for (let i = 0; i < size; ++i) {
this._data[i] = fn();
}
}
request() {
let item = this._data[this._cursor];
this._cursor = (this._cursor + 1) % this._data.length;
return item;
}
}
+20
View File
@@ -0,0 +1,20 @@
export default class CircularPool<T = {}> {
private _cursor: number;
private _data: T[];
constructor (fn: () => T, size: number) {
this._cursor = 0;
this._data = new Array(size);
for (let i = 0; i < size; ++i) {
this._data[i] = fn();
}
}
public request () {
const item = this._data[this._cursor];
this._cursor = (this._cursor + 1) % this._data.length;
return item;
}
}
-73
View File
@@ -1,73 +0,0 @@
import sort from './timsort';
export default class FixedArray {
constructor(size) {
this._count = 0;
this._data = new Array(size);
}
_resize(size) {
if (size > this._data.length) {
for (let i = this._data.length; i < size; ++i) {
this._data[i] = undefined;
}
}
}
get length() {
return this._count;
}
get data() {
return this._data;
}
reset() {
for (let i = 0; i < this._count; ++i) {
this._data[i] = undefined;
}
this._count = 0;
}
push(val) {
if (this._count >= this._data.length) {
this._resize(this._data.length * 2);
}
this._data[this._count] = val;
++this._count;
}
pop() {
--this._count;
if (this._count < 0) {
this._count = 0;
}
let ret = this._data[this._count];
this._data[this._count] = undefined;
return ret;
}
fastRemove(idx) {
if (idx >= this._count || idx < 0) {
return;
}
let last = this._count - 1;
this._data[idx] = this._data[last];
this._data[last] = undefined;
this._count -= 1;
}
indexOf(val) {
return this._data.indexOf(val);
}
sort(cmp) {
return sort(this._data, 0, this._count, cmp);
}
}
+76
View File
@@ -0,0 +1,76 @@
import sort from './timsort';
export default class FixedArray<T = {}> {
private _count: number;
private _data: Array<T | undefined>;
constructor (size: number) {
this._count = 0;
this._data = new Array(size);
}
public _resize (size: number) {
if (size > this._data.length) {
for (let i = this._data.length; i < size; ++i) {
this._data[i] = undefined;
}
}
}
get length () {
return this._count;
}
get data () {
return this._data;
}
public reset () {
for (let i = 0; i < this._count; ++i) {
this._data[i] = undefined;
}
this._count = 0;
}
public push (val) {
if (this._count >= this._data.length) {
this._resize(this._data.length * 2);
}
this._data[this._count] = val;
++this._count;
}
public pop () {
--this._count;
if (this._count < 0) {
this._count = 0;
}
const ret = this._data[this._count];
this._data[this._count] = undefined;
return ret;
}
public fastRemove (idx) {
if (idx >= this._count || idx < 0) {
return;
}
const last = this._count - 1;
this._data[idx] = this._data[last];
this._data[last] = undefined;
this._count -= 1;
}
public indexOf (val) {
return this._data.indexOf(val);
}
public sort (cmp) {
return sort(this._data, 0, this._count, cmp);
}
}
@@ -3,4 +3,4 @@ export { default as FixedArray } from './fixed-array';
export { default as LinkedArray } from './linked-array';
export { default as Pool } from './pool';
export { default as RecyclePool } from './recycle-pool';
export { default as TypedArrayPool } from './typed-array-pool';
export { default as TypedArrayPool } from './typed-array-pool';
-82
View File
@@ -1,82 +0,0 @@
import Pool from './pool';
// NOTE: you must have `_prev` and `_next` field in the object returns by `fn`
export default class LinkedArray {
constructor(fn, size) {
this._fn = fn;
this._count = 0;
this._head = null;
this._tail = null;
this._pool = new Pool(fn, size);
}
get head() {
return this._head;
}
get tail() {
return this._tail;
}
get length() {
return this._count;
}
add() {
let node = this._pool.alloc();
if (!this._tail) {
this._head = node;
} else {
this._tail._next = node;
node._prev = this._tail;
}
this._tail = node;
this._count += 1;
return node;
}
remove(node) {
if (node._prev) {
node._prev._next = node._next;
} else {
this._head = node._next;
}
if (node._next) {
node._next._prev = node._prev;
} else {
this._tail = node._prev;
}
node._next = null;
node._prev = null;
this._pool.free(node);
this._count -= 1;
}
forEach(fn, binder) {
let cursor = this._head;
if (!cursor) {
return;
}
if (binder) {
fn = fn.bind(binder);
}
let idx = 0;
let next = cursor;
while (cursor) {
next = cursor._next;
fn(cursor, idx, this);
cursor = next;
++idx;
}
}
}
+95
View File
@@ -0,0 +1,95 @@
import Pool from './pool';
// NOTE: you must have `_prev` and `_next` field in the object returns by `fn`
interface INode {
_prev: INode;
_next: INode;
}
type NodeAllocator = () => INode;
export default class LinkedArray<T = {}> {
private _fn: NodeAllocator;
private _count: number;
private _head: INode | null;
private _tail: INode | null;
private _pool: Pool<INode>;
constructor (fn: NodeAllocator, size: number) {
this._fn = fn;
this._count = 0;
this._head = null;
this._tail = null;
this._pool = new Pool(fn, size);
}
get head () {
return this._head;
}
get tail () {
return this._tail;
}
get length () {
return this._count;
}
public add () {
const node = this._pool.alloc();
if (!this._tail) {
this._head = node;
} else {
this._tail._next = node;
node._prev = this._tail;
}
this._tail = node;
this._count += 1;
return node;
}
public remove (node) {
if (node._prev) {
node._prev._next = node._next;
} else {
this._head = node._next;
}
if (node._next) {
node._next._prev = node._prev;
} else {
this._tail = node._prev;
}
node._next = null;
node._prev = null;
this._pool.free(node);
this._count -= 1;
}
public forEach (fn, binder) {
let cursor = this._head;
if (!cursor) {
return;
}
if (binder) {
fn = fn.bind(binder);
}
let idx = 0;
let next = cursor;
while (cursor) {
next = cursor._next;
fn(cursor, idx, this);
cursor = next;
++idx;
}
}
}
-187
View File
@@ -1,187 +0,0 @@
export class OptimizedArray {
/**
* Initialize this array with specified capacity.
* @param {Number} [size] The size.
*/
constructor(size = 0) {
this._size = size;
this._data = new Array(size);
}
/**
* Size of this array.
* @return {Number}
*/
get size() {
return this._size;
}
/**
* The underlying Array of this array.
* @return {Array}
*/
get data() {
return this._data;
}
/**
* Capacity of this array.
*/
get capacity() {
return this._data.length;
}
/**
* Push a value to back of this array.
* @param {any} value
*/
push(value) {
if (this._size > this._data.length)
this._extends(this._data.length);
this._data[this._size] = value;
++this._size;
}
/**
* Remove the last element and return it, if exists.
*/
pop() {
if (this._size == 0)
return;
--this._size;
let ret = this._data[this._size];
this._data[this._size] = undefined;
return ret;
}
/**
* Remove all elements.
*/
clear() {
for (let i = 0; i < this._data.length; ++i)
this._data[i] = undefined;
this._size = 0;
}
/**
* @ignore
* @param {Number} size
*/
_extends(size) {
let finalSize = this._data.length + size;
for (let i = this._data.length; i < finalSize; ++i)
this._data[i] = undefined;
}
}
export class OptimizedValueArray {
/**
* Initialize this array with specified capacity.
* @param {any} ctor The constructor to create the value.
* @param {Number} [size] The size.
*/
constructor(ctor, dtor, size = 0) {
this._size = size;
this._data = new Array();
this._ctor = ctor;
this._dtor = dtor;
this._extends(size);
}
/**
* Size of this array.
* @return {Number}
*/
get size() {
return this._size;
}
/**
* The underlying Array of this array.
* @return {Array}
*/
get data() {
return this._data;
}
/**
* Capacity of this array.
*/
get capacity() {
return this._data.length;
}
/**
* Push a value to back of this array.
*/
push() {
if (this._size >= this._data.length)
this._extends(this._data.length + 1);
let retval = this._data[this._size];
++this._size;
return retval;
}
/**
* Remove the last element, if exists.
* Since that element is not erased, so we cannot return it.
*/
pop() {
if (this._size == 0)
return;
--this._size;
this._dtor(this._data[this._size]);
}
/**
* Remove all elements.
*/
clear() {
this._size = 0;
for (let i = 0; i < this._data.length; ++i)
this._dtor(this._data[i]);
}
splice(from, number) {
if (number == 0)
return;
if (from >= this.size)
return; // throw
number = Math.min(this.size - from, number);
let originalSize = this._size;
this._size -= number;
for (let i = 0, moveStart = from + number, moveNumber = originalSize - moveStart; i < moveNumber; ++i) {
let temp = this._data[from + i];
this._data[from + i] = this._data[moveStart + i];
this._data[moveStart + i] = temp;
}
for (let i = this._size; i != originalSize; ++i)
this._dtor(this._data[i]);
}
forEach(fx) {
for (let i = 0; i < this.size; ++i)
fx(this.data[i], i, this);
}
map(fx) {
let result = new Array();
for (let i = 0; i < this.size; ++i)
result.push(fx(this.data[i], i, this));
return result;
}
/**
* @ignore
* @param {Number} size
*/
_extends(size) {
let finalSize = this._data.length + size;
for (let i = this._data.length; i < finalSize; ++i)
this._data[i] = this._ctor();
}
}
+212
View File
@@ -0,0 +1,212 @@
export class OptimizedArray<T = {}> {
private _size: number;
private _data: Array<T | undefined>;
/**
* Initialize this array with specified capacity.
* @param {Number} [size] The size.
*/
constructor (size = 0) {
this._size = size;
this._data = new Array(size);
}
/**
* Size of this array.
* @return {Number}
*/
get size () {
return this._size;
}
/**
* The underlying Array of this array.
* @return {Array}
*/
get data () {
return this._data;
}
/**
* Capacity of this array.
*/
get capacity () {
return this._data.length;
}
/**
* Push a value to back of this array.
* @param {any} value
*/
public push (value) {
if (this._size > this._data.length) {
this._extends(this._data.length);
}
this._data[this._size] = value;
++this._size;
}
/**
* Remove the last element and return it, if exists.
*/
public pop () {
if (this._size === 0) {
return;
}
--this._size;
const ret = this._data[this._size];
this._data[this._size] = undefined;
return ret;
}
/**
* Remove all elements.
*/
public clear () {
for (let i = 0; i < this._data.length; ++i) {
this._data[i] = undefined;
}
this._size = 0;
}
/**
* @ignore
* @param {Number} size
*/
public _extends (size) {
const finalSize = this._data.length + size;
for (let i = this._data.length; i < finalSize; ++i) {
this._data[i] = undefined;
}
}
}
type Allocator<T> = () => T;
type Deallocator<T> = (value: T) => void;
export class OptimizedValueArray<T = {}> {
private _size: number;
private _data: T[];
private _ctor;
private _dtor;
/**
* Initialize this array with specified capacity.
* @param {any} ctor The constructor to create the value.
* @param {Number} [size] The size.
*/
constructor (ctor: Allocator<T>, dtor: Deallocator<T>, size = 0) {
this._size = size;
this._data = new Array();
this._ctor = ctor;
this._dtor = dtor;
this._extends(size);
}
/**
* Size of this array.
* @return {Number}
*/
get size () {
return this._size;
}
/**
* The underlying Array of this array.
* @return {Array}
*/
get data () {
return this._data as T[];
}
/**
* Capacity of this array.
*/
get capacity () {
return this._data.length;
}
/**
* Push a value to back of this array.
*/
public push () {
if (this._size >= this._data.length) {
this._extends(this._data.length + 1);
}
const retval = this._data[this._size];
++this._size;
return retval;
}
/**
* Remove the last element, if exists.
* Since that element is not erased, so we cannot return it.
*/
public pop () {
if (this._size === 0) {
return;
}
--this._size;
this._dtor(this._data[this._size]);
}
/**
* Remove all elements.
*/
public clear () {
this._size = 0;
for (const value of this._data) {
this._dtor(value);
}
}
public splice (from, number) {
if (number === 0) {
return;
}
if (from >= this.size) {
return;
} // throw
number = Math.min(this.size - from, number);
const originalSize = this._size;
this._size -= number;
for (let i = 0, moveStart = from + number, moveNumber = originalSize - moveStart; i < moveNumber; ++i) {
const temp = this._data[from + i];
this._data[from + i] = this._data[moveStart + i];
this._data[moveStart + i] = temp;
}
for (let i = this._size; i !== originalSize; ++i) {
this._dtor(this._data[i]);
}
}
public forEach (fx) {
for (let i = 0; i < this.size; ++i) {
fx(this.data[i], i, this);
}
}
public map (fx) {
const result = new Array();
for (let i = 0; i < this.size; ++i) {
result.push(fx(this.data[i], i, this));
}
return result;
}
/**
* @ignore
* @param {Number} size
*/
public _extends (size) {
const finalSize = this._data.length + size;
for (let i = this._data.length; i < finalSize; ++i) {
this._data[i] = this._ctor();
}
}
}
-166
View File
@@ -1,166 +0,0 @@
// reference: https://github.com/v8/v8/blob/master/src/js/array.js
function _compare(a, b) {
return a - b;
}
function _sort(array, from, to, comparefn) {
function _insertionSort(a, from, to) {
for (let i = from + 1; i < to; i++) {
let element = a[i];
let j;
for (j = i - 1; j >= from; j--) {
let tmp = a[j];
let order = comparefn(tmp, element);
if (order > 0) {
a[j + 1] = tmp;
} else {
break;
}
}
a[j + 1] = element;
}
}
// function _getThirdIndex(a, from, to) {
// let t_array = new Array();
// // Use both 'from' and 'to' to determine the pivot candidates.
// let increment = 200 + ((to - from) & 15);
// let j = 0;
// from += 1;
// to -= 1;
// for (let i = from; i < to; i += increment) {
// t_array[j] = [i, a[i]];
// j++;
// }
// t_array.sort(function (a, b) {
// return comparefn(a[1], b[1]);
// });
// let third_index = t_array[t_array.length >> 1][0];
// return third_index;
// }
function _quickSort(a, from, to) {
let third_index = 0;
while (true) {
// Insertion sort is faster for short arrays.
if (to - from <= 10) {
_insertionSort(a, from, to);
return;
}
// if (to - from > 1000) {
// third_index = _getThirdIndex(a, from, to);
// } else {
third_index = from + ((to - from) >> 1);
// }
// Find a pivot as the median of first, last and middle element.
let v0 = a[from];
let v1 = a[to - 1];
let v2 = a[third_index];
let c01 = comparefn(v0, v1);
if (c01 > 0) {
// v1 < v0, so swap them.
let tmp = v0;
v0 = v1;
v1 = tmp;
} // v0 <= v1.
let c02 = comparefn(v0, v2);
if (c02 >= 0) {
// v2 <= v0 <= v1.
let tmp = v0;
v0 = v2;
v2 = v1;
v1 = tmp;
} else {
// v0 <= v1 && v0 < v2
let c12 = comparefn(v1, v2);
if (c12 > 0) {
// v0 <= v2 < v1
let tmp = v1;
v1 = v2;
v2 = tmp;
}
}
// v0 <= v1 <= v2
a[from] = v0;
a[to - 1] = v2;
let pivot = v1;
let low_end = from + 1; // Upper bound of elements lower than pivot.
let high_start = to - 1; // Lower bound of elements greater than pivot.
a[third_index] = a[low_end];
a[low_end] = pivot;
// From low_end to i are elements equal to pivot.
// From i to high_start are elements that haven't been compared yet.
partition: for (let i = low_end + 1; i < high_start; i++) {
let element = a[i];
let order = comparefn(element, pivot);
if (order < 0) {
a[i] = a[low_end];
a[low_end] = element;
low_end++;
} else if (order > 0) {
do {
high_start--;
if (high_start == i) break partition;
let top_elem = a[high_start];
order = comparefn(top_elem, pivot);
} while (order > 0);
a[i] = a[high_start];
a[high_start] = element;
if (order < 0) {
element = a[i];
a[i] = a[low_end];
a[low_end] = element;
low_end++;
}
}
}
if (to - high_start < low_end - from) {
_quickSort(a, high_start, to);
to = low_end;
} else {
_quickSort(a, from, low_end);
from = high_start;
}
}
}
if (to - from < 2) {
return array;
}
_quickSort(array, from, to);
return array;
}
/**
* Calls the _quickSort function with it's initial values.
*
* @public
* @param {array} array The input array which should be sorted
* @param {Number} from
* @param {Number} to
* @param {Function} cmp
* @returns {array} array Sorted array
*/
export default function (array, from, to, cmp) {
if (from === undefined) {
from = 0;
}
if (to === undefined) {
to = array.length;
}
if (cmp === undefined) {
cmp = _compare;
}
return _sort(array, from, to, cmp);
}
+166
View File
@@ -0,0 +1,166 @@
// reference: https://github.com/v8/v8/blob/master/src/js/array.js
// tslint:disable:no-shadowed-variable
function _compare (a, b) {
return a - b;
}
function _sort (array, from, to, comparefn) {
function _insertionSort (a, from, to) {
for (let i = from + 1; i < to; i++) {
const element = a[i];
let j;
for (j = i - 1; j >= from; j--) {
const tmp = a[j];
const order = comparefn(tmp, element);
if (order > 0) {
a[j + 1] = tmp;
} else {
break;
}
}
a[j + 1] = element;
}
}
// function _getThirdIndex(a, from, to) {
// let t_array = new Array();
// // Use both 'from' and 'to' to determine the pivot candidates.
// let increment = 200 + ((to - from) & 15);
// let j = 0;
// from += 1;
// to -= 1;
// for (let i = from; i < to; i += increment) {
// t_array[j] = [i, a[i]];
// j++;
// }
// t_array.sort(function (a, b) {
// return comparefn(a[1], b[1]);
// });
// let third_index = t_array[t_array.length >> 1][0];
// return third_index;
// }
function _quickSort (a, from, to) {
let third_index = 0;
while (true) {
// Insertion sort is faster for short arrays.
if (to - from <= 10) {
_insertionSort(a, from, to);
return;
}
// if (to - from > 1000) {
// third_index = _getThirdIndex(a, from, to);
// } else {
third_index = from + ((to - from) >> 1);
// }
// Find a pivot as the median of first, last and middle element.
let v0 = a[from];
let v1 = a[to - 1];
let v2 = a[third_index];
const c01 = comparefn(v0, v1);
if (c01 > 0) {
// v1 < v0, so swap them.
const tmp = v0;
v0 = v1;
v1 = tmp;
} // v0 <= v1.
const c02 = comparefn(v0, v2);
if (c02 >= 0) {
// v2 <= v0 <= v1.
const tmp = v0;
v0 = v2;
v2 = v1;
v1 = tmp;
} else {
// v0 <= v1 && v0 < v2
const c12 = comparefn(v1, v2);
if (c12 > 0) {
// v0 <= v2 < v1
const tmp = v1;
v1 = v2;
v2 = tmp;
}
}
// v0 <= v1 <= v2
a[from] = v0;
a[to - 1] = v2;
const pivot = v1;
let low_end = from + 1; // Upper bound of elements lower than pivot.
let high_start = to - 1; // Lower bound of elements greater than pivot.
a[third_index] = a[low_end];
a[low_end] = pivot;
// From low_end to i are elements equal to pivot.
// From i to high_start are elements that haven't been compared yet.
partition: for (let i = low_end + 1; i < high_start; i++) {
let element = a[i];
let order = comparefn(element, pivot);
if (order < 0) {
a[i] = a[low_end];
a[low_end] = element;
low_end++;
} else if (order > 0) {
do {
high_start--;
if (high_start === i) { break partition; }
const top_elem = a[high_start];
order = comparefn(top_elem, pivot);
} while (order > 0);
a[i] = a[high_start];
a[high_start] = element;
if (order < 0) {
element = a[i];
a[i] = a[low_end];
a[low_end] = element;
low_end++;
}
}
}
if (to - high_start < low_end - from) {
_quickSort(a, high_start, to);
to = low_end;
} else {
_quickSort(a, from, low_end);
from = high_start;
}
}
}
if (to - from < 2) {
return array;
}
_quickSort(array, from, to);
return array;
}
/**
* Calls the _quickSort function with it's initial values.
*
* @param array The input array which should be sorted
* @param from
* @param to
* @param cmp
* @returns array Sorted array
*/
export default function<T> (array: T[], from?: number, to?: number, cmp?: CompareFunction<T>): T[] {
if (from === undefined) {
from = 0;
}
if (to === undefined) {
to = array.length;
}
if (cmp === undefined) {
cmp = _compare;
}
return _sort(array, from, to, cmp);
}
-967
View File
@@ -1,967 +0,0 @@
// reference: https://github.com/mziccard/node-timsort
/**
* Default minimum size of a run.
*/
const DEFAULT_MIN_MERGE = 32;
/**
* Minimum ordered subsequece required to do galloping.
*/
const DEFAULT_MIN_GALLOPING = 7;
/**
* Default tmp storage length. Can increase depending on the size of the
* smallest run to merge.
*/
const DEFAULT_TMP_STORAGE_LENGTH = 256;
/**
* Pre-computed powers of 10 for efficient lexicographic comparison of
* small integers.
*/
const POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]
/**
* Estimate the logarithm base 10 of a small integer.
*
* @param {number} x - The integer to estimate the logarithm of.
* @return {number} - The estimated logarithm of the integer.
*/
function log10(x) {
if (x < 1e5) {
if (x < 1e2) {
return x < 1e1 ? 0 : 1;
}
if (x < 1e4) {
return x < 1e3 ? 2 : 3;
}
return 4;
}
if (x < 1e7) {
return x < 1e6 ? 5 : 6;
}
if (x < 1e9) {
return x < 1e8 ? 7 : 8;
}
return 9;
}
/**
* Default alphabetical comparison of items.
*
* @param {string|object|number} a - First element to compare.
* @param {string|object|number} b - Second element to compare.
* @return {number} - A positive number if a.toString() > b.toString(), a
* negative number if .toString() < b.toString(), 0 otherwise.
*/
function alphabeticalCompare(a, b) {
if (a === b) {
return 0;
}
if (~~a === a && ~~b === b) {
if (a === 0 || b === 0) {
return a < b ? -1 : 1;
}
if (a < 0 || b < 0) {
if (b >= 0) {
return -1;
}
if (a >= 0) {
return 1;
}
a = -a;
b = -b;
}
const al = log10(a);
const bl = log10(b);
let t = 0;
if (al < bl) {
a *= POWERS_OF_TEN[bl - al - 1];
b /= 10;
t = -1;
} else if (al > bl) {
b *= POWERS_OF_TEN[al - bl - 1];
a /= 10;
t = 1;
}
if (a === b) {
return t;
}
return a < b ? -1 : 1;
}
let aStr = String(a);
let bStr = String(b);
if (aStr === bStr) {
return 0;
}
return aStr < bStr ? -1 : 1;
}
/**
* Compute minimum run length for TimSort
*
* @param {number} n - The size of the array to sort.
*/
function minRunLength(n) {
let r = 0;
while (n >= DEFAULT_MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}
/**
* Counts the length of a monotonically ascending or strictly monotonically
* descending sequence (run) starting at array[lo] in the range [lo, hi). If
* the run is descending it is made ascending.
*
* @param {array} array - The array to reverse.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
* @param {function} compare - Item comparison function.
* @return {number} - The length of the run.
*/
function makeAscendingRun(array, lo, hi, compare) {
let runHi = lo + 1;
if (runHi === hi) {
return 1;
}
// Descending
if (compare(array[runHi++], array[lo]) < 0) {
while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
runHi++;
}
reverseRun(array, lo, runHi);
// Ascending
} else {
while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
runHi++;
}
}
return runHi - lo;
}
/**
* Reverse an array in the range [lo, hi).
*
* @param {array} array - The array to reverse.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
*/
function reverseRun(array, lo, hi) {
hi--;
while (lo < hi) {
let t = array[lo];
array[lo++] = array[hi];
array[hi--] = t;
}
}
/**
* Perform the binary sort of the array in the range [lo, hi) where start is
* the first element possibly out of order.
*
* @param {array} array - The array to sort.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
* @param {number} start - First element possibly out of order.
* @param {function} compare - Item comparison function.
*/
function binaryInsertionSort(array, lo, hi, start, compare) {
if (start === lo) {
start++;
}
for (; start < hi; start++) {
let pivot = array[start];
// Ranges of the array where pivot belongs
let left = lo;
let right = start;
/*
* pivot >= array[i] for i in [lo, left)
* pivot < array[i] for i in in [right, start)
*/
while (left < right) {
let mid = (left + right) >>> 1;
if (compare(pivot, array[mid]) < 0) {
right = mid;
} else {
left = mid + 1;
}
}
/*
* Move elements right to make room for the pivot. If there are elements
* equal to pivot, left points to the first slot after them: this is also
* a reason for which TimSort is stable
*/
let n = start - left;
// Switch is just an optimization for small arrays
switch (n) {
case 3:
array[left + 3] = array[left + 2];
/* falls through */
case 2:
array[left + 2] = array[left + 1];
/* falls through */
case 1:
array[left + 1] = array[left];
break;
default:
while (n > 0) {
array[left + n] = array[left + n - 1];
n--;
}
}
array[left] = pivot;
}
}
/**
* Find the position at which to insert a value in a sorted range. If the range
* contains elements equal to the value the leftmost element index is returned
* (for stability).
*
* @param {number} value - Value to insert.
* @param {array} array - The array in which to insert value.
* @param {number} start - First element in the range.
* @param {number} length - Length of the range.
* @param {number} hint - The index at which to begin the search.
* @param {function} compare - Item comparison function.
* @return {number} - The index where to insert value.
*/
function gallopLeft(value, array, start, length, hint, compare) {
let lastOffset = 0;
let maxOffset = 0;
let offset = 1;
if (compare(value, array[start + hint]) > 0) {
maxOffset = length - hint;
while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
lastOffset += hint;
offset += hint;
// value <= array[start + hint]
} else {
maxOffset = hint + 1;
while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
let tmp = lastOffset;
lastOffset = hint - offset;
offset = hint - tmp;
}
/*
* Now array[start+lastOffset] < value <= array[start+offset], so value
* belongs somewhere in the range (start + lastOffset, start + offset]. Do a
* binary search, with invariant array[start + lastOffset - 1] < value <=
* array[start + offset].
*/
lastOffset++;
while (lastOffset < offset) {
let m = lastOffset + ((offset - lastOffset) >>> 1);
if (compare(value, array[start + m]) > 0) {
lastOffset = m + 1;
} else {
offset = m;
}
}
return offset;
}
/**
* Find the position at which to insert a value in a sorted range. If the range
* contains elements equal to the value the rightmost element index is returned
* (for stability).
*
* @param {number} value - Value to insert.
* @param {array} array - The array in which to insert value.
* @param {number} start - First element in the range.
* @param {number} length - Length of the range.
* @param {number} hint - The index at which to begin the search.
* @param {function} compare - Item comparison function.
* @return {number} - The index where to insert value.
*/
function gallopRight(value, array, start, length, hint, compare) {
let lastOffset = 0;
let maxOffset = 0;
let offset = 1;
if (compare(value, array[start + hint]) < 0) {
maxOffset = hint + 1;
while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
let tmp = lastOffset;
lastOffset = hint - offset;
offset = hint - tmp;
// value >= array[start + hint]
} else {
maxOffset = length - hint;
while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
lastOffset += hint;
offset += hint;
}
/*
* Now array[start+lastOffset] < value <= array[start+offset], so value
* belongs somewhere in the range (start + lastOffset, start + offset]. Do a
* binary search, with invariant array[start + lastOffset - 1] < value <=
* array[start + offset].
*/
lastOffset++;
while (lastOffset < offset) {
let m = lastOffset + ((offset - lastOffset) >>> 1);
if (compare(value, array[start + m]) < 0) {
offset = m;
} else {
lastOffset = m + 1;
}
}
return offset;
}
class TimSort {
constructor(array, compare) {
this.array = array;
this.compare = compare;
this.minGallop = DEFAULT_MIN_GALLOPING;
this.length = array.length;
this.tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH;
if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) {
this.tmpStorageLength = this.length >>> 1;
}
this.tmp = new Array(this.tmpStorageLength);
this.stackLength =
(this.length < 120 ? 5 :
this.length < 1542 ? 10 :
this.length < 119151 ? 19 : 40);
this.runStart = new Array(this.stackLength);
this.runLength = new Array(this.stackLength);
this.stackSize = 0;
}
/**
* Push a new run on TimSort's stack.
*
* @param {number} runStart - Start index of the run in the original array.
* @param {number} runLength - Length of the run;
*/
pushRun(runStart, runLength) {
this.runStart[this.stackSize] = runStart;
this.runLength[this.stackSize] = runLength;
this.stackSize += 1;
}
/**
* Merge runs on TimSort's stack so that the following holds for all i:
* 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1]
* 2) runLength[i - 2] > runLength[i - 1]
*/
mergeRuns() {
while (this.stackSize > 1) {
let n = this.stackSize - 2;
if ((n >= 1 &&
this.runLength[n - 1] <= this.runLength[n] + this.runLength[n + 1]) ||
(n >= 2 &&
this.runLength[n - 2] <= this.runLength[n] + this.runLength[n - 1])) {
if (this.runLength[n - 1] < this.runLength[n + 1]) {
n--;
}
} else if (this.runLength[n] > this.runLength[n + 1]) {
break;
}
this.mergeAt(n);
}
}
/**
* Merge all runs on TimSort's stack until only one remains.
*/
forceMergeRuns() {
while (this.stackSize > 1) {
let n = this.stackSize - 2;
if (n > 0 && this.runLength[n - 1] < this.runLength[n + 1]) {
n--;
}
this.mergeAt(n);
}
}
/**
* Merge the runs on the stack at positions i and i+1. Must be always be called
* with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack).
*
* @param {number} i - Index of the run to merge in TimSort's stack.
*/
mergeAt(i) {
let compare = this.compare;
let array = this.array;
let start1 = this.runStart[i];
let length1 = this.runLength[i];
let start2 = this.runStart[i + 1];
let length2 = this.runLength[i + 1];
this.runLength[i] = length1 + length2;
if (i === this.stackSize - 3) {
this.runStart[i + 1] = this.runStart[i + 2];
this.runLength[i + 1] = this.runLength[i + 2];
}
this.stackSize--;
/*
* Find where the first element in the second run goes in run1. Previous
* elements in run1 are already in place
*/
let k = gallopRight(array[start2], array, start1, length1, 0, compare);
start1 += k;
length1 -= k;
if (length1 === 0) {
return;
}
/*
* Find where the last element in the first run goes in run2. Next elements
* in run2 are already in place
*/
length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
if (length2 === 0) {
return;
}
/*
* Merge remaining runs. A tmp array with length = min(length1, length2) is
* used
*/
if (length1 <= length2) {
this.mergeLow(start1, length1, start2, length2);
} else {
this.mergeHigh(start1, length1, start2, length2);
}
}
/**
* Merge two adjacent runs in a stable way. The runs must be such that the
* first element of run1 is bigger than the first element in run2 and the
* last element of run1 is greater than all the elements in run2.
* The method should be called when run1.length <= run2.length as it uses
* TimSort temporary array to store run1. Use mergeHigh if run1.length >
* run2.length.
*
* @param {number} start1 - First element in run1.
* @param {number} length1 - Length of run1.
* @param {number} start2 - First element in run2.
* @param {number} length2 - Length of run2.
*/
mergeLow(start1, length1, start2, length2) {
let compare = this.compare;
let array = this.array;
let tmp = this.tmp;
let i = 0;
for (i = 0; i < length1; i++) {
tmp[i] = array[start1 + i];
}
let cursor1 = 0;
let cursor2 = start2;
let dest = start1;
array[dest++] = array[cursor2++];
if (--length2 === 0) {
for (i = 0; i < length1; i++) {
array[dest + i] = tmp[cursor1 + i];
}
return;
}
if (length1 === 1) {
for (i = 0; i < length2; i++) {
array[dest + i] = array[cursor2 + i];
}
array[dest + length2] = tmp[cursor1];
return;
}
let minGallop = this.minGallop;
while (true) {
let count1 = 0;
let count2 = 0;
let exit = false;
do {
if (compare(array[cursor2], tmp[cursor1]) < 0) {
array[dest++] = array[cursor2++];
count2++;
count1 = 0;
if (--length2 === 0) {
exit = true;
break;
}
} else {
array[dest++] = tmp[cursor1++];
count1++;
count2 = 0;
if (--length1 === 1) {
exit = true;
break;
}
}
} while ((count1 | count2) < minGallop);
if (exit) {
break;
}
do {
count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
if (count1 !== 0) {
for (i = 0; i < count1; i++) {
array[dest + i] = tmp[cursor1 + i];
}
dest += count1;
cursor1 += count1;
length1 -= count1;
if (length1 <= 1) {
exit = true;
break;
}
}
array[dest++] = array[cursor2++];
if (--length2 === 0) {
exit = true;
break;
}
count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
if (count2 !== 0) {
for (i = 0; i < count2; i++) {
array[dest + i] = array[cursor2 + i];
}
dest += count2;
cursor2 += count2;
length2 -= count2;
if (length2 === 0) {
exit = true;
break;
}
}
array[dest++] = tmp[cursor1++];
if (--length1 === 1) {
exit = true;
break;
}
minGallop--;
} while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
if (exit) {
break;
}
if (minGallop < 0) {
minGallop = 0;
}
minGallop += 2;
}
this.minGallop = minGallop;
if (minGallop < 1) {
this.minGallop = 1;
}
if (length1 === 1) {
for (i = 0; i < length2; i++) {
array[dest + i] = array[cursor2 + i];
}
array[dest + length2] = tmp[cursor1];
} else if (length1 === 0) {
throw new Error('mergeLow preconditions were not respected');
} else {
for (i = 0; i < length1; i++) {
array[dest + i] = tmp[cursor1 + i];
}
}
}
/**
* Merge two adjacent runs in a stable way. The runs must be such that the
* first element of run1 is bigger than the first element in run2 and the
* last element of run1 is greater than all the elements in run2.
* The method should be called when run1.length > run2.length as it uses
* TimSort temporary array to store run2. Use mergeLow if run1.length <=
* run2.length.
*
* @param {number} start1 - First element in run1.
* @param {number} length1 - Length of run1.
* @param {number} start2 - First element in run2.
* @param {number} length2 - Length of run2.
*/
mergeHigh(start1, length1, start2, length2) {
let compare = this.compare;
let array = this.array;
let tmp = this.tmp;
let i = 0;
for (i = 0; i < length2; i++) {
tmp[i] = array[start2 + i];
}
let cursor1 = start1 + length1 - 1;
let cursor2 = length2 - 1;
let dest = start2 + length2 - 1;
let customCursor = 0;
let customDest = 0;
array[dest--] = array[cursor1--];
if (--length1 === 0) {
customCursor = dest - (length2 - 1);
for (i = 0; i < length2; i++) {
array[customCursor + i] = tmp[i];
}
return;
}
if (length2 === 1) {
dest -= length1;
cursor1 -= length1;
customDest = dest + 1;
customCursor = cursor1 + 1;
for (i = length1 - 1; i >= 0; i--) {
array[customDest + i] = array[customCursor + i];
}
array[dest] = tmp[cursor2];
return;
}
let minGallop = this.minGallop;
while (true) {
let count1 = 0;
let count2 = 0;
let exit = false;
do {
if (compare(tmp[cursor2], array[cursor1]) < 0) {
array[dest--] = array[cursor1--];
count1++;
count2 = 0;
if (--length1 === 0) {
exit = true;
break;
}
} else {
array[dest--] = tmp[cursor2--];
count2++;
count1 = 0;
if (--length2 === 1) {
exit = true;
break;
}
}
} while ((count1 | count2) < minGallop);
if (exit) {
break;
}
do {
count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
if (count1 !== 0) {
dest -= count1;
cursor1 -= count1;
length1 -= count1;
customDest = dest + 1;
customCursor = cursor1 + 1;
for (i = count1 - 1; i >= 0; i--) {
array[customDest + i] = array[customCursor + i];
}
if (length1 === 0) {
exit = true;
break;
}
}
array[dest--] = tmp[cursor2--];
if (--length2 === 1) {
exit = true;
break;
}
count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
if (count2 !== 0) {
dest -= count2;
cursor2 -= count2;
length2 -= count2;
customDest = dest + 1;
customCursor = cursor2 + 1;
for (i = 0; i < count2; i++) {
array[customDest + i] = tmp[customCursor + i];
}
if (length2 <= 1) {
exit = true;
break;
}
}
array[dest--] = array[cursor1--];
if (--length1 === 0) {
exit = true;
break;
}
minGallop--;
} while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
if (exit) {
break;
}
if (minGallop < 0) {
minGallop = 0;
}
minGallop += 2;
}
this.minGallop = minGallop;
if (minGallop < 1) {
this.minGallop = 1;
}
if (length2 === 1) {
dest -= length1;
cursor1 -= length1;
customDest = dest + 1;
customCursor = cursor1 + 1;
for (i = length1 - 1; i >= 0; i--) {
array[customDest + i] = array[customCursor + i];
}
array[dest] = tmp[cursor2];
} else if (length2 === 0) {
throw new Error('mergeHigh preconditions were not respected');
} else {
customCursor = dest - (length2 - 1);
for (i = 0; i < length2; i++) {
array[customCursor + i] = tmp[i];
}
}
}
}
/**
* Sort an array in the range [lo, hi) using TimSort.
*
* @param {array} array - The array to sort.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
* @param {function=} compare - Item comparison function. Default is alphabetical.
*/
export default function (array, lo, hi, compare) {
if (!Array.isArray(array)) {
throw new TypeError('Can only sort arrays');
}
/*
* Handle the case where a comparison function is not provided. We do
* lexicographic sorting
*/
if (lo === undefined) {
lo = 0;
}
if (hi === undefined) {
hi = array.length;
}
if (compare === undefined) {
compare = alphabeticalCompare;
}
let remaining = hi - lo;
// The array is already sorted
if (remaining < 2) {
return;
}
let runLength = 0;
// On small arrays binary sort can be used directly
if (remaining < DEFAULT_MIN_MERGE) {
runLength = makeAscendingRun(array, lo, hi, compare);
binaryInsertionSort(array, lo, hi, lo + runLength, compare);
return;
}
let ts = new TimSort(array, compare);
let minRun = minRunLength(remaining);
do {
runLength = makeAscendingRun(array, lo, hi, compare);
if (runLength < minRun) {
let force = remaining;
if (force > minRun) {
force = minRun;
}
binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
runLength = force;
}
// Push new run and merge if necessary
ts.pushRun(lo, runLength);
ts.mergeRuns();
// Go find next run
remaining -= runLength;
lo += runLength;
} while (remaining !== 0);
// Force merging of remaining runs
ts.forceMergeRuns();
}
+977
View File
@@ -0,0 +1,977 @@
// reference: https://github.com/mziccard/node-timsort
/**
* Default minimum size of a run.
*/
const DEFAULT_MIN_MERGE = 32;
/**
* Minimum ordered subsequece required to do galloping.
*/
const DEFAULT_MIN_GALLOPING = 7;
/**
* Default tmp storage length. Can increase depending on the size of the
* smallest run to merge.
*/
const DEFAULT_TMP_STORAGE_LENGTH = 256;
/**
* Pre-computed powers of 10 for efficient lexicographic comparison of
* small integers.
*/
const POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9];
/**
* Estimate the logarithm base 10 of a small integer.
*
* @param {number} x - The integer to estimate the logarithm of.
* @return {number} - The estimated logarithm of the integer.
*/
function log10 (x) {
if (x < 1e5) {
if (x < 1e2) {
return x < 1e1 ? 0 : 1;
}
if (x < 1e4) {
return x < 1e3 ? 2 : 3;
}
return 4;
}
if (x < 1e7) {
return x < 1e6 ? 5 : 6;
}
if (x < 1e9) {
return x < 1e8 ? 7 : 8;
}
return 9;
}
/**
* Default alphabetical comparison of items.
*
* @param {string|object|number} a - First element to compare.
* @param {string|object|number} b - Second element to compare.
* @return {number} - A positive number if a.toString() > b.toString(), a
* negative number if .toString() < b.toString(), 0 otherwise.
*/
function alphabeticalCompare (a, b) {
if (a === b) {
return 0;
}
if (~~a === a && ~~b === b) {
if (a === 0 || b === 0) {
return a < b ? -1 : 1;
}
if (a < 0 || b < 0) {
if (b >= 0) {
return -1;
}
if (a >= 0) {
return 1;
}
a = -a;
b = -b;
}
const al = log10(a);
const bl = log10(b);
let t = 0;
if (al < bl) {
a *= POWERS_OF_TEN[bl - al - 1];
b /= 10;
t = -1;
} else if (al > bl) {
b *= POWERS_OF_TEN[al - bl - 1];
a /= 10;
t = 1;
}
if (a === b) {
return t;
}
return a < b ? -1 : 1;
}
const aStr = String(a);
const bStr = String(b);
if (aStr === bStr) {
return 0;
}
return aStr < bStr ? -1 : 1;
}
/**
* Compute minimum run length for TimSort
*
* @param {number} n - The size of the array to sort.
*/
function minRunLength (n) {
let r = 0;
while (n >= DEFAULT_MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}
/**
* Counts the length of a monotonically ascending or strictly monotonically
* descending sequence (run) starting at array[lo] in the range [lo, hi). If
* the run is descending it is made ascending.
*
* @param {array} array - The array to reverse.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
* @param {function} compare - Item comparison function.
* @return {number} - The length of the run.
*/
function makeAscendingRun (array, lo, hi, compare) {
let runHi = lo + 1;
if (runHi === hi) {
return 1;
}
// Descending
if (compare(array[runHi++], array[lo]) < 0) {
while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
runHi++;
}
reverseRun(array, lo, runHi);
// Ascending
} else {
while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
runHi++;
}
}
return runHi - lo;
}
/**
* Reverse an array in the range [lo, hi).
*
* @param {array} array - The array to reverse.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
*/
function reverseRun (array, lo, hi) {
hi--;
while (lo < hi) {
const t = array[lo];
array[lo++] = array[hi];
array[hi--] = t;
}
}
/**
* Perform the binary sort of the array in the range [lo, hi) where start is
* the first element possibly out of order.
*
* @param {array} array - The array to sort.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
* @param {number} start - First element possibly out of order.
* @param {function} compare - Item comparison function.
*/
function binaryInsertionSort (array, lo, hi, start, compare) {
if (start === lo) {
start++;
}
for (; start < hi; start++) {
const pivot = array[start];
// Ranges of the array where pivot belongs
let left = lo;
let right = start;
/*
* pivot >= array[i] for i in [lo, left)
* pivot < array[i] for i in in [right, start)
*/
while (left < right) {
const mid = (left + right) >>> 1;
if (compare(pivot, array[mid]) < 0) {
right = mid;
} else {
left = mid + 1;
}
}
/*
* Move elements right to make room for the pivot. If there are elements
* equal to pivot, left points to the first slot after them: this is also
* a reason for which TimSort is stable
*/
let n = start - left;
// Switch is just an optimization for small arrays
switch (n) {
case 3:
array[left + 3] = array[left + 2];
/* falls through */
case 2:
array[left + 2] = array[left + 1];
/* falls through */
case 1:
array[left + 1] = array[left];
break;
default:
while (n > 0) {
array[left + n] = array[left + n - 1];
n--;
}
}
array[left] = pivot;
}
}
/**
* Find the position at which to insert a value in a sorted range. If the range
* contains elements equal to the value the leftmost element index is returned
* (for stability).
*
* @param {number} value - Value to insert.
* @param {array} array - The array in which to insert value.
* @param {number} start - First element in the range.
* @param {number} length - Length of the range.
* @param {number} hint - The index at which to begin the search.
* @param {function} compare - Item comparison function.
* @return {number} - The index where to insert value.
*/
function gallopLeft (value, array, start, length, hint, compare) {
let lastOffset = 0;
let maxOffset = 0;
let offset = 1;
if (compare(value, array[start + hint]) > 0) {
maxOffset = length - hint;
while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
lastOffset += hint;
offset += hint;
// value <= array[start + hint]
} else {
maxOffset = hint + 1;
while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
const tmp = lastOffset;
lastOffset = hint - offset;
offset = hint - tmp;
}
/*
* Now array[start+lastOffset] < value <= array[start+offset], so value
* belongs somewhere in the range (start + lastOffset, start + offset]. Do a
* binary search, with invariant array[start + lastOffset - 1] < value <=
* array[start + offset].
*/
lastOffset++;
while (lastOffset < offset) {
const m = lastOffset + ((offset - lastOffset) >>> 1);
if (compare(value, array[start + m]) > 0) {
lastOffset = m + 1;
} else {
offset = m;
}
}
return offset;
}
/**
* Find the position at which to insert a value in a sorted range. If the range
* contains elements equal to the value the rightmost element index is returned
* (for stability).
*
* @param {number} value - Value to insert.
* @param {array} array - The array in which to insert value.
* @param {number} start - First element in the range.
* @param {number} length - Length of the range.
* @param {number} hint - The index at which to begin the search.
* @param {function} compare - Item comparison function.
* @return {number} - The index where to insert value.
*/
function gallopRight (value, array, start, length, hint, compare) {
let lastOffset = 0;
let maxOffset = 0;
let offset = 1;
if (compare(value, array[start + hint]) < 0) {
maxOffset = hint + 1;
while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
const tmp = lastOffset;
lastOffset = hint - offset;
offset = hint - tmp;
// value >= array[start + hint]
} else {
maxOffset = length - hint;
while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
lastOffset += hint;
offset += hint;
}
/*
* Now array[start+lastOffset] < value <= array[start+offset], so value
* belongs somewhere in the range (start + lastOffset, start + offset]. Do a
* binary search, with invariant array[start + lastOffset - 1] < value <=
* array[start + offset].
*/
lastOffset++;
while (lastOffset < offset) {
const m = lastOffset + ((offset - lastOffset) >>> 1);
if (compare(value, array[start + m]) < 0) {
offset = m;
} else {
lastOffset = m + 1;
}
}
return offset;
}
class TimSort<T = {}> {
public array: T[];
public compare: CompareFunction<T>;
public minGallop: number;
public length: number;
public tmpStorageLength: number;
public tmp: T[];
public stackLength: number;
public runStart: number[];
public runLength: number[];
public stackSize: number;
constructor (array, compare) {
this.array = array;
this.compare = compare;
this.minGallop = DEFAULT_MIN_GALLOPING;
this.length = array.length;
this.tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH;
if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) {
this.tmpStorageLength = this.length >>> 1;
}
this.tmp = new Array(this.tmpStorageLength);
this.stackLength =
(this.length < 120 ? 5 :
this.length < 1542 ? 10 :
this.length < 119151 ? 19 : 40);
this.runStart = new Array(this.stackLength);
this.runLength = new Array(this.stackLength);
this.stackSize = 0;
}
/**
* Push a new run on TimSort's stack.
*
* @param {number} runStart - Start index of the run in the original array.
* @param {number} runLength - Length of the run;
*/
public pushRun (runStart, runLength) {
this.runStart[this.stackSize] = runStart;
this.runLength[this.stackSize] = runLength;
this.stackSize += 1;
}
/**
* Merge runs on TimSort's stack so that the following holds for all i:
* 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1]
* 2) runLength[i - 2] > runLength[i - 1]
*/
public mergeRuns () {
while (this.stackSize > 1) {
let n = this.stackSize - 2;
if ((n >= 1 &&
this.runLength[n - 1] <= this.runLength[n] + this.runLength[n + 1]) ||
(n >= 2 &&
this.runLength[n - 2] <= this.runLength[n] + this.runLength[n - 1])) {
if (this.runLength[n - 1] < this.runLength[n + 1]) {
n--;
}
} else if (this.runLength[n] > this.runLength[n + 1]) {
break;
}
this.mergeAt(n);
}
}
/**
* Merge all runs on TimSort's stack until only one remains.
*/
public forceMergeRuns () {
while (this.stackSize > 1) {
let n = this.stackSize - 2;
if (n > 0 && this.runLength[n - 1] < this.runLength[n + 1]) {
n--;
}
this.mergeAt(n);
}
}
/**
* Merge the runs on the stack at positions i and i+1. Must be always be called
* with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack).
*
* @param {number} i - Index of the run to merge in TimSort's stack.
*/
public mergeAt (i) {
const compare = this.compare;
const array = this.array;
let start1 = this.runStart[i];
let length1 = this.runLength[i];
const start2 = this.runStart[i + 1];
let length2 = this.runLength[i + 1];
this.runLength[i] = length1 + length2;
if (i === this.stackSize - 3) {
this.runStart[i + 1] = this.runStart[i + 2];
this.runLength[i + 1] = this.runLength[i + 2];
}
this.stackSize--;
/*
* Find where the first element in the second run goes in run1. Previous
* elements in run1 are already in place
*/
const k = gallopRight(array[start2], array, start1, length1, 0, compare);
start1 += k;
length1 -= k;
if (length1 === 0) {
return;
}
/*
* Find where the last element in the first run goes in run2. Next elements
* in run2 are already in place
*/
length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
if (length2 === 0) {
return;
}
/*
* Merge remaining runs. A tmp array with length = min(length1, length2) is
* used
*/
if (length1 <= length2) {
this.mergeLow(start1, length1, start2, length2);
} else {
this.mergeHigh(start1, length1, start2, length2);
}
}
/**
* Merge two adjacent runs in a stable way. The runs must be such that the
* first element of run1 is bigger than the first element in run2 and the
* last element of run1 is greater than all the elements in run2.
* The method should be called when run1.length <= run2.length as it uses
* TimSort temporary array to store run1. Use mergeHigh if run1.length >
* run2.length.
*
* @param {number} start1 - First element in run1.
* @param {number} length1 - Length of run1.
* @param {number} start2 - First element in run2.
* @param {number} length2 - Length of run2.
*/
public mergeLow (start1, length1, start2, length2) {
const compare = this.compare;
const array = this.array;
const tmp = this.tmp;
let i = 0;
for (i = 0; i < length1; i++) {
tmp[i] = array[start1 + i];
}
let cursor1 = 0;
let cursor2 = start2;
let dest = start1;
array[dest++] = array[cursor2++];
if (--length2 === 0) {
for (i = 0; i < length1; i++) {
array[dest + i] = tmp[cursor1 + i];
}
return;
}
if (length1 === 1) {
for (i = 0; i < length2; i++) {
array[dest + i] = array[cursor2 + i];
}
array[dest + length2] = tmp[cursor1];
return;
}
let minGallop = this.minGallop;
while (true) {
let count1 = 0;
let count2 = 0;
let exit = false;
do {
if (compare(array[cursor2], tmp[cursor1]) < 0) {
array[dest++] = array[cursor2++];
count2++;
count1 = 0;
if (--length2 === 0) {
exit = true;
break;
}
} else {
array[dest++] = tmp[cursor1++];
count1++;
count2 = 0;
if (--length1 === 1) {
exit = true;
break;
}
}
} while ((count1 | count2) < minGallop);
if (exit) {
break;
}
do {
count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
if (count1 !== 0) {
for (i = 0; i < count1; i++) {
array[dest + i] = tmp[cursor1 + i];
}
dest += count1;
cursor1 += count1;
length1 -= count1;
if (length1 <= 1) {
exit = true;
break;
}
}
array[dest++] = array[cursor2++];
if (--length2 === 0) {
exit = true;
break;
}
count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
if (count2 !== 0) {
for (i = 0; i < count2; i++) {
array[dest + i] = array[cursor2 + i];
}
dest += count2;
cursor2 += count2;
length2 -= count2;
if (length2 === 0) {
exit = true;
break;
}
}
array[dest++] = tmp[cursor1++];
if (--length1 === 1) {
exit = true;
break;
}
minGallop--;
} while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
if (exit) {
break;
}
if (minGallop < 0) {
minGallop = 0;
}
minGallop += 2;
}
this.minGallop = minGallop;
if (minGallop < 1) {
this.minGallop = 1;
}
if (length1 === 1) {
for (i = 0; i < length2; i++) {
array[dest + i] = array[cursor2 + i];
}
array[dest + length2] = tmp[cursor1];
} else if (length1 === 0) {
throw new Error('mergeLow preconditions were not respected');
} else {
for (i = 0; i < length1; i++) {
array[dest + i] = tmp[cursor1 + i];
}
}
}
/**
* Merge two adjacent runs in a stable way. The runs must be such that the
* first element of run1 is bigger than the first element in run2 and the
* last element of run1 is greater than all the elements in run2.
* The method should be called when run1.length > run2.length as it uses
* TimSort temporary array to store run2. Use mergeLow if run1.length <=
* run2.length.
*
* @param {number} start1 - First element in run1.
* @param {number} length1 - Length of run1.
* @param {number} start2 - First element in run2.
* @param {number} length2 - Length of run2.
*/
public mergeHigh (start1, length1, start2, length2) {
const compare = this.compare;
const array = this.array;
const tmp = this.tmp;
let i = 0;
for (i = 0; i < length2; i++) {
tmp[i] = array[start2 + i];
}
let cursor1 = start1 + length1 - 1;
let cursor2 = length2 - 1;
let dest = start2 + length2 - 1;
let customCursor = 0;
let customDest = 0;
array[dest--] = array[cursor1--];
if (--length1 === 0) {
customCursor = dest - (length2 - 1);
for (i = 0; i < length2; i++) {
array[customCursor + i] = tmp[i];
}
return;
}
if (length2 === 1) {
dest -= length1;
cursor1 -= length1;
customDest = dest + 1;
customCursor = cursor1 + 1;
for (i = length1 - 1; i >= 0; i--) {
array[customDest + i] = array[customCursor + i];
}
array[dest] = tmp[cursor2];
return;
}
let minGallop = this.minGallop;
while (true) {
let count1 = 0;
let count2 = 0;
let exit = false;
do {
if (compare(tmp[cursor2], array[cursor1]) < 0) {
array[dest--] = array[cursor1--];
count1++;
count2 = 0;
if (--length1 === 0) {
exit = true;
break;
}
} else {
array[dest--] = tmp[cursor2--];
count2++;
count1 = 0;
if (--length2 === 1) {
exit = true;
break;
}
}
} while ((count1 | count2) < minGallop);
if (exit) {
break;
}
do {
count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
if (count1 !== 0) {
dest -= count1;
cursor1 -= count1;
length1 -= count1;
customDest = dest + 1;
customCursor = cursor1 + 1;
for (i = count1 - 1; i >= 0; i--) {
array[customDest + i] = array[customCursor + i];
}
if (length1 === 0) {
exit = true;
break;
}
}
array[dest--] = tmp[cursor2--];
if (--length2 === 1) {
exit = true;
break;
}
count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
if (count2 !== 0) {
dest -= count2;
cursor2 -= count2;
length2 -= count2;
customDest = dest + 1;
customCursor = cursor2 + 1;
for (i = 0; i < count2; i++) {
array[customDest + i] = tmp[customCursor + i];
}
if (length2 <= 1) {
exit = true;
break;
}
}
array[dest--] = array[cursor1--];
if (--length1 === 0) {
exit = true;
break;
}
minGallop--;
} while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
if (exit) {
break;
}
if (minGallop < 0) {
minGallop = 0;
}
minGallop += 2;
}
this.minGallop = minGallop;
if (minGallop < 1) {
this.minGallop = 1;
}
if (length2 === 1) {
dest -= length1;
cursor1 -= length1;
customDest = dest + 1;
customCursor = cursor1 + 1;
for (i = length1 - 1; i >= 0; i--) {
array[customDest + i] = array[customCursor + i];
}
array[dest] = tmp[cursor2];
} else if (length2 === 0) {
throw new Error('mergeHigh preconditions were not respected');
} else {
customCursor = dest - (length2 - 1);
for (i = 0; i < length2; i++) {
array[customCursor + i] = tmp[i];
}
}
}
}
/**
* Sort an array in the range [lo, hi) using TimSort.
*
* @param {array} array - The array to sort.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
* @param {function=} compare - Item comparison function. Default is alphabetical.
*/
export default function (array, lo, hi, compare) {
if (!Array.isArray(array)) {
throw new TypeError('Can only sort arrays');
}
/*
* Handle the case where a comparison function is not provided. We do
* lexicographic sorting
*/
if (lo === undefined) {
lo = 0;
}
if (hi === undefined) {
hi = array.length;
}
if (compare === undefined) {
compare = alphabeticalCompare;
}
let remaining = hi - lo;
// The array is already sorted
if (remaining < 2) {
return;
}
let runLength = 0;
// On small arrays binary sort can be used directly
if (remaining < DEFAULT_MIN_MERGE) {
runLength = makeAscendingRun(array, lo, hi, compare);
binaryInsertionSort(array, lo, hi, lo + runLength, compare);
return;
}
const ts = new TimSort(array, compare);
const minRun = minRunLength(remaining);
do {
runLength = makeAscendingRun(array, lo, hi, compare);
if (runLength < minRun) {
let force = remaining;
if (force > minRun) {
force = minRun;
}
binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
runLength = force;
}
// Push new run and merge if necessary
ts.pushRun(lo, runLength);
ts.mergeRuns();
// Go find next run
remaining -= runLength;
lo += runLength;
} while (remaining !== 0);
// Force merging of remaining runs
ts.forceMergeRuns();
}
-129
View File
@@ -1,129 +0,0 @@
let _bufferPools = Array(8);
for (let i = 0; i < 8; ++i) {
_bufferPools[i] = [];
}
function _nextPow16(v) {
for (let i = 16; i <= (1 << 28); i *= 16) {
if (v <= i) {
return i;
}
}
return 0;
}
function _log2(v) {
let r, shift;
r = (v > 0xFFFF) << 4; v >>>= r;
shift = (v > 0xFF) << 3; v >>>= shift; r |= shift;
shift = (v > 0xF) << 2; v >>>= shift; r |= shift;
shift = (v > 0x3) << 1; v >>>= shift; r |= shift;
return r | (v >> 1);
}
function _alloc(n) {
let sz = _nextPow16(n);
let bin = _bufferPools[_log2(sz) >> 2];
if (bin.length > 0) {
return bin.pop();
}
return new ArrayBuffer(sz);
}
function _free(buf) {
_bufferPools[_log2(buf.byteLength) >> 2].push(buf);
}
export default {
alloc_int8(n) {
let result = new Int8Array(_alloc(n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_uint8(n) {
let result = new Uint8Array(_alloc(n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_int16(n) {
let result = new Int16Array(_alloc(2 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_uint16(n) {
let result = new Uint16Array(_alloc(2 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_int32(n) {
let result = new Int32Array(_alloc(4 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_uint32(n) {
let result = new Uint32Array(_alloc(4 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_float32(n) {
let result = new Float32Array(_alloc(4 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_float64(n) {
let result = new Float64Array(_alloc(8 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_dataview(n) {
let result = new DataView(_alloc(n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
free(array) {
_free(array.buffer);
},
reset() {
let _bufferPools = Array(8);
for (let i = 0; i < 8; ++i) {
_bufferPools[i] = [];
}
},
};
+128
View File
@@ -0,0 +1,128 @@
let _bufferPools: ArrayBuffer[][] = Array(8);
for (let i = 0; i < 8; ++i) {
_bufferPools[i] = [];
}
function _nextPow16 (v) {
for (let i = 16; i <= (1 << 28); i *= 16) {
if (v <= i) {
return i;
}
}
return 0;
}
function _log2 (v: number) {
let r = ((v > 0xFFFF) as unknown as number) << 4; v >>>= r;
let shift = ((v > 0xFF) as unknown as number) << 3; v >>>= shift; r |= shift;
shift = ((v > 0xF) as unknown as number) << 2; v >>>= shift; r |= shift;
shift = ((v > 0x3) as unknown as number) << 1; v >>>= shift; r |= shift;
return r | (v >> 1);
}
function _alloc (n: number) {
const sz = _nextPow16(n);
const bin = _bufferPools[_log2(sz) >> 2];
if (bin.length > 0) {
return bin.pop() as ArrayBuffer;
}
return new ArrayBuffer(sz);
}
function _free (buf) {
_bufferPools[_log2(buf.byteLength) >> 2].push(buf);
}
export default {
alloc_int8 (n) {
const result = new Int8Array(_alloc(n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_uint8 (n) {
const result = new Uint8Array(_alloc(n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_int16 (n) {
const result = new Int16Array(_alloc(2 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_uint16 (n) {
const result = new Uint16Array(_alloc(2 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_int32 (n) {
const result = new Int32Array(_alloc(4 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_uint32 (n) {
const result = new Uint32Array(_alloc(4 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_float32 (n) {
const result = new Float32Array(_alloc(4 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
alloc_float64 (n) {
const result = new Float64Array(_alloc(8 * n), 0, n);
if (result.length !== n) {
return result.subarray(0, n);
}
return result;
},
// alloc_dataview (n) {
// const result = new DataView(_alloc(n), 0, n);
// if (result.length !== n) {
// return result.subarray(0, n);
// }
// return result;
// },
free (array) {
_free(array.buffer);
},
reset () {
_bufferPools = Array(8);
for (let i = 0; i < 8; ++i) {
_bufferPools[i] = [];
}
},
};
-23
View File
@@ -1,23 +0,0 @@
function parallel(tasks, callback) {
let length = tasks.length;
if (length === 0) {
callback(null);
}
let completed = 0;
for (let i = 0; i < tasks.length; ++i) {
let task = tasks[i];
task(err => {
if (err) {
callback(err);
} else if (++completed === length) {
callback(null);
}
});
}
}
export default {
parallel
};
View File
-48
View File
@@ -1,48 +0,0 @@
import gfx from '../../renderer/gfx';
export const gfxFilters = {
'linear': gfx.FILTER_LINEAR,
'nearest': gfx.FILTER_NEAREST,
};
export const gfxWraps = {
'repeat': gfx.WRAP_REPEAT,
'clamp': gfx.WRAP_CLAMP,
'mirror': gfx.WRAP_MIRROR,
};
export const gfxTextureFmts = {
// compress formats
'rgb-dxt1': gfx.TEXTURE_FMT_RGB_DXT1,
'rgba-dxt1': gfx.TEXTURE_FMT_RGBA_DXT1,
'rgba-dxt3': gfx.TEXTURE_FMT_RGBA_DXT3,
'rgba-dxt5': gfx.TEXTURE_FMT_RGBA_DXT5,
'rgb-etc1': gfx.TEXTURE_FMT_RGB_ETC1,
'rgb-pvrtc-2bppv1': gfx.TEXTURE_FMT_RGB_PVRTC_2BPPV1,
'rgba-pvrtc-2bppv1': gfx.TEXTURE_FMT_RGBA_PVRTC_2BPPV1,
'rgb-pvrtc-4bppv1': gfx.TEXTURE_FMT_RGB_PVRTC_4BPPV1,
'rgba-pvrtc-4bppv1': gfx.TEXTURE_FMT_RGBA_PVRTC_4BPPV1,
// normal formats
'a8': gfx.TEXTURE_FMT_A8,
'l8': gfx.TEXTURE_FMT_L8,
'l8-a8': gfx.TEXTURE_FMT_L8_A8,
'r5-g6-b5': gfx.TEXTURE_FMT_R5_G6_B5,
'r5-g5-b5-a1': gfx.TEXTURE_FMT_R5_G5_B5_A1,
'r4-g4-b4-a4': gfx.TEXTURE_FMT_R4_G4_B4_A4,
'rgb8': gfx.TEXTURE_FMT_RGB8,
'rgba8': gfx.TEXTURE_FMT_RGBA8,
'rgb16f': gfx.TEXTURE_FMT_RGB16F,
'rgba16f': gfx.TEXTURE_FMT_RGBA16F,
'rgb32f': gfx.TEXTURE_FMT_RGB32F,
'rgba32f': gfx.TEXTURE_FMT_RGBA32F,
'r32f': gfx.TEXTURE_FMT_R32F,
'111110f': gfx.TEXTURE_FMT_111110F,
'srgb': gfx.TEXTURE_FMT_SRGB,
'srgba': gfx.TEXTURE_FMT_SRGBA,
// depth formats
'd16': gfx.TEXTURE_FMT_D16,
'd32': gfx.TEXTURE_FMT_D32,
'd24s8': gfx.TEXTURE_FMT_D24S8,
};
-26
View File
@@ -1,26 +0,0 @@
function _normalize (url) {
return url
.replace(/\\/g, '/')
.replace(/[\/]+/g, '/')
.replace(/\/\?/g, '?')
.replace(/\/\#/g, '#')
.replace(/\:\//g, '://');
}
export default {
/**
* @method normalize
* @param {string} url
*/
normalize(url) {
return _normalize(url);
},
/**
* @method join
*/
join() {
let joined = [].slice.call(arguments, 0).join('/');
return _normalize(joined);
},
};
-52
View File
@@ -1,52 +0,0 @@
let _loaderInfos = [];
let _classInfos = [];
let _typeInfos = [];
let _systemInfos = [];
export default {
registerLoader(id, def) {
_loaderInfos.push({
id, def
});
},
registerType(id, def) {
_typeInfos.push({
id, def
});
},
registerClass(id, def) {
_classInfos.push({
id, def
});
},
registerSystem(id, system, component, priority) {
_systemInfos.push({
id, system, component, priority
});
},
_init (app) {
for (let i = 0; i < _loaderInfos.length; ++i) {
let info = _loaderInfos[i];
app._assetMng.registerLoader(info.id, info.def);
}
for (let i = 0; i < _typeInfos.length; ++i) {
let info = _typeInfos[i];
app.registerType(info.id, info.def);
}
for (let i = 0; i < _classInfos.length; ++i) {
let info = _classInfos[i];
app.registerClass(info.id, info.def);
}
for (let i = 0; i < _systemInfos.length; ++i) {
let info = _systemInfos[i];
app.registerSystem(info.id, info.system, info.component, info.priority);
}
}
};
-426
View File
@@ -1,426 +0,0 @@
/**
* (c) 2016 Mikola Lysenko. MIT License
* https://github.com/regl-project/resl
*/
/* global XMLHttpRequest */
const configParameters = [
'manifest',
'onDone',
'onProgress',
'onError'
];
const manifestParameters = [
'type',
'src',
'stream',
'credentials',
'parser'
];
const parserParameters = [
'onData',
'onDone'
];
const STATE_ERROR = -1;
const STATE_DATA = 0;
const STATE_COMPLETE = 1;
function raise(message) {
throw new Error('resl: ' + message);
}
function checkType(object, parameters, name) {
Object.keys(object).forEach(function (param) {
if (parameters.indexOf(param) < 0) {
raise('invalid parameter "' + param + '" in ' + name);
}
});
}
function Loader(name, cancel) {
this.state = STATE_DATA;
this.ready = false;
this.progress = 0;
this.name = name;
this.cancel = cancel;
}
export default function resl(config) {
if (typeof config !== 'object' || !config) {
raise('invalid or missing configuration');
}
checkType(config, configParameters, 'config');
let manifest = config.manifest;
if (typeof manifest !== 'object' || !manifest) {
raise('missing manifest');
}
function getFunction(name) {
if (name in config) {
let func = config[name];
if (typeof func !== 'function') {
raise('invalid callback "' + name + '"');
}
return func;
}
return null;
}
let onDone = getFunction('onDone');
if (!onDone) {
raise('missing onDone() callback');
}
let onProgress = getFunction('onProgress');
let onError = getFunction('onError');
let assets = {};
let state = STATE_DATA;
function loadXHR(request) {
let name = request.name;
let stream = request.stream;
let binary = request.type === 'binary';
let parser = request.parser;
let xhr = new XMLHttpRequest();
let asset = null;
let loader = new Loader(name, cancel);
if (stream) {
xhr.onreadystatechange = onReadyStateChange;
} else {
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
onReadyStateChange();
}
};
}
if (binary) {
xhr.responseType = 'arraybuffer';
}
function onReadyStateChange() {
if (xhr.readyState < 2 ||
loader.state === STATE_COMPLETE ||
loader.state === STATE_ERROR) {
return;
}
if (xhr.status !== 200) {
return abort('error loading resource "' + request.name + '"');
}
if (xhr.readyState > 2 && loader.state === STATE_DATA) {
let response;
if (request.type === 'binary') {
response = xhr.response;
} else {
response = xhr.responseText;
}
if (parser.data) {
try {
asset = parser.data(response);
} catch (e) {
return abort(e);
}
} else {
asset = response;
}
}
if (xhr.readyState > 3 && loader.state === STATE_DATA) {
if (parser.done) {
try {
asset = parser.done();
} catch (e) {
return abort(e);
}
}
loader.state = STATE_COMPLETE;
}
assets[name] = asset;
loader.progress = 0.75 * loader.progress + 0.25;
loader.ready =
(request.stream && !!asset) ||
loader.state === STATE_COMPLETE;
notifyProgress();
}
function cancel() {
if (loader.state === STATE_COMPLETE || loader.state === STATE_ERROR) {
return;
}
xhr.onreadystatechange = null;
xhr.abort();
loader.state = STATE_ERROR;
}
// set up request
if (request.credentials) {
xhr.withCredentials = true;
}
xhr.open('GET', request.src, true);
xhr.send();
return loader;
}
function loadElement(request, element) {
let name = request.name;
let parser = request.parser;
let loader = new Loader(name, cancel);
let asset = element;
function handleProgress() {
if (loader.state === STATE_DATA) {
if (parser.data) {
try {
asset = parser.data(element);
} catch (e) {
return abort(e);
}
} else {
asset = element;
}
}
}
function onProgress(e) {
handleProgress();
assets[name] = asset;
if (e.lengthComputable) {
loader.progress = Math.max(loader.progress, e.loaded / e.total);
} else {
loader.progress = 0.75 * loader.progress + 0.25;
}
notifyProgress(name);
}
let completed = false;
function onComplete() {
if (completed) return;
completed = true;
handleProgress();
if (loader.state === STATE_DATA) {
if (parser.done) {
try {
asset = parser.done();
} catch (e) {
return abort(e);
}
}
loader.state = STATE_COMPLETE;
}
loader.progress = 1;
loader.ready = true;
assets[name] = asset;
removeListeners();
notifyProgress('finish ' + name);
}
function onError() {
abort('error loading asset "' + name + '"');
}
if (request.stream) {
element.addEventListener('progress', onProgress);
}
if (request.type === 'image') {
element.addEventListener('load', onComplete);
} else {
// 'canplay' event is not supported on iOS
element.addEventListener('loadedmetadata', onComplete);
// there is no event in ios wechat browser
setTimeout(onComplete, 5000);
// TODO: could do platform-specific switching here
}
element.addEventListener('error', onError);
function removeListeners() {
if (request.stream) {
element.removeEventListener('progress', onProgress);
}
if (request.type === 'image') {
element.removeEventListener('load', onComplete);
} else {
element.removeEventListener('loadedmetadata', onComplete);
}
element.removeEventListener('error', onError);
}
function cancel() {
if (loader.state === STATE_COMPLETE || loader.state === STATE_ERROR) {
return;
}
loader.state = STATE_ERROR;
removeListeners();
element.src = '';
}
// set up request
if (request.credentials) {
element.crossOrigin = 'use-credentials';
} else {
element.crossOrigin = 'anonymous';
}
element.src = request.src;
return loader;
}
let loaders = {
text: loadXHR,
binary: function (request) {
// TODO use fetch API for streaming if supported
return loadXHR(request);
},
image: function (request) {
return loadElement(request, document.createElement('img'));
},
video: function (request) {
return loadElement(request, document.createElement('video'));
},
audio: function (request) {
return loadElement(request, document.createElement('audio'));
}
};
// First we parse all objects in order to verify that all type information
// is correct
let pending = Object.keys(manifest).map(function (name) {
let request = manifest[name];
if (typeof request === 'string') {
request = {
src: request
};
} else if (typeof request !== 'object' || !request) {
raise('invalid asset definition "' + name + '"');
}
checkType(request, manifestParameters, 'asset "' + name + '"');
function getParameter(prop, accepted, init) {
let value = init;
if (prop in request) {
value = request[prop];
}
if (accepted.indexOf(value) < 0) {
raise('invalid ' + prop + ' "' + value + '" for asset "' + name + '", possible values: ' + accepted);
}
return value;
}
function getString(prop, required, init) {
let value = init;
if (prop in request) {
value = request[prop];
} else if (required) {
raise('missing ' + prop + ' for asset "' + name + '"');
}
if (typeof value !== 'string') {
raise('invalid ' + prop + ' for asset "' + name + '", must be a string');
}
return value;
}
function getParseFunc(name, dflt) {
if (name in request.parser) {
let result = request.parser[name];
if (typeof result !== 'function') {
raise('invalid parser callback ' + name + ' for asset "' + name + '"');
}
return result;
} else {
return dflt;
}
}
let parser = {};
if ('parser' in request) {
if (typeof request.parser === 'function') {
parser = {
data: request.parser
};
} else if (typeof request.parser === 'object' && request.parser) {
checkType(request.parser, parserParameters, 'parser for asset "' + name + '"');
if (!('onData' in request.parser)) {
raise('missing onData callback for parser in asset "' + name + '"');
}
parser = {
data: getParseFunc('onData'),
done: getParseFunc('onDone')
};
} else {
raise('invalid parser for asset "' + name + '"');
}
}
return {
name: name,
type: getParameter('type', Object.keys(loaders), 'text'),
stream: !!request.stream,
credentials: !!request.credentials,
src: getString('src', true, ''),
parser: parser
};
}).map(function (request) {
return (loaders[request.type])(request);
});
function abort(message) {
if (state === STATE_ERROR || state === STATE_COMPLETE) {
return;
}
state = STATE_ERROR;
pending.forEach(function (loader) {
loader.cancel();
});
if (onError) {
if (typeof message === 'string') {
onError(new Error('resl: ' + message));
} else {
onError(message);
}
} else {
console.error('resl error:', message);
}
}
function notifyProgress(message) {
if (state === STATE_ERROR || state === STATE_COMPLETE) {
return;
}
let progress = 0;
let numReady = 0;
pending.forEach(function (loader) {
if (loader.ready) {
numReady += 1;
}
progress += loader.progress;
});
if (numReady === pending.length) {
state = STATE_COMPLETE;
onDone(assets);
} else {
if (onProgress) {
onProgress(progress / pending.length, message);
}
}
}
if (pending.length === 0) {
setTimeout(function () {
notifyProgress('done');
}, 1);
}
}
+6 -6
View File
@@ -62,14 +62,14 @@ export class Debugger implements Ammo.btIDebugDraw {
defines: {
USE_COLOR: true,
},
states: {
primitive: cc.GFXPrimitiveMode.LINE_LIST,
// depthStencilState: {
// depthFunc: GFXComparisonFunc.LESS_EQUAL,
// },
}
});
material.setProperty('color', new Color(0, 255, 0, 255));
material.overridePipelineStates({
primitive: cc.GFXPrimitiveMode.LINE_LIST,
// depthStencilState: {
// depthFunc: GFXComparisonFunc.LESS_EQUAL,
// },
});
this._modelComponent.sharedMaterials = [ material ];
}
}
+18
View File
@@ -31,6 +31,8 @@ import { ImageAsset } from '../../../assets/image-asset';
import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator';
import { ccenum } from '../../../core/value-types/enum';
import { UI } from '../../../renderer/ui/ui';
import { Material } from '../../assets';
import { RenderableComponent } from '../../framework/renderable-component';
import { FontAtlas } from '../assembler/label/bmfontUtils';
import { ISharedLabelData } from '../assembler/label/ttfUtils';
import { UIRenderComponent } from './ui-render-component';
@@ -618,6 +620,22 @@ export class LabelComponent extends UIRenderComponent {
return result;
}
protected _instanceMaterial () {
if (this._sharedMaterial) {
this._updateMaterial(
Material.getInstantiatedMaterial(this._sharedMaterial,
new RenderableComponent(),
CC_EDITOR ? true : false,
));
} else {
this._updateMaterial(
Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'),
new RenderableComponent(),
CC_EDITOR ? true : false,
));
}
}
private _checkStringEmpty () {
this._renderPermit = !!this.string;
}
+16
View File
@@ -270,6 +270,22 @@ export class MaskComponent extends UIRenderComponent {
return this._maskMaterial !== null && this._clearMaskMaterial !== null && this._renderPermit;
}
protected _instanceMaterial () {
if (this._sharedMaterial) {
this._updateMaterial(
Material.getInstantiatedMaterial(this._sharedMaterial,
new RenderableComponent(),
CC_EDITOR ? true : false,
));
} else {
this._updateMaterial(
Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-base'),
new RenderableComponent(),
CC_EDITOR ? true : false,
));
}
}
// _resizeNodeToTargetNode: CC_EDITOR && function () {
// if (this.spriteFrame) {
// const rect = this.spriteFrame.getRect();
+21 -1
View File
@@ -32,6 +32,8 @@ import { clampf } from '../../../core/utils/misc';
import { Vec2 } from '../../../core/value-types';
import { ccenum } from '../../../core/value-types/enum';
import { UI } from '../../../renderer/ui/ui';
import { Material } from '../../assets';
import { RenderableComponent } from '../../framework/renderable-component';
import { UIRenderComponent } from './ui-render-component';
/**
@@ -353,7 +355,9 @@ export class SpriteComponent extends UIRenderComponent {
* @example
* sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM;
*/
@property()
@property({
type: SizeMode,
})
get sizeMode () {
return this._sizeMode;
}
@@ -514,6 +518,22 @@ export class SpriteComponent extends UIRenderComponent {
return canRender;
}
protected _instanceMaterial () {
if (this._sharedMaterial) {
this._updateMaterial(
Material.getInstantiatedMaterial(this._sharedMaterial,
new RenderableComponent(),
CC_EDITOR ? true : false,
));
} else {
this._updateMaterial(
Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'),
new RenderableComponent(),
CC_EDITOR ? true : false,
));
}
}
private _flushAssembler () {
const assembler = SpriteComponent.Assembler!.getAssembler(this);
+15 -8
View File
@@ -38,7 +38,6 @@ import { GFXBlendFactor } from '../../../gfx/define';
import { RenderData } from '../../../renderer/ui/renderData';
import { UI } from '../../../renderer/ui/ui';
import { Material } from '../../assets/material';
import { RenderableComponent } from '../../framework/renderable-component';
import { IAssembler, IAssemblerManager } from '../assembler/assembler';
import { CanvasComponent } from './canvas-component';
import { UITransformComponent } from './ui-transfrom-component';
@@ -120,6 +119,10 @@ export class UIRenderComponent extends Component {
}
set priority (value) {
if (this._priority === value) {
return;
}
this._priority = value;
}
@@ -160,7 +163,9 @@ export class UIRenderComponent extends Component {
}
this._sharedMaterial = value;
this._instanceMaterial();
if (this._instanceMaterial) {
this._instanceMaterial();
}
}
get material () {
@@ -226,7 +231,9 @@ export class UIRenderComponent extends Component {
}
public __preload (){
this._instanceMaterial();
if (this._instanceMaterial) {
this._instanceMaterial();
}
}
public onEnable () {
@@ -271,6 +278,10 @@ export class UIRenderComponent extends Component {
// }
// this._allocedDatas.length = 0;
this.destroyRenderData();
if (this._material){
this._material.destroy();
}
this._updateMaterial(null);
this._renderData = null;
}
@@ -381,11 +392,7 @@ export class UIRenderComponent extends Component {
}
}
private _instanceMaterial (){
if (this._sharedMaterial) {
this._updateMaterial(Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false));
}
}
protected _instanceMaterial? (): void;
}
cc.UIRenderComponent = UIRenderComponent;
+8 -7
View File
@@ -32,6 +32,7 @@ import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat,
import { GFXDevice } from '../gfx/device';
import { GFXTexture, IGFXTextureInfo } from '../gfx/texture';
import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view';
import { SamplerInfoIndex } from '../renderer/core/sampler-lib';
import { Asset } from './asset';
import { ImageAsset } from './image-asset';
@@ -313,10 +314,10 @@ export class TextureBase extends EventTargetFactory(Asset) {
* @param wrapR
*/
public setWrapMode (wrapS: WrapMode, wrapT: WrapMode, wrapR?: WrapMode) {
if (wrapS !== this._wrapS) { this._wrapS = wrapS; this._samplerInfo[3] = wrapS; }
if (wrapT !== this._wrapT) { this._wrapT = wrapT; this._samplerInfo[4] = wrapT; }
if (wrapS !== this._wrapS) { this._wrapS = wrapS; this._samplerInfo[SamplerInfoIndex.addressU] = wrapS; }
if (wrapT !== this._wrapT) { this._wrapT = wrapT; this._samplerInfo[SamplerInfoIndex.addressV] = wrapT; }
if (wrapR === undefined) { return; }
if (wrapR !== this._wrapR) { this._wrapR = wrapR; this._samplerInfo[5] = wrapR; }
if (wrapR !== this._wrapR) { this._wrapR = wrapR; this._samplerInfo[SamplerInfoIndex.addressW] = wrapR; }
}
/**
@@ -326,8 +327,8 @@ export class TextureBase extends EventTargetFactory(Asset) {
* @param magFilter
*/
public setFilters (minFilter: Filter, magFilter: Filter) {
if (minFilter !== this._minFilter) { this._minFilter = minFilter; this._samplerInfo[0] = minFilter; }
if (magFilter !== this._magFilter) { this._magFilter = magFilter; this._samplerInfo[1] = magFilter; }
if (minFilter !== this._minFilter) { this._minFilter = minFilter; this._samplerInfo[SamplerInfoIndex.minFilter] = minFilter; }
if (magFilter !== this._magFilter) { this._magFilter = magFilter; this._samplerInfo[SamplerInfoIndex.magFilter] = magFilter; }
}
/**
@@ -336,7 +337,7 @@ export class TextureBase extends EventTargetFactory(Asset) {
* @param mipFilter
*/
public setMipFilter (mipFilter: Filter) {
if (mipFilter !== this._mipFilter) { this._mipFilter = mipFilter; this._samplerInfo[2] = mipFilter; }
if (mipFilter !== this._mipFilter) { this._mipFilter = mipFilter; this._samplerInfo[SamplerInfoIndex.mipFilter] = mipFilter; }
}
/**
@@ -365,7 +366,7 @@ export class TextureBase extends EventTargetFactory(Asset) {
* @param anisotropy
*/
public setAnisotropy (anisotropy: number) {
if (anisotropy !== this._anisotropy) { this._anisotropy = anisotropy; this._samplerInfo[6] = anisotropy; }
if (anisotropy !== this._anisotropy) { this._anisotropy = anisotropy; this._samplerInfo[SamplerInfoIndex.maxAnisotropy] = anisotropy; }
}
/**
+26
View File
@@ -138,6 +138,19 @@ export abstract class GFXInputAssembler extends GFXObject {
drawInfo.firstInstance = this._firstInstance;
}
/**
* update VB data on the fly.
* @param vbuffer - an ArrayBuffer containing the full VB
* @param attr - name of the attribute to update (default names are specified in GFXAttributeName)
* @param data - the new VB attribute data to be uploaded
* @example
* // get VB array buffer from mesh, better to cache this somewhere convenient
* const vbInfo = mesh.struct.vertexBundles[0].data;
* const vbuffer = mesh.data.buffer.slice(vbInfo.offset, vbInfo.offset + vbInfo.length);
* const submodel = someModelComponent.model.getSubModel(0);
* // say the new positions is stored in 'data' as a plain array
* submodel.inputAssembler.updateVertexBuffer(vbuffer, cc.GFXAttributeName.ATTR_POSITION, data);
*/
public updateVertexAttr (vbuffer: GFXBufferSource, attr: string, data: number[]) {
let offset = 0;
let count = 0;
@@ -166,6 +179,19 @@ export abstract class GFXInputAssembler extends GFXObject {
vb.update(vbuffer);
}
/**
* update IB data on the fly.
* need to call submodel.updateCommandBuffer after this if index count changed
* @param ibuffer - an ArrayBuffer containing the full IB
* @param data - the new IB data to be uploaded
* @example
* // get IB array buffer from mesh, better to cache this somewhere convenient
* const ibInfo = mesh.struct.primitives[0].indices.range;
* submesh.ibuffer = mesh.data.buffer.slice(ibInfo.offset, ibInfo.offset + ibInfo.length);
* const submodel = someModelComponent.model.getSubModel(0);
* submodel.inputAssembler.updateIndexBuffer(ibuffer, [0, 1, 2]);
* submodel.updateCommandBuffer(); // index count changed
*/
public updateIndexBuffer (ibuffer: GFXBufferSource, data: number[]) {
const count = this._indexCount;
const ib = this._indexBuffer;
+4 -1
View File
@@ -312,10 +312,13 @@ export class WebGLGFXDevice extends GFXDevice {
// console.info('MAX_VERTEX_ATTRIBS: ' + this._maxVertexAttributes);
console.info('MAX_VERTEX_UNIFORM_VECTORS: ' + this._maxVertexUniformVectors);
console.info('MAX_FRAGMENT_UNIFORM_VECTORS: ' + this._maxFragmentUniformVectors);
console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits);
// console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits);
// console.info('MAX_VERTEX_TEXTURE_IMAGE_UNITS: ' + this._maxVertexTextureUnits);
console.info('DEPTH_BITS: ' + this._depthBits);
console.info('STENCIL_BITS: ' + this._stencilBits);
if (this._EXT_texture_filter_anisotropic) {
console.info('MAX_TEXTURE_MAX_ANISOTROPY_EXT: ' + this._EXT_texture_filter_anisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
}
console.info('USE_VAO: ' + this._useVAO);
// init states
-11
View File
@@ -1516,8 +1516,6 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
let gpuShader: WebGL2GPUShader | null = null;
let gpuInputAssembler: IWebGL2GPUInputAssembler | null = null;
let glPrimitive = WebGL2RenderingContext.TRIANGLES;
let glWrapS;
let glWrapT;
for (let i = 0; i < cmdPackage.cmds.length; ++i) {
const cmd = cmdPackage.cmds.array[i];
@@ -2015,15 +2013,6 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
}
}
const gpuSampler = gpuBinding.gpuSampler;
if (gpuTexture.isPowerOf2) {
glWrapS = gpuSampler.glWrapS;
glWrapT = gpuSampler.glWrapT;
} else {
glWrapS = WebGLRenderingContext.CLAMP_TO_EDGE;
glWrapT = WebGLRenderingContext.CLAMP_TO_EDGE;
}
if (cache.glSamplerUnits[texUnit] !== gpuBinding.gpuSampler.glSampler) {
gl.bindSampler(texUnit, gpuBinding.gpuSampler.glSampler);
cache.glSamplerUnits[texUnit] = gpuBinding.gpuSampler.glSampler;
+6 -3
View File
@@ -3,7 +3,7 @@ import { GFXBindingLayout, IGFXBindingLayoutInfo } from '../binding-layout';
import { GFXBuffer, IGFXBufferInfo } from '../buffer';
import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator';
import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer';
import { GFXBufferTextureCopy, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXQueueType } from '../define';
import { GFXBufferTextureCopy, GFXFormat, GFXFormatSize, GFXQueueType } from '../define';
import { GFXAPI, GFXDevice, GFXFeature, IGFXDeviceInfo } from '../device';
import { GFXFramebuffer, IGFXFramebufferInfo } from '../framebuffer';
import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler';
@@ -20,7 +20,7 @@ import { WebGL2GFXBindingLayout } from './webgl2-binding-layout';
import { WebGL2GFXBuffer } from './webgl2-buffer';
import { WebGL2GFXCommandAllocator } from './webgl2-command-allocator';
import { WebGL2GFXCommandBuffer } from './webgl2-command-buffer';
import { WebGL2CmdFuncCopyTexImagesToTexture, WebGL2CmdFuncCopyBuffersToTexture } from './webgl2-commands';
import { WebGL2CmdFuncCopyBuffersToTexture, WebGL2CmdFuncCopyTexImagesToTexture } from './webgl2-commands';
import { WebGL2GFXFramebuffer } from './webgl2-framebuffer';
import { WebGL2GFXInputAssembler } from './webgl2-input-assembler';
import { WebGL2GFXPipelineLayout } from './webgl2-pipeline-layout';
@@ -229,7 +229,7 @@ export class WebGL2GFXDevice extends GFXDevice {
// console.info('MAX_VERTEX_ATTRIBS: ' + this._maxVertexAttributes);
console.info('MAX_VERTEX_UNIFORM_VECTORS: ' + this._maxVertexUniformVectors);
console.info('MAX_FRAGMENT_UNIFORM_VECTORS: ' + this._maxFragmentUniformVectors);
console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits);
// console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits);
// console.info('MAX_VERTEX_TEXTURE_IMAGE_UNITS: ' + this._maxVertexTextureUnits);
console.info('MAX_UNIFORM_BUFFER_BINDINGS: ' + this._maxUniformBufferBindings);
// console.info('MAX_UNIFORM_BLOCK_SIZE: ' + this._maxUniformBlockSize);
@@ -237,6 +237,9 @@ export class WebGL2GFXDevice extends GFXDevice {
console.info('DEPTH_BITS: ' + this._depthBits);
console.info('STENCIL_BITS: ' + this._stencilBits);
// console.info('UNIFORM_BUFFER_OFFSET_ALIGNMENT: ' + uboOffsetAlignment);
if (this._EXT_texture_filter_anisotropic) {
console.info('MAX_TEXTURE_MAX_ANISOTROPY_EXT: ' + this._EXT_texture_filter_anisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
}
console.info('USE_VAO: ' + this._useVAO);
// init states
+7 -1
View File
@@ -290,7 +290,13 @@ export function loadUuid (item, callback) {
cc.deserialize.Details.pool.put(tdInfo);
var wrappedCallback = function(err, asset) {
if (!err && asset.onLoaded) asset.onLoaded();
if (!err && asset.onLoaded) {
try {
asset.onLoaded();
} catch(error) {
err = error;
}
}
callback(err, asset);
};
+15 -41
View File
@@ -1,9 +1,12 @@
import { GFXBuffer } from '../gfx/buffer';
import { GFXBindingType, GFXType, IGFXColor } from '../gfx/define';
import { GFXBindingType, GFXType } from '../gfx/define';
import { GFXSampler } from '../gfx/sampler';
import { GFXUniformBlock, GFXUniformSampler } from '../gfx/shader';
import { GFXTextureView } from '../gfx/texture-view';
import { Vec3 } from '../core/value-types';
export const PIPELINE_FLOW_FORWARD: string = 'ForwardFlow';
export const PIPELINE_FLOW_SMAA: string = 'SMAAFlow';
export const PIPELINE_FLOW_TONEMAP: string = 'ToneMapFlow';
export enum RenderPassStage {
DEFAULT = 100,
@@ -33,7 +36,8 @@ export class UBOGlobal {
public static TIME_OFFSET: number = 0;
public static SCREEN_SIZE_OFFSET: number = UBOGlobal.TIME_OFFSET + 4;
public static SCREEN_SCALE_OFFSET: number = UBOGlobal.SCREEN_SIZE_OFFSET + 4;
public static MAT_VIEW_OFFSET: number = UBOGlobal.SCREEN_SCALE_OFFSET + 4;
public static NATIVE_SIZE_OFFSET: number = UBOGlobal.SCREEN_SCALE_OFFSET + 4;
public static MAT_VIEW_OFFSET: number = UBOGlobal.NATIVE_SIZE_OFFSET + 4;
public static MAT_VIEW_INV_OFFSET: number = UBOGlobal.MAT_VIEW_OFFSET + 16;
public static MAT_PROJ_OFFSET: number = UBOGlobal.MAT_VIEW_INV_OFFSET + 16;
public static MAT_PROJ_INV_OFFSET: number = UBOGlobal.MAT_PROJ_OFFSET + 16;
@@ -53,6 +57,7 @@ export class UBOGlobal {
{ name: 'cc_time', type: GFXType.FLOAT4, count: 1 },
{ name: 'cc_screenSize', type: GFXType.FLOAT4, count: 1 },
{ name: 'cc_screenScale', type: GFXType.FLOAT4, count: 1 },
{ name: 'cc_nativeSize', type: GFXType.FLOAT4, count: 1 },
{ name: 'cc_matView', type: GFXType.MAT4, count: 1 },
{ name: 'cc_matViewInv', type: GFXType.MAT4, count: 1 },
{ name: 'cc_matProj', type: GFXType.MAT4, count: 1 },
@@ -114,9 +119,10 @@ export class UBOForwardLight {
public static SPHERE_LIGHT_POS_OFFSET: number = 0;
public static SPHERE_LIGHT_SIZE_RANGE_OFFSET: number = UBOForwardLight.SPHERE_LIGHT_POS_OFFSET + UBOForwardLight.MAX_SPHERE_LIGHTS * 4;
public static SPHERE_LIGHT_COLOR_OFFSET: number = UBOForwardLight.SPHERE_LIGHT_SIZE_RANGE_OFFSET + UBOForwardLight.MAX_SPHERE_LIGHTS * 4;
public static SPOT_LIGHT_POS_SIZE_OFFSET: number = UBOForwardLight.SPHERE_LIGHT_COLOR_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4;
public static SPOT_LIGHT_DIR_RANGE_OFFSET: number = UBOForwardLight.SPOT_LIGHT_POS_SIZE_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4;
public static SPOT_LIGHT_COLOR_OFFSET: number = UBOForwardLight.SPOT_LIGHT_DIR_RANGE_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4;
public static SPOT_LIGHT_POS_OFFSET: number = UBOForwardLight.SPHERE_LIGHT_COLOR_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4;
public static SPOT_LIGHT_SIZE_RANGE_ANGLE_OFFSET: number = UBOForwardLight.SPOT_LIGHT_POS_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4;
public static SPOT_LIGHT_DIR_OFFSET: number = UBOForwardLight.SPOT_LIGHT_SIZE_RANGE_ANGLE_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4;
public static SPOT_LIGHT_COLOR_OFFSET: number = UBOForwardLight.SPOT_LIGHT_DIR_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4;
public static COUNT: number = UBOForwardLight.SPOT_LIGHT_COLOR_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4;
public static SIZE: number = UBOForwardLight.COUNT * 4;
@@ -125,8 +131,9 @@ export class UBOForwardLight {
{ name: 'cc_sphereLitPos', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPHERE_LIGHTS },
{ name: 'cc_sphereLitSizeRange', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPHERE_LIGHTS },
{ name: 'cc_sphereLitColor', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPHERE_LIGHTS },
{ name: 'cc_spotLitPosSize', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS },
{ name: 'cc_spotLitDirRange', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS },
{ name: 'cc_spotLitPos', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS },
{ name: 'cc_spotLitSizeRangeAngle', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS },
{ name: 'cc_spotLitDir', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS },
{ name: 'cc_spotLitColor', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS },
],
};
@@ -175,36 +182,3 @@ export interface IInternalBindingInst extends IInternalBindingDesc {
sampler?: GFXSampler;
textureView?: GFXTextureView;
}
export function SRGBToLinear (gamma: IGFXColor): IGFXColor {
const r = Math.pow(gamma.r, 2.2);
const g = Math.pow(gamma.g, 2.2);
const b = Math.pow(gamma.b, 2.2);
return { r, g, b, a: 1.0 };
}
export function LinearToSRGB (linear: IGFXColor): IGFXColor {
const r = Math.pow(linear.r, 0.454545);
const g = Math.pow(linear.g, 0.454545);
const b = Math.pow(linear.b, 0.454545);
return { r, g, b, a: 1.0 };
}
// Color temperature (in Kelvin) to RGB script.
// Valid from 1000 to 40000 K (and additionally 0 for pure full white)
export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) {
const temp = kelvin / 100.0;
if (temp <= 66.0) {
rgb.x = 1.0;
rgb.y = 0.390081579 * Math.log(temp) - 0.631841444;
if (temp <= 19.0) {
rgb.z = 0.0;
} else {
rgb.z = 0.543206789 * Math.log(temp - 10.0) - 1.19625409;
}
} else {
rgb.x = 1.29293619 * Math.pow(temp - 60.0, -0.1332047592);
rgb.y = 11.3259693 * Math.pow(temp - 60.0, -0.0755148492);
rgb.z = 1.0;
}
}
-2
View File
@@ -25,8 +25,6 @@ export class ForwardFlow extends RenderFlow {
this.createStage(ForwardStage, {
name: 'ForwardStage',
priority: ForwardStagePriority.FORWARD,
framebuffer: this._pipeline.shadingFBO,
// framebuffer,
});
return true;
+49 -63
View File
@@ -5,18 +5,18 @@ import { v3 } from '../../core/value-types/vec3';
import { vec3 } from '../../core/vmath';
import { GFXBuffer } from '../../gfx/buffer';
import { GFXBindingType, GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define';
import { GFXFeature } from '../../gfx/device';
import { GFXRenderPass } from '../../gfx/render-pass';
import { Light, Model } from '../../renderer';
import { DirectionalLight } from '../../renderer/scene/directional-light';
import { LightType } from '../../renderer/scene/light';
import { SphereLight } from '../../renderer/scene/sphere-light';
import { SpotLight } from '../../renderer/scene/spot-light';
import { RenderPassStage, UBOForwardLight } from '../define';
import { PIPELINE_FLOW_FORWARD, PIPELINE_FLOW_TONEMAP, RenderPassStage, UBOForwardLight, PIPELINE_FLOW_SMAA } from '../define';
import { ToneMapFlow } from '../ppfx/tonemap-flow';
import { IRenderPipelineInfo, RenderPipeline } from '../render-pipeline';
import { RenderView } from '../render-view';
import { ForwardFlow } from './forward-flow';
import { SMAAEdgeFlow } from '../ppfx/smaa-flow';
export enum ForwardFlowPriority {
FORWARD = 0,
@@ -49,24 +49,26 @@ export class ForwardPipeline extends RenderPipeline {
public initialize (info: IRenderPipelineInfo): boolean {
if (this._device.hasFeature(GFXFeature.FORMAT_R11G11B10F) ||
this._device.hasFeature(GFXFeature.TEXTURE_HALF_FLOAT) ||
this._device.hasFeature(GFXFeature.TEXTURE_FLOAT)) {
this._isHDRSupported = true;
}
// this._isHDRSupported = false;
if (!this.createShadingTarget(info)) {
if (!this._initialize(info)) {
return false;
}
if (!this.createQuadInputAssembler()) {
return false;
}
if (!this._globalBindings.get(UBOForwardLight.BLOCK.name)) {
const lightsUBO = this._root.device.createBuffer({
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: UBOForwardLight.SIZE,
});
if (!this.createUBOs()) {
return false;
if (!lightsUBO) {
return false;
}
this._globalBindings.set(UBOForwardLight.BLOCK.name, {
type: GFXBindingType.UNIFORM_BUFFER,
blockInfo: UBOForwardLight.BLOCK,
buffer: lightsUBO,
});
}
const mainWindow = this._root.mainWindow;
@@ -87,12 +89,19 @@ export class ForwardPipeline extends RenderPipeline {
// create flows
this.createFlow(ForwardFlow, {
name: 'ForwardFlow',
name: PIPELINE_FLOW_FORWARD,
priority: ForwardFlowPriority.FORWARD,
});
/*
this.createFlow(SMAAEdgeFlow, {
name: PIPELINE_FLOW_SMAA,
priority: 0,
});
*/
this.createFlow(ToneMapFlow, {
name: 'ToneMapFlow',
name: PIPELINE_FLOW_TONEMAP,
priority: 0,
});
@@ -100,45 +109,13 @@ export class ForwardPipeline extends RenderPipeline {
}
public destroy () {
this.destroyFlows();
this.clearRenderPasses();
this.destroyUBOs();
this.destroyQuadInputAssembler();
this.destroyShadingTarget();
}
protected createUBOs (): boolean {
super.createUBOs();
if (!this._globalBindings.get(UBOForwardLight.BLOCK.name)) {
const lightsUBO = this._root.device.createBuffer({
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: UBOForwardLight.SIZE,
});
if (!lightsUBO) {
return false;
}
this._globalBindings.set(UBOForwardLight.BLOCK.name, {
type: GFXBindingType.UNIFORM_BUFFER,
blockInfo: UBOForwardLight.BLOCK,
buffer: lightsUBO,
});
}
return true;
}
protected destroyUBOs () {
super.destroyUBOs();
const lightsUBO = this._globalBindings.get(UBOForwardLight.BLOCK.name);
if (lightsUBO) {
lightsUBO.buffer!.destroy();
this._globalBindings.delete(UBOForwardLight.BLOCK.name);
}
this._destroy();
}
protected updateUBOs (view: RenderView) {
@@ -166,11 +143,13 @@ export class ForwardPipeline extends RenderPipeline {
if (sphereNum >= UBOForwardLight.MAX_SPHERE_LIGHTS) {
continue;
}
vec3.array(_vec4Array, (light as SphereLight).position);
const sphereLit = light as SphereLight;
vec3.array(_vec4Array, sphereLit.position);
this._uboLights.view.set(_vec4Array, UBOForwardLight.SPHERE_LIGHT_POS_OFFSET + sphereNum * 4);
_vec4Array[0] = (light as SphereLight).size;
_vec4Array[1] = (light as SphereLight).range;
_vec4Array[0] = sphereLit.size;
_vec4Array[1] = sphereLit.range;
_vec4Array[2] = 0.0;
this._uboLights.view.set(_vec4Array, UBOForwardLight.SPHERE_LIGHT_SIZE_RANGE_OFFSET + sphereNum * 4);
@@ -181,7 +160,7 @@ export class ForwardPipeline extends RenderPipeline {
_vec4Array[1] *= tempRGB.y;
_vec4Array[2] *= tempRGB.z;
}
_vec4Array[3] = (light as SphereLight).luminance * 10000.0;
_vec4Array[3] = sphereLit.luminance * 10000.0;
this._uboLights.view.set(_vec4Array, UBOForwardLight.SPHERE_LIGHT_COLOR_OFFSET + sphereNum * 4);
sphereNum++;
break;
@@ -189,13 +168,20 @@ export class ForwardPipeline extends RenderPipeline {
if (spotNum >= UBOForwardLight.MAX_SPOT_LIGHTS) {
continue;
}
vec3.array(_vec4Array, (light as SpotLight).position);
_vec4Array[3] = (light as SpotLight).size;
this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_POS_SIZE_OFFSET + spotNum * 4);
vec3.array(_vec4Array, (light as SpotLight).direction);
_vec4Array[3] = (light as SpotLight).range;
this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_DIR_RANGE_OFFSET + spotNum * 4);
const spotLit = light as SpotLight;
vec3.array(_vec4Array, spotLit.position);
_vec4Array[3] = spotLit.size;
this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_POS_OFFSET + spotNum * 4);
_vec4Array[0] = spotLit.size;
_vec4Array[1] = spotLit.range;
_vec4Array[2] = spotLit.spotAngle;
this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_SIZE_RANGE_ANGLE_OFFSET + spotNum * 4);
vec3.array(_vec4Array, spotLit.direction);
this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_DIR_OFFSET + spotNum * 4);
vec3.array(_vec4Array, light.color);
if (light.useColorTemperature) {
@@ -204,7 +190,7 @@ export class ForwardPipeline extends RenderPipeline {
_vec4Array[1] *= tempRGB.y;
_vec4Array[2] *= tempRGB.z;
}
_vec4Array[3] = (light as SpotLight).luminance * 10000.0;
_vec4Array[3] = spotLit.luminance * 10000.0;
this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_COLOR_OFFSET + spotNum * 4);
spotNum++;
break;
+4 -3
View File
@@ -1,6 +1,6 @@
import { GFXCommandBuffer } from '../../gfx/command-buffer';
import { GFXCommandBufferType, IGFXColor, GFXClearFlag } from '../../gfx/define';
import { SRGBToLinear } from '../define';
import { GFXClearFlag, GFXCommandBufferType, IGFXColor } from '../../gfx/define';
import { SRGBToLinear } from '../pipeline-funcs';
import { RenderFlow } from '../render-flow';
import { IRenderStageInfo, RenderStage } from '../render-stage';
import { RenderView } from '../render-view';
@@ -21,7 +21,6 @@ export class ForwardStage extends RenderStage {
}
this._priority = info.priority;
this._framebuffer = info.framebuffer;
this._cmdBuff = this._device.createCommandBuffer({
allocator: this._device.commandAllocator,
@@ -65,6 +64,8 @@ export class ForwardStage extends RenderStage {
colors.length = 1;
}
this._framebuffer = this._pipeline.curShadingFBO;
cmdBuff.begin();
cmdBuff.beginRenderPass(this._framebuffer!, this._renderArea,
camera.clearFlag, colors, camera.clearDepth, camera.clearStencil);
+15
View File
@@ -0,0 +1,15 @@
import { IGFXColor } from '../gfx/define';
export function SRGBToLinear (gamma: IGFXColor): IGFXColor {
const r = Math.pow(gamma.r, 2.2);
const g = Math.pow(gamma.g, 2.2);
const b = Math.pow(gamma.b, 2.2);
return { r, g, b, a: 1.0 };
}
export function LinearToSRGB (linear: IGFXColor): IGFXColor {
const r = Math.pow(linear.r, 0.454545);
const g = Math.pow(linear.g, 0.454545);
const b = Math.pow(linear.b, 0.454545);
return { r, g, b, a: 1.0 };
}
File diff suppressed because one or more lines are too long
+82
View File
@@ -0,0 +1,82 @@
import { GFXBindingLayout } from '../../gfx/binding-layout';
import { GFXClearFlag, GFXCommandBufferType } from '../../gfx/define';
import { UBOGlobal } from '../define';
import { RenderFlow } from '../render-flow';
import { IRenderStageInfo, RenderStage } from '../render-stage';
import { RenderView } from '../render-view';
export class SMAAEdgeStage extends RenderStage {
private _hTexSampler: number = 0;
private _bindingLayout: GFXBindingLayout | null = null;
constructor (flow: RenderFlow) {
super(flow);
}
public initialize (info: IRenderStageInfo): boolean {
if (info.name !== undefined) {
this._name = info.name;
}
this._priority = info.priority;
if (info.framebuffer !== undefined) {
this._framebuffer = info.framebuffer ;
}
this._cmdBuff = this._device.createCommandBuffer({
allocator: this._device.commandAllocator,
type: GFXCommandBufferType.PRIMARY,
});
this._pass = this._flow.material.passes[0];
this._hTexSampler = this._pass.getBinding('u_texSampler');
const globalUBO = this._pipeline.globalBindings.get(UBOGlobal.BLOCK.name);
this._pso = this._pass.createPipelineState();
this._bindingLayout = this._pso!.pipelineLayout.layouts[0];
this._pass.bindBuffer(UBOGlobal.BLOCK.binding, globalUBO!.buffer!);
this._pass.bindTextureView(this._hTexSampler, this._pipeline.curShadingTexView);
this._pass.update();
this._bindingLayout.update();
return true;
}
public destroy () {
if (this._cmdBuff) {
this._cmdBuff.destroy();
this._cmdBuff = null;
}
}
public resize (width: number, height: number) {
}
public render (view: RenderView) {
const camera = view.camera!;
if (this._cmdBuff) {
this._renderArea.width = camera.width;
this._renderArea.height = camera.height;
this._cmdBuff.begin();
this._cmdBuff.beginRenderPass(this._framebuffer!, this._renderArea,
GFXClearFlag.ALL, [{ r: 0.0, g: 0.0, b: 0.0, a: 1.0 }], 1.0, 0);
this._cmdBuff.bindPipelineState(this._pso!);
this._cmdBuff.bindBindingLayout(this._bindingLayout!);
this._cmdBuff.bindInputAssembler(this._pipeline.quadIA);
this._cmdBuff.draw(this._pipeline.quadIA);
this._cmdBuff.endRenderPass();
this._cmdBuff.end();
}
this._device.queue.submit([this._cmdBuff!]);
}
}
+45
View File
@@ -0,0 +1,45 @@
import { IRenderFlowInfo, RenderFlow } from '../render-flow';
import { RenderPipeline } from '../render-pipeline';
import { SMAAEdgeStage } from './smaa-edge-stage';
import { SMAABlendStage } from './smaa-blend-stage';
export class SMAAEdgeFlow extends RenderFlow {
constructor (pipeline: RenderPipeline) {
super(pipeline);
}
public initialize (info: IRenderFlowInfo): boolean {
if (info.name !== undefined) {
this._name = info.name;
}
this._priority = info.priority;
const material = new cc.Material();
material.initialize({
effectName: 'builtin-smaa',
});
this._material = material;
this.createStage(SMAAEdgeStage, {
name: 'SMAAEdgeStage',
priority: 0,
framebuffer: this._pipeline.smaaEdgeFBO,
});
this.createStage(SMAABlendStage, {
name: 'SMAABlendStage',
priority: 0,
framebuffer: this._pipeline.smaaBlendFBO,
});
return true;
}
public destroy (): void {
this.destroyStages();
}
}
+22 -11
View File
@@ -1,15 +1,17 @@
import { GFXBindingLayout } from '../../gfx/binding-layout';
import { GFXCommandBuffer } from '../../gfx/command-buffer';
import { GFXCommandBufferType, IGFXColor, GFXClearFlag } from '../../gfx/define';
import { GFXClearFlag, GFXCommandBufferType, IGFXColor } from '../../gfx/define';
import { UBOGlobal } from '../define';
import { RenderFlow } from '../render-flow';
import { IRenderStageInfo, RenderStage } from '../render-stage';
import { RenderView } from '../render-view';
const colors: IGFXColor[] = [];
const bufs: GFXCommandBuffer[] = [];
export class ToneMapStage extends RenderStage {
private _hTexSampler: number = 0;
private _hBlendTexSampler: number = 0;
private _bindingLayout: GFXBindingLayout | null = null;
constructor (flow: RenderFlow) {
super(flow);
}
@@ -21,7 +23,10 @@ export class ToneMapStage extends RenderStage {
}
this._priority = info.priority;
this._framebuffer = info.framebuffer;
if (info.framebuffer !== undefined) {
this._framebuffer = info.framebuffer ;
}
this._cmdBuff = this._device.createCommandBuffer({
allocator: this._device.commandAllocator,
@@ -29,15 +34,19 @@ export class ToneMapStage extends RenderStage {
});
this._pass = this._flow.material.passes[0];
const binding = this._pass.getBinding('u_texSampler');
this._hTexSampler = this._pass.getBinding('u_texSampler');
this._hBlendTexSampler = this._pass.getBinding('u_blendTexSampler');
const globalUBO = this._pipeline.globalBindings.get(UBOGlobal.BLOCK.name);
this._pass.bindBuffer(UBOGlobal.BLOCK.binding, globalUBO!.buffer!);
this._pass.bindTextureView(binding, this._pipeline.shadingTexView);
this._pass.update();
this._pso = this._pass.createPipelineState();
this._pso!.pipelineLayout.layouts[0].update();
this._bindingLayout = this._pso!.pipelineLayout.layouts[0];
this._pass.bindBuffer(UBOGlobal.BLOCK.binding, globalUBO!.buffer!);
this._pass.bindTextureView(this._hTexSampler, this._pipeline.curShadingTexView);
// this._pass.bindTextureView(this._hBlendTexSampler, this._pipeline.smaaBlendTexView);
this._pass.update();
this._bindingLayout.update();
return true;
}
@@ -60,7 +69,7 @@ export class ToneMapStage extends RenderStage {
this._renderArea.width = camera.width;
this._renderArea.height = camera.height;
const framebuffer = !view.isOffscreen? view.window!.framebuffer : view.framebuffer;
const framebuffer = !view.isOffscreen ? view.window!.framebuffer : view.framebuffer;
this._cmdBuff.begin();
this._cmdBuff.beginRenderPass(framebuffer, this._renderArea,
@@ -74,5 +83,7 @@ export class ToneMapStage extends RenderStage {
}
this._device.queue.submit([this._cmdBuff!]);
// this._pipeline.swapFBOs();
}
}
+8
View File
@@ -19,10 +19,18 @@ export abstract class RenderFlow {
return this._pipeline;
}
public get name (): string {
return this._name;
}
public get priority (): number {
return this._priority;
}
public get stages (): RenderStage[] {
return this._stages!;
}
public get material (): Material {
return this._material!;
}
+248 -61
View File
@@ -64,18 +64,42 @@ export abstract class RenderPipeline {
return this._isHDR;
}
public get shadingTexView (): GFXTextureView {
return this._shadingTexView!;
}
public get shadingFBO (): GFXFramebuffer {
return this._shadingFBO!;
}
public get depthStencilTexView (): GFXTextureView {
return this._depthStencilTexView!;
}
public get curShadingTexView (): GFXTextureView {
return this._shadingTexViews[this._curIdx];
}
public get prevShadingTexView (): GFXTextureView {
return this._shadingTexViews[this._prevIdx];
}
public get curShadingFBO (): GFXFramebuffer {
return this._shadingFBOs[this._curIdx];
}
public get prevShadingFBO (): GFXFramebuffer {
return this._shadingFBOs[this._prevIdx];
}
public get smaaEdgeTexView (): GFXTextureView {
return this._smaaEdgeTexView!;
}
public get smaaEdgeFBO (): GFXFramebuffer {
return this._smaaEdgeFBO!;
}
public get smaaBlendTexView (): GFXTextureView {
return this._smaaBlendTexView!;
}
public get smaaBlendFBO (): GFXFramebuffer {
return this._smaaBlendFBO!;
}
public get quadIA (): GFXInputAssembler {
return this._quadIA!;
}
@@ -108,11 +132,24 @@ export abstract class RenderPipeline {
protected _isHDRSupported: boolean = false;
protected _isHDR: boolean = false;
protected _shadingPass: GFXRenderPass | null = null;
protected _shadingTex: GFXTexture | null = null;
protected _shadingTexView: GFXTextureView | null = null;
protected _fboCount: number = 1;
protected _shadingTextures: GFXTexture[] = [];
protected _shadingTexViews: GFXTextureView[] = [];
protected _depthStencilTex: GFXTexture | null = null;
protected _depthStencilTexView: GFXTextureView | null = null;
protected _shadingFBO: GFXFramebuffer | null = null;
protected _shadingFBOs: GFXFramebuffer[] = [];
protected _shadingTexWidth: number = 0.0;
protected _shadingTexHeight: number = 0.0;
protected _curIdx: number = 0;
protected _prevIdx: number = 1;
protected _useSMAA: boolean = false;
protected _smaaPass: GFXRenderPass | null = null;
protected _smaaEdgeFBO: GFXFramebuffer | null = null;
protected _smaaEdgeTex: GFXTexture | null = null;
protected _smaaEdgeTexView: GFXTextureView | null = null;
protected _smaaBlendFBO: GFXFramebuffer | null = null;
protected _smaaBlendTex: GFXTexture | null = null;
protected _smaaBlendTexView: GFXTextureView | null = null;
protected _quadVB: GFXBuffer | null = null;
protected _quadIB: GFXBuffer | null = null;
protected _quadIA: GFXInputAssembler | null = null;
@@ -152,6 +189,12 @@ export abstract class RenderPipeline {
}
}
public swapFBOs () {
const temp = this._curIdx;
this._curIdx = this._prevIdx;
this._prevIdx = temp;
}
public addRenderPass (stage: number, renderPass: GFXRenderPass) {
if (renderPass) {
this._renderPasses.set(stage, renderPass);
@@ -199,7 +242,31 @@ export abstract class RenderPipeline {
this._flows = [];
}
protected createShadingTarget (info: IRenderPipelineInfo): boolean {
public getFlow (name: string): RenderFlow | null {
for (const flow of this._flows) {
if (flow.name === name) {
return flow;
}
}
return null;
}
protected _initialize (info: IRenderPipelineInfo): boolean {
if (this._device.hasFeature(GFXFeature.FORMAT_R11G11B10F) ||
this._device.hasFeature(GFXFeature.TEXTURE_HALF_FLOAT) ||
this._device.hasFeature(GFXFeature.TEXTURE_FLOAT)) {
this._isHDRSupported = true;
}
// this._isHDRSupported = false;
this._fboCount = 1;
this._shadingTextures = new Array<GFXTexture>(this._fboCount);
this._shadingTexViews = new Array<GFXTextureView>(this._fboCount);
this._shadingFBOs = new Array<GFXFramebuffer>(this._fboCount);
let colorFmt: GFXFormat;
let depthStencilFmt: GFXFormat;
@@ -233,37 +300,22 @@ export abstract class RenderPipeline {
// colorFmt = GFXFormat.RGBA16F;
const scale = 1.0;
const texWidth = Math.min(this._device.width * scale, 2048);
const texHeight = Math.min(this._device.height * scale, 2048);
let screenScale = Math.min(texWidth / this._device.width, texHeight / this._device.height);
screenScale = Math.min(scale, screenScale);
// this._shadingTexWidth = Math.floor(this._device.width * screenScale);
// this._shadingTexHeight = Math.floor(this._device.height * screenScale);
this._shadingTexWidth = this._device.nativeWidth;
this._shadingTexHeight = this._device.nativeHeight;
console.info('CC_USE_HDR: ' + this._isHDR);
console.info('Shading Color Format: ' + GFXFormatInfos[colorFmt].name);
console.info('Shading Depth Format: ' + GFXFormatInfos[depthStencilFmt].name);
this._shadingTex = this._device.createTexture({
type: GFXTextureType.TEX2D,
usage: GFXTextureUsageBit.COLOR_ATTACHMENT | GFXTextureUsageBit.SAMPLED,
format: colorFmt,
width: this._device.nativeWidth,
height: this._device.nativeHeight,
});
this._shadingTexView = this._device.createTextureView({
texture : this._shadingTex,
type : GFXTextureViewType.TV2D,
format : colorFmt,
});
this._depthStencilTex = this._device.createTexture({
type : GFXTextureType.TEX2D,
usage : GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT | GFXTextureUsageBit.SAMPLED,
format : depthStencilFmt,
width : this._device.nativeWidth,
height : this._device.nativeHeight,
});
this._depthStencilTexView = this._device.createTextureView({
texture : this._depthStencilTex,
type : GFXTextureViewType.TV2D,
format : depthStencilFmt,
});
console.info('SHADING_SIZE: ' + this._shadingTexWidth + ' x ' + this._shadingTexHeight);
console.info('SCREEN_SCALE: ' + screenScale);
console.info('SHADING_COLOR_FORMAT: ' + GFXFormatInfos[colorFmt].name);
console.info('SHADING_DEPTH_FORMAT: ' + GFXFormatInfos[depthStencilFmt].name);
this._shadingPass = this._device.createRenderPass({
colorAttachments: [{
@@ -286,26 +338,160 @@ export abstract class RenderPipeline {
},
});
this._shadingFBO = this._device.createFramebuffer({
renderPass: this._shadingPass,
colorViews: [ this._shadingTexView ],
depthStencilView: this._depthStencilTexView!,
this._depthStencilTex = this._device.createTexture({
type : GFXTextureType.TEX2D,
usage : GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT | GFXTextureUsageBit.SAMPLED,
format : depthStencilFmt,
width : this._shadingTexWidth,
height : this._shadingTexHeight,
});
this._depthStencilTexView = this._device.createTextureView({
texture : this._depthStencilTex,
type : GFXTextureViewType.TV2D,
format : depthStencilFmt,
});
for (let i = 0; i < this._fboCount; ++i) {
this._shadingTextures[i] = this._device.createTexture({
type: GFXTextureType.TEX2D,
usage: GFXTextureUsageBit.COLOR_ATTACHMENT | GFXTextureUsageBit.SAMPLED,
format: colorFmt,
width: this._shadingTexWidth,
height: this._shadingTexHeight,
});
this._shadingTexViews[i] = this._device.createTextureView({
texture : this._shadingTextures[i],
type : GFXTextureViewType.TV2D,
format : colorFmt,
});
this._shadingFBOs[i] = this._device.createFramebuffer({
renderPass: this._shadingPass,
colorViews: [ this._shadingTexViews[i] ],
depthStencilView: this._depthStencilTexView!,
});
}
// create smaa framebuffer
const smaaColorFmt = GFXFormat.RGBA8;
this._smaaPass = this._device.createRenderPass({
colorAttachments: [{
format: smaaColorFmt,
loadOp: GFXLoadOp.CLEAR,
storeOp: GFXStoreOp.STORE,
sampleCount: 1,
beginLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL,
endLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL,
}],
});
this._smaaEdgeTex = this._device.createTexture({
type: GFXTextureType.TEX2D,
usage: GFXTextureUsageBit.COLOR_ATTACHMENT | GFXTextureUsageBit.SAMPLED,
format: smaaColorFmt,
width: this._shadingTexWidth,
height: this._shadingTexHeight,
});
this._smaaEdgeTexView = this._device.createTextureView({
texture : this._smaaEdgeTex,
type : GFXTextureViewType.TV2D,
format : smaaColorFmt,
});
this._smaaEdgeFBO = this._device.createFramebuffer({
renderPass: this._smaaPass,
colorViews: [ this._smaaEdgeTexView ],
});
this._smaaBlendTex = this._device.createTexture({
type: GFXTextureType.TEX2D,
usage: GFXTextureUsageBit.COLOR_ATTACHMENT | GFXTextureUsageBit.SAMPLED,
format: smaaColorFmt,
width: this._shadingTexWidth,
height: this._shadingTexHeight,
});
this._smaaBlendTexView = this._device.createTextureView({
texture : this._smaaBlendTex,
type : GFXTextureViewType.TV2D,
format : smaaColorFmt,
});
this._smaaBlendFBO = this._device.createFramebuffer({
renderPass: this._smaaPass,
colorViews: [ this._smaaBlendTexView ],
});
if (!this.createQuadInputAssembler()) {
return false;
}
if (!this.createUBOs()) {
return false;
}
return true;
}
protected destroyShadingTarget () {
if (this._shadingTexView) {
this._shadingTexView.destroy();
this._shadingTexView = null;
protected _destroy () {
this.destroyFlows();
this.clearRenderPasses();
this.destroyQuadInputAssembler();
this.destroyUBOs();
if (this._smaaEdgeTexView) {
this._smaaEdgeTexView.destroy();
this._smaaEdgeTexView = null;
}
if (this._shadingTex) {
this._shadingTex.destroy();
this._shadingTex = null;
if (this._smaaEdgeTex) {
this._smaaEdgeTex.destroy();
this._smaaEdgeTex = null;
}
if (this._smaaEdgeFBO) {
this._smaaEdgeFBO.destroy();
this._smaaEdgeFBO = null;
}
if (this._smaaBlendTexView) {
this._smaaBlendTexView.destroy();
this._smaaBlendTexView = null;
}
if (this._smaaBlendTex) {
this._smaaBlendTex.destroy();
this._smaaBlendTex = null;
}
if (this._smaaBlendFBO) {
this._smaaBlendFBO.destroy();
this._smaaBlendFBO = null;
}
for (let i = 0; i < this._shadingTexViews.length; ++i) {
if (this._shadingTexViews[i]) {
this._shadingTexViews[i].destroy();
}
if (this._shadingTextures[i]) {
this._shadingTextures[i].destroy();
}
if (this._shadingFBOs[i]) {
this._shadingFBOs[i].destroy();
}
}
this._shadingTexViews.splice(0);
this._shadingTextures.splice(0);
this._shadingFBOs.splice(0);
if (this._depthStencilTexView) {
this._depthStencilTexView.destroy();
this._depthStencilTexView = null;
@@ -316,11 +502,6 @@ export abstract class RenderPipeline {
this._depthStencilTex = null;
}
if (this._shadingFBO) {
this._shadingFBO.destroy();
this._shadingFBO = null;
}
if (this._shadingPass) {
this._shadingPass.destroy();
this._shadingPass = null;
@@ -490,8 +671,8 @@ export abstract class RenderPipeline {
this._defaultUboGlobal!.view.set(_vec4Array, UBOGlobal.SCREEN_SIZE_OFFSET);
if (!view.isOffscreen) {
_vec4Array[0] = camera.width / device.nativeWidth;
_vec4Array[1] = camera.height / device.nativeHeight;
_vec4Array[0] = camera.width / this._shadingTexWidth;
_vec4Array[1] = camera.height / this._shadingTexHeight;
} else {
_vec4Array[0] = 1.0;
_vec4Array[1] = 1.0;
@@ -500,6 +681,12 @@ export abstract class RenderPipeline {
_vec4Array[3] = 1.0 / _vec4Array[1];
this._defaultUboGlobal!.view.set(_vec4Array, UBOGlobal.SCREEN_SCALE_OFFSET);
_vec4Array[0] = this._shadingTexWidth;
_vec4Array[1] = this._shadingTexHeight;
_vec4Array[2] = 1.0 / _vec4Array[0];
_vec4Array[3] = 1.0 / _vec4Array[1];
this._defaultUboGlobal!.view.set(_vec4Array, UBOGlobal.NATIVE_SIZE_OFFSET);
mat4.array(_mat4Array, camera.matView);
this._defaultUboGlobal!.view.set(_mat4Array, UBOGlobal.MAT_VIEW_OFFSET);
@@ -558,7 +745,7 @@ export abstract class RenderPipeline {
this._globalBindings.get(UBOGlobal.BLOCK.name)!.buffer!.update(this._defaultUboGlobal!.view.buffer);
const planarShadow = scene.planarShadow;
planarShadow.update(scene.mainLight);
planarShadow.updateDirLight(scene.mainLight);
this._globalBindings.get(UBOShadow.BLOCK.name)!.buffer!.update(planarShadow.data);
}
+3 -4
View File
@@ -2,17 +2,16 @@ import { GFXCommandBuffer } from '../gfx/command-buffer';
import { IGFXColor, IGFXRect } from '../gfx/define';
import { GFXDevice } from '../gfx/device';
import { GFXFramebuffer } from '../gfx/framebuffer';
import { Camera } from '../renderer/scene/camera';
import { GFXPipelineState } from '../gfx/pipeline-state';
import { Pass } from '../renderer';
import { RenderFlow } from './render-flow';
import { RenderPipeline } from './render-pipeline';
import { RenderView } from './render-view';
import { GFXPipelineState } from '../gfx/pipeline-state';
import { Pass } from '../renderer';
export interface IRenderStageInfo {
name?: string;
priority: number;
framebuffer: GFXFramebuffer;
framebuffer?: GFXFramebuffer;
}
export abstract class RenderStage {
+1 -4
View File
@@ -30,10 +30,7 @@ export class UIPipeline extends RenderPipeline {
}
public destroy () {
this.destroyFlows();
this.clearRenderPasses();
this.destroyUBOs();
this.destroyQuadInputAssembler();
this._destroy();
}
protected updateUBOs (view: RenderView) {
+8 -6
View File
@@ -1,11 +1,12 @@
// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
import { EffectAsset } from '../../3d/assets/effect-asset';
import { IDefineMap, IPassInfoFull, Pass } from './pass';
import { IDefineMap, IPassInfoFull, Pass, PassOverrides } from './pass';
export interface IEffectInfo {
techIdx?: number;
defines?: IDefineMap[];
techIdx: number;
defines: IDefineMap[];
states: PassOverrides[];
}
export class Effect {
@@ -13,16 +14,17 @@ export class Effect {
return effect.techniques[techIdx].passes;
}
public static parseEffect (effect: EffectAsset, info?: IEffectInfo) {
public static parseEffect (effect: EffectAsset, info: IEffectInfo) {
// techniques
const { techIdx, defines } = info || {} as IEffectInfo;
const { techIdx, defines, states } = info;
const tech = effect.techniques[techIdx || 0];
const passNum = tech.passes.length;
const passes: Pass[] = [];
for (let k = 0; k < passNum; ++k) {
const passInfo = tech.passes[k] as IPassInfoFull;
const defs = passInfo.curDefs = defines && defines[k] || {};
const defs = passInfo.curDefs = defines.length > k ? defines[k] : {};
if (passInfo.switch && !defs[passInfo.switch]) { continue; }
passInfo.states = states.length > k ? states[k] : {};
passInfo.idxInTech = k;
const pass = new Pass(cc.game._gfxDevice);
pass.initialize(passInfo);
+7 -4
View File
@@ -1,6 +1,6 @@
// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
import { IPassInfo, IShaderInfo } from '../../3d/assets/effect-asset';
import { IPassInfo, IPassStates, IShaderInfo } from '../../3d/assets/effect-asset';
import { builtinResMgr } from '../../3d/builtin';
import { TextureBase } from '../../assets/texture-base';
import { color4, mat2, mat3, mat4, vec2, vec3, vec4 } from '../../core/vmath';
@@ -26,9 +26,9 @@ export interface IPassInfoFull extends IPassInfo {
// generated part
idxInTech: number;
curDefs: IDefineMap;
states: PassOverrides;
}
export type PassOverrides = RecursivePartial<IPassInfo>;
export type PassOverrides = RecursivePartial<IPassStates>;
const _type2fn = {
[GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v,
@@ -135,6 +135,7 @@ export class Pass {
// pipeline state
const device = this._device;
this._fillinPipelineInfo(info);
this._fillinPipelineInfo(info.states);
for (const u of shaderInfo.blocks) {
if (u.name.startsWith('CC')) { continue; }
@@ -171,11 +172,13 @@ export class Pass {
for (const u of shaderInfo.samplers) {
this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding);
const inf = info.properties && info.properties[u.name];
if (inf && inf.sampler) { this._samplers[u.binding] = samplerLib.getSampler(device, inf.sampler); }
const texName = inf && inf.value ? inf.value + '-texture' : _type2default[u.type];
const texture = builtinResMgr.get<TextureBase>(texName);
if (texture) {
this._textureViews[u.binding] = texture.getGFXTextureView()!;
this._samplers[u.binding] = samplerLib.getSampler(device, texture.getGFXSamplerInfo());
const samplerInfo = texture.getGFXSamplerInfo();
if (!this._samplers[u.binding] || samplerInfo.length) { this._samplers[u.binding] = samplerLib.getSampler(device, samplerInfo); }
}
else { console.warn('illegal texture default value ' + texName); }
}
+3 -1
View File
@@ -100,6 +100,8 @@ class ProgramLib {
* programLib.define(program);
*/
public define (prog: IShaderInfo) {
const cur = this._templates[prog.name];
if (cur && cur.hash === prog.hash) { return; }
const tmpl = Object.assign({ id: ++_shdID }, prog) as IProgramInfo;
if (!tmpl.localsInited) { insertBuiltinBindings(tmpl, localBindingsDesc, 'locals'); tmpl.localsInited = true; }
@@ -157,7 +159,7 @@ class ProgramLib {
return name + defs.reduce((acc, cur) => cur.result ? `${acc}|${cur.name}${cur.result}` : acc, '');
}
public getGFXShader (device: GFXDevice, name: string, defines: IDefineMap = {}, pipeline: RenderPipeline) {
public getGFXShader (device: GFXDevice, name: string, defines: IDefineMap, pipeline: RenderPipeline) {
Object.assign(defines, pipeline.macros);
const key = this.getKey(name, defines);
let program = this._cache[key];
+32 -14
View File
@@ -3,6 +3,22 @@
import { GFXDevice } from '../../gfx/device';
import { GFXSampler, IGFXSamplerInfo } from '../../gfx/sampler';
export enum SamplerInfoIndex {
minFilter,
magFilter,
mipFilter,
addressU,
addressV,
addressW,
maxAnisotropy,
cmpFunc,
minLOD,
maxLOD,
mipLODBias,
borderColor,
total = borderColor + 4,
}
const gfxInfo: IGFXSamplerInfo = {};
class SamplerLib {
@@ -12,19 +28,22 @@ class SamplerLib {
const hash = info.toString();
const cache = this._cache[hash];
if (cache) { return cache; }
gfxInfo.minFilter = info[0];
gfxInfo.magFilter = info[1];
gfxInfo.mipFilter = info[2];
gfxInfo.addressU = info[3];
gfxInfo.addressV = info[4];
gfxInfo.addressW = info[5];
gfxInfo.maxAnisotropy = info[6];
if (info.length > 7) {
gfxInfo.cmpFunc = info[7];
gfxInfo.borderColor = { r: info[8], g: info[9], b: info[10], a: info[11] };
gfxInfo.minLOD = info[12];
gfxInfo.maxLOD = info[13];
gfxInfo.mipLODBias = info[14];
gfxInfo.minFilter = info[SamplerInfoIndex.minFilter];
gfxInfo.magFilter = info[SamplerInfoIndex.magFilter];
gfxInfo.mipFilter = info[SamplerInfoIndex.mipFilter];
gfxInfo.addressU = info[SamplerInfoIndex.addressU];
gfxInfo.addressV = info[SamplerInfoIndex.addressV];
gfxInfo.addressW = info[SamplerInfoIndex.addressW];
gfxInfo.maxAnisotropy = info[SamplerInfoIndex.maxAnisotropy];
if (info.length > SamplerInfoIndex.cmpFunc) {
gfxInfo.cmpFunc = info[SamplerInfoIndex.cmpFunc];
gfxInfo.minLOD = info[SamplerInfoIndex.minLOD];
gfxInfo.maxLOD = info[SamplerInfoIndex.maxLOD];
gfxInfo.mipLODBias = info[SamplerInfoIndex.mipLODBias];
if (info.length >= SamplerInfoIndex.total) {
const ofs = SamplerInfoIndex.borderColor;
gfxInfo.borderColor = { r: info[ofs], g: info[ofs + 1], b: info[ofs + 2], a: info[ofs + 3] };
}
}
const sampler = this._cache[hash] = device.createSampler(gfxInfo);
return sampler;
@@ -32,4 +51,3 @@ class SamplerLib {
}
export const samplerLib = new SamplerLib();
cc.samplerLib = samplerLib;
+4
View File
@@ -7,6 +7,10 @@ export { addStage };
export { RenderQueue, PassStage } from './core/constants';
export { Pass } from './core/pass';
export { Effect } from './core/effect';
export { programLib } from './core/program-lib';
import { samplerLib } from './core/sampler-lib';
cc.samplerLib = samplerLib;
export { samplerLib };
export { Light } from './scene/light';
export { Camera } from './scene/camera';
+27 -1
View File
@@ -1,8 +1,34 @@
import { Vec3 } from '../../core/value-types';
import { ColorTemperatureToRGB } from '../../pipeline/define';
import { Node } from '../../scene-graph/node';
import { RenderScene } from './render-scene';
// Color temperature (in Kelvin) to RGB
export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) {
if (kelvin < 1000.0) {
kelvin = 1000.0;
} else if (kelvin > 15000.0) {
kelvin = 15000.0;
}
// Approximate Planckian locus in CIE 1960 UCS
const kSqr = kelvin * kelvin;
const u = (0.860117757 + 1.54118254e-4 * kelvin + 1.28641212e-7 * kSqr) / ( 1.0 + 8.42420235e-4 * kelvin + 7.08145163e-7 * kSqr);
const v = (0.317398726 + 4.22806245e-5 * kelvin + 4.20481691e-8 * kSqr) / ( 1.0 - 2.89741816e-5 * kelvin + 1.61456053e-7 * kSqr);
const d = (2.0 * u - 8.0 * v + 4.0);
const x = 3.0 * u / d;
const y = 2.0 * v / d;
const z = 1.0 - x - y;
const X = 1.0 / y * x;
const Z = 1.0 / y * z;
// XYZ to RGB with BT.709 primaries
rgb.x = 3.2404542 * X + -1.5371385 + -0.4985314 * Z;
rgb.y = -0.9692660 * X + 1.8760108 + 0.0415560 * Z;
rgb.z = 0.0556434 * X + -0.2040259 + 1.0572252 * Z;
}
export enum LightType {
DIRECTIONAL,
SPHERE,
+33 -4
View File
@@ -1,10 +1,13 @@
import { Color, Vec3 } from '../../core/value-types';
import { Color, Quat, Vec3 } from '../../core/value-types';
import { color4, vec3 } from '../../core/vmath';
import { UBOShadow } from '../../pipeline/define';
import { Light } from './light';
import { DirectionalLight } from './directional-light';
import { RenderScene } from './render-scene';
import { SphereLight } from './sphere-light';
const _forward = new Vec3(0, 0, -1);
const _v3 = new Vec3();
const _qt = new Quat();
export class PlanarShadow {
@@ -51,12 +54,12 @@ export class PlanarShadow {
}
// tslint:disable: one-variable-per-declaration
public update (light: Light) {
public updateSphereLight (light: SphereLight) {
light.node.getWorldPosition(_v3);
const n = this._normal, d = this._distance + this._offset;
const NdL = vec3.dot(n, _v3);
const lx = _v3.x, ly = _v3.y, lz = _v3.z;
const nx = n.x, ny = n.y, nz = n.z;
const NdL = vec3.dot(n, _v3);
const m = this._data;
m[0] = NdL - d - lx * nx;
m[1] = -ly * nx;
@@ -75,5 +78,31 @@ export class PlanarShadow {
m[14] = lz * d;
m[15] = NdL;
}
public updateDirLight (light: DirectionalLight) {
light.node.getWorldRotation(_qt);
vec3.transformQuat(_v3, _forward, _qt);
const n = this._normal, d = this._distance + this._offset;
const NdL = vec3.dot(n, _v3), scale = 1 / NdL;
const lx = _v3.x * scale, ly = _v3.y * scale, lz = _v3.z * scale;
const nx = n.x, ny = n.y, nz = n.z;
const m = this._data;
m[0] = 1 - nx * lx;
m[1] = -nx * ly;
m[2] = -nx * lz;
m[3] = 0;
m[4] = -ny * lx;
m[5] = 1 - ny * ly;
m[6] = -ny * lz;
m[7] = 0;
m[8] = -nz * lx;
m[9] = -nz * ly;
m[10] = 1 - nz * lz;
m[11] = 0;
m[12] = lx * d;
m[13] = ly * d;
m[14] = lz * d;
m[15] = 1;
}
// tslint:enable: one-variable-per-declaration
}
+11 -9
View File
@@ -21,7 +21,7 @@ export class Skybox extends Model {
if (val === this._isRGBE) { return; }
this._isRGBE = val;
this._material.destroy();
this._material.initialize({ defines: { USE_RGBE_CUBEMAP: val } });
this._initMaterial();
this.setSubModelMaterial(0, this._material);
this._updateBindingLayout();
}
@@ -33,18 +33,12 @@ export class Skybox extends Model {
protected _cubemap = this._default;
protected _isRGBE = false;
protected _material: Material;
protected _material = new Material();
constructor (scene: RenderScene) {
super(scene, null);
this._scene = scene;
this._material = new Material();
this._material.initialize({
effectName: 'builtin-skybox',
defines: { USE_RGBE_CUBEMAP: this._isRGBE },
});
this._material.setProperty('cubeMap', this._cubemap);
this._initMaterial();
const mesh = createMesh(box({ width: 2, height: 2, length: 2 }));
const subMeshData = mesh.renderingMesh!.getSubmesh(0)!;
@@ -52,6 +46,14 @@ export class Skybox extends Model {
this._updateBindingLayout();
}
protected _initMaterial () {
this._material.initialize({
effectName: 'builtin-skybox',
defines: { USE_RGBE_CUBEMAP: this._isRGBE },
});
this._material.setProperty('cubeMap', this._cubemap);
}
protected _updateBindingLayout () {
this._matPSORecord.get(this._material)![0].pipelineLayout.layouts[0].update();
}
+15 -12
View File
@@ -43,7 +43,6 @@
const { vec3, quat } = cc.vmath;
function onStart() {
const root = cc.director.root;
const scene = new cc.Scene('scene');
@@ -60,6 +59,18 @@
effectName: 'builtin-unlit',
defines: { USE_COLOR: true },
});
const material2 = new cc.Material();
material2.initialize({
effectName: 'builtin-unlit',
defines: { USE_COLOR: true },
states: {
depthStencilState: { depthTest: false, depthWrite: false },
rasterizerState: { cullMode: cc.GFXCullMode.NONE },
blendState: { targets: [
{ blend: true, blendDst: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA, blendDstAlpha: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA }
] }
}
});
const createArrow = (color, rotation) => {
const arrow = new cc.Node('arrow');
@@ -80,10 +91,9 @@
primitiveMode: cc.GFXPrimitiveMode.LINE_LIST,
});
bodyModel.material = material;
bodyModel.material.setProperty('color', color);
bodyModel.material.overridePipelineStates({ primitive: cc.GFXPrimitiveMode.LINE_LIST });
bodyModel.material.setProperty('color', color);
return arrow;
};
const createBorderPlane = (color, position, rotation) => {
@@ -101,15 +111,8 @@
const ibInfo = mesh.struct.primitives[0].indices.range;
submesh.ibuffer = mesh.data.buffer.slice(ibInfo.offset, ibInfo.offset + ibInfo.length);
planeModel.material = material;
planeModel.material = material2;
planeModel.material.setProperty('color', color.lerp(cc.color(0, 0, 0, 0), 0.5));
planeModel.material.overridePipelineStates({
depthStencilState: { depthTest: false, depthWrite: false },
rasterizerState: { cullMode: cc.GFXCullMode.NONE },
blendState: { targets: [
{ blend: true, blendDst: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA, blendDstAlpha: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA }
] }
});
const border = new cc.Node('border');
border.parent = borderPlane;
const borderModel = border.addComponent(cc.ModelComponent);
@@ -119,8 +122,8 @@
primitiveMode: cc.GFXPrimitiveMode.LINE_LIST,
});
borderModel.material = material;
borderModel.material.setProperty('color', color);
borderModel.material.overridePipelineStates({ primitive: cc.GFXPrimitiveMode.LINE_LIST });
borderModel.material.setProperty('color', color);
return borderPlane;
};
+21
View File
@@ -69,6 +69,7 @@
const lightNode = new cc.Node('Light');
lightNode.parent = rt;
lightNode.setPosition(-10, 10, -10);
lightNode.setRotationFromEuler(-50, 0, 0);
const lightComp = lightNode.addComponent(cc.DirectionalLightComponent);
// parsed effect file is embedded in cocos/3d/builtin/effects.js
@@ -109,6 +110,26 @@
// material.setProperty('matLightPlaneProj', getLightPlaneProj(cc.v3(-10, altitude + 10, -10), // light
// cc.geometry.plane.create(nm.x, nm.y, nm.z, cc.vmath.vec3.dot(nm, models.plane.node.getWorldPosition()))));
// const { vec3, quat } = cc.vmath;
// const L = vec3.transformQuat(cc.v3(), cc.v3(0, 0, -1), quat.fromEuler(cc.quat(), 10, 20, 30));
// const N = vec3.transformQuat(cc.v3(), cc.v3(0, 1, 0), quat.fromEuler(cc.quat(), 10, 0, 0)), d = 0;
// const sp = cc.primitives.sphere();
// const pos = sp.positions;
// const V = cc.v3();
// for (let i = 0; i < pos.length; i += 3) {
// vec3.set(V, pos[i], pos[i+1], pos[i+2]);
// const scale = (d - vec3.dot(V, N)) / vec3.dot(N, L);
// pos[i] = V.x + scale * L.x;
// pos[i+1] = V.y + scale * L.y;
// pos[i+2] = V.z + scale * L.z;
// }
// const spNode = new cc.Node('test');
// spNode.parent = rt;
// const spCom = spNode.addComponent('cc.ModelComponent');
// spCom.material = cc.builtinResMgr.get('default-material');
// spCom.mesh = cc.utils.createMesh(sp);
cc.director.runSceneImmediate(scene);
}
cc.game.run({ id: 'canvas' }, onStart);