diff --git a/cocos/3d/framework/index.js b/cocos/3d/framework/index.js index 9dac6884b1..ff59f71c33 100644 --- a/cocos/3d/framework/index.js +++ b/cocos/3d/framework/index.js @@ -33,6 +33,7 @@ import SkyboxComponent from './skybox-component'; import { BoxColliderComponent, SphereColliderComponent } from './physics/collider-component'; import { RigidBodyComponent } from './physics/rigid-body-component'; import './physics/index'; +import ParticleSystemComponent from './particle/particle-system-component'; cc.CameraComponent = CameraComponent; cc.AnimationComponent = AnimationComponent; @@ -43,4 +44,5 @@ cc.SkyboxComponent = SkyboxComponent; cc.RigidBodyComponent = RigidBodyComponent; cc.BoxColliderComponent = BoxColliderComponent; -cc.SphereColliderComponent = SphereColliderComponent; \ No newline at end of file +cc.SphereColliderComponent = SphereColliderComponent; +cc.ParticleSystemComponent = ParticleSystemComponent; diff --git a/cocos/3d/framework/particle/animator/color-overtime.js b/cocos/3d/framework/particle/animator/color-overtime.js new file mode 100644 index 0000000000..aba6e5a437 --- /dev/null +++ b/cocos/3d/framework/particle/animator/color-overtime.js @@ -0,0 +1,22 @@ +import { color4, pseudoRandom } from '../../../../core/vmath'; +import { CCClass } from '../../../../core/data'; + +const COLOR_OVERTIME_RAND_OFFSET = 91041; + +export default class ColorOvertimeModule { + + enable = false; + + color = null; + + animate(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))); + } + } +} + +CCClass.fastDefine('cc.ColorOvertimeModule', ColorOvertimeModule, { + enable: false, + color: null +}); diff --git a/cocos/3d/framework/particle/animator/curve-range.js b/cocos/3d/framework/particle/animator/curve-range.js new file mode 100644 index 0000000000..4c51d6b9cc --- /dev/null +++ b/cocos/3d/framework/particle/animator/curve-range.js @@ -0,0 +1,58 @@ +import { lerp } from '../../../../core/vmath'; +import { Enum } from '../../../../core/value-types'; +import { AnimationCurve } from '../../../geom-utils'; +import { CCClass } from '../../../../core/data'; + +const Mode = Enum({ + Constant: 0, + Curve: 1, + TwoCurves: 2, + TwoConstants: 3 +}); + +export default class CurveRange { + + mode = Mode.Constant; + + curve = null; + + curveMin = null; + + curveMax = null; + + constant = 0; + + constantMin = 0; + + constantMax = 0; + + multiplier = 1; + + constructor() { + + } + + evaluate(time, rndRatio) { + switch (this.mode) { + case Mode.Constant: + return this.constant; + case Mode.Curve: + return this.curve.evaluate(time) * this.multiplier; + case Mode.TwoCurves: + return lerp(this.curveMin.evaluate(time), this.curveMax.evaluate(time), rndRatio) * this.multiplier; + case Mode.TwoConstants: + return lerp(this.constantMin, this.constantMax, rndRatio); + } + } +} + +CCClass.fastDefine('cc.CurveRange', CurveRange, { + mode: Mode.Constant, + constant: 0, + constantMin: 0, + constantMax: 0, + curve: new AnimationCurve(), + curveMin: new AnimationCurve(), + curveMax: new AnimationCurve(), + multiplier: 1 +}); diff --git a/cocos/3d/framework/particle/animator/force-overtime.js b/cocos/3d/framework/particle/animator/force-overtime.js new file mode 100644 index 0000000000..1d33ce76b3 --- /dev/null +++ b/cocos/3d/framework/particle/animator/force-overtime.js @@ -0,0 +1,48 @@ +import { vec3, quat, pseudoRandom } from '../../../../core/vmath'; +import { calculateTransform, Space } from '../particle-general-function'; +import CurveRange from './curve-range'; +import { CCClass } from '../../../../core/data'; + +const FORCE_OVERTIME_RAND_OFFSET = 212165; + +export default class ForceOvertimeModule { + + enable = false; + + x = null; + + y = null; + + z = null; + + space = Space.Local; + + // TODO:currently not supported + randomized = false; + + constructor() { + this.rotation = quat.create(); + } + + 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))); + if (this.needTransform) { + vec3.transformQuat(force, force, this.rotation); + } + vec3.scaleAndAdd(p.velocity, p.velocity, force, dt); + } +} + +CCClass.fastDefine('cc.ForceOvertimeModule',ForceOvertimeModule,{ + enable : false, + x : new CurveRange(), + y : new CurveRange(), + z : new CurveRange(), + space : Space.Local, + randomized : false +}); diff --git a/cocos/3d/framework/particle/animator/gradient-range.js b/cocos/3d/framework/particle/animator/gradient-range.js new file mode 100644 index 0000000000..2e9343ef94 --- /dev/null +++ b/cocos/3d/framework/particle/animator/gradient-range.js @@ -0,0 +1,143 @@ +import { color4 } from '../../../../core/vmath'; +import { Enum } from '../../../../core/value-types'; +import Gradient from './gradient'; +import { CCClass } from '../../../../core/data'; + +const GRADIENT_MODE_FIX = 0; +const GRADIENT_MODE_BLEND = 1; + +const GRADIENT_RANGE_MODE_COLOR = 0; +const GRADIENT_RANGE_MODE_TWO_COLOR = 1; +const GRADIENT_RANGE_MODE_RANDOM_COLOR = 2; +const GRADIENT_RANGE_MODE_GRADIENT = 3; +const GRADIENT_RANGE_MODE_TWO_GRADIENT = 4; + +const Mode = Enum({ + Color: 0, + Gradient: 1, + TwoColors: 2, + TwoGradients: 3, + RandomColor: 4 +}); + +export default class GradientRange { + + mode = Mode.Color; + + color = cc.Color.WHITE; + + colorMin = cc.Color.WHITE; + + colorMax = cc.Color.WHITE; + + gradient = new Gradient(); + + gradientMin = null; + + gradientMax = null; + + evaluate(time, rndRatio) { + switch (this.mode) { + case Mode.Color: + return this.color; + case Mode.TwoColors: + this.colorMin.lerp(this.colorMax, rndRatio, this.color); + return this.color; + case Mode.RandomColor: + return this.gradient.randomColor(); + case Mode.Gradient: + return this.gradient.evaluate(time); + case Mode.TwoGradients: + this.colorMin = this.gradientMin.evaluate(time); + this.colorMax = this.gradientMax.evaluate(time); + this.colorMin.lerp(this.colorMax, rndRatio, this.color); + return this.color; + } + } +} + +CCClass.fastDefine('cc.GradientRange', GradientRange, { + mode: Mode.Color, + color: cc.Color.WHITE, + colorMin: cc.Color.WHITE, + colorMax: cc.Color.WHITE, + gradient: new Gradient(), + gradientMin: null, + gradientMax: null +}); + +export class GradientUniform { + constructor(gr) { + this.gr = gr; + if (gr._mode == 'color') { + this.minColor = new Float32Array(4); + 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); + this.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.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.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.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.maxColorKeyValue = new Float32Array(3 * this.maxColorKeyTime.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); + } + } + + uploadUniform(device, name) { + 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') { + 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') { + 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 + '_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') { + 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 + '_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 + '_maxColorKeyValue', this.maxColorKeyValue); + device.setUniform('u_' + name + '_maxColorKeyTime', this.maxColorKeyTime); + device.setUniform('u_' + name + '_maxAlphaKeyValue', this.maxAlphaKeyValue); + device.setUniform('u_' + name + '_maxAlphaKeyTime', this.maxAlphaKeyTime); + } + } + + 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; + } + for (let i = 0; i < gradient._alphaKeys.length; i++) { + alphaKeyTime[i] = gradient._alphaKeys[i]._time; + alphaKeyValue[i] = gradient._alphaKeys[i]._alpha; + } + } +} diff --git a/cocos/3d/framework/particle/animator/gradient.js b/cocos/3d/framework/particle/animator/gradient.js new file mode 100644 index 0000000000..20d5f6f2cf --- /dev/null +++ b/cocos/3d/framework/particle/animator/gradient.js @@ -0,0 +1,132 @@ +import { repeat } from '../../../../core/vmath'; +import { Enum, ValueType } from '../../../../core/value-types'; +import { CCClass } from '../../../../core/data'; + +const Mode = Enum({ + Blend: 0, + Fixed: 1 +}); + +export class ColorKey { + + color = cc.Color.WHITE; + + time = 0; +} + +CCClass.fastDefine('cc.ColorKey', ColorKey, { + color: cc.Color.WHITE, + time: 0 +}); + +export class AlphaKey { + + alpha = 1; + + time = 0; +} + +CCClass.fastDefine('cc.AlphaKey', AlphaKey, { + alpha: 1, + time: 0 +}); + +export default class Gradient extends ValueType { + + colorKeys = []; + + alphaKeys = [] + + mode = Mode.Blend; + + constructor() { + super(); + this._color = cc.Color.WHITE; + } + + setKeys(colorKeys, alphaKeys) { + this.colorKeys = colorKeys; + this.alphaKeys = alphaKeys; + } + + sortKeys() { + if (this.colorKeys.length > 1) { + this.colorKeys.sort((a, b) => a.time - b.time); + } + if (this.alphaKeys.length > 1) { + this.alphaKeys.sort((a, b) => a.time - b.time); + } + } + + getRGB(time) { + 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; + if (time >= preTime && time < curTime) { + if (this._mode === 'fixed') { + return this.colorKeys[i].color; + } + let factor = (time - preTime) / (curTime - preTime); + this.colorKeys[i - 1].color.lerp(this.colorKeys[i].color, factor, this._color); + return this._color; + } + } + console.warn('something went wrong. can not get gradient color.'); + } else if (this.colorKeys.length === 1) { + this._color.set(this.colorKeys[0].color); + return this._color; + } else { + this._color.r = 255; + this._color.g = 255; + this._color.b = 255; + this._color.a = 255; + return this._color; + } + } + + 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; + if (time >= preTime && time < curTime) { + if (this._mode === 'fixed') { + return this.alphaKeys[i].alpha; + } + let factor = (time - preTime) / (curTime - preTime); + return (this.alphaKeys[i - 1].alpha * (1 - factor) + this.alphaKeys[i].alpha * factor); + } + } + console.warn('something went wrong. can not get gradient alpha.'); + } else if (this.alphaKeys.length === 1) { + return this.alphaKeys[0].alpha; + } else { + return 255; + } + } + + evaluate(time) { + this.getRGB(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; + return this._color; + } +} + +CCClass.fastDefine('cc.Gradient', Gradient, { + mode: Mode.Blend, + colorKeys: [], + alphaKeys: [] +}); diff --git a/cocos/3d/framework/particle/animator/limit-velocity-overtime.js b/cocos/3d/framework/particle/animator/limit-velocity-overtime.js new file mode 100644 index 0000000000..fd4919aac7 --- /dev/null +++ b/cocos/3d/framework/particle/animator/limit-velocity-overtime.js @@ -0,0 +1,75 @@ +import { vec3, lerp, pseudoRandom } from '../../../../core/vmath'; +import { CCClass } from '../../../../core/data'; +import { Space } from '../particle-general-function'; + +const LIMIT_VELOCITY_RAND_OFFSET = 23541; + +export default class LimitVelocityOvertimeModule { + + enable = false; + + limitX = null; + + limitY = null; + + limitZ = null; + + limit = null; + + dampen = null; + + separateAxes = false; + + space = Space.Local; + + // TODO:functions related to drag are temporarily not supported + drag = null; + + multiplyDragByParticleSize = false; + + multiplyDragByParticleVelocity = false; + + constructor() { + } + + animate(p) { + let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + let 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)); + } + 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.copy(p.ultimateVelocity, dampedVel); + } + +} + +function dampenBeyondLimit(vel, limit, dampen) { + let sgn = Math.sign(vel); + let abs = Math.abs(vel); + if (abs > limit) { + abs = lerp(abs, limit, dampen); + } + return abs * sgn; +} + +CCClass.fastDefine('cc.LimitVelocityOvertimeModule',LimitVelocityOvertimeModule,{ + enable : false, + limitX : null, + limitY : null, + limitZ : null, + limit : null, + dampen : null, + separateAxes : false, + space : Space.Local, + // TODO:functions related to drag are temporarily not supported + drag : null, + multiplyDragByParticleSize : false, + multiplyDragByParticleVelocity : false +}); diff --git a/cocos/3d/framework/particle/animator/optimized-curve.js b/cocos/3d/framework/particle/animator/optimized-curve.js new file mode 100644 index 0000000000..c022c98dbe --- /dev/null +++ b/cocos/3d/framework/particle/animator/optimized-curve.js @@ -0,0 +1,297 @@ +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; + } + } +} diff --git a/cocos/3d/framework/particle/animator/rotation-overtime.js b/cocos/3d/framework/particle/animator/rotation-overtime.js new file mode 100644 index 0000000000..f9608a2dbd --- /dev/null +++ b/cocos/3d/framework/particle/animator/rotation-overtime.js @@ -0,0 +1,53 @@ +import { pseudoRandom } from "../../../../core/vmath"; +import { CCClass } from "../../../../core/data"; +import CurveRange from "./curve-range"; + +const ROTATION_OVERTIME_RAND_OFFSET = 125292; + +export default class RotationOvertimeModule { + + enable = false; + + _separateAxes = false; + + get separateAxes() { + return this._separateAxes; + } + + set separateAxes(val) { + if (!val) { + this._separateAxes = val; + } + else { + console.error('rotation overtime separateAxes is not supported!'); + } + } + + x = null; + + y = null; + + z = null; + + constructor() { + + } + + animate(p, dt) { + let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + if (!this._separateAxes) { + p.rotation.x += this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET)) * dt; + } + else { + // TODO: separateAxes is temporarily not supported! + } + } +} + +CCClass.fastDefine('cc.RotationOvertimeModule',RotationOvertimeModule,{ + enable : false, + _separateAxes : false, + x : new CurveRange(), + y : new CurveRange(), + z : new CurveRange() +}); diff --git a/cocos/3d/framework/particle/animator/size-overtime.js b/cocos/3d/framework/particle/animator/size-overtime.js new file mode 100644 index 0000000000..f8498988d9 --- /dev/null +++ b/cocos/3d/framework/particle/animator/size-overtime.js @@ -0,0 +1,35 @@ +import { vec3, pseudoRandom } from '../../../../core/vmath'; +import CurveRange from './curve-range'; +import { CCClass } from '../../../../core/data'; + +const SIZE_OVERTIME_RAND_OFFSET = 39825; + +export default class SizeOvertimeModule { + + enable = false; + + separateAxes = false; + + size = null; + + x = null; + + y = null; + + z = null; + + animate(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))); + } + } +} + +CCClass.fastDefine('cc.SizeOvertimeModule', SizeOvertimeModule, { + enable: false, + separateAxes: false, + size: new CurveRange(), + x: new CurveRange(), + y: new CurveRange(), + z: new CurveRange() +}); diff --git a/cocos/3d/framework/particle/animator/texture-animation.js b/cocos/3d/framework/particle/animator/texture-animation.js new file mode 100644 index 0000000000..65ab0b0fd2 --- /dev/null +++ b/cocos/3d/framework/particle/animator/texture-animation.js @@ -0,0 +1,132 @@ +import { repeat, lerp, pseudoRandom } from "../../../../core/vmath"; +import { Enum } from "../../../../core/value-types"; +import CurveRange from "./curve-range"; +import { CCClass } from "../../../../core/data"; + +const TEXTURE_ANIMATION_RAND_OFFSET = 90794; + +const Mode = Enum({ + Grid: 0, + Sprites: 1 +}); + +const Animation = Enum({ + WholeSheet: 0, + SingleRow: 1 +}); + +export default class TextureAnimationModule { + + _enable = false; + + get enable() { + return this._enable; + } + + set enable(val) { + this._enable = val; + this.ps.renderer._updateMaterialParams(); + } + + _mode = Mode.Grid + + get mode() { + return this._mode; + } + + set mode(val) { + if (val === Mode.Sprites) { + console.error("particle texture animation's sprites is not supported!"); + return; + } + } + + numTilesX = 0; + + numTilesY = 0; + + animation = Animation.WholeSheet; + + frameOverTime = null; + + startFrame = null; + + cycleCount = 0; + + _flipU = 0; + + get flipU() { + return this._flipU; + } + + set flipU(val) { + console.error("particle texture animation's flipU is not supported!"); + } + + _flipV = 0; + + get flipV() { + return this._flipV; + } + + set flipV(val) { + console.error("particle texture animation's flipV is not supported!"); + } + + _uvChannelMask = -1 + + get uvChannelMask() { + return this._uvChannelMask; + } + + set uvChannelMask(val) { + console.error("particle texture animation's uvChannelMask is not supported!"); + } + + randomRow = false; + + rowIndex = 0; + + onInit(ps) { + 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); + } + 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; + 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)); + } + } + } +} + +CCClass.fastDefine('cc.TextureAnimationModule', TextureAnimationModule, { + _enable: false, + _mode: Mode.Grid, + numTilesX: 0, + numTilesY: 0, + animation: Animation.WholeSheet, + frameOverTime: new CurveRange(), + startFrame: new CurveRange(), + cycleCount: 0, + _flipU: 0, + _flipV: 0, + _uvChannelMask: -1, + randomRow: false, + rowIndex: 0 +}); diff --git a/cocos/3d/framework/particle/animator/velocity-overtime.js b/cocos/3d/framework/particle/animator/velocity-overtime.js new file mode 100644 index 0000000000..1153f83e07 --- /dev/null +++ b/cocos/3d/framework/particle/animator/velocity-overtime.js @@ -0,0 +1,50 @@ +import { vec3, quat, pseudoRandom } from '../../../../core/vmath'; +import { calculateTransform, Space } from '../particle-general-function'; +import CurveRange from './curve-range'; +import { CCClass } from '../../../../core/data'; + +const VELOCITY_OVERTIME_RAND_OFFSET = 197866; + +export default class VelocityOvertimeModule { + + enable = false; + + x = null; + + y = null; + + z = null; + + speedModifier = null; + + space = Space.Local; + + constructor() { + this.rotation = quat.create(); + } + + update(space, worldTransform) { + 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))); + 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))); + } + +} + +CCClass.fastDefine('cc.VelocityOvertimeModule', VelocityOvertimeModule, { + enable: false, + x: new CurveRange(), + y: new CurveRange(), + z: new CurveRange(), + speedModifier: new CurveRange(), + space: Space.Local +}); diff --git a/cocos/3d/framework/particle/burst.js b/cocos/3d/framework/particle/burst.js new file mode 100644 index 0000000000..634447ffc2 --- /dev/null +++ b/cocos/3d/framework/particle/burst.js @@ -0,0 +1,68 @@ +import { repeat } from "../../../core/vmath"; +import CurveRange from "./animator/curve-range"; +import { CCClass } from "../../../core/data"; + + +export default class Burst { + + _time = 0; + + get time() { + return this._time; + } + + set time(val) { + this._time = val; + this._curTime = val; + } + + minCount = 30; + + maxCount = 30; + + _repeatCount = 1; + + get repeatCount() { + return this._repeatCount; + } + + set repeatCount(val) { + this._repeatCount = val; + this._remainingCount = val; + } + + repeatInterval = 1; + + count = null; + + constructor() { + this._remainingCount = 1; + this._curTime = 0.0; + } + + update(psys, dt) { + if (psys.loop && this._remainingCount === 0) { + this._remainingCount = this._repeatCount; + this._curTime = this._time; + } + if (this._remainingCount > 0) { + let preFrameTime = repeat(psys._time - psys.startDelay.evaluate(), psys.duration) - dt; + preFrameTime = (preFrameTime > 0.0) ? preFrameTime : 0.0; + let curFrameTime = repeat(psys.time - psys.startDelay.evaluate(), psys.duration); + if (this._curTime >= preFrameTime && this._curTime < curFrameTime) { + psys.emit(this.count.evaluate(this._curTime / psys.duration)); + this._curTime += this.repeatInterval; + --this._remainingCount; + } + } + } +} + +CCClass.fastDefine('cc.Burst', Burst, { + _time: 0, + minCount: 30, + maxCount: 30, + _repeatCount: 1, + repeatInterval: 1, + count: new CurveRange +}); diff --git a/cocos/3d/framework/particle/emitter/shape-module.js b/cocos/3d/framework/particle/emitter/shape-module.js new file mode 100644 index 0000000000..f8c6c9769c --- /dev/null +++ b/cocos/3d/framework/particle/emitter/shape-module.js @@ -0,0 +1,307 @@ +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 { Enum, Vec3 } from '../../../../core/value-types'; +import CurveRange from '../animator/curve-range'; +import { CCClass } from '../../../../core/data'; + +let _intermediVec = vec3.create(0, 0, 0); +let _intermediArr = new Array(); +const _unitBoxExtent = vec3.create(0.5, 0.5, 0.5); + +const ShapeType = Enum({ + Box: 0, + Circle: 1, + Cone: 2, + Sphere: 3, + Hemisphere: 4 +}); + +const EmitLocation = Enum({ + Base: 0, + Edge: 1, + Shell: 2, + Volume: 3 +}); + +const ArcMode = Enum({ + Random: 0, + Loop: 1, + PingPong: 2 +}); + +export default class ShapeModule { + + enable = false; + + shapeType = ShapeType.Box; + + emitFrom = EmitLocation.Base; + + _position = new Vec3(0, 0, 0); + + get position() { + return this._position; + } + set position(val) { + this._position = val; + this.constructMat(); + } + + + _rotation = new Vec3(0, 0, 0); + + get rotation() { + return this._rotation; + } + set rotation(val) { + this._rotation = val; + this.constructMat(); + } + + + _scale = new Vec3(0, 0, 0); + + get scale() { + return this._scale; + } + set scale(val) { + this._scale = val; + this.constructMat(); + } + + alignToDirection = false; + + randomDirectionAmount = 0; + + sphericalDirectionAmount = 0; + + randomPositionAmount = 0; + + radius = 0; + + radiusThickness = 1; + + arc = 0; + + arcMode = ArcMode.Random; + + arcSpread = 0; + + arcSpeed = new CurveRange(); + + angle = 0; + + length = 0; + + boxThickness = new Vec3(0, 0, 0); + + constructor() { + this.mat = mat4.create(); + this.quat = quat.create(); + } + + onInit(ps) { + this.constructMat(); + this.particleSystem = ps; + this.lastTime = ps._time; + this.totalAngle = 0; + } + + 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) { + switch (this.shapeType) { + case ShapeType.Box: + boxEmit(this.emitFrom, this.boxThickness, p.position, p.velocity); + break; + case ShapeType.Circle: + 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); + break; + case ShapeType.Sphere: + sphereEmit(this.emitFrom, this.radius, this.radiusThickness, p.position, p.velocity); + break; + case ShapeType.Hemisphere: + hemisphereEmit(this.emitFrom, this.radius, this.radiusThickness, p.position, p.velocity); + break; + default: + console.warn(this.shapeType + ' shapeType is not supported by ShapeModule.'); + } + if (this.randomPositionAmount > 0) { + p.position.x += randomRange(-this.randomPositionAmount, this.randomPositionAmount); + p.position.y += randomRange(-this.randomPositionAmount, this.randomPositionAmount); + p.position.z += randomRange(-this.randomPositionAmount, this.randomPositionAmount); + } + 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); + vec3.lerp(p.velocity, p.velocity, sphericalVel, this.sphericalDirectionAmount); + } + this.lastTime = this.particleSystem._time; + } + + generateArcAngle() { + if (this.arcMode === ArcMode.Random) { + return randomRange(0, this.arc); + } + let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem._time) * (this.particleSystem._time - this.lastTime); + this.totalAngle = angle; + if (this.arcSpread !== 0) { + angle = Math.floor(angle / (this.arc * this.arcSpread)) * this.arc * this.arcSpread; + } + switch (this.arcMode) { + case ArcMode.Loop: + return repeat(angle, this.arc); + case ArcMode.PingPong: + return pingPong(angle, this.arc); + } + } +} + +function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) { + switch (emitFrom) { + case EmitLocation.Volume: + randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius); + vec3.copy(dir, pos); + vec3.normalize(dir, dir); + break; + case EmitLocation.Shell: + randomUnitVector(pos); + vec3.scale(pos, pos, radius); + vec3.copy(dir, pos); + break; + default: + console.warn(emitFrom + ' is not supported for sphere emitter.'); + } +} + +function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) { + switch (emitFrom) { + case EmitLocation.Volume: + randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius); + if (pos.z > 0) { + pos.z *= -1; + } + vec3.copy(dir, pos); + vec3.normalize(dir, dir); + break; + case EmitLocation.Shell: + randomUnitVector(pos); + vec3.scale(pos, pos, radius); + if (pos.z < 0) { + pos.z *= -1; + } + vec3.copy(dir, pos); + break; + default: + console.warn(emitFrom + ' is not supported for hemisphere emitter.'); + } +} + +function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) { + switch (emitFrom) { + case EmitLocation.Base: + randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta); + vec2.scale(dir, pos, Math.sin(angle)); + dir.z = -Math.cos(angle) * radius; + vec3.normalize(dir, dir); + pos.z = 0; + break; + case EmitLocation.Shell: + fixedAngleUnitVector2(pos, theta); + vec2.scale(dir, pos, Math.sin(angle)); + dir.z = -Math.cos(angle); + vec3.normalize(dir, dir); + vec2.scale(pos, pos, radius); + pos.z = 0; + break; + case EmitLocation.Volume: + randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta); + vec2.scale(dir, pos, Math.sin(angle)); + dir.z = -Math.cos(angle) * radius; + vec3.normalize(dir, dir); + pos.z = 0; + vec3.add(pos, pos, vec3.scale(_intermediVec, dir, length * random() / -dir.z)); + break; + default: + console.warn(emitFrom + ' is not supported for cone emitter.'); + } +} + +function boxEmit(emitFrom, boxThickness, pos, dir) { + switch (emitFrom) { + case EmitLocation.Volume: + randomPointInCube(pos, _unitBoxExtent); + // randomPointBetweenCube(pos, vec3.multiply(_intermediVec, _unitBoxExtent, boxThickness), _unitBoxExtent); + break; + case EmitLocation.Shell: + _intermediArr.splice(0, _intermediArr.length); + _intermediArr.push(randomRange(-0.5, 0.5)); + _intermediArr.push(randomRange(-0.5, 0.5)); + _intermediArr.push(randomSign() * 0.5); + randomSortArray(_intermediArr); + applyBoxThickness(_intermediArr, boxThickness); + vec3.set(pos, _intermediArr[0], _intermediArr[1], _intermediArr[2]); + break; + case EmitLocation.Edge: + _intermediArr.splice(0, _intermediArr.length); + _intermediArr.push(randomRange(-0.5, 0.5)); + _intermediArr.push(randomSign() * 0.5); + _intermediArr.push(randomSign() * 0.5); + randomSortArray(_intermediArr); + applyBoxThickness(_intermediArr, boxThickness); + vec3.set(pos, _intermediArr[0], _intermediArr[1], _intermediArr[2]); + break; + default: + console.warn(emitFrom + ' is not supported for box emitter.'); + } + vec3.copy(dir, particleEmitZAxis); +} + +function circleEmit(radius, radiusThickness, theta, pos, dir) { + randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta); + vec3.normalize(dir, pos); +} + +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); + } + if (thickness.y > 0) { + pos[1] += 0.5 * randomRange(-thickness.y, thickness.y); + pos[1] = clamp(pos[0], -0.5, 0.5); + } + if (thickness.z > 0) { + pos[2] += 0.5 * randomRange(-thickness.z, thickness.z); + pos[2] = clamp(pos[0], -0.5, 0.5); + } +} + +CCClass.fastDefine('cc.ShapeModule', ShapeModule, { + enable: false, + shapeType: ShapeType.Box, + emitFrom: EmitLocation.Base, + _position: new Vec3(0, 0, 0), + _rotation: new Vec3(0, 0, 0), + _scale: new Vec3(0, 0, 0), + alignToDirection: false, + randomDirectionAmount: 0, + sphericalDirectionAmount: 0, + randomPositionAmount: 0, + radius: 0, + radiusThickness: 1, + arc: 0, + arcMode: ArcMode.Random, + arcSpread: 0, + arcSpeed: null, + angle: 0, + length: 0, + boxThickness: new Vec3(0, 0, 0) +}); diff --git a/cocos/3d/framework/particle/particle-emit-params.js b/cocos/3d/framework/particle/particle-emit-params.js new file mode 100644 index 0000000000..015ce0d1da --- /dev/null +++ b/cocos/3d/framework/particle/particle-emit-params.js @@ -0,0 +1,16 @@ +import Particle from './particle'; + +export default class ParticleEmitParams { + constructor() { + this._particle = new Particle(); // to be integrable with particle structure + this.positionSet = false; + this.velocitySet = false; + this.angularVelocitySet = false; + this.axisOfRotationSet = false; + this.rotationSet = false; + this.startSizeSet = false; + this.startColorSet = false; + this.randomSeedSet = false; + this.startLifetimeSet = false; + } +} diff --git a/cocos/3d/framework/particle/particle-general-function.js b/cocos/3d/framework/particle/particle-general-function.js new file mode 100644 index 0000000000..06076406e8 --- /dev/null +++ b/cocos/3d/framework/particle/particle-general-function.js @@ -0,0 +1,114 @@ +import { mat4, quat, randomRange, vec3, random, vec2, randomRangeInt } from '../../../core/vmath'; +import { sign } from '../../../core/vmath/bits'; +import { Enum } from '../../../core/value-types'; + +export const particleEmitZAxis = vec3.create(0, 0, -1); + +export const Space = Enum({ + World: 0, + Local: 1, + Custom: 2 +}); + +export function calculateTransform(systemSpace, moduleSpace, worldTransform, outQuat) { + if (moduleSpace !== systemSpace) { + if (systemSpace === 'world') { + mat4.getRotation(outQuat, worldTransform); + } + else { + mat4.invert(worldTransform, worldTransform); + mat4.getRotation(outQuat, worldTransform); + } + return true; + } + else { + quat.set(outQuat, 0, 0, 0, 1); + return false; + } +} + +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); + 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); + vec3.set(out, x, y, z); +} + +export function randomPointInUnitSphere(out) { + randomUnitVector(out); + vec3.scale(out, out, random()); +} + +export function randomPointBetweenSphere(out, minRadius, maxRadius) { + randomUnitVector(out); + vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random()); +} + +export function randomPointInUnitCircle(out) { + randomUnitVector2(out); + vec3.scale(out, out, random()); +} + +export function randomPointBetweenCircle(out, minRadius, maxRadius) { + randomUnitVector2(out); + vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random()); +} + +export function randomPointBetweenCircleAtFixedAngle(out, minRadius, maxRadius, theta) { + fixedAngleUnitVector2(out, theta); + vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random()); +} + +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) { + const subscript = ['x', 'y', 'z']; + let 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; + if (x < 0) { + out[subscript[i]] = -minBox[subscript[i]] + x * (maxBox[subscript[i]] - minBox[subscript[i]]); + } + else { + out[subscript[i]] = minBox[subscript[i]] + x * (maxBox[subscript[i]] - minBox[subscript[i]]); + } + } +} + +// Fisher–Yates shuffle +export function randomSortArray(arr) { + for (let i = 0; i < arr.length; i++) { + let transpose = i + randomRangeInt(0, arr.length - i); + let val = arr[transpose]; + arr[transpose] = arr[i]; + arr[i] = val; + } +} + +export function randomSign() { + let sgn = randomRange(-1, 1); + sgn === 0 ? sgn++ : sgn; + return sign(sgn); +} diff --git a/cocos/3d/framework/particle/particle-system-component.js b/cocos/3d/framework/particle/particle-system-component.js new file mode 100644 index 0000000000..e0cf121e42 --- /dev/null +++ b/cocos/3d/framework/particle/particle-system-component.js @@ -0,0 +1,540 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import Component from '../../../components/CCComponent'; +import { vec3, vec2, mat4, quat, randomRangeInt, pseudoRandom } from '../../../core/vmath'; +import registry from '../../misc/registry'; +import Gradient, { ColorKey, AlphaKey } from './animator/gradient'; +import CurveRange from './animator/curve-range'; +import GradientRange from './animator/gradient-range'; +import ParticleSystemRenderer from './renderer/particle-system-renderer'; +import SizeOvertimeModule from './animator/size-overtime'; +import ColorOverLifetimeModule from './animator/color-overtime'; +import VelocityOvertimeModule from './animator/velocity-overtime'; +import ForceOvertimeModule from './animator/force-overtime'; +import LimitVelocityOvertimeModule from './animator/limit-velocity-overtime'; +import RotationOvertimeModule from './animator/rotation-overtime'; +import TextureAnimationModule from './animator/texture-animation'; +import ShapeModule from './emitter/shape-module'; +import Burst from './burst'; +import { particleEmitZAxis, Space } from './particle-general-function'; +import { INT_MAX } from '../../../core/vmath/bits'; +import ParticleSystemGpuRenderer from './renderer/particle-system-gpu-renderer'; +import { ccclass, executionOrder, executeInEditMode, property, requireComponent } from '../../../core/data/class-decorator'; + +registry.registerClass('Burst', Burst); +registry.registerClass('ColorKey', ColorKey); +registry.registerClass('AlphaKey', AlphaKey); +registry.registerClass('Gradient', Gradient); +registry.registerClass('GradientRange', GradientRange); +registry.registerClass('CurveRange', CurveRange); +registry.registerClass('SizeOvertimeModule', SizeOvertimeModule); +registry.registerClass('ColorOverLifetimeModule', ColorOverLifetimeModule); +registry.registerClass('ParticleSystemRenderer', ParticleSystemRenderer); +registry.registerClass('ParticleSystemGpuRenderer', ParticleSystemGpuRenderer); +registry.registerClass('VelocityOvertimeModule', VelocityOvertimeModule); +registry.registerClass('ForceOvertimeModule', ForceOvertimeModule); +registry.registerClass('LimitVelocityOvertimeModule', LimitVelocityOvertimeModule); +registry.registerClass('RotationOvertimeModule', RotationOvertimeModule); +registry.registerClass('TextureAnimationModule', TextureAnimationModule); +registry.registerClass('ShapeModule', ShapeModule); + +let _world_mat = mat4.create(); + +@ccclass('cc.ParticleSystemComponent') +@requireComponent(ParticleSystemRenderer) +@executionOrder(99) +@executeInEditMode +export default class ParticleSystemComponent extends Component { + + @property + capacity = 2000; + + @property + startColor = null; + + @property({ + type: CurveRange + }) + startSize = null; + + @property({ + type: CurveRange + }) + startSpeed = null; + + @property({ + type: CurveRange + }) + startRotation = null; + + @property({ + type: CurveRange + }) + startDelay = null; + + @property({ + type: CurveRange + }) + startLifetime = null; + + @property + duration = 5.0; + + @property + loop = true; + + @property + _prewarm = false; + + @property + get prewarm() { + return this._prewarm; + } + + 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; + + @property({ + type: Space + }) + 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); + } + this._simulationSpace = val; + } + + @property + simulationSpeed = 1.0; + + @property + playOnAwake = false; + + @property({ + type: CurveRange + }) + gravityModifier = null; + + // emission module + @property({ + type: CurveRange + }) + rateOverTime = null; + + @property({ + type: CurveRange + }) + rateOverDistance = null; + + @property({ + type: [Burst] + }) + bursts = null; + + // color over lifetime module + @property({ + type: ColorOverLifetimeModule + }) + colorOverLifetimeModule = null; + + // shpae module + @property({ + type: ShapeModule + }) + shapeModule = null; + + // particle system renderer + @property({ + type: ParticleSystemRenderer + }) + renderer = null; + + // size over lifetime module + @property({ + type: SizeOvertimeModule + }) + sizeOvertimeModule = null; + + @property({ + type: VelocityOvertimeModule + }) + velocityOvertimeModule = null; + + @property({ + type: ForceOvertimeModule + }) + forceOvertimeModule = null; + + @property({ + type: LimitVelocityOvertimeModule + }) + limitVelocityOvertimeModule = null; + + @property({ + type: RotationOvertimeModule + }) + rotationOvertimeModule = null; + + @property({ + type: TextureAnimationModule + }) + textureAnimationModule = null; + + constructor() { + super(); + + // internal status + this._isPlaying = false; + this._isPaused = false; + this._isStopped = true; + this._isEmitting = false; + + this._time = 0.0; // playback position in seconds. + this._emitRateTimeCounter = 0.0; + this._emitRateDistanceCounter = 0.0; + this._oldWPos = vec3.create(0, 0, 0); + this._curWPos = vec3.create(0, 0, 0); + + this._customData1 = vec2.create(0, 0); + this._customData2 = vec2.create(0, 0); + + this._subEmitters = []; // array of { emitter: ParticleSystemComponent, type: 'birth', 'collision' or 'death'} + } + + onLoad() { + // HACK, TODO + this.renderer.onInit(); + this.shapeModule.onInit(this); + this.textureAnimationModule.onInit(this); + + this.node.getWorldPosition(this._oldWPos); + vec3.copy(this._curWPos, this._oldWPos); + + // this._system.add(this); + } + + onDestroy() { + // this._system.remove(this); + } + + onEnable() { + if (this._playOnAwake) { + this.play(); + } + } + + onDisable() { + + } + + // TODO: fastforward current particle system by simulating particles over given period of time, then pause it. + // simulate(time, withChildren, restart, fixedTimeStep) { + + // } + + play() { + if (this._isPaused) { + this._isPaused = false; + } + if (this._isStopped) { + this._isStopped = false; + } + + this._time = 0.0; + this._emitRateTimeCounter = 0.0; + this._emitRateDistanceCounter = 0.0; + + this._isPlaying = true; + + // prewarm + if (this._prewarm) { + this._prewarmSystem(); + } + } + + pause() { + if (this._isStopped) { + console.warn('pause(): particle system is already stopped.'); + return; + } + if (this._isPlaying) { + this._isPlaying = false; + } + + this._isPaused = true; + } + + stop() { + if (this._isPlaying) { + this._isPlaying = false; + } + if (this._isPaused) { + this._isPaused = false; + } + + this.clear(); + this._time = 0.0; + this._emitRateTimeCounter = 0.0; + this._emitRateDistanceCounter = 0.0; + + this._isStopped = true; + } + + // remove all particles from current particle system. + clear() { + this._particles.reset(); + this._renderer._model.clear(); + } + + emit(count, emitParams = null) { + if (emitParams !== null) { + // TODO: + } + + for (let i = 0; i < count; ++i) { + let particle = this.renderer._getFreeParticle(); + if (particle === null) + return; + let rand = pseudoRandom(randomRangeInt(0, INT_MAX)); + + if (this.shapeModule.enable) { + this.shapeModule.emit(particle); + } + else { + vec3.set(particle.position, 0, 0, 0); + vec3.copy(particle.velocity, particleEmitZAxis); + } + + vec3.scale(particle.velocity, particle.velocity, this.startSpeed.evaluate(this._time / this.duration, rand)); + + switch (this._simulationSpace) { + case Space.Local: + break; + case Space.World: { + this.node.getWorldMatrix(_world_mat); + vec3.transformMat4(particle.position, particle.position, _world_mat); + let worldRot = quat.create(); + this.node.getWorldRotation(worldRot); + vec3.transformQuat(particle.velocity, particle.velocity, worldRot); + } + break; + case Space.Custom: + // TODO: + break; + } + // apply startRotation. now 2D only. + vec3.set(particle.rotation, this.startRotation.evaluate(this._time / this.duration, rand), 0, 0); + + // apply startSize. now 2D only. + vec3.set(particle.startSize, this.startSize.evaluate(this._time / this.duration, rand), 0, 0); + vec3.copy(particle.size, particle.startSize); + + // apply startColor. + particle.startColor.set(this.startColor.evaluate(this._time / this.duration, rand)); + particle.startColor.to01(particle.startColor01); + particle.color.set(particle.startColor); + + // apply startLifetime. + particle.startLifetime = this.startLifetime.evaluate(this._time / this.duration, rand); + particle.remainingLifetime = particle.startLifetime; + + particle.randomSeed = randomRangeInt(0, 233280); + + 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.remove(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; + for (let i = 0; i < cnt; ++i) { + this._time += dt; + this._emit(dt); + this._renderer._updateParticles(dt); + } + } + + // internal function + _emit(dt) { + // emit particles. + let startDelay = this.startDelay.evaluate(); + if (this._time > startDelay) { + if (!this._isStopped) { + this._isEmitting = true; + } + if (this._time > (this.duration + startDelay)) { + // this._time = startDelay; // delay will not be applied from the second loop.(Unity) + // this._emitRateTimeCounter = 0.0; + // this._emitRateDistanceCounter = 0.0; + if (!this.loop) { + this._isEmitting = false; + this._isStopped = true; + } + } + + // 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); + this._emitRateTimeCounter -= emitNum; + this.emit(emitNum); + } + // emit by rateOverDistance + this.node.getWorldPosition(this._curWPos); + let 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); + this._emitRateDistanceCounter -= emitNum; + this.emit(emitNum); + } + + // bursts + for (let i = 0; i < this.bursts.length; ++i) { + this.bursts[i].update(this, dt); + } + } + } + + update(dt) { + let scaledDeltaTime = dt * this.simulationSpeed; + if (this._isPlaying) { + this._time += scaledDeltaTime; + + // excute emission + this._emit(scaledDeltaTime); + + // simulation, update particles. + this.renderer._updateParticles(scaledDeltaTime); + + // update render data + this.renderer._updateRenderData(); + } + } + + addSubEmitter(subEmitter) { + this._subEmitters.push(subEmitter); + } + + removeSubEmitter(idx) { + this._subEmitters.remove(idx); + } + + addBurst(burst) { + this._bursts.push(burst); + } + + removeBurst(idx) { + this._bursts.remove(idx); + } + + getParticleCount() { + return this._particles.length; + } + + setCustomData1(x, y) { + vec2.set(this._customData1, x, y); + } + + setCustomData2(x, y) { + vec2.set(this._customData2, x, y); + } + + get isPlaying() { + return this._isPlaying; + } + + get isPaused() { + return this._isPaused; + } + + get isStopped() { + return this._isStopped; + } + + get isEmitting() { + return this._isEmitting; + } + + get time() { + return this._time; + } +} diff --git a/cocos/3d/framework/particle/particle-system-manager.js b/cocos/3d/framework/particle/particle-system-manager.js new file mode 100644 index 0000000000..d6d6763018 --- /dev/null +++ b/cocos/3d/framework/particle/particle-system-manager.js @@ -0,0 +1,25 @@ +import System from '../../ecs/system'; +import { FixedArray } from '../../memop'; + +export default class ParticleSystemManager extends System { + constructor() { + super(); + + this._particleSystems = new FixedArray(10); + } + + add(comp) { + this._particleSystems.push(comp); + } + + remove(comp) { + this._particleSystems.fastRemove(this._particleSystems.indexOf(comp)); + } + + tick() { + for (let i = 0; i < this._particleSystems.length; ++i) { + let particleSystem = this._particleSystems.data[i]; + particleSystem.tick(this._app.deltaTime); + } + } +} diff --git a/cocos/3d/framework/particle/particle.js b/cocos/3d/framework/particle/particle.js new file mode 100644 index 0000000000..82228dc683 --- /dev/null +++ b/cocos/3d/framework/particle/particle.js @@ -0,0 +1,25 @@ +import { vec3, color4 } from '../../../core/vmath'; + +export default class Particle { + constructor(particleSystem) { + this.particleSystem = particleSystem; + this.position = vec3.create(0, 0, 0); + this.velocity = vec3.create(0, 0, 0); + this.animatedVelocity = vec3.create(0, 0, 0); + this.ultimateVelocity = vec3.create(0, 0, 0); + this.angularVelocity = vec3.create(0, 0, 0); + this.axisOfRotation = vec3.create(0, 0, 0); + this.rotation = vec3.create(0, 0, 0); + this.startSize = vec3.create(0, 0, 0); + this.size = vec3.create(0, 0, 0); + this.startColor = cc.Color.WHITE; + this.startColor01 = color4.create(); + this.color = cc.Color.WHITE; + this.randomSeed = 0; // uint + this.remainingLifetime = 0.0; + this.startLifetime = 0.0; + this.emitAccumulator0 = 0.0; + this.emitAccumulator1 = 0.0; + this.frameIndex = 0.0; + } +} diff --git a/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js new file mode 100644 index 0000000000..ad4cbe5525 --- /dev/null +++ b/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js @@ -0,0 +1,288 @@ +import ParticleSystemRenderer from "./particle-system-renderer"; +import Material from "../../../assets/material"; +import Particle from "../particle"; +import gfx from "../../../../renderer/gfx"; +import { CurveUniform } from "../animator/optimized-curve"; +import { quat } from "../../../../core/vmath"; +import { GradientUniform } from "../animator/gradient-range"; + +let _temp_rot = quat.create(); +let _world_rot_uniform = new Float32Array(4); + +let _vert_attr_name = { + POSITION_STARTTIME: 'a_position_starttime', + VERT_IDX_SIZE_ANGLE: 'a_vertIdx_size_angle', + COLOR: 'a_color', + DIR_LIFE: 'a_dir_life', + RANDOM_SEED: 'a_rndSeed' +}; + +let _gpu_vert_attr = [ + { name: _vert_attr_name.POSITION_STARTTIME, type: gfx.ATTR_TYPE_FLOAT32, num: 4 }, + { name: _vert_attr_name.VERT_IDX_SIZE_ANGLE, type: gfx.ATTR_TYPE_FLOAT32, num: 4 }, + { name: _vert_attr_name.COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 4 }, + { name: _vert_attr_name.DIR_LIFE, type: gfx.ATTR_TYPE_FLOAT32, num: 4 }, + { name: _vert_attr_name.RANDOM_SEED, type: gfx.ATTR_TYPE_FLOAT32, num: 1 } +]; + +let _space_map = { + 'local': 0, + 'world': 1 +}; + +let _animationMode = { + 'wholeSheet': 0, + 'singleRow': 1 +}; + +let ATTR_INDEX = { + POS: 0, + VERT_IDX: 1, + SIZE: 2, + ANGLE: 3, + COLOR: 4, + DIR: 5, + LIFE_TIME: 6, + START_TIME: 7, + RANDOM_SEED: 8 +}; + +export default class ParticleSystemGpuRenderer extends ParticleSystemRenderer { + onInit(ps) { + this.particleSystem = ps; + if (this._material === null || this._material === undefined) { + this._material = new Material(); + this._material.effect = cc.EffectAsset.get('builtin-effect-particle-add'); + } + //the following code is just for test use,it will be deleted on release + let m = new Material(); + m.copy(this._material); + m.effect = cc.EffectAsset.get('builtin-effect-particle-add-gpu'); + Object.keys(this._material._props).forEach(pn => { + m.setProperty(pn, this._material._props[pn]); + }); + this._material = m; + //end test code + this._vertAttrs = _gpu_vert_attr; + this._updateMaterialParams(); + this._updateModel(); + this._tempParticle = new Particle(); + this._particleNum = 0; + this._vertIndexMap = new Int8Array(Object.keys(ATTR_INDEX).length); + this._constructAttributeIndex(); + } + + _constructAttributeIndex() { + let offset = 0; + for (let i = 0; i < _gpu_vert_attr.length; i++) { + switch (_gpu_vert_attr[i].name) { + case _vert_attr_name.POSITION_STARTTIME: + this._vertIndexMap[ATTR_INDEX.POS] = offset; + this._vertIndexMap[ATTR_INDEX.START_TIME] = offset + 3; + break; + case _vert_attr_name.VERT_IDX_SIZE_ANGLE: + this._vertIndexMap[ATTR_INDEX.VERT_IDX] = offset; + this._vertIndexMap[ATTR_INDEX.SIZE] = offset + 2; + this._vertIndexMap[ATTR_INDEX.ANGLE] = offset + 3; + break; + case _vert_attr_name.COLOR: + this._vertIndexMap[ATTR_INDEX.COLOR] = offset; + break; + case _vert_attr_name.DIR_LIFE: + this._vertIndexMap[ATTR_INDEX.DIR] = offset; + this._vertIndexMap[ATTR_INDEX.LIFE_TIME] = offset + 3; + break; + case _vert_attr_name.RANDOM_SEED: + this._vertIndexMap[ATTR_INDEX.RANDOM_SEED] = offset; + break; + } + offset += _gpu_vert_attr[i].num; + } + } + + _getFreeParticle() { + if (this._particleNum >= this.particleSystem._capacity) { + return null; + } + return this._tempParticle; + } + + _setNewParticle(p) { + let offset = this._particleNum * this._model._vertAttrsSize * 4; + for (let i = 0; i < 4; i++) { + this._model._vdataF32[offset++] = p.position.x; + this._model._vdataF32[offset++] = p.position.y; + this._model._vdataF32[offset++] = p.position.z; + this._model._vdataF32[offset++] = this.particleSystem._time; + + this._model._vdataF32[offset++] = this.constructor.uv[2 * i]; + this._model._vdataF32[offset++] = this.constructor.uv[2 * i + 1]; + this._model._vdataF32[offset++] = p.startSize.x; + this._model._vdataF32[offset++] = p.rotation.x; + + this._model._vdataF32[offset++] = p.startColor.r; + this._model._vdataF32[offset++] = p.startColor.g; + this._model._vdataF32[offset++] = p.startColor.b; + this._model._vdataF32[offset++] = p.startColor.a; + + this._model._vdataF32[offset++] = p.velocity.x; + this._model._vdataF32[offset++] = p.velocity.y; + this._model._vdataF32[offset++] = p.velocity.z; + this._model._vdataF32[offset++] = p.startLifetime; + + this._model._vdataF32[offset++] = p.randomSeed; + } + this._particleNum++; + } + + _updateParticles() { + for (let i = 0; i < this._particleNum; ++i) { + let pBaseIndex = i * this._model._vertAttrsSize * 4; + if (this.particleSystem._time - this._model._vdataF32[pBaseIndex + this._vertIndexMap[ATTR_INDEX.START_TIME]] > this._model._vdataF32[pBaseIndex + this._vertIndexMap[ATTR_INDEX.LIFE_TIME]]) { + let lastParticleBaseIndex = (this._particleNum - 1) * this._model._vertAttrsSize * 4; + this._model._vdataF32.copyWithin(pBaseIndex, lastParticleBaseIndex, lastParticleBaseIndex + this._model._vertAttrsSize * 4); + i--; + this._particleNum--; + } + } + } + + _updateRenderData() { + this._model.updateIA(this._particleNum * 6); + } + + updateShaderUniform() { + this._model._device.setUniform('u_psTime', this.particleSystem._time); + let needUploadRot = false; + if (this.particleSystem._velocityOvertimeModule.enable) { + this._material.define('VELOCITY_OVERTIME_MODULE_ENABLE', true); + if (this.velocity_pos_x_uniform === undefined) { + this.velocity_pos_x_uniform = new CurveUniform(); + this.velocity_pos_x_uniform.constructCurveIntegral(this.particleSystem._velocityOvertimeModule._x); + } + if (this.velocity_pos_y_uniform === undefined) { + this.velocity_pos_y_uniform = new CurveUniform(); + this.velocity_pos_y_uniform.constructCurveIntegral(this.particleSystem._velocityOvertimeModule._y); + } + if (this.velocity_pos_z_uniform === undefined) { + this.velocity_pos_z_uniform = new CurveUniform(); + this.velocity_pos_z_uniform.constructCurveIntegral(this.particleSystem._velocityOvertimeModule._z); + } + if (this._renderMode === 'stretchedBillboard') { + if (this.velocity_x_uniform === undefined) { + this.velocity_x_uniform = new CurveUniform(); + this.velocity_x_uniform.constructCurve(this.particleSystem._velocityOvertimeModule._x); + } + if (this.velocity_y_uniform === undefined) { + this.velocity_y_uniform = new CurveUniform(); + this.velocity_y_uniform.constructCurve(this.particleSystem._velocityOvertimeModule._y); + } + if (this.velocity_z_uniform === undefined) { + this.velocity_z_uniform = new CurveUniform(); + this.velocity_z_uniform.constructCurve(this.particleSystem._velocityOvertimeModule._z); + } + this.velocity_x_uniform.uploadUniform(this._model._device, 'velocity_x'); + this.velocity_y_uniform.uploadUniform(this._model._device, 'velocity_y'); + this.velocity_z_uniform.uploadUniform(this._model._device, 'velocity_z'); + } + this.velocity_pos_x_uniform.uploadUniform(this._model._device, 'velocity_pos_x'); + this.velocity_pos_y_uniform.uploadUniform(this._model._device, 'velocity_pos_y'); + this.velocity_pos_z_uniform.uploadUniform(this._model._device, 'velocity_pos_z'); + this._model._device.setUniform('u_speedModifier', this.particleSystem._velocityOvertimeModule._speedModifier.evaluate()); + this._model._device.setUniform('u_velocity_space', _space_map[this.particleSystem._velocityOvertimeModule._space]); + if (this.particleSystem._velocityOvertimeModule._space === 'local') { + needUploadRot = true; + } + } else { + this._material.define('VELOCITY_OVERTIME_MODULE_ENABLE', false); + } + if (this.particleSystem._forceOvertimeModule.enable) { + this._material.define('FORCE_OVERTIME_MODULE_ENABLE', true); + if (this.force_pos_x_uniform === undefined) { + this.force_pos_x_uniform = new CurveUniform(); + this.force_pos_x_uniform.constructCurveIntegralTwice(this.particleSystem._forceOvertimeModule._x); + } + if (this.force_pos_y_uniform === undefined) { + this.force_pos_y_uniform = new CurveUniform(); + this.force_pos_y_uniform.constructCurveIntegralTwice(this.particleSystem._forceOvertimeModule._y); + } + if (this.force_pos_z_uniform === undefined) { + this.force_pos_z_uniform = new CurveUniform(); + this.force_pos_z_uniform.constructCurveIntegralTwice(this.particleSystem._forceOvertimeModule._z); + } + if (this._renderMode === 'stretchedBillboard') { + if (this.force_vel_x_uniform === undefined) { + this.force_vel_x_uniform = new CurveUniform(); + this.force_vel_x_uniform.constructCurveIntegral(this.particleSystem._forceOvertimeModule._x); + } + if (this.force_vel_y_uniform === undefined) { + this.force_vel_y_uniform = new CurveUniform(); + this.force_vel_y_uniform.constructCurveIntegral(this.particleSystem._forceOvertimeModule._y); + } + if (this.force_vel_z_uniform === undefined) { + this.force_vel_z_uniform = new CurveUniform(); + this.force_vel_z_uniform.constructCurveIntegral(this.particleSystem._forceOvertimeModule._z); + } + this.force_vel_x_uniform.uploadUniform(this._model._device, 'force_vel_x'); + this.force_vel_y_uniform.uploadUniform(this._model._device, 'force_vel_y'); + this.force_vel_z_uniform.uploadUniform(this._model._device, 'force_vel_z'); + } + this.force_pos_x_uniform.uploadUniform(this._model._device, 'force_pos_x'); + this.force_pos_y_uniform.uploadUniform(this._model._device, 'force_pos_y'); + this.force_pos_z_uniform.uploadUniform(this._model._device, 'force_pos_z'); + this._model._device.setUniform('u_force_space', _space_map[this.particleSystem._forceOvertimeModule._space]); + if (this.particleSystem._forceOvertimeModule._space === 'local') { + needUploadRot = true; + } + } else { + this._material.define('FORCE_OVERTIME_MODULE_ENABLE', false); + } + if (needUploadRot || this.particleSystem._simulationSpace) { + quat.array(_world_rot_uniform, this.particleSystem._entity.getWorldRot(_temp_rot)); + this._model._device.setUniform('u_worldRot', _world_rot_uniform); + } + if (this.particleSystem._sizeOvertimeModule.enable) { + this._material.define('SIZE_OVERTIME_MODULE_ENABLE', true); + if (this.size_uniform === undefined) { + this.size_uniform = new CurveUniform(); + this.size_uniform.constructCurve(this.particleSystem._sizeOvertimeModule._size); + } + this.size_uniform.uploadUniform(this._model._device, 'size'); + } else { + this._material.define('SIZE_OVERTIME_MODULE_ENABLE', false); + } + if (this.particleSystem._colorOverLifetimeModule.enable) { + this._material.define('COLOR_OVERTIME_MODULE_ENABLE', true); + if (this.color_uniform === undefined) { + this.color_uniform = new GradientUniform(this.particleSystem._colorOverLifetimeModule._color); + } + this.color_uniform.uploadUniform(this._model._device, 'color'); + } else { + this._material.define('COLOR_OVERTIME_MODULE_ENABLE', false); + } + if (this.particleSystem._textureAnimationModule.enable) { + this._material.define('TEXTURE_ANIMATION_ENABLE', true); + if (this.frame_uniform === undefined) { + this.frame_uniform = new CurveUniform(); + this.frame_uniform.constructCurve(this.particleSystem._textureAnimationModule._frameOverTime); + } + this.frame_uniform.uploadUniform(this._model._device, 'frameOverTime'); + this._model._device.setUniform('u_cycles', this.particleSystem._textureAnimationModule._cycleCount); + this._model._device.setUniform('u_animation_mode', _animationMode[this.particleSystem._textureAnimationModule._animation]); + this._model._device.setUniform('u_random_row', this.particleSystem._textureAnimationModule._randomRow); + this._model._device.setUniform('u_row_index', this.particleSystem._textureAnimationModule._rowIndex); + } else { + this._material.define('TEXTURE_ANIMATION_ENABLE', false); + } + if (this.particleSystem._rotationOvertimeModule.enable) { + this._material.define('ROTATE_OVERTIME_MODULE_ENABLE', true); + if (this.size_uniform === undefined) { + this.size_uniform = new CurveUniform(); + this.size_uniform.constructCurveIntegral(this.particleSystem._rotationOvertimeModule._z); + } + this.size_uniform.uploadUniform(this._model._device, 'rotate'); + } else { + this._material.define('ROTATE_OVERTIME_MODULE_ENABLE', false); + } + } +} diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-renderer.js new file mode 100644 index 0000000000..c3bb5694fb --- /dev/null +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.js @@ -0,0 +1,294 @@ +import renderer from '../../../../renderer'; +import { vec3, vec4, vec2, mat4 } from '../../../../core/vmath'; +import gfx from '../../../../renderer/gfx'; +import Material from '../../../assets/material'; +import { RecyclePool } from '../../../memop'; +import Particle from '../particle'; +import RenderableComponent from '../../renderable-component'; +import { Enum } from '../../../../core/value-types'; +import { property, ccclass, executeInEditMode } from '../../../../core/data/class-decorator'; +import { Space } from '../particle-general-function'; + +let _tempAttribUV = vec3.create(); +let _tempAttribUV0 = vec2.create(); +let _tempAttribColor = vec4.create(); +let _tempWorldTrans = mat4.create(); + +let _uvs = [ + 0, 0, // bottom-left + 1, 0, // bottom-right + 0, 1, // top-left + 1, 1 // top-right +]; + +const RenderMode = Enum({ + Billboard: 0, + StrecthedBillboard: 1, + HorizontalBillboard: 2, + VerticalBillboard: 3, + Mesh: 4 +}); + +@ccclass('cc.ParticleSystemRenderer') +@executeInEditMode +export default class ParticleSystemRenderer extends RenderableComponent { + + @property({ + type: RenderMode + }) + _renderMode = RenderMode.Billboard; + + @property({ + type: RenderMode + }) + get renderMode() { + return this._renderMode; + } + + set renderMode(val) { + if (this._renderMode === val) { + return; + } + this._renderMode = val; + this._updateMaterialParams(); + this._updateModel(); + } + + @property + _velocityScale = 1; + + @property + get velocityScale() { + return this._velocityScale; + } + + set velocityScale(val) { + this._velocityScale = val; + this._updateMaterialParams(); + this._updateModel(); + } + + @property + _lengthScale = 1; + + @property + get lengthScale() { + return this._lengthScale; + } + + set lengthScale(val) { + this._lengthScale = val; + this._updateMaterialParams(); + this._updateModel(); + } + + constructor() { + super(); + this._model = null; + + this.frameTile = cc.v2(1, 1); + this.attrs = new Array(5); + + this.device = cc.game._renderContext; + } + + onInit() { + this._vertAttrs = [ + { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3, index: gfx.ATTR_INDEX_POSITION }, + { name: gfx.ATTR_UV, type: gfx.ATTR_TYPE_FLOAT32, num: 3, index: gfx.ATTR_INDEX_UV }, + { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2, index: gfx.ATTR_INDEX_UV0 }, + { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, index: gfx.ATTR_INDEX_COLOR, normalize: true } + ]; + this.particleSystem = this.node.getComponent('cc.ParticleSystemComponent'); + this._particles = new RecyclePool(() => { + return new Particle(this); + }, this.particleSystem.capacity); + if (this.sharedMaterial == null) { + this.material = new Material(); + this.sharedMaterial.effectAsset = cc.EffectAsset.get('builtin-effect-particle-add'); + } + this._updateMaterialParams(); + this._updateModel(); + } + + onEnable() { + this._scene.addModel(this._model); + } + + onDisable() { + this._scene.removeModel(this._model); + } + + onDestroy() { + this._model.destroy(); + } + + _updateMaterialParams() { + if (!this.particleSystem) { + return; + } + if (this.particleSystem._simulationSpace === Space.World) { + this.sharedMaterial.define('USE_WORLD_SPACE', true); + } else { + this.sharedMaterial.define('USE_WORLD_SPACE', false); + } + + if (this._renderMode === RenderMode.Billboard) { + this.sharedMaterial.define('USE_BILLBOARD', true); + this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', false); + this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', false); + this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', false); + } else if (this._renderMode === RenderMode.StrecthedBillboard) { + this.sharedMaterial.define('USE_BILLBOARD', false); + this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', true); + this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', false); + this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', false); + this.sharedMaterial.setProperty('velocityScale', this._velocityScale); + this.sharedMaterial.setProperty('lengthScale', this._lengthScale); + } else if (this._renderMode === RenderMode.HorizontalBillboard) { + this.sharedMaterial.define('USE_BILLBOARD', false); + this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', false); + this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', true); + this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', false); + } else if (this._renderMode === RenderMode.VerticalBillboard) { + this.sharedMaterial.define('USE_BILLBOARD', false); + this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', false); + this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', false); + this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', true); + } else { + console.warn(`particle system renderMode ${this._renderMode} not support.`); + } + + if (this.particleSystem.textureAnimationModule.enable) { + this.sharedMaterial.setProperty('frameTile', vec2.set(this.frameTile, this.particleSystem.textureAnimationModule.numTilesX, this.particleSystem.textureAnimationModule.numTilesY)); + } + else { + this.sharedMaterial.setProperty('frameTile', this.frameTile); + } + } + + _updateModel() { + if (!this.particleSystem) { + return; + } + if (this._model === null) { + this._model = new renderer.ParticleBatchModel(this.device, this.particleSystem.capacity, this._vertAttrs); + this._model.setParticleRenderer(this); + this._model.setNode(this.node); + } + this._model.setEffect(this.sharedMaterial ? this.sharedMaterial.effect : null); + if (Object.getPrototypeOf(this).constructor.name === 'ParticleSystemGpuRenderer') + return; + if (this._renderMode === RenderMode.StrecthedBillboard) { + this._model.enableStretchedBillboard(); + } else { + this._model.disableStretchedBillboard(); + } + } + + _getFreeParticle() { + if (this._particles.length >= this.particleSystem._capacity) + return null; + return this._particles.add(); + } + + _setNewParticle(p) { + + } + + _updateParticles(dt) { + this.node.getWorldMatrix(_tempWorldTrans); + if (this.particleSystem.velocityOvertimeModule.enable) { + this.particleSystem.velocityOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); + } + if (this.particleSystem.forceOvertimeModule.enable) { + this.particleSystem.forceOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); + } + 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) { + this._particles.remove(i); + --i; + continue; + } + + p.velocity.y -= this.particleSystem.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity. + if (this.particleSystem.sizeOvertimeModule.enable) { + this.particleSystem.sizeOvertimeModule.animate(p); + } + if (this.particleSystem.colorOverLifetimeModule.enable) { + this.particleSystem.colorOverLifetimeModule.animate(p); + } + if (this.particleSystem.forceOvertimeModule.enable) { + this.particleSystem.forceOvertimeModule.animate(p, dt); + } + if (this.particleSystem.velocityOvertimeModule.enable) { + this.particleSystem.velocityOvertimeModule.animate(p); + } + else { + vec3.copy(p.ultimateVelocity, p.velocity); + } + if (this.particleSystem.limitVelocityOvertimeModule.enable) { + this.particleSystem.limitVelocityOvertimeModule.animate(p); + } + if (this.particleSystem.rotationOvertimeModule.enable) { + this.particleSystem.rotationOvertimeModule.animate(p, dt); + } + if (this.particleSystem.textureAnimationModule.enable) { + this.particleSystem.textureAnimationModule.animate(p); + } + vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. + } + } + + // internal function + _updateRenderData() { + // update vertex buffer + let idx = 0; + let uploadVel = this._renderMode == RenderMode.StrecthedBillboard; + for (let i = 0; i < this._particles.length; ++i) { + let p = this._particles.data[i]; + let fi = 0; + if (this.particleSystem.textureAnimationModule.enable) { + fi = p.frameIndex; + } + idx = i * 4; + let attrNum = 0; + for (let j = 0; j < 4; ++j) { // four verts per particle. + attrNum = 0; + this.attrs[attrNum++] = p.position; + _tempAttribUV.x = _uvs[2 * j]; + _tempAttribUV.y = _uvs[2 * j + 1]; + _tempAttribUV.z = fi; + this.attrs[attrNum++] = _tempAttribUV; + _tempAttribUV0.x = p.size.x; + _tempAttribUV0.y = p.rotation.x; + this.attrs[attrNum++] = _tempAttribUV0; + this.attrs[attrNum++] = p.color._val; + + if (uploadVel) { + this.attrs[attrNum++] = p.ultimateVelocity; + } + + this._model.addParticleVertexData(idx++, this.attrs); + } + } + + // because we use index buffer, per particle index count = 6. + this._model.updateIA(this._particles.length * 6); + } + + updateShaderUniform() { + + } + + _onMaterialModified(index, material) { + this._updateMaterialParams(); + this._updateModel(); + } +} + +Object.assign(ParticleSystemRenderer, { uv: _uvs }); diff --git a/cocos/3d/framework/renderable-component.js b/cocos/3d/framework/renderable-component.js index eac40b9af4..744cdf8a6a 100644 --- a/cocos/3d/framework/renderable-component.js +++ b/cocos/3d/framework/renderable-component.js @@ -98,8 +98,8 @@ export default class RenderableComponent extends RenderSystemActor { } setMaterial(material, index) { - this._onMaterialModified(index, material); this._materials[index] = material; + this._onMaterialModified(index, material); } _onMaterialModified(index, material) { diff --git a/cocos/3d/geom-utils/curve.js b/cocos/3d/geom-utils/curve.js index 1efad2bb95..cbf3d1e342 100644 --- a/cocos/3d/geom-utils/curve.js +++ b/cocos/3d/geom-utils/curve.js @@ -1,219 +1,207 @@ import { repeat, pingPong, inverseLerp, clamp } from '../../core/vmath'; +import { Enum } from '../../core/value-types'; +import { CCClass } from '../../core/data'; const LOOK_FORWARD = 3; +const WrapMode = Enum({ + Default: 0, + Once: 1, + Loop: 2, + PingPong: 3, + ClampForever: 4 +}); + export class Keyframe { + time = 0; + + value = 0; + + inTangent = 0; + + outTangent = 0; } -Keyframe.schema = { - time: { - type: 'number', - default: 0, - }, - value: { - type: 'number', - default: 0, - }, - inTangent: { - type: 'number', - default: 0, - }, - outTangent: { - type: 'number', - default: 0, - } -}; +CCClass.fastDefine('cc.Keyframe', Keyframe, { + time: 0, + value: 0, + inTangent: 0, + outTangent: 0 +}); export class OptimizedKey { - constructor() { - this.index = -1; - this.time = 0; - this.endTime = 0; - this.coefficient = new Float32Array(4); - } + constructor() { + this.index = -1; + this.time = 0; + this.endTime = 0; + this.coefficient = new Float32Array(4); + } - evaluate(T) { - let t = T - this.time; - return evalOptCurve(t, this.coefficient); - } + evaluate(T) { + let t = T - this.time; + return evalOptCurve(t, this.coefficient); + } } export function evalOptCurve(t, coefs) { - return (t * (t * (t * coefs[0] + coefs[1]) + coefs[2])) + coefs[3]; + return (t * (t * (t * coefs[0] + coefs[1]) + coefs[2])) + coefs[3]; } export class AnimationCurve { - constructor(keyFrames) { - this._keyFrames = keyFrames; - this.cachedKey = new OptimizedKey(); - } - addKey(keyFrame) { - if (this._keyFrames === null) - this._keyFrames = []; - this._keyFrames.push(keyFrame); - } + keyFrames = null; - //cubic Hermite spline - evaluate_slow(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; - switch (wrapMode) { - case 'loop': - wrappedTime = repeat(time - startTime, endTime - startTime) + startTime; - break; - case 'pingPong': - wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime; - break; - case 'clampForever': - wrappedTime = clamp(time, startTime, endTime); - break; + preWrapMode = WrapMode.Default; + + postWrapMode = WrapMode.Default; + + constructor(keyFrames) { + this.keyFrames = keyFrames; + this.cachedKey = new OptimizedKey(); } - let preKFIndex = 0; - 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) { - preKFIndex = i; - break; - } + + addKey(keyFrame) { + if (this.keyFrames == null) + this.keyFrames = []; + this.keyFrames.push(keyFrame); + } + + //cubic Hermite spline + evaluate_slow(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; + switch (wrapMode) { + case WrapMode.Loop: + wrappedTime = repeat(time - startTime, endTime - startTime) + startTime; + break; + case WrapMode.PingPong: + wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime; + break; + case WrapMode.ClampForever: + wrappedTime = clamp(time, startTime, endTime); + break; } - } - } - let keyframe0 = this._keyFrames[preKFIndex]; - let keyframe1 = this._keyFrames[preKFIndex + 1]; - - let t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime); - let dt = keyframe1.time - keyframe0.time; - - let m0 = keyframe0.outTangent * dt; - let m1 = keyframe1.inTangent * dt; - - let t2 = t * t; - let 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; - - return a * keyframe0.value + b * m0 + c * m1 + d * keyframe1.value; - } - - 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; - switch (wrapMode) { - case 'loop': - wrappedTime = repeat(time - startTime, endTime - startTime) + startTime; - break; - case 'pingPong': - wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime; - break; - case 'clampForever': - wrappedTime = clamp(time, startTime, endTime); - break; - } - if (wrappedTime >= this.cachedKey.time && wrappedTime < this.cachedKey.endTime) { - return this.cachedKey.evaluate(wrappedTime); - } else { - let leftIndex = this.findIndex(this.cachedKey, wrappedTime); - let rightIndex = leftIndex + 1; - if (rightIndex == this._keyFrames.length) { - rightIndex -= 1; - } - this.calcOptimizedKey(this.cachedKey, leftIndex, rightIndex); - return this.cachedKey.evaluate(wrappedTime); - } - } - - calcOptimizedKey(optKey, leftIndex, rightIndex) { - let lhs = this._keyFrames[leftIndex]; - let 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; - - optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx; - optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length; - optKey.coefficient[2] = lhs.outTangent; - optKey.coefficient[3] = lhs.value; - } - - findIndex(optKey, t) { - let cachedIndex = optKey.index; - if (cachedIndex !== -1) { - let 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) { - return currIndex; - } + let preKFIndex = 0; + 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) { + preKFIndex = i; + break; + } + } + } } - } else { - for (let i = 0; i < LOOK_FORWARD; i++) { - let currIndex = cachedIndex - i; - if (currIndex >= 0 && this._keyFrames[currIndex - 1].time <= t) { - return currIndex - 1; - } + let keyframe0 = this.keyFrames[preKFIndex]; + let keyframe1 = this.keyFrames[preKFIndex + 1]; + + let t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime); + let dt = keyframe1.time - keyframe0.time; + + let m0 = keyframe0.outTangent * dt; + let m1 = keyframe1.inTangent * dt; + + let t2 = t * t; + let 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; + + return a * keyframe0.value + b * m0 + c * m1 + d * keyframe1.value; + } + + 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; + switch (wrapMode) { + case WrapMode.Loop: + wrappedTime = repeat(time - startTime, endTime - startTime) + startTime; + break; + case WrapMode.PingPong: + wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime; + break; + case WrapMode.ClampForever: + wrappedTime = clamp(time, startTime, endTime); + break; + } + if (wrappedTime >= this.cachedKey.time && wrappedTime < this.cachedKey.endTime) { + return this.cachedKey.evaluate(wrappedTime); + } else { + let leftIndex = this.findIndex(this.cachedKey, wrappedTime); + let rightIndex = leftIndex + 1; + if (rightIndex == this.keyFrames.length) { + rightIndex -= 1; + } + this.calcOptimizedKey(this.cachedKey, leftIndex, rightIndex); + return this.cachedKey.evaluate(wrappedTime); } - } } - let left = 0; - let right = this._keyFrames.length; - let mid = parseInt((left + right) / 2); - while (right - left > 1) { - if (this._keyFrames[mid].time >= t) { - right = mid; - } else { - left = mid + 1; - } - mid = parseInt((left + right) / 2); + + calcOptimizedKey(optKey, leftIndex, rightIndex) { + let lhs = this.keyFrames[leftIndex]; + let 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; + + optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx; + optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length; + optKey.coefficient[2] = lhs.outTangent; + optKey.coefficient[3] = lhs.value; + } + + findIndex(optKey, t) { + let cachedIndex = optKey.index; + if (cachedIndex !== -1) { + let 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) { + return currIndex; + } + } + } else { + for (let i = 0; i < LOOK_FORWARD; i++) { + let currIndex = cachedIndex - i; + if (currIndex >= 0 && this.keyFrames[currIndex - 1].time <= t) { + return currIndex - 1; + } + } + } + } + let left = 0; + let right = this.keyFrames.length; + let mid = parseInt((left + right) / 2); + while (right - left > 1) { + if (this.keyFrames[mid].time >= t) { + right = mid; + } else { + left = mid + 1; + } + mid = parseInt((left + right) / 2); + } + return left; } - return left; - } } -AnimationCurve.schema = { - keyFrames: { - type: 'Keyframe', - default: null, - array: true, - }, - preWrapMode: { - type: 'enums', - default: 'default', - options: [ - 'default', - 'once', - 'loop', - 'pingPong', - 'clampForever' - ], - }, - postWrapMode: { - type: 'enums', - default: 'default', - options: [ - 'default', - 'once', - 'loop', - 'pingPong', - 'clampForever' - ], - } -}; +CCClass.fastDefine('cc.AnimationCurve', AnimationCurve, { + preWrapMode: WrapMode.Default, + postWrapMode: WrapMode.Default, + keyFrames: [] +}); diff --git a/cocos/renderer/models/particle-batch-model.js b/cocos/renderer/models/particle-batch-model.js index 34f0c296df..690f1ad5a3 100644 --- a/cocos/renderer/models/particle-batch-model.js +++ b/cocos/renderer/models/particle-batch-model.js @@ -6,115 +6,114 @@ import InputAssembler from '../core/input-assembler'; import Model from '../scene/model'; function _createInputAssembler(out) { - let vb = new gfx.VertexBuffer( - out._device, - new gfx.VertexFormat(out._vertAttrs), - gfx.USAGE_DYNAMIC, - null, - out._capacity * 4 - ); + let vb = new gfx.VertexBuffer( + out._device, + new gfx.VertexFormat(out._vertAttrs), + gfx.USAGE_DYNAMIC, + null, + out._capacity * 4 + ); - let indices = new Array(out._capacity); - let dst = 0; - for (let i = 0; i < out._capacity; ++i) { - let baseIdx = 4 * i; - indices[dst++] = baseIdx; - indices[dst++] = baseIdx + 1; - indices[dst++] = baseIdx + 2; - indices[dst++] = baseIdx + 3; - indices[dst++] = baseIdx + 2; - indices[dst++] = baseIdx + 1; - } - let ib = new gfx.IndexBuffer( - out._device, - gfx.INDEX_FMT_UINT16, - gfx.USAGE_STATIC, - new Uint16Array(indices), - indices.length - ); + let indices = new Array(out._capacity); + let dst = 0; + for (let i = 0; i < out._capacity; ++i) { + let baseIdx = 4 * i; + indices[dst++] = baseIdx; + indices[dst++] = baseIdx + 1; + indices[dst++] = baseIdx + 2; + indices[dst++] = baseIdx + 3; + indices[dst++] = baseIdx + 2; + indices[dst++] = baseIdx + 1; + } + let ib = new gfx.IndexBuffer( + out._device, + gfx.INDEX_FMT_UINT16, + gfx.USAGE_STATIC, + new Uint16Array(indices), + indices.length + ); - out._ia = new InputAssembler(vb, ib); + out._ia = new InputAssembler(vb, ib); } export default class ParticleBatchModel extends Model { - constructor(device, capacity, vertAttrs) { - super(); + constructor(device, capacity, vertAttrs) { + super(); - this._type = 'particle-batch'; - this._device = device; - this._capacity = capacity; - this.setVertexAttributes(vertAttrs); - } - - setVertexAttributes(attrs) { - this._vertAttrs = attrs; - // rebuid - _createInputAssembler(this); - this._vertAttrsSize = this._ia._vertexBuffer._format._bytes / 4; // number of float - this._vdataF32 = new Float32Array(this._capacity * 4 * this._vertAttrsSize); - } - - enableStretchedBillboard() { - if (this._vertAttrs.find(attr => attr.name === gfx.ATTR_COLOR0) === undefined) { - this._vertAttrs.push({ name: gfx.ATTR_COLOR0, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); - this.setVertexAttributes(this._vertAttrs); + this._type = 'particle-batch'; + this._device = device; + this._capacity = capacity; + this.setVertexAttributes(vertAttrs); } - } - disableStretchedBillboard() { - if (this._vertAttrs.find(attr => attr.name === gfx.ATTR_COLOR0) !== undefined) { - this._vertAttrs.pop(); - this.setVertexAttributes(this._vertAttrs); + setVertexAttributes(attrs) { + this._vertAttrs = attrs; + // rebuid + _createInputAssembler(this); + this._vertAttrsSize = this._ia._vertexBuffer._format._bytes / 4; // number of float + this._vBuffer = new ArrayBuffer(this._capacity * this._ia._vertexBuffer._format._bytes); + this._vdataF32 = new Float32Array(this._vBuffer); + this._vdataUint32 = new Uint32Array(this._vBuffer); } - } - setParticleRenderer(r) { - this._renderer = r; - } - - addParticleVertexData(index, pvdata) { - // if (pvdata.length !== this._vertAttrs.length) { - // console.error('particle vertex stream data not match.'); - // } - let offset = index * this._vertAttrsSize; - for (let i = 0; i < this._vertAttrs.length; ++i) { - let curAttr = this._vertAttrs[i]; - if (curAttr.num === 1) { - this._vdataF32[offset] = pvdata[i]; // if not a single float? - offset++; - } else if (curAttr.num === 2) { - this._vdataF32[offset] = pvdata[i].x; - this._vdataF32[offset + 1] = pvdata[i].y; - offset += 2; - } else if (curAttr.num === 3) { - this._vdataF32[offset] = pvdata[i].x; - this._vdataF32[offset + 1] = pvdata[i].y; - this._vdataF32[offset + 2] = pvdata[i].z; - offset += 3; - } else if (curAttr.num === 4) { - this._vdataF32[offset] = pvdata[i].x; - this._vdataF32[offset + 1] = pvdata[i].y; - this._vdataF32[offset + 2] = pvdata[i].z; - this._vdataF32[offset + 3] = pvdata[i].w; - offset += 4; - } else { - console.error('particle vertex attribute format not support'); - } + enableStretchedBillboard() { + if (this._vertAttrs.find(attr => attr.name === gfx.ATTR_COLOR0) === undefined) { + this._vertAttrs.push({ name: gfx.ATTR_COLOR0, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); + this.setVertexAttributes(this._vertAttrs); + } } - } - updateIA(count) { - this._ia._count = count; - this._ia._vertexBuffer.update(0, this._vdataF32); - } + disableStretchedBillboard() { + if (this._vertAttrs.find(attr => attr.name === gfx.ATTR_COLOR0) !== undefined) { + this._vertAttrs.pop(); + this.setVertexAttributes(this._vertAttrs); + } + } - clear() { - this._ia._count = 0; - } + setParticleRenderer(r) { + this._renderer = r; + } - destroy() { - this._vdataF32 = null; - this._ia._vertexBuffer.destroy(); - this._ia._indexBuffer.destroy(); - } + addParticleVertexData(index, pvdata) { + // if (pvdata.length !== this._vertAttrs.length) { + // console.error('particle vertex stream data not match.'); + // } + let offset = index * this._vertAttrsSize; + for (let i = 0; i < this._vertAttrs.length; ++i) { + let curAttr = this._vertAttrs[i]; + if (curAttr.num === 1) { + this._vdataF32[offset] = pvdata[i]; // if not a single float? + offset++; + } else if (curAttr.num === 2) { + this._vdataF32[offset] = pvdata[i].x; + this._vdataF32[offset + 1] = pvdata[i].y; + offset += 2; + } else if (curAttr.num === 3) { + this._vdataF32[offset] = pvdata[i].x; + this._vdataF32[offset + 1] = pvdata[i].y; + this._vdataF32[offset + 2] = pvdata[i].z; + offset += 3; + } else if (curAttr.index === gfx.ATTR_INDEX_COLOR) { + this._vdataUint32[offset] = pvdata[i]; + offset += 1; + } else { + console.error('particle vertex attribute format not support'); + } + } + } + + updateIA(count) { + this._ia._count = count; + this._ia._vertexBuffer.update(0, this._vdataF32); + } + + clear() { + this._ia._count = 0; + } + + destroy() { + this._vdataF32 = null; + this._ia._vertexBuffer.destroy(); + this._ia._indexBuffer.destroy(); + } }