refactor particle

This commit is contained in:
zhuxuguang
2019-01-25 16:47:08 +08:00
parent acc540e67a
commit 39927e48b5
18 changed files with 925 additions and 855 deletions
@@ -2,6 +2,9 @@ import { color4, pseudoRandom } from '../../../../core/vmath';
import { CCClass } from '../../../../core/data';
import GradientRange from './gradient-range';
import { property, ccclass } from '../../../../core/data/class-decorator';
import Particle from '../particle';
// tslint:disable: max-line-length
const COLOR_OVERTIME_RAND_OFFSET = 91041;
@@ -9,14 +12,14 @@ const COLOR_OVERTIME_RAND_OFFSET = 91041;
export default class ColorOvertimeModule {
@property
enable = false;
public enable = false;
@property({
type: GradientRange
type: GradientRange,
})
color = new GradientRange();
public color = new GradientRange();
animate(particle) {
public animate (particle: Particle) {
if (this.enable) {
color4.multiply(particle.color, particle.startColor01, this.color.evaluate(1.0 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + COLOR_OVERTIME_RAND_OFFSET)));
}
@@ -8,49 +8,49 @@ const Mode = Enum({
Constant: 0,
Curve: 1,
TwoCurves: 2,
TwoConstants: 3
TwoConstants: 3,
});
@ccclass('cc.CurveRange')
export default class CurveRange {
@property({
type: Mode
type: Mode,
})
mode = Mode.Constant;
public mode = Mode.Constant;
@property({
type: AnimationCurve
type: AnimationCurve,
})
curve = new AnimationCurve();
public curve = new AnimationCurve();
@property({
type: AnimationCurve
type: AnimationCurve,
})
curveMin = new AnimationCurve();
public curveMin = new AnimationCurve();
@property({
type: AnimationCurve
type: AnimationCurve,
})
curveMax = new AnimationCurve();
public curveMax = new AnimationCurve();
@property
constant = 0;
public constant = 0;
@property
constantMin = 0;
public constantMin = 0;
@property
constantMax = 0;
public constantMax = 0;
@property
multiplier = 1;
public multiplier = 1;
constructor() {
constructor () {
}
evaluate(time, rndRatio) {
public evaluate (time: number, rndRatio: number) {
switch (this.mode) {
case Mode.Constant:
return this.constant;
@@ -4,46 +4,53 @@ import CurveRange from './curve-range';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
// tslint:disable: max-line-length
const FORCE_OVERTIME_RAND_OFFSET = 212165;
@ccclass('cc.ForceOvertimeModule')
export default class ForceOvertimeModule {
@property
enable = false;
public enable = false;
@property({
type: CurveRange
type: CurveRange,
})
x = new CurveRange();
public x = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
y = new CurveRange();
public y = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
z = new CurveRange();
public z = new CurveRange();
@property
space = Space.Local;
@property({
type: Space,
})
public space = Space.Local;
// TODO:currently not supported
randomized = false;
public randomized = false;
constructor() {
private rotation: quat;
private needTransform: boolean;
constructor () {
this.rotation = quat.create();
this.needTransform = false;
}
update(space, worldTransform) {
this.needTransform = calculateTransform(space, this._space, worldTransform, this.rotation);
public update (space, worldTransform) {
this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation);
}
animate(p, dt) {
let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
let force = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)));
public animate (p, dt) {
const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
const force = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)));
if (this.needTransform) {
vec3.transformQuat(force, force, this.rotation);
}
@@ -4,6 +4,8 @@ import Gradient from './gradient';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
// tslint:disable: max-line-length
const GRADIENT_MODE_FIX = 0;
const GRADIENT_MODE_BLEND = 1;
@@ -18,42 +20,42 @@ const Mode = Enum({
Gradient: 1,
TwoColors: 2,
TwoGradients: 3,
RandomColor: 4
RandomColor: 4,
});
@ccclass('cc.GradientRange')
export default class GradientRange {
@property({
type: Mode
type: Mode,
})
mode = Mode.Color;
public mode = Mode.Color;
@property
color = cc.Color.WHITE;
public color = cc.Color.WHITE;
@property
colorMin = cc.Color.WHITE;
public colorMin = cc.Color.WHITE;
@property
colorMax = cc.Color.WHITE;
public colorMax = cc.Color.WHITE;
@property({
type: Gradient
type: Gradient,
})
gradient = new Gradient();
public gradient = new Gradient();
@property({
type: Gradient
type: Gradient,
})
gradientMin = new Gradient();
public gradientMin = new Gradient();
@property({
type: Gradient
type: Gradient,
})
gradientMax = new Gradient();
public gradientMax = new Gradient();
evaluate(time, rndRatio) {
public evaluate (time: number, rndRatio: number) {
switch (this.mode) {
case Mode.Color:
return this.color;
@@ -84,60 +86,72 @@ export default class GradientRange {
// });
export class GradientUniform {
constructor(gr) {
public gr: GradientRange;
public minColor: Float32Array;
public maxColor: Float32Array;
public minColorKeyTime: Float32Array;
public minColorKeyValue: Float32Array;
public minAlphaKeyTime: Float32Array;
public minAlphaKeyValue: Float32Array;
public maxColorKeyTime: Float32Array;
public maxColorKeyValue: Float32Array;
public maxAlphaKeyTime: Float32Array;
public maxAlphaKeyValue: Float32Array;
constructor (gr: GradientRange) {
this.gr = gr;
if (gr._mode == 'color') {
if (gr.mode === 'color') {
this.minColor = new Float32Array(4);
color4.array(this.minColor, gr._color);
} else if (gr._mode == 'twoColors') {
color4.array(this.minColor, gr.color);
} else if (gr.mode === 'twoColors') {
this.minColor = new Float32Array(4);
this.maxColor = new Float32Array(4);
color4.array(this.minColor, gr._colorMin);
color4.array(this.maxColor, gr._colorMax);
} else if (gr._mode == 'gradient') {
this.minColorKeyTime = new Float32Array(gr._gradient._colorKeys.length);
color4.array(this.minColor, gr.colorMin);
color4.array(this.maxColor, gr.colorMax);
} else if (gr.mode === 'gradient') {
this.minColorKeyTime = new Float32Array(gr.gradient.colorKeys.length);
this.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.length);
this.minAlphaKeyTime = new Float32Array(gr._gradient._alphaKeys.length);
this.minAlphaKeyTime = new Float32Array(gr.gradient.alphaKeys.length);
this.minAlphaKeyValue = new Float32Array(this.minAlphaKeyTime.length);
this.constructor.generateGradientUniform(gr._gradient, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue);
} else if (gr._mode == 'twoGradients') {
this.minColorKeyTime = new Float32Array(gr._gradientMin._colorKeys.length);
this.constructor.generateGradientUniform(gr.gradient, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue);
} else if (gr.mode === 'twoGradients') {
this.minColorKeyTime = new Float32Array(gr.gradientMin.colorKeys.length);
this.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.length);
this.minAlphaKeyTime = new Float32Array(gr._gradientMin._alphaKeys.length);
this.minAlphaKeyTime = new Float32Array(gr.gradientMin.alphaKeys.length);
this.minAlphaKeyValue = new Float32Array(this.minAlphaKeyTime.length);
this.constructor.generateGradientUniform(gr._gradientMin, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue);
this.maxColorKeyTime = new Float32Array(gr._gradientMax._colorKeys.length);
this.constructor.generateGradientUniform(gr.gradientMin, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue);
this.maxColorKeyTime = new Float32Array(gr.gradientMax.colorKeys.length);
this.maxColorKeyValue = new Float32Array(3 * this.maxColorKeyTime.length);
this.maxAlphaKeyTime = new Float32Array(gr._gradientMax._alphaKeys.length);
this.maxAlphaKeyTime = new Float32Array(gr.gradientMax.alphaKeys.length);
this.maxAlphaKeyValue = new Float32Array(this.maxAlphaKeyTime.length);
this.constructor.generateGradientUniform(gr._gradientMax, this.maxColorKeyTime, this.maxColorKeyValue, this.maxAlphaKeyTime, this.maxAlphaKeyValue);
this.constructor.generateGradientUniform(gr.gradientMax, this.maxColorKeyTime, this.maxColorKeyValue, this.maxAlphaKeyTime, this.maxAlphaKeyValue);
}
}
uploadUniform(device, name) {
if (this.gr._mode == 'color') {
public uploadUniform (device: any, name: string) {
if (this.gr.mode === 'color') {
device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_COLOR);
device.setUniform('u_' + name + '_minColor', this.minColor);
} else if (this.gr._mode == 'twoColors') {
} else if (this.gr.mode === 'twoColors') {
device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_TWO_COLOR);
device.setUniform('u_' + name + '_minColor', this.minColor);
device.setUniform('u_' + name + '_maxColor', this.maxColor);
} else if (this.gr._mode == 'gradient') {
} else if (this.gr.mode === 'gradient') {
device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_GRADIENT);
device.setUniform('u_' + name + '_minGradMode', this.gr._gradient._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
device.setUniform('u_' + name + '_minGradMode', this.gr.gradient.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
device.setUniform('u_' + name + '_minColorKeyValue', this.minColorKeyValue);
device.setUniform('u_' + name + '_minColorKeyTime', this.minColorKeyTime);
device.setUniform('u_' + name + '_minAlphaKeyValue', this.minAlphaKeyValue);
device.setUniform('u_' + name + '_minAlphaKeyTime', this.minAlphaKeyTime);
} else if (this.gr._mode == 'twoGradients') {
} else if (this.gr.mode === 'twoGradients') {
device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_TWO_GRADIENT);
device.setUniform('u_' + name + '_minGradMode', this.gr._gradientMin._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
device.setUniform('u_' + name + '_minGradMode', this.gr.gradientMin.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
device.setUniform('u_' + name + '_minColorKeyValue', this.minColorKeyValue);
device.setUniform('u_' + name + '_minColorKeyTime', this.minColorKeyTime);
device.setUniform('u_' + name + '_minAlphaKeyValue', this.minAlphaKeyValue);
device.setUniform('u_' + name + '_minAlphaKeyTime', this.minAlphaKeyTime);
device.setUniform('u_' + name + '_maxGradMode', this.gr._gradientMax._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
device.setUniform('u_' + name + '_maxGradMode', this.gr.gradientMax.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
device.setUniform('u_' + name + '_maxColorKeyValue', this.maxColorKeyValue);
device.setUniform('u_' + name + '_maxColorKeyTime', this.maxColorKeyTime);
device.setUniform('u_' + name + '_maxAlphaKeyValue', this.maxAlphaKeyValue);
@@ -145,16 +159,16 @@ export class GradientUniform {
}
}
static generateGradientUniform(gradient, colorKeyTime, colorKeyValue, alphaKeyTime, alphaKeyValue) {
for (let i = 0; i < gradient._colorKeys.length; i++) {
colorKeyTime[i] = gradient._colorKeys[i]._time;
colorKeyValue[i * 3] = gradient._colorKeys[i]._color.r;
colorKeyValue[i * 3 + 1] = gradient._colorKeys[i]._color.g;
colorKeyValue[i * 3 + 2] = gradient._colorKeys[i]._color.b;
public static generateGradientUniform (gradient: Gradient, colorKeyTime: number, colorKeyValue: Float32Array, alphaKeyTime: number, alphaKeyValue: Float32Array) {
for (let i = 0; i < gradient.colorKeys.length; i++) {
colorKeyTime[i] = gradient.colorKeys[i].time;
colorKeyValue[i * 3] = gradient.colorKeys[i].color.r;
colorKeyValue[i * 3 + 1] = gradient.colorKeys[i].color.g;
colorKeyValue[i * 3 + 2] = gradient.colorKeys[i].color.b;
}
for (let i = 0; i < gradient._alphaKeys.length; i++) {
alphaKeyTime[i] = gradient._alphaKeys[i]._time;
alphaKeyValue[i] = gradient._alphaKeys[i]._alpha;
for (let i = 0; i < gradient.alphaKeys.length; i++) {
alphaKeyTime[i] = gradient.alphaKeys[i].time;
alphaKeyValue[i] = gradient.alphaKeys[i].alpha;
}
}
}
@@ -1,21 +1,21 @@
import { repeat } from '../../../../core/vmath';
import { Enum, ValueType } from '../../../../core/value-types';
import { Enum, ValueType, Color } from '../../../../core/value-types';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
const Mode = Enum({
Blend: 0,
Fixed: 1
Fixed: 1,
});
@ccclass('cc.ColorKey')
export class ColorKey {
@property
color = cc.Color.WHITE;
public color = cc.Color.WHITE;
@property
time = 0;
public time = 0;
}
// CCClass.fastDefine('cc.ColorKey', ColorKey, {
@@ -27,10 +27,10 @@ export class ColorKey {
export class AlphaKey {
@property
alpha = 1;
public alpha = 1;
@property
time = 0;
public time = 0;
}
// CCClass.fastDefine('cc.AlphaKey', AlphaKey, {
@@ -42,24 +42,26 @@ export class AlphaKey {
export default class Gradient {
@property
colorKeys = [];
public colorKeys = new Array<ColorKey>();
@property
alphaKeys = []
public alphaKeys = new Array<AlphaKey>();
@property
mode = Mode.Blend;
public mode = Mode.Blend;
constructor() {
private _color: Color;
constructor () {
this._color = cc.Color.WHITE;
}
setKeys(colorKeys, alphaKeys) {
public setKeys (colorKeys, alphaKeys) {
this.colorKeys = colorKeys;
this.alphaKeys = alphaKeys;
}
sortKeys() {
public sortKeys () {
if (this.colorKeys.length > 1) {
this.colorKeys.sort((a, b) => a.time - b.time);
}
@@ -68,17 +70,17 @@ export default class Gradient {
}
}
getRGB(time) {
private getRGB (time: number) {
if (this.colorKeys.length > 1) {
time = repeat(time, 1);
for (let i = 1; i < this.colorKeys.length; ++i) {
let preTime = this.colorKeys[i - 1].time;
let curTime = this.colorKeys[i].time;
const preTime = this.colorKeys[i - 1].time;
const curTime = this.colorKeys[i].time;
if (time >= preTime && time < curTime) {
if (this._mode === 'fixed') {
if (this.mode === 'fixed') {
return this.colorKeys[i].color;
}
let factor = (time - preTime) / (curTime - preTime);
const factor = (time - preTime) / (curTime - preTime);
this.colorKeys[i - 1].color.lerp(this.colorKeys[i].color, factor, this._color);
return this._color;
}
@@ -96,17 +98,17 @@ export default class Gradient {
}
}
getAlpha(time) {
private getAlpha (time) {
if (this.alphaKeys.length > 1) {
time = repeat(time, 1);
for (let i = 1; i < this.alphaKeys.length; ++i) {
let preTime = this.alphaKeys[i - 1].time;
let curTime = this.alphaKeys[i].time;
const preTime = this.alphaKeys[i - 1].time;
const curTime = this.alphaKeys[i].time;
if (time >= preTime && time < curTime) {
if (this._mode === 'fixed') {
if (this.mode === 'fixed') {
return this.alphaKeys[i].alpha;
}
let factor = (time - preTime) / (curTime - preTime);
const factor = (time - preTime) / (curTime - preTime);
return (this.alphaKeys[i - 1].alpha * (1 - factor) + this.alphaKeys[i].alpha * factor);
}
}
@@ -118,19 +120,19 @@ export default class Gradient {
}
}
evaluate(time) {
public evaluate (time) {
this.getRGB(time);
this._color.a = this.getAlpha(time);
this._color.a = this.getAlpha(time)!;
return this._color;
}
randomColor() {
let c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)];
let a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)];
this._color.r = c.r;
this._color.g = c.g;
this._color.b = c.b;
this._color.a = a;
public randomColor () {
const c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)];
const a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)];
this._color.r = c.color.r;
this._color.g = c.color.g;
this._color.b = c.color.b;
this._color.a = a.alpha;
return this._color;
}
}
@@ -3,73 +3,78 @@ import { CCClass } from '../../../../core/data';
import { Space } from '../particle-general-function';
import { property, ccclass } from '../../../../core/data/class-decorator';
import CurveRange from './curve-range';
import Particle from '../particle';
// tslint:disable: max-line-length
const LIMIT_VELOCITY_RAND_OFFSET = 23541;
@ccclass('cc.LimitVelocityOvertimeModule')
export default class LimitVelocityOvertimeModule {
enable = false;
@property
public enable = false;
@property({
type: CurveRange
type: CurveRange,
})
limitX = new CurveRange();
public limitX = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
limitY = new CurveRange();
public limitY = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
limitZ = new CurveRange();
public limitZ = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
limit = new CurveRange();
public limit = new CurveRange();
@property
dampen = 0;
public dampen = 0;
@property
separateAxes = false;
public separateAxes = false;
@property
space = Space.Local;
@property({
type: Space,
})
public space = Space.Local;
// TODO:functions related to drag are temporarily not supported
drag = null;
public drag = null;
multiplyDragByParticleSize = false;
public multiplyDragByParticleSize = false;
multiplyDragByParticleVelocity = false;
public multiplyDragByParticleVelocity = false;
constructor() {
constructor () {
}
animate(p) {
let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
let dampedVel = vec3.create(0, 0, 0);
public animate (p: Particle) {
const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
const dampedVel = vec3.create(0, 0, 0);
if (this.separateAxes) {
vec3.set(dampedVel,
dampenBeyondLimit(p.ultimateVelocity.x, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen),
dampenBeyondLimit(p.ultimateVelocity.y, this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen),
dampenBeyondLimit(p.ultimateVelocity.z, this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen));
dampenBeyondLimit(p.ultimateVelocity.x, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen),
dampenBeyondLimit(p.ultimateVelocity.y, this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen),
dampenBeyondLimit(p.ultimateVelocity.z, this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen));
}
else {
vec3.normalize(dampedVel, p.ultimateVelocity);
vec3.scale(dampedVel, dampedVel, dampenBeyondLimit(vec3.magnitude(p.ultimateVelocity), this.limit.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen));
vec3.scale(dampedVel, dampedVel, dampenBeyondLimit(vec3.magnitude(p.ultimateVelocity), this.limit.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen));
}
vec3.copy(p.ultimateVelocity, dampedVel);
}
}
function dampenBeyondLimit(vel, limit, dampen) {
let sgn = Math.sign(vel);
function dampenBeyondLimit (vel: number, limit: number, dampen: number) {
const sgn = Math.sign(vel);
let abs = Math.abs(vel);
if (abs > limit) {
abs = lerp(abs, limit, dampen);
@@ -1,297 +0,0 @@
import { OptimizedKey, evalOptCurve } from "../../../geom-utils/curve";
import { repeat } from "../../../../core/vmath";
const CURVE_MODE_CONSTANT = 0;
const CURVE_MODE_RANDOM_CONSTANT = 1;
const CURVE_MODE_CURVE = 2;
const CURVE_MODE_RANDOM_CURVE = 3;
const UNIFORM_CURVE_KEY_NUM = 8;
//calculate the coefficience of the first order integral of the curve
function integrateKeyframe(coef) {
coef[0] = coef[0] / 4;
coef[1] = coef[1] / 3;
coef[2] = coef[2] / 2;
coef[3] = coef[3];
return coef;
}
//calculate the coefficience of the second order integral of the curve
function integrateKeyframeTwice(coef) {
coef[0] = coef[0] / 20;
coef[1] = coef[1] / 12;
coef[2] = coef[2] / 6;
coef[3] = coef[3] / 2;
return coef;
}
export class OptimizedCurve {
constructor(constructUniform = false) {
this.optimizedKeys = new Array; //the i-th optimezed key stores coefficients of [i,i+1] segment in the original curve,so if the time of last key of the original key is 1,the last key won't be kept in the opt curve.
this.integral = new Array; //the integral of the curve between 0 and corresponding key,the i-th integral corresponds to the i+1-th key in optimizedKeys (because the integral of the first key is always zero,the first key won't be stored)
this.constructUniform = constructUniform;
}
buildCurve(animationCurve, multiplier = 1) {
let keyNum = animationCurve.keyFrames.length - 1;
let i = 0;
if (this.optimizedKeys.length < keyNum) {
let keyToAdd = keyNum - this.optimizedKeys.length;
for (i = 0; i < keyToAdd; i++) {
let optKey = new OptimizedKey();
this.optimizedKeys.push(optKey);
}
} else {
this.optimizedKeys.splice(keyNum);
}
if (animationCurve.keyFrames.length === 1) {
this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames[0].value * multiplier;
this.optimizedKeys[0].time = 0;
this.optimizedKeys[0].endTime = 1;
} else {
let keyOffset = 0;
if (animationCurve.keyFrames[0].time !== 0) {
this.optimizedKeys.splice(0, 0, new OptimizedKey());
this.optimizedKeys[0].time = 0;
this.optimizedKeys[0].endTime = animationCurve.keyFrames[0].time;
this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames[0].value;
keyOffset = 1;
}
for (i = 0; i < keyNum; i++) {
animationCurve.calcOptimizedKey(this.optimizedKeys[i + keyOffset], i, Math.min(i + 1, keyNum));
this.optimizedKeys[i + keyOffset].index += keyOffset;
}
if (animationCurve.keyFrames[animationCurve.keyFrames.length - 1].time !== 1) {
this.optimizedKeys.push(new OptimizedKey());
this.optimizedKeys[this.optimizedKeys.length - 1].time = animationCurve.keyFrames[animationCurve.length - 1].time;
this.optimizedKeys[this.optimizedKeys.length - 1].endTime = 1;
this.optimizedKeys[this.optimizedKeys.length - 1].coefficient[3] = animationCurve.keyFrames[animationCurve.length - 1].value;
}
}
for (i = 0; i < this.optimizedKeys.length; i++) {
this.optimizedKeys[i].coefficient[0] *= multiplier;
this.optimizedKeys[i].coefficient[1] *= multiplier;
this.optimizedKeys[i].coefficient[2] *= multiplier;
this.optimizedKeys[i].coefficient[3] *= multiplier;
}
if (this.constructUniform) {
this.coefUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM * 4);
this.timeUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM);
this.updateKeyUniform();
}
}
evaluate(time) {
time = repeat(time, 1);
for (let i = 1; i < this.optimizedKeys.length; i++) {
if (time < this.optimizedKeys[i].time) {
return this.optimizedKeys[i - 1].evaluate(time);
}
}
return this.optimizedKeys[this.optimizedKeys.length - 1].evaluate(time);
}
//calculate first order integral coefficients of all keys
integrateOnce() {
let i = 0;
if (this.integral.length + 1 < this.optimizedKeys.length) {
for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) {
this.integral.push(0);
}
} else {
this.integral.splice(this.optimizedKeys.length - 1);
}
for (i = 0; i < this.integral.length; i++) {
integrateKeyframe(this.optimizedKeys[i].coefficient);
let deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time;
let prevIntegral = i === 0 ? 0 : this.integral[i - 1];
this.integral[i] = prevIntegral + (deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient));
}
integrateKeyframe(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient);
if (this.constructUniform) {
this.updateKeyUniform();
this.updateIntegralUniform();
}
}
//get the integral of the curve using calculated coefficients
evaluateIntegral(t, ts = 1) {
t = repeat(t, 1);
for (let i = 1; i < this.optimizedKeys.length; i++) {
if (t < this.optimizedKeys[i].time) {
let prevInt = i === 1 ? 0 : this.integral[i - 2];
let dt = t - this.optimizedKeys[i - 1].time;
return ts * (prevInt + (dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient)));
}
}
let dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time;
return ts * (this.integral[this.integral.length - 1] + (dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient)));
}
//calculate second order integral coefficients of all keys
integrateTwice() {
let i = 0;
if (this.integral.length + 1 < this.optimizedKeys.length) {
for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) {
this.integral.push(0);
}
} else {
this.integral.splice(this.optimizedKeys.length - 1);
}
for (i = 0; i < this.integral.length; i++) {
integrateKeyframeTwice(this.optimizedKeys[i].coefficient);
let deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time;
let prevIntegral = i === 0 ? 0 : this.integral[i - 1];
this.integral[i] = prevIntegral + (deltaT * deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient));
}
integrateKeyframeTwice(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient);
if (this.constructUniform) {
this.updateKeyUniform();
this.updateIntegralUniform();
}
}
//get the second order integral of the curve using calculated coefficients
evaluateIntegralTwice(t, ts = 1) {
t = repeat(t, 1);
for (let i = 1; i < this.optimizedKeys.length; i++) {
if (t < this.optimizedKeys[i].time) {
let prevInt = i === 1 ? 0 : this.integral[i - 2];
let dt = t - this.optimizedKeys[i - 1].time;
return ts * ts * (prevInt + (dt * dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient)));
}
}
let dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time;
return ts * ts * (this.integral[this.integral.length - 1] + (dt * dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient)));
}
updateKeyUniform() {
for (let i = 0; i < this.optimizedKeys.length; i++) {
this.coefUniform[i * 4] = this.optimizedKeys[i].coefficient[0];
this.coefUniform[i * 4 + 1] = this.optimizedKeys[i].coefficient[1];
this.coefUniform[i * 4 + 2] = this.optimizedKeys[i].coefficient[2];
this.coefUniform[i * 4 + 3] = this.optimizedKeys[i].coefficient[3];
this.timeUniform[i] = this.optimizedKeys[i].endTime;
}
}
updateIntegralUniform() {
this.integralUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM - 1);
for (let i = 0; i < this.integral.length; i++) {
this.integralUniform[i] = this.integral[i];
}
}
}
export class CurveUniform {
constructCurve(cr) {
this.mode = cr.mode;
switch (cr.mode) {
case 'constant':
this.minConstant = cr.constant;
break;
case 'twoConstants':
this.minConstant = cr.constantMin;
this.maxConstant = cr.constantMax;
break;
case 'curve':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curve, cr.multiplier);
break;
case 'twoCurves':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
this.maxCurve = new OptimizedCurve(true);
this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
break;
}
}
constructCurveIntegral(cr) {
this.mode = cr.mode;
switch (cr.mode) {
case 'constant':
this.minConstant = cr.constant;
break;
case 'twoConstants':
this.minConstant = cr.constantMin;
this.maxConstant = cr.constantMax;
break;
case 'curve':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curve, cr.multiplier);
this.minCurve.integrateOnce();
break;
case 'twoCurves':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
this.minCurve.integrateOnce();
this.maxCurve = new OptimizedCurve(true);
this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
this.maxCurve.integrateOnce();
break;
}
}
constructCurveIntegralTwice(cr) {
this.mode = cr.mode;
switch (cr.mode) {
case 'constant':
this.minConstant = cr.constant;
break;
case 'twoConstants':
this.minConstant = cr.constantMin;
this.maxConstant = cr.constantMax;
break;
case 'curve':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curve, cr.multiplier);
this.minCurve.integrateTwice();
break;
case 'twoCurves':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
this.minCurve.integrateTwice();
this.maxCurve = new OptimizedCurve(true);
this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
this.maxCurve.integrateTwice();
break;
}
}
uploadUniform(device, name) {
switch (this.mode) {
case 'constant':
device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CONSTANT);
device.setUniform('u_' + name + '_minConstant', this.minConstant);
break;
case 'twoConstants':
device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CONSTANT);
device.setUniform('u_' + name + '_minConstant', this.minConstant);
device.setUniform('u_' + name + '_maxConstant', this.maxConstant);
break;
case 'curve':
device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CURVE);
device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform);
device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform);
if (this.minCurve.integralUniform !== undefined) {
device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform);
}
break;
case 'twoCurves':
device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CURVE);
device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform);
device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform);
if (this.minCurve.integralUniform !== undefined) {
device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform);
}
device.setUniform('u_' + name + '_maxKeyTime', this.maxCurve.timeUniform);
device.setUniform('u_' + name + '_maxKeyCoef', this.maxCurve.coefUniform);
if (this.minCurve.integralUniform !== undefined) {
device.setUniform('u_' + name + '_maxIntegral', this.maxCurve.integralUniform);
}
break;
}
}
}
@@ -0,0 +1,313 @@
import { OptimizedKey, evalOptCurve, AnimationCurve } from "../../../geom-utils/curve";
import { repeat } from "../../../../core/vmath";
import CurveRange from "./curve-range";
// tslint:disable: max-line-length
const CURVE_MODE_CONSTANT = 0;
const CURVE_MODE_RANDOM_CONSTANT = 1;
const CURVE_MODE_CURVE = 2;
const CURVE_MODE_RANDOM_CURVE = 3;
const UNIFORM_CURVE_KEY_NUM = 8;
// calculate the coefficience of the first order integral of the curve
function integrateKeyframe (coef: Float32Array) {
coef[0] = coef[0] / 4;
coef[1] = coef[1] / 3;
coef[2] = coef[2] / 2;
coef[3] = coef[3];
return coef;
}
// calculate the coefficience of the second order integral of the curve
function integrateKeyframeTwice (coef: Float32Array) {
coef[0] = coef[0] / 20;
coef[1] = coef[1] / 12;
coef[2] = coef[2] / 6;
coef[3] = coef[3] / 2;
return coef;
}
export class OptimizedCurve {
private optimizedKeys: OptimizedKey[];
private integral: number[];
private constructUniform: boolean;
private coefUniform: Float32Array;
private timeUniform: Float32Array;
private integralUniform: Float32Array;
constructor (constructUniform = false) {
this.optimizedKeys = new Array<OptimizedKey>(); // the i-th optimezed key stores coefficients of [i,i+1] segment in the original curve,so if the time of last key of the original key is 1,the last key won't be kept in the opt curve.
this.integral = new Array<number>(); // the integral of the curve between 0 and corresponding key,the i-th integral corresponds to the i+1-th key in optimizedKeys (because the integral of the first key is always zero,the first key won't be stored)
this.constructUniform = constructUniform;
}
public buildCurve (animationCurve: AnimationCurve, multiplier: number = 1) {
const keyNum = animationCurve.keyFrames!.length - 1;
let i = 0;
if (this.optimizedKeys.length < keyNum) {
const keyToAdd = keyNum - this.optimizedKeys.length;
for (i = 0; i < keyToAdd; i++) {
const optKey = new OptimizedKey();
this.optimizedKeys.push(optKey);
}
} else {
this.optimizedKeys.splice(keyNum);
}
if (animationCurve.keyFrames!.length === 1) {
this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames![0].value * multiplier;
this.optimizedKeys[0].time = 0;
this.optimizedKeys[0].endTime = 1;
} else {
let keyOffset = 0;
if (animationCurve.keyFrames![0].time !== 0) {
this.optimizedKeys.splice(0, 0, new OptimizedKey());
this.optimizedKeys[0].time = 0;
this.optimizedKeys[0].endTime = animationCurve.keyFrames![0].time;
this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames![0].value;
keyOffset = 1;
}
for (i = 0; i < keyNum; i++) {
animationCurve.calcOptimizedKey(this.optimizedKeys[i + keyOffset], i, Math.min(i + 1, keyNum));
this.optimizedKeys[i + keyOffset].index += keyOffset;
}
if (animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].time !== 1) {
this.optimizedKeys.push(new OptimizedKey());
this.optimizedKeys[this.optimizedKeys.length - 1].time = animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].time;
this.optimizedKeys[this.optimizedKeys.length - 1].endTime = 1;
this.optimizedKeys[this.optimizedKeys.length - 1].coefficient[3] = animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].value;
}
}
for (i = 0; i < this.optimizedKeys.length; i++) {
this.optimizedKeys[i].coefficient[0] *= multiplier;
this.optimizedKeys[i].coefficient[1] *= multiplier;
this.optimizedKeys[i].coefficient[2] *= multiplier;
this.optimizedKeys[i].coefficient[3] *= multiplier;
}
if (this.constructUniform) {
this.coefUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM * 4);
this.timeUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM);
this.updateKeyUniform();
}
}
public evaluate (time: number) {
time = repeat(time, 1);
for (let i = 1; i < this.optimizedKeys.length; i++) {
if (time < this.optimizedKeys[i].time) {
return this.optimizedKeys[i - 1].evaluate(time);
}
}
return this.optimizedKeys[this.optimizedKeys.length - 1].evaluate(time);
}
// calculate first order integral coefficients of all keys
public integrateOnce () {
let i = 0;
if (this.integral.length + 1 < this.optimizedKeys.length) {
for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) {
this.integral.push(0);
}
} else {
this.integral.splice(this.optimizedKeys.length - 1);
}
for (i = 0; i < this.integral.length; i++) {
integrateKeyframe(this.optimizedKeys[i].coefficient);
const deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time;
const prevIntegral = i === 0 ? 0 : this.integral[i - 1];
this.integral[i] = prevIntegral + (deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient));
}
integrateKeyframe(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient);
if (this.constructUniform) {
this.updateKeyUniform();
this.updateIntegralUniform();
}
}
// get the integral of the curve using calculated coefficients
public evaluateIntegral (t: number, ts: number = 1) {
t = repeat(t, 1);
for (let i = 1; i < this.optimizedKeys.length; i++) {
if (t < this.optimizedKeys[i].time) {
const prevInt = i === 1 ? 0 : this.integral[i - 2];
const dt = t - this.optimizedKeys[i - 1].time;
return ts * (prevInt + (dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient)));
}
}
const dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time;
return ts * (this.integral[this.integral.length - 1] + (dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient)));
}
// calculate second order integral coefficients of all keys
public integrateTwice () {
let i = 0;
if (this.integral.length + 1 < this.optimizedKeys.length) {
for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) {
this.integral.push(0);
}
} else {
this.integral.splice(this.optimizedKeys.length - 1);
}
for (i = 0; i < this.integral.length; i++) {
integrateKeyframeTwice(this.optimizedKeys[i].coefficient);
const deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time;
const prevIntegral = i === 0 ? 0 : this.integral[i - 1];
this.integral[i] = prevIntegral + (deltaT * deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient));
}
integrateKeyframeTwice(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient);
if (this.constructUniform) {
this.updateKeyUniform();
this.updateIntegralUniform();
}
}
// get the second order integral of the curve using calculated coefficients
public evaluateIntegralTwice (t: number, ts: number = 1) {
t = repeat(t, 1);
for (let i = 1; i < this.optimizedKeys.length; i++) {
if (t < this.optimizedKeys[i].time) {
const prevInt = i === 1 ? 0 : this.integral[i - 2];
const dt = t - this.optimizedKeys[i - 1].time;
return ts * ts * (prevInt + (dt * dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient)));
}
}
const dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time;
return ts * ts * (this.integral[this.integral.length - 1] + (dt * dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient)));
}
public updateKeyUniform () {
for (let i = 0; i < this.optimizedKeys.length; i++) {
this.coefUniform[i * 4] = this.optimizedKeys[i].coefficient[0];
this.coefUniform[i * 4 + 1] = this.optimizedKeys[i].coefficient[1];
this.coefUniform[i * 4 + 2] = this.optimizedKeys[i].coefficient[2];
this.coefUniform[i * 4 + 3] = this.optimizedKeys[i].coefficient[3];
this.timeUniform[i] = this.optimizedKeys[i].endTime;
}
}
public updateIntegralUniform () {
this.integralUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM - 1);
for (let i = 0; i < this.integral.length; i++) {
this.integralUniform[i] = this.integral[i];
}
}
}
export class CurveUniform {
private mode: number;
private minConstant: number;
private maxConstant: number;
private minCurve: OptimizedCurve;
private maxCurve: OptimizedCurve;
public constructCurve (cr: CurveRange) {
this.mode = cr.mode;
switch (cr.mode) {
case 'constant':
this.minConstant = cr.constant;
break;
case 'twoConstants':
this.minConstant = cr.constantMin;
this.maxConstant = cr.constantMax;
break;
case 'curve':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curve, cr.multiplier);
break;
case 'twoCurves':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
this.maxCurve = new OptimizedCurve(true);
this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
break;
}
}
public constructCurveIntegral (cr: CurveRange) {
this.mode = cr.mode;
switch (cr.mode) {
case 'constant':
this.minConstant = cr.constant;
break;
case 'twoConstants':
this.minConstant = cr.constantMin;
this.maxConstant = cr.constantMax;
break;
case 'curve':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curve, cr.multiplier);
this.minCurve.integrateOnce();
break;
case 'twoCurves':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
this.minCurve.integrateOnce();
this.maxCurve = new OptimizedCurve(true);
this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
this.maxCurve.integrateOnce();
break;
}
}
public constructCurveIntegralTwice (cr: CurveRange) {
this.mode = cr.mode;
switch (cr.mode) {
case 'constant':
this.minConstant = cr.constant;
break;
case 'twoConstants':
this.minConstant = cr.constantMin;
this.maxConstant = cr.constantMax;
break;
case 'curve':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curve, cr.multiplier);
this.minCurve.integrateTwice();
break;
case 'twoCurves':
this.minCurve = new OptimizedCurve(true);
this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
this.minCurve.integrateTwice();
this.maxCurve = new OptimizedCurve(true);
this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
this.maxCurve.integrateTwice();
break;
}
}
public uploadUniform (device: any, name: number) {
switch (this.mode) {
case 'constant':
device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CONSTANT);
device.setUniform('u_' + name + '_minConstant', this.minConstant);
break;
case 'twoConstants':
device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CONSTANT);
device.setUniform('u_' + name + '_minConstant', this.minConstant);
device.setUniform('u_' + name + '_maxConstant', this.maxConstant);
break;
case 'curve':
device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CURVE);
device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform);
device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform);
if (this.minCurve.integralUniform !== undefined) {
device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform);
}
break;
case 'twoCurves':
device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CURVE);
device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform);
device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform);
if (this.minCurve.integralUniform !== undefined) {
device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform);
}
device.setUniform('u_' + name + '_maxKeyTime', this.maxCurve.timeUniform);
device.setUniform('u_' + name + '_maxKeyCoef', this.maxCurve.coefUniform);
if (this.minCurve.integralUniform !== undefined) {
device.setUniform('u_' + name + '_maxIntegral', this.maxCurve.integralUniform);
}
break;
}
}
}
@@ -2,23 +2,26 @@ import { pseudoRandom } from "../../../../core/vmath";
import { CCClass } from "../../../../core/data";
import CurveRange from "./curve-range";
import { property, ccclass } from "../../../../core/data/class-decorator";
import Particle from "../particle";
// tslint:disable: max-line-length
const ROTATION_OVERTIME_RAND_OFFSET = 125292;
@ccclass('cc.RotationOvertimeModule')
export default class RotationOvertimeModule {
@property
enable = false;
public enable = false;
@property
_separateAxes = false;
private _separateAxes = false;
get separateAxes() {
@property
get separateAxes () {
return this._separateAxes;
}
set separateAxes(val) {
set separateAxes (val) {
if (!val) {
this._separateAxes = val;
}
@@ -28,28 +31,28 @@ export default class RotationOvertimeModule {
}
@property({
type: CurveRange
type: CurveRange,
})
x = new CurveRange();
public x = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
y = new CurveRange();
public y = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
z = new CurveRange();
public z = new CurveRange();
constructor() {
constructor () {
}
animate(p, dt) {
let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
public animate (p: Particle, dt: number) {
const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
if (!this._separateAxes) {
p.rotation.x += this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET)) * dt;
p.rotation.x += this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET))! * dt;
}
else {
// TODO: separateAxes is temporarily not supported!
@@ -2,41 +2,43 @@ import { vec3, pseudoRandom } from '../../../../core/vmath';
import CurveRange from './curve-range';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
import Particle from '../particle';
// tslint:disable: max-line-length
const SIZE_OVERTIME_RAND_OFFSET = 39825;
@ccclass('cc.SizeOvertimeModule')
export default class SizeOvertimeModule {
@property
enable = false;
public enable = false;
@property
separateAxes = false;
public separateAxes = false;
@property({
type: CurveRange
type: CurveRange,
})
size = new CurveRange();
public size = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
x = new CurveRange();
public x = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
y = new CurveRange();
public y = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
z = new CurveRange();
public z = new CurveRange();
animate(particle) {
public animate (particle: Particle) {
if (!this.separateAxes) {
vec3.scale(particle.size, particle.startSize, this.size.evaluate(1 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET)));
vec3.scale(particle.size, particle.startSize, this.size.evaluate(1 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET))!);
}
}
}
@@ -3,42 +3,45 @@ import { Enum } from "../../../../core/value-types";
import CurveRange from "./curve-range";
import { CCClass } from "../../../../core/data";
import { property, ccclass } from "../../../../core/data/class-decorator";
import ParticleSystemComponent from "../particle-system-component";
import Particle from "../particle";
// tslint:disable: max-line-length
const TEXTURE_ANIMATION_RAND_OFFSET = 90794;
const Mode = Enum({
Grid: 0,
Sprites: 1
Sprites: 1,
});
const Animation = Enum({
WholeSheet: 0,
SingleRow: 1
SingleRow: 1,
});
@ccclass('cc.TextureAnimationModule')
export default class TextureAnimationModule {
@property
_enable = false;
private _enable = false;
get enable() {
get enable () {
return this._enable;
}
set enable(val) {
set enable (val) {
this._enable = val;
this.ps.renderer._updateMaterialParams();
this.ps!.renderer!._updateMaterialParams();
}
@property
_mode = Mode.Grid
private _mode = Mode.Grid;
get mode() {
get mode () {
return this._mode;
}
set mode(val) {
set mode (val) {
if (val === Mode.Sprites) {
console.error("particle texture animation's sprites is not supported!");
return;
@@ -46,89 +49,91 @@ export default class TextureAnimationModule {
}
@property
numTilesX = 0;
public numTilesX = 0;
@property
numTilesY = 0;
public numTilesY = 0;
@property
animation = Animation.WholeSheet;
public animation = Animation.WholeSheet;
@property({
type: CurveRange
type: CurveRange,
})
frameOverTime = new CurveRange();
public frameOverTime = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
startFrame = new CurveRange();
public startFrame = new CurveRange();
@property
cycleCount = 0;
public cycleCount = 0;
@property
_flipU = 0;
private _flipU = 0;
get flipU() {
get flipU () {
return this._flipU;
}
set flipU(val) {
set flipU (val) {
console.error("particle texture animation's flipU is not supported!");
}
@property
_flipV = 0;
private _flipV = 0;
get flipV() {
get flipV () {
return this._flipV;
}
set flipV(val) {
set flipV (val) {
console.error("particle texture animation's flipV is not supported!");
}
@property
_uvChannelMask = -1
private _uvChannelMask = -1;
get uvChannelMask() {
get uvChannelMask () {
return this._uvChannelMask;
}
set uvChannelMask(val) {
set uvChannelMask (val) {
console.error("particle texture animation's uvChannelMask is not supported!");
}
@property
randomRow = false;
public randomRow = false;
@property
rowIndex = 0;
public rowIndex = 0;
onInit(ps) {
private ps: ParticleSystemComponent | null = null;
public onInit (ps: ParticleSystemComponent) {
this.ps = ps;
}
animate(p) {
let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
let startFrame = this.startFrame.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) / (this.numTilesX * this.numTilesY);
if (this.animation == Animation.WholeSheet) {
p.frameIndex = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1);
public animate (p: Particle) {
const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
const startFrame = this.startFrame.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! / (this.numTilesX * this.numTilesY);
if (this.animation === Animation.WholeSheet) {
p.frameIndex = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1);
}
else if (this.animation == Animation.SingleRow) {
let rowLength = 1 / this.numTilesY;
if (this._randomRow) {
let f = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1);
let startRow = Math.floor(Math.random() * this.numTilesY);
let from = startRow * rowLength;
let to = from + rowLength;
else if (this.animation === Animation.SingleRow) {
const rowLength = 1 / this.numTilesY;
if (this.randomRow) {
const f = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1);
const startRow = Math.floor(Math.random() * this.numTilesY);
const from = startRow * rowLength;
const to = from + rowLength;
p.frameIndex = lerp(from, to, f);
}
else {
let from = this.rowIndex * rowLength;
let to = from + rowLength;
p.frameIndex = lerp(from, to, repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1));
const from = this.rowIndex * rowLength;
const to = from + rowLength;
p.frameIndex = lerp(from, to, repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1));
}
}
}
@@ -1,57 +1,66 @@
import { vec3, quat, pseudoRandom } from '../../../../core/vmath';
import { vec3, quat, pseudoRandom, mat4 } from '../../../../core/vmath';
import { calculateTransform, Space } from '../particle-general-function';
import CurveRange from './curve-range';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
import Particle from '../particle';
// tslint:disable: max-line-length
const VELOCITY_OVERTIME_RAND_OFFSET = 197866;
@ccclass('cc.VelocityOvertimeModule')
export default class VelocityOvertimeModule {
@property
enable = false;
public enable = false;
@property({
type: CurveRange
type: CurveRange,
})
x = new CurveRange();
public x = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
y = new CurveRange();
public y = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
z = new CurveRange();
public z = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
speedModifier = new CurveRange();
public speedModifier = new CurveRange();
@property
space = Space.Local;
@property({
type: Space,
})
public space = Space.Local;
constructor() {
private rotation: quat;
private needTransform: boolean;
constructor () {
this.rotation = quat.create();
this.speedModifier.constant = 1;
this.needTransform = false;
}
update(space, worldTransform) {
public update (space: number, worldTransform: mat4) {
this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation);
}
animate(p) {
let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
let vel = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)));
public animate (p: Particle) {
const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
const vel = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)));
if (this.needTransform) {
vec3.transformQuat(vel, vel, this.rotation);
}
vec3.add(p.animatedVelocity, p.animatedVelocity, vel);
vec3.add(p.ultimateVelocity, p.velocity, p.animatedVelocity);
vec3.scale(p.ultimateVelocity, p.ultimateVelocity, this.speedModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)));
vec3.scale(p.ultimateVelocity, p.ultimateVelocity, this.speedModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))!);
}
}
@@ -1,12 +1,14 @@
import { randomUnitVector, particleEmitZAxis, randomSortArray, randomSign, randomPointBetweenSphere, randomPointInCube, randomPointBetweenCircleAtFixedAngle, fixedAngleUnitVector2 } from '../particle-general-function';
import { vec3, vec2, random, randomRange, mat4, quat, clamp, repeat, pingPong } from '../../../../core/vmath';
import { vec3, vec2, random, randomRange, mat4, quat, clamp, repeat, pingPong, toRadian, toDegree } from '../../../../core/vmath';
import { Enum, Vec3 } from '../../../../core/value-types';
import CurveRange from '../animator/curve-range';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
import ParticleSystemComponent from '../particle-system-component';
let _intermediVec = vec3.create(0, 0, 0);
let _intermediArr = new Array();
// tslint:disable: max-line-length
const _intermediVec = vec3.create(0, 0, 0);
const _intermediArr = new Array();
const _unitBoxExtent = vec3.create(0.5, 0.5, 0.5);
const ShapeType = Enum({
@@ -14,130 +16,162 @@ const ShapeType = Enum({
Circle: 1,
Cone: 2,
Sphere: 3,
Hemisphere: 4
Hemisphere: 4,
});
const EmitLocation = Enum({
Base: 0,
Edge: 1,
Shell: 2,
Volume: 3
Volume: 3,
});
const ArcMode = Enum({
Random: 0,
Loop: 1,
PingPong: 2
PingPong: 2,
});
@ccclass('cc.ShapeModule')
export default class ShapeModule {
@property
enable = false;
public enable = false;
@property({
type: ShapeType
type: ShapeType,
})
shapeType = ShapeType.Box;
public shapeType = ShapeType.Box;
@property({
type: EmitLocation
type: EmitLocation,
})
emitFrom = EmitLocation.Volume;
public emitFrom = EmitLocation.Volume;
@property
_position = new Vec3(0, 0, 0);
private _position = new Vec3(0, 0, 0);
get position() {
@property
get position () {
return this._position;
}
set position(val) {
set position (val) {
this._position = val;
this.constructMat();
}
@property
_rotation = new Vec3(0, 0, 0);
private _rotation = new Vec3(0, 0, 0);
get rotation() {
@property
get rotation () {
return this._rotation;
}
set rotation(val) {
set rotation (val) {
this._rotation = val;
this.constructMat();
}
@property
_scale = new Vec3(0, 0, 0);
private _scale = new Vec3(1, 1, 1);
get scale() {
@property
get scale () {
return this._scale;
}
set scale(val) {
set scale (val) {
this._scale = val;
this.constructMat();
}
@property
alignToDirection = false;
public alignToDirection = false;
@property
randomDirectionAmount = 0;
public randomDirectionAmount = 0;
@property
sphericalDirectionAmount = 0;
public sphericalDirectionAmount = 0;
@property
randomPositionAmount = 0;
public randomPositionAmount = 0;
@property
radius = 0;
public radius = 1;
@property
radiusThickness = 1;
public radiusThickness = 1;
@property
arc = 0;
private _arc = toRadian(360);
@property
arcMode = ArcMode.Random;
@property
arcSpread = 0;
@property({
type: CurveRange
})
arcSpeed = new CurveRange();
@property
angle = 0;
@property
length = 0;
@property
boxThickness = new Vec3(0, 0, 0);
constructor() {
this.mat = mat4.create();
this.quat = quat.create();
get arc () {
return toDegree(this._arc);
}
onInit(ps) {
set arc (val) {
this._arc = toRadian(val);
}
@property({
type: ArcMode,
})
public arcMode = ArcMode.Random;
@property
public arcSpread = 0;
@property({
type: CurveRange,
})
public arcSpeed = new CurveRange();
@property
private _angle = toRadian(25);
@property
get angle () {
return toDegree(this._angle);
}
set angle (val) {
this._angle = toRadian(val);
}
@property
public length = 0;
@property
public boxThickness = new Vec3(0, 0, 0);
private mat: mat4;
private quat: quat;
private particleSystem: ParticleSystemComponent | null;
private lastTime: number;
private totalAngle: number;
constructor () {
this.mat = mat4.create();
this.quat = quat.create();
this.particleSystem = null;
this.lastTime = 0;
this.totalAngle = 0;
}
public onInit (ps: ParticleSystemComponent) {
this.constructMat();
this.particleSystem = ps;
this.lastTime = ps._time;
this.totalAngle = 0;
}
constructMat() {
private constructMat () {
quat.fromEuler(this.quat, this._rotation.x, this._rotation.y, this._rotation.z);
mat4.fromRTS(this.mat, this.quat, this._position, this._scale);
}
emit(p) {
public emit (p) {
switch (this.shapeType) {
case ShapeType.Box:
boxEmit(this.emitFrom, this.boxThickness, p.position, p.velocity);
@@ -146,7 +180,7 @@ export default class ShapeModule {
circleEmit(this.radius, this.radiusThickness, this.generateArcAngle(), p.position, p.velocity);
break;
case ShapeType.Cone:
coneEmit(this.emitFrom, this.radius, this.radiusThickness, this.generateArcAngle(), this.angle, this.length, p.position, p.velocity);
coneEmit(this.emitFrom, this.radius, this.radiusThickness, this.generateArcAngle(), this._angle, this.length, p.position, p.velocity);
break;
case ShapeType.Sphere:
sphereEmit(this.emitFrom, this.radius, this.radiusThickness, p.position, p.velocity);
@@ -165,31 +199,31 @@ export default class ShapeModule {
vec3.transformQuat(p.velocity, p.velocity, this.quat);
vec3.transformMat4(p.position, p.position, this.mat);
if (this.sphericalDirectionAmount > 0) {
let sphericalVel = vec3.normalize(_intermediVec, p.position);
const sphericalVel = vec3.normalize(_intermediVec, p.position);
vec3.lerp(p.velocity, p.velocity, sphericalVel, this.sphericalDirectionAmount);
}
this.lastTime = this.particleSystem._time;
this.lastTime = this.particleSystem!._time;
}
generateArcAngle() {
private generateArcAngle () {
if (this.arcMode === ArcMode.Random) {
return randomRange(0, this.arc);
return randomRange(0, this._arc);
}
let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem._time) * (this.particleSystem._time - this.lastTime);
let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem!._time, 1)! * (this.particleSystem!._time - this.lastTime);
this.totalAngle = angle;
if (this.arcSpread !== 0) {
angle = Math.floor(angle / (this.arc * this.arcSpread)) * this.arc * this.arcSpread;
angle = Math.floor(angle / (this._arc * this.arcSpread)) * this._arc * this.arcSpread;
}
switch (this.arcMode) {
case ArcMode.Loop:
return repeat(angle, this.arc);
return repeat(angle, this._arc);
case ArcMode.PingPong:
return pingPong(angle, this.arc);
return pingPong(angle, this._arc);
}
}
}
function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
function sphereEmit (emitFrom, radius, radiusThickness, pos, dir) {
switch (emitFrom) {
case EmitLocation.Volume:
randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius);
@@ -206,7 +240,7 @@ function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
}
}
function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
function hemisphereEmit (emitFrom, radius, radiusThickness, pos, dir) {
switch (emitFrom) {
case EmitLocation.Volume:
randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius);
@@ -229,7 +263,7 @@ function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
}
}
function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) {
function coneEmit (emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) {
switch (emitFrom) {
case EmitLocation.Base:
randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta);
@@ -259,7 +293,7 @@ function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos,
}
}
function boxEmit(emitFrom, boxThickness, pos, dir) {
function boxEmit (emitFrom, boxThickness, pos, dir) {
switch (emitFrom) {
case EmitLocation.Volume:
randomPointInCube(pos, _unitBoxExtent);
@@ -289,12 +323,12 @@ function boxEmit(emitFrom, boxThickness, pos, dir) {
vec3.copy(dir, particleEmitZAxis);
}
function circleEmit(radius, radiusThickness, theta, pos, dir) {
function circleEmit (radius, radiusThickness, theta, pos, dir) {
randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta);
vec3.normalize(dir, pos);
}
function applyBoxThickness(pos, thickness) {
function applyBoxThickness (pos, thickness) {
if (thickness.x > 0) {
pos[0] += 0.5 * randomRange(-thickness.x, thickness.x);
pos[0] = clamp(pos[0], -0.5, 0.5);
@@ -7,10 +7,10 @@ export const particleEmitZAxis = vec3.create(0, 0, -1);
export const Space = Enum({
World: 0,
Local: 1,
Custom: 2
Custom: 2,
});
export function calculateTransform(systemSpace, moduleSpace, worldTransform, outQuat) {
export function calculateTransform (systemSpace, moduleSpace, worldTransform, outQuat) {
if (moduleSpace !== systemSpace) {
if (systemSpace === 'world') {
mat4.getRotation(outQuat, worldTransform);
@@ -27,67 +27,70 @@ export function calculateTransform(systemSpace, moduleSpace, worldTransform, out
}
}
export function fixedAngleUnitVector2(out, theta) {
export function fixedAngleUnitVector2 (out, theta) {
vec2.set(out, Math.cos(theta), Math.sin(theta));
}
export function randomUnitVector2(out) {
let a = randomRange(0, 2 * Math.PI);
let x = Math.cos(a);
let y = Math.sin(a);
export function randomUnitVector2 (out) {
const a = randomRange(0, 2 * Math.PI);
const x = Math.cos(a);
const y = Math.sin(a);
vec2.set(out, x, y);
}
export function randomUnitVector(out) {
let z = randomRange(-1, 1);
let a = randomRange(0, 2 * Math.PI);
let r = Math.sqrt(1 - z * z);
let x = r * Math.cos(a);
let y = r * Math.sin(a);
export function randomUnitVector (out) {
const z = randomRange(-1, 1);
const a = randomRange(0, 2 * Math.PI);
const r = Math.sqrt(1 - z * z);
const x = r * Math.cos(a);
const y = r * Math.sin(a);
vec3.set(out, x, y, z);
}
export function randomPointInUnitSphere(out) {
export function randomPointInUnitSphere (out) {
randomUnitVector(out);
vec3.scale(out, out, random());
}
export function randomPointBetweenSphere(out, minRadius, maxRadius) {
export function randomPointBetweenSphere (out, minRadius, maxRadius) {
randomUnitVector(out);
vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random());
}
export function randomPointInUnitCircle(out) {
export function randomPointInUnitCircle (out) {
randomUnitVector2(out);
out.z = 0;
vec3.scale(out, out, random());
}
export function randomPointBetweenCircle(out, minRadius, maxRadius) {
export function randomPointBetweenCircle (out, minRadius, maxRadius) {
randomUnitVector2(out);
out.z = 0;
vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random());
}
export function randomPointBetweenCircleAtFixedAngle(out, minRadius, maxRadius, theta) {
export function randomPointBetweenCircleAtFixedAngle (out, minRadius, maxRadius, theta) {
fixedAngleUnitVector2(out, theta);
out.z = 0;
vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random());
}
export function randomPointInCube(out, extents) {
export function randomPointInCube (out, extents) {
vec3.set(out,
randomRange(-extents.x, extents.x),
randomRange(-extents.y, extents.y),
randomRange(-extents.z, extents.z));
}
export function randomPointBetweenCube(out, minBox, maxBox) {
export function randomPointBetweenCube (out, minBox, maxBox) {
const subscript = ['x', 'y', 'z'];
let edge = randomRangeInt(0, 3);
const edge = randomRangeInt(0, 3);
for (let i = 0; i < 3; i++) {
if (i === edge) {
out[subscript[i]] = randomRange(-maxBox[subscript[i]], maxBox[subscript[i]]);
continue;
}
let x = random() * 2 - 1;
const x = random() * 2 - 1;
if (x < 0) {
out[subscript[i]] = -minBox[subscript[i]] + x * (maxBox[subscript[i]] - minBox[subscript[i]]);
}
@@ -98,16 +101,16 @@ export function randomPointBetweenCube(out, minBox, maxBox) {
}
// Fisher–Yates shuffle
export function randomSortArray(arr) {
export function randomSortArray (arr) {
for (let i = 0; i < arr.length; i++) {
let transpose = i + randomRangeInt(0, arr.length - i);
let val = arr[transpose];
const transpose = i + randomRangeInt(0, arr.length - i);
const val = arr[transpose];
arr[transpose] = arr[i];
arr[i] = val;
}
}
export function randomSign() {
export function randomSign () {
let sgn = randomRange(-1, 1);
sgn === 0 ? sgn++ : sgn;
return sign(sgn);
@@ -18,7 +18,7 @@ import { particleEmitZAxis, Space } from './particle-general-function';
import { INT_MAX } from '../../../core/vmath/bits';
import { ccclass, executionOrder, executeInEditMode, property, requireComponent, menu } from '../../../core/data/class-decorator';
let _world_mat = mat4.create();
const _world_mat = mat4.create();
@ccclass('cc.ParticleSystemComponent')
@menu('Components/ParticleSystemComponent')
@@ -28,155 +28,165 @@ let _world_mat = mat4.create();
export default class ParticleSystemComponent extends Component {
@property
capacity = 2000;
public capacity = 2000;
@property({
type:GradientRange
type: GradientRange,
})
startColor = new GradientRange();
public startColor = new GradientRange();
@property({
type: CurveRange
type: CurveRange,
})
startSize = new CurveRange();
public startSize = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
startSpeed = new CurveRange();
public startSpeed = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
startRotation = new CurveRange();
public startRotation = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
startDelay = new CurveRange();
public startDelay = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
startLifetime = new CurveRange();
public startLifetime = new CurveRange();
@property
duration = 5.0;
public duration = 5.0;
@property
loop = true;
public loop = true;
@property
_prewarm = false;
private _prewarm = false;
@property
get prewarm() {
get prewarm () {
return this._prewarm;
}
set prewarm(val) {
if (val === true && this._loop === false) {
set prewarm (val) {
if (val === true && this.loop === false) {
// console.warn('prewarm only works if loop is also enabled.');
}
this._prewarm = val;
}
@property
_simulationSpace = Space.Local;
private _simulationSpace = Space.Local;
@property({
type: Space
type: Space,
})
get simulationSpace() {
get simulationSpace () {
return this._simulationSpace;
}
set simulationSpace(val) {
if (val === Space.World) {
this._renderer._material.define('USE_WORLD_SPACE', true);
} else {
this._renderer._material.define('USE_WORLD_SPACE', false);
set simulationSpace (val) {
if (val !== this._simulationSpace) {
this._simulationSpace = val;
this.renderer!._updateMaterialParams();
}
this._simulationSpace = val;
}
@property
simulationSpeed = 1.0;
public simulationSpeed = 1.0;
@property
playOnAwake = true;
public playOnAwake = true;
@property({
type: CurveRange
type: CurveRange,
})
gravityModifier = new CurveRange();
public gravityModifier = new CurveRange();
// emission module
@property({
type: CurveRange
type: CurveRange,
})
rateOverTime = new CurveRange();
public rateOverTime = new CurveRange();
@property({
type: CurveRange
type: CurveRange,
})
rateOverDistance = new CurveRange();
public rateOverDistance = new CurveRange();
@property({
type: [Burst]
type: [Burst],
})
bursts = new Array();
public bursts = new Array();
// color over lifetime module
@property({
type: ColorOverLifetimeModule
type: ColorOverLifetimeModule,
})
colorOverLifetimeModule = new ColorOverLifetimeModule();
public colorOverLifetimeModule = new ColorOverLifetimeModule();
// shpae module
@property({
type: ShapeModule
type: ShapeModule,
})
shapeModule = new ShapeModule();
// particle system renderer
@property({
type: ParticleSystemRenderer
})
renderer = null;
public shapeModule = new ShapeModule();
// size over lifetime module
@property({
type: SizeOvertimeModule
type: SizeOvertimeModule,
})
sizeOvertimeModule = new SizeOvertimeModule();
public sizeOvertimeModule = new SizeOvertimeModule();
@property({
type: VelocityOvertimeModule
type: VelocityOvertimeModule,
})
velocityOvertimeModule = new VelocityOvertimeModule();
public velocityOvertimeModule = new VelocityOvertimeModule();
@property({
type: ForceOvertimeModule
type: ForceOvertimeModule,
})
forceOvertimeModule = new ForceOvertimeModule();
public forceOvertimeModule = new ForceOvertimeModule();
@property({
type: LimitVelocityOvertimeModule
type: LimitVelocityOvertimeModule,
})
limitVelocityOvertimeModule = new LimitVelocityOvertimeModule();
public limitVelocityOvertimeModule = new LimitVelocityOvertimeModule();
@property({
type: RotationOvertimeModule
type: RotationOvertimeModule,
})
rotationOvertimeModule = new RotationOvertimeModule();
public rotationOvertimeModule = new RotationOvertimeModule();
@property({
type: TextureAnimationModule
type: TextureAnimationModule,
})
textureAnimationModule = new TextureAnimationModule();
public textureAnimationModule = new TextureAnimationModule();
constructor() {
// particle system renderer
private renderer: ParticleSystemRenderer | null;
private _isPlaying: boolean;
private _isPaused: boolean;
private _isStopped: boolean;
private _isEmitting: boolean;
private _time: number; // playback position in seconds.
private _emitRateTimeCounter: number;
private _emitRateDistanceCounter: number;
private _oldWPos: vec3;
private _curWPos: vec3;
private _customData1: vec2;
private _customData2: vec2;
private _subEmitters: any[]; // array of { emitter: ParticleSystemComponent, type: 'birth', 'collision' or 'death'}
constructor () {
super();
this.rateOverTime.constant = 10;
@@ -200,9 +210,10 @@ export default class ParticleSystemComponent extends Component {
this._customData2 = vec2.create(0, 0);
this._subEmitters = []; // array of { emitter: ParticleSystemComponent, type: 'birth', 'collision' or 'death'}
this.renderer = null;
}
onLoad() {
private onLoad () {
// HACK, TODO
this.renderer = this.getComponent(ParticleSystemRenderer);
this.renderer.onInit();
@@ -215,17 +226,17 @@ export default class ParticleSystemComponent extends Component {
// this._system.add(this);
}
onDestroy() {
private onDestroy () {
// this._system.remove(this);
}
onEnable() {
private onEnable () {
if (this.playOnAwake) {
this.play();
}
}
onDisable() {
private onDisable () {
}
@@ -234,7 +245,7 @@ export default class ParticleSystemComponent extends Component {
// }
play() {
public play () {
if (this._isPaused) {
this._isPaused = false;
}
@@ -254,7 +265,7 @@ export default class ParticleSystemComponent extends Component {
}
}
pause() {
public pause () {
if (this._isStopped) {
console.warn('pause(): particle system is already stopped.');
return;
@@ -266,7 +277,7 @@ export default class ParticleSystemComponent extends Component {
this._isPaused = true;
}
stop() {
public stop () {
if (this._isPlaying) {
this._isPlaying = false;
}
@@ -283,21 +294,21 @@ export default class ParticleSystemComponent extends Component {
}
// remove all particles from current particle system.
clear() {
this._particles.reset();
this._renderer._model.clear();
public clear () {
this.renderer!.clear();
}
emit(count, emitParams = null) {
private emit (count, emitParams = null) {
if (emitParams !== null) {
// TODO:
}
for (let i = 0; i < count; ++i) {
let particle = this.renderer._getFreeParticle();
if (particle === null)
const particle = this.renderer!._getFreeParticle();
if (particle === null) {
return;
let rand = pseudoRandom(randomRangeInt(0, INT_MAX));
}
const rand = pseudoRandom(randomRangeInt(0, INT_MAX));
if (this.shapeModule.enable) {
this.shapeModule.emit(particle);
@@ -312,13 +323,12 @@ export default class ParticleSystemComponent extends Component {
switch (this._simulationSpace) {
case Space.Local:
break;
case Space.World: {
case Space.World:
this.node.getWorldMatrix(_world_mat);
vec3.transformMat4(particle.position, particle.position, _world_mat);
let worldRot = quat.create();
const worldRot = quat.create();
this.node.getWorldRotation(worldRot);
vec3.transformQuat(particle.velocity, particle.velocity, worldRot);
}
break;
case Space.Custom:
// TODO:
@@ -342,88 +352,28 @@ export default class ParticleSystemComponent extends Component {
particle.randomSeed = randomRangeInt(0, 233280);
this.renderer._setNewParticle(particle);
this.renderer!._setNewParticle(particle);
} // end of particles forLoop.
}
// simulation, update particles.
_updateParticles(dt) {
this._entity.getWorldMatrix(_world_mat);
if (this._velocityOvertimeModule.enable) {
this._velocityOvertimeModule.update(this._simulationSpace, _world_mat);
}
if (this._forceOvertimeModule.enable) {
this._forceOvertimeModule.update(this._simulationSpace, _world_mat);
}
for (let i = 0; i < this._particles.length; ++i) {
let p = this._particles.data[i];
p.remainingLifetime -= dt;
vec3.set(p.animatedVelocity, 0, 0, 0);
if (p.remainingLifetime < 0.0) {
// subEmitter
// if (this._subEmitters.length > 0) {
// for (let idx = 0; idx < this._subEmitters.length; ++idx) {
// let subEmitter = this._subEmitters[idx];
// if (subEmitter.type === 'death') {
// vec3.copy(subEmitter.emitter.entity.lpos, p.position);
// subEmitter.emitter.play();
// }
// }
// }
this._particles.removeAt(i);
--i;
continue;
}
p.velocity.y -= this._gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity.
if (this._sizeOvertimeModule.enable) {
this._sizeOvertimeModule.animate(p);
}
if (this._colorOverLifetimeModule.enable) {
this._colorOverLifetimeModule.animate(p);
}
if (this._forceOvertimeModule.enable) {
this._forceOvertimeModule.animate(p, dt);
}
if (this._velocityOvertimeModule.enable) {
this._velocityOvertimeModule.animate(p);
}
else {
vec3.copy(p.ultimateVelocity, p.velocity);
}
if (this._limitVelocityOvertimeModule.enable) {
this._limitVelocityOvertimeModule.animate(p);
}
if (this._rotationOvertimeModule.enable) {
this._rotationOvertimeModule.animate(p, dt);
}
if (this._textureAnimationModule.enable) {
this._textureAnimationModule.animate(p);
}
vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity.
}
}
// initialize particle system as though it had already completed a full cycle.
_prewarmSystem() {
this._startDelay.mode = 'constant'; // clear startDelay.
this._startDelay.constant = 0;
let dt = 1.0; // should use varying value?
let cnt = this.duration / dt;
private _prewarmSystem () {
this.startDelay.mode = 'constant'; // clear startDelay.
this.startDelay.constant = 0;
const dt = 1.0; // should use varying value?
const cnt = this.duration / dt;
for (let i = 0; i < cnt; ++i) {
this._time += dt;
this._emit(dt);
this._renderer._updateParticles(dt);
this.renderer!._updateParticles(dt);
}
}
// internal function
_emit(dt) {
private _emit (dt) {
// emit particles.
let startDelay = this.startDelay.evaluate();
const startDelay = this.startDelay.evaluate();
if (this._time > startDelay) {
if (!this._isStopped) {
this._isEmitting = true;
@@ -441,30 +391,30 @@ export default class ParticleSystemComponent extends Component {
// emit by rateOverTime
this._emitRateTimeCounter += this.rateOverTime.evaluate(this._time / this.duration, 1) * dt;
if (this._emitRateTimeCounter > 1 && this._isEmitting) {
let emitNum = Math.floor(this._emitRateTimeCounter);
const emitNum = Math.floor(this._emitRateTimeCounter);
this._emitRateTimeCounter -= emitNum;
this.emit(emitNum);
}
// emit by rateOverDistance
this.node.getWorldPosition(this._curWPos);
let distance = vec3.distance(this._curWPos, this._oldWPos);
const distance = vec3.distance(this._curWPos, this._oldWPos);
vec3.copy(this._oldWPos, this._curWPos);
this._emitRateDistanceCounter += distance * this.rateOverDistance.evaluate(this._time / this.duration, 1);
if (this._emitRateDistanceCounter > 1 && this._isEmitting) {
let emitNum = Math.floor(this._emitRateDistanceCounter);
const emitNum = Math.floor(this._emitRateDistanceCounter);
this._emitRateDistanceCounter -= emitNum;
this.emit(emitNum);
}
// bursts
for (let i = 0; i < this.bursts.length; ++i) {
this.bursts[i].update(this, dt);
for (const burst of this.bursts) {
burst.update(this, dt);
}
}
}
update(dt) {
let scaledDeltaTime = dt * this.simulationSpeed;
private update (dt) {
const scaledDeltaTime = dt * this.simulationSpeed;
if (this._isPlaying) {
this._time += scaledDeltaTime;
@@ -472,58 +422,58 @@ export default class ParticleSystemComponent extends Component {
this._emit(scaledDeltaTime);
// simulation, update particles.
this.renderer._updateParticles(scaledDeltaTime);
this.renderer!._updateParticles(scaledDeltaTime);
// update render data
this.renderer._updateRenderData();
this.renderer!._updateRenderData();
}
}
addSubEmitter(subEmitter) {
private addSubEmitter (subEmitter) {
this._subEmitters.push(subEmitter);
}
removeSubEmitter(idx) {
this._subEmitters.remove(idx);
private removeSubEmitter (idx) {
this._subEmitters.splice(this._subEmitters.indexOf(idx), 1);
}
addBurst(burst) {
this._bursts.push(burst);
private addBurst (burst) {
this.bursts.push(burst);
}
removeBurst(idx) {
this._bursts.remove(idx);
private removeBurst (idx) {
this.bursts.splice(this.bursts.indexOf(idx), 1);
}
getParticleCount() {
return this._particles.length;
public getParticleCount () {
return this.renderer!.getParticleCount();
}
setCustomData1(x, y) {
public setCustomData1 (x, y) {
vec2.set(this._customData1, x, y);
}
setCustomData2(x, y) {
public setCustomData2 (x, y) {
vec2.set(this._customData2, x, y);
}
get isPlaying() {
get isPlaying () {
return this._isPlaying;
}
get isPaused() {
get isPaused () {
return this._isPaused;
}
get isStopped() {
get isStopped () {
return this._isStopped;
}
get isEmitting() {
get isEmitting () {
return this._isEmitting;
}
get time() {
get time () {
return this._time;
}
}
@@ -7,7 +7,7 @@ import * as renderer from '../../../../renderer';
import gfx from '../../../../renderer/gfx';
import ParticleBatchModel from '../../../../renderer/models/particle-batch-model';
import { Material } from '../../../assets/material';
import { RecyclePool } from '../../../memop';
import RecyclePool from '../../../memop/recycle-pool';
import Particle from '../particle';
import { RenderableComponent } from '../../renderable-component';
import { Space } from '../particle-general-function';
@@ -157,7 +157,12 @@ export default class ParticleSystemRenderer extends RenderableComponent {
this._model!.destroy();
}
public _getFreeParticle () {
private clear () {
this._particles.reset();
this._model!.destroy();
}
public _getFreeParticle (): Particle | null {
if (this._particles.length >= this.particleSystem._capacity) {
return null;
}
@@ -256,6 +261,10 @@ export default class ParticleSystemRenderer extends RenderableComponent {
}
public getParticleCount (): number {
return this._particles.length;
}
public _onMaterialModified (index: number, material: Material) {
this._updateMaterialParams();
this._updateModel();
@@ -9,70 +9,77 @@ const WrapMode = Enum({
Once: 1,
Loop: 2,
PingPong: 3,
ClampForever: 4
ClampForever: 4,
});
export class Keyframe {
time = 0;
public time = 0;
value = 0;
public value = 0;
inTangent = 0;
public inTangent = 0;
outTangent = 0;
public outTangent = 0;
}
CCClass.fastDefine('cc.Keyframe', Keyframe, {
time: 0,
value: 0,
inTangent: 0,
outTangent: 0
outTangent: 0,
});
export class OptimizedKey {
constructor() {
public index: number;
public time: number;
public endTime: number;
public coefficient: Float32Array;
constructor () {
this.index = -1;
this.time = 0;
this.endTime = 0;
this.coefficient = new Float32Array(4);
}
evaluate(T) {
let t = T - this.time;
public evaluate (T: number) {
const t = T - this.time;
return evalOptCurve(t, this.coefficient);
}
}
export function evalOptCurve(t, coefs) {
export function evalOptCurve (t: number, coefs: Float32Array) {
return (t * (t * (t * coefs[0] + coefs[1]) + coefs[2])) + coefs[3];
}
export class AnimationCurve {
keyFrames = null;
public keyFrames: Keyframe[] | null;
preWrapMode = WrapMode.Default;
public preWrapMode: number = WrapMode.Default;
postWrapMode = WrapMode.Default;
public postWrapMode: number = WrapMode.Default;
constructor(keyFrames) {
private cachedKey: OptimizedKey;
constructor (keyFrames: Keyframe[] | null = null) {
this.keyFrames = keyFrames;
this.cachedKey = new OptimizedKey();
}
addKey(keyFrame) {
if (this.keyFrames == null)
public addKey (keyFrame: Keyframe) {
if (this.keyFrames == null) {
this.keyFrames = [];
}
this.keyFrames.push(keyFrame);
}
//cubic Hermite spline
evaluate_slow(time) {
// cubic Hermite spline
public evaluate_slow (time: number) {
let wrappedTime = time;
let wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
let startTime = this.keyFrames[0].time;
let endTime = this.keyFrames[this.keyFrames.length - 1].time;
const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
const startTime = this.keyFrames![0].time;
const endTime = this.keyFrames![this.keyFrames!.length - 1].time;
switch (wrapMode) {
case WrapMode.Loop:
wrappedTime = repeat(time - startTime, endTime - startTime) + startTime;
@@ -85,43 +92,44 @@ export class AnimationCurve {
break;
}
let preKFIndex = 0;
if (wrappedTime > this.keyFrames[0].time) {
if (wrappedTime >= this.keyFrames[this.keyFrames.length - 1].time)
preKFIndex = this.keyFrames.length - 2;
if (wrappedTime > this.keyFrames![0].time) {
if (wrappedTime >= this.keyFrames![this.keyFrames!.length - 1].time) {
preKFIndex = this.keyFrames!.length - 2;
}
else {
for (let i = 0; i < this.keyFrames.length - 1; i++) {
if (wrappedTime >= this.keyFrames[0].time && wrappedTime <= this.keyFrames[i + 1].time) {
for (let i = 0; i < this.keyFrames!.length - 1; i++) {
if (wrappedTime >= this.keyFrames![0].time && wrappedTime <= this.keyFrames![i + 1].time) {
preKFIndex = i;
break;
}
}
}
}
let keyframe0 = this.keyFrames[preKFIndex];
let keyframe1 = this.keyFrames[preKFIndex + 1];
const keyframe0 = this.keyFrames![preKFIndex];
const keyframe1 = this.keyFrames![preKFIndex + 1];
let t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime);
let dt = keyframe1.time - keyframe0.time;
const t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime);
const dt = keyframe1.time - keyframe0.time;
let m0 = keyframe0.outTangent * dt;
let m1 = keyframe1.inTangent * dt;
const m0 = keyframe0.outTangent * dt;
const m1 = keyframe1.inTangent * dt;
let t2 = t * t;
let t3 = t2 * t;
const t2 = t * t;
const t3 = t2 * t;
let a = 2 * t3 - 3 * t2 + 1;
let b = t3 - 2 * t2 + t;
let c = t3 - t2;
let d = -2 * t3 + 3 * t2;
const a = 2 * t3 - 3 * t2 + 1;
const b = t3 - 2 * t2 + t;
const c = t3 - t2;
const d = -2 * t3 + 3 * t2;
return a * keyframe0.value + b * m0 + c * m1 + d * keyframe1.value;
}
evaluate(time) {
public evaluate (time) {
let wrappedTime = time;
let wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
let startTime = this.keyFrames[0].time;
let endTime = this.keyFrames[this.keyFrames.length - 1].time;
const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
const startTime = this.keyFrames![0].time;
const endTime = this.keyFrames![this.keyFrames!.length - 1].time;
switch (wrapMode) {
case WrapMode.Loop:
wrappedTime = repeat(time - startTime, endTime - startTime) + startTime;
@@ -136,9 +144,9 @@ export class AnimationCurve {
if (wrappedTime >= this.cachedKey.time && wrappedTime < this.cachedKey.endTime) {
return this.cachedKey.evaluate(wrappedTime);
} else {
let leftIndex = this.findIndex(this.cachedKey, wrappedTime);
const leftIndex = this.findIndex(this.cachedKey, wrappedTime);
let rightIndex = leftIndex + 1;
if (rightIndex == this.keyFrames.length) {
if (rightIndex === this.keyFrames!.length) {
rightIndex -= 1;
}
this.calcOptimizedKey(this.cachedKey, leftIndex, rightIndex);
@@ -146,18 +154,18 @@ export class AnimationCurve {
}
}
calcOptimizedKey(optKey, leftIndex, rightIndex) {
let lhs = this.keyFrames[leftIndex];
let rhs = this.keyFrames[rightIndex];
private calcOptimizedKey (optKey: OptimizedKey, leftIndex: number, rightIndex: number) {
const lhs = this.keyFrames![leftIndex];
const rhs = this.keyFrames![rightIndex];
optKey.index = leftIndex;
optKey.time = lhs.time;
optKey.endTime = rhs.time;
let dx = rhs.time - lhs.time;
let dy = rhs.value - lhs.value;
let length = 1 / (dx * dx);
let d1 = lhs.outTangent * dx;
let d2 = rhs.inTangent * dx;
const dx = rhs.time - lhs.time;
const dy = rhs.value - lhs.value;
const length = 1 / (dx * dx);
const d1 = lhs.outTangent * dx;
const d2 = rhs.inTangent * dx;
optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx;
optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length;
@@ -165,31 +173,31 @@ export class AnimationCurve {
optKey.coefficient[3] = lhs.value;
}
findIndex(optKey, t) {
let cachedIndex = optKey.index;
private findIndex (optKey: OptimizedKey, t: number) {
const cachedIndex = optKey.index;
if (cachedIndex !== -1) {
let cachedTime = this.keyFrames[cachedIndex].time;
const cachedTime = this.keyFrames![cachedIndex].time;
if (t > cachedTime) {
for (let i = 0; i < LOOK_FORWARD; i++) {
let currIndex = cachedIndex + i;
if (currIndex + 1 < this.keyFrames.length && this.keyFrames[currIndex + 1].time > t) {
const currIndex = cachedIndex + i;
if (currIndex + 1 < this.keyFrames!.length && this.keyFrames![currIndex + 1].time > t) {
return currIndex;
}
}
} else {
for (let i = 0; i < LOOK_FORWARD; i++) {
let currIndex = cachedIndex - i;
if (currIndex >= 0 && this.keyFrames[currIndex - 1].time <= t) {
const currIndex = cachedIndex - i;
if (currIndex >= 0 && this.keyFrames![currIndex - 1].time <= t) {
return currIndex - 1;
}
}
}
}
let left = 0;
let right = this.keyFrames.length;
let right = this.keyFrames!.length;
let mid = parseInt((left + right) / 2);
while (right - left > 1) {
if (this.keyFrames[mid].time >= t) {
if (this.keyFrames![mid].time >= t) {
right = mid;
} else {
left = mid + 1;
@@ -203,5 +211,5 @@ export class AnimationCurve {
CCClass.fastDefine('cc.AnimationCurve', AnimationCurve, {
preWrapMode: WrapMode.Default,
postWrapMode: WrapMode.Default,
keyFrames: []
keyFrames: [],
});
+1 -1
View File
@@ -62,7 +62,7 @@ export default class RecyclePool<T = any> {
public remove (obj: T) {
if (this._objIdx.has(obj)) {
this.removeAt(this._objIdx.get(obj));
this.removeAt(this._objIdx.get(obj)!);
}
}