diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 19e3d509d5..2558b41ff0 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -574,15 +574,11 @@ Please do not specifiy "default" attribute in decorator of "%s" property in "%s" Default value must be initialized at their declaration: ``` // Before: -@property({ - type: cc.Integer - default: 0 // <-- -}) +@property({ default: 0 }) // <-- +@integer value; // After: -@property({ - type: cc.Integer -}) +@integer value = 0; // <-- ``` @@ -732,6 +728,10 @@ The renderer doesn't support the renderMode %s Cannot change hierarchy while activating or deactivating the parent. +### 3822 + +addComponent: Cannot add any component to the scene. + ### 3900 Invalid clip to add diff --git a/README.md b/README.md index c3c4050f17..e19977e323 100644 --- a/README.md +++ b/README.md @@ -46,8 +46,8 @@ This is all you have to do to setup engine development environment. ## Links - [Official site](http://www.cocos.com/en) -- [Forum](https://forum.cocos.com/c/3D) -- [Documentation](https://github.com/cocos-creator/docs-3d) -- API Referencess: Not yet published -- Download: To be announced +- [Forum](https://forum.cocos.org/c/3D) +- [Documentation](https://docs.cocos.com/creator3d/manual/zh) +- [API Referencess](https://docs.cocos.com/creator3d/api/zh) +- [Download](https://www.cocos.com/creator3d) - Road Map: To be announced diff --git a/cocos/audio/assets/player-dom.ts b/cocos/audio/assets/player-dom.ts index aa766a7066..a8dc1007ef 100644 --- a/cocos/audio/assets/player-dom.ts +++ b/cocos/audio/assets/player-dom.ts @@ -35,32 +35,46 @@ export class AudioPlayerDOM extends AudioPlayer { protected _loop = false; protected _oneShoting = false; protected _audio: HTMLAudioElement; + protected _cbRegistered = false; + private _remove_cb: () => void; private _post_play: () => void; private _on_gesture: () => void; + private _post_gesture: () => void; constructor (info: IAudioInfo) { super(info); this._audio = info.clip; + this._remove_cb = () => { + if (!this._cbRegistered) { return; } + cc.game.canvas.removeEventListener('touchend', this._on_gesture); + cc.game.canvas.removeEventListener('mouseup', this._on_gesture); + this._cbRegistered = false; + }; + this._post_play = () => { this._state = PlayingState.PLAYING; this._eventTarget.emit('started'); + this._remove_cb(); // should remove callbacks after any success play + }; + + this._post_gesture = () => { + if (this._interrupted) { this._post_play(); this._interrupted = false; } + else { this._audio!.pause(); this._audio!.currentTime = 0; } }; this._on_gesture = () => { if (!this._audio) { return; } const promise = this._audio.play(); - if (!promise) { - console.warn('no promise returned from HTMLMediaElement.play()'); + if (!promise) { // Chrome50/Firefox53 below + // delay eval here to yield uniform behavior with other platforms + this._state = PlayingState.PLAYING; + cc.director.once(cc.Director.EVENT_AFTER_UPDATE, this._post_gesture); return; } - promise.then(() => { - if (this._interrupted) { this._post_play(); this._interrupted = false; } - else { this._audio!.pause(); this._audio!.currentTime = 0; } - cc.game.canvas.removeEventListener('touchend', this._on_gesture); - cc.game.canvas.removeEventListener('mouseup', this._on_gesture); - }); + promise.then(this._post_gesture); + this._remove_cb(); }; this._audio.volume = this._volume; @@ -76,6 +90,7 @@ export class AudioPlayerDOM extends AudioPlayer { we can freely invoke play() outside event listeners later */ cc.game.canvas.addEventListener('touchend', this._on_gesture); cc.game.canvas.addEventListener('mouseup', this._on_gesture); + this._cbRegistered = true; } public play () { @@ -83,7 +98,9 @@ export class AudioPlayerDOM extends AudioPlayer { if (this._blocking) { this._interrupted = true; return; } const promise = this._audio.play(); if (!promise) { - console.warn('no promise returned from HTMLMediaElement.play()'); + // delay eval here to yield uniform behavior with other platforms + this._state = PlayingState.PLAYING; + cc.director.once(cc.Director.EVENT_AFTER_UPDATE, this._post_play); return; } promise.then(this._post_play).catch(() => { this._interrupted = true; }); diff --git a/cocos/audio/assets/player-web.ts b/cocos/audio/assets/player-web.ts index 448be7141d..c177865c05 100644 --- a/cocos/audio/assets/player-web.ts +++ b/cocos/audio/assets/player-web.ts @@ -27,7 +27,6 @@ * @category component/audio */ -import { director, Director } from '../../core/director'; import { clamp } from '../../core/math/utils'; import sys from '../../core/platform/sys'; import { AudioPlayer, IAudioInfo, PlayingState } from './player'; @@ -71,11 +70,13 @@ export class AudioPlayerWeb extends AudioPlayer { this._sourceNode.buffer = this._audio; this._sourceNode.loop = this._loop; this._sourceNode.connect(this._gainNode); - this._sourceNode.start(0, this._offset); - this._state = PlayingState.PLAYING; this._startTime = this._context.currentTime; // delay eval here to yield uniform behavior with other platforms - director.once(Director.EVENT_AFTER_UPDATE, () => { this._eventTarget.emit('started'); }); + cc.director.once(cc.Director.EVENT_AFTER_UPDATE, () => { + this._sourceNode.start(0, this._offset); + this._eventTarget.emit('started'); + this._state = PlayingState.PLAYING; + }); /* still not supported by all platforms * this._sourceNode.onended = this._on_ended; /* doing it manually for now */ @@ -96,7 +97,8 @@ export class AudioPlayerWeb extends AudioPlayer { cc.game.canvas.removeEventListener('mouseup', this._on_gesture); }); }; - if (this._context.state !== 'running') { + // Chrome41/Firefox40 below don't have resume + if (this._context.state !== 'running' && this._context.resume) { cc.game.canvas.addEventListener('touchend', this._on_gesture); cc.game.canvas.addEventListener('mouseup', this._on_gesture); } diff --git a/cocos/audio/assets/player-wx.ts b/cocos/audio/assets/player-wx.ts index efbaeaa9d6..dde598e960 100644 --- a/cocos/audio/assets/player-wx.ts +++ b/cocos/audio/assets/player-wx.ts @@ -48,6 +48,10 @@ export class AudioPlayerWX extends AudioPlayer { constructor (info: IAudioInfo) { super(info); this._audio = info.clip; + // [HACK] volume property doesn't work on some devices during the first playthrough + this._audio.play(); + this._audio.stop(); + this._audio.onPlay(() => { if (this._state === PlayingState.PLAYING) { return; } this._state = PlayingState.PLAYING; @@ -81,9 +85,6 @@ export class AudioPlayerWX extends AudioPlayer { } }); this._audio.onError((res: any) => console.error(res.errMsg)); - /* handle hide & show */ - wx.onAudioInterruptionBegin(this._onHide); - wx.onAudioInterruptionEnd(this._onShow); } public play () { @@ -107,11 +108,10 @@ export class AudioPlayerWX extends AudioPlayer { same time so here we fall back to re-start style approach */ if (!this._audio) { return; } this._offset = 0; - this._audio.seek(0); - this._audio.volume = volume; - if (this._oneShoting) { return; } - this._audio.loop = false; this._oneShoting = true; + this._audio.stop(); + this._audio.loop = false; + this._audio.volume = volume; this._audio.play(); } diff --git a/cocos/audio/audio-source-component.ts b/cocos/audio/audio-source-component.ts index 6e2574f44c..f63df1ee8f 100644 --- a/cocos/audio/audio-source-component.ts +++ b/cocos/audio/audio-source-component.ts @@ -60,7 +60,10 @@ export class AudioSourceComponent extends Component { * @zh * 设定要播放的音频。 */ - @property({ type: AudioClip }) + @property({ + type: AudioClip, + tooltip:'设定要播放的音频', + }) set clip (val) { this._clip = val; this._syncStates(); @@ -75,7 +78,9 @@ export class AudioSourceComponent extends Component { * @zh * 是否循环播放音频? */ - @property + @property({ + tooltip:'是否循环播放音频', + }) set loop (val) { this._loop = val; if (this._clip) { this._clip.setLoop(val); } @@ -95,7 +100,9 @@ export class AudioSourceComponent extends Component { * 请注意,根据最新的自动播放策略,现在大部分时候,自动播放只会在第一次收到用户输入后生效。
* 参考:https://www.chromium.org/audio-video/autoplay */ - @property + @property({ + tooltip:'是否启用自动播放', + }) set playOnAwake (val) { this._playOnAwake = val; } @@ -111,7 +118,10 @@ export class AudioSourceComponent extends Component { * * 请注意,在某些平台上,音量控制可能不起效。
*/ - @property + @property({ + range:[0.0,1.0], + tooltip:'音频的音量(大小范围为 0.0 到 1.0 )\n请注意,在某些平台上,音量控制可能不起效' + }) set volume (val) { if (isNaN(val)) { console.warn('illegal audio volume!'); return; } val = clamp(val, 0, 1); @@ -132,6 +142,14 @@ export class AudioSourceComponent extends Component { if (this._playOnAwake) { this.play(); } } + public onDisable () { + this.pause(); + } + + public onDestroy () { + this.stop(); + } + /** * @en * Plays the clip diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index 216df95d0b..2e7acf500c 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -9,14 +9,14 @@ export default [ "shaders": [ { "name": "builtin-billboard|vert:vs_main|tinted-fs:add", - "hash": 3876741410, + "hash": 3128769502, "glsl3": { - "vert": `\nprecision mediump float;\nuniform Constants{\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp mat4 cc_matWorlds[10];\n};\nvec4 quaternionFromAxisAngle(float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis(vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler(vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT(vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS(vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix(inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply(vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat(inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis(vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace(vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner(inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if 1 || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if 1\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nuniform builtin {\n vec4 cc_size_rotation;\n};\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(0., 0., cc_size_rotation.z), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }\n` + "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if 1 || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if 1\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nuniform builtin {\n vec4 cc_size_rotation;\n};\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(0., 0., cc_size_rotation.z), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxisAngle(float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis(vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler(vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT(vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS(vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix(inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply(vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat(inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis(vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace(vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner(inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if 1 || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if 1\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nuniform vec4 cc_size_rotation;\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(0., 0., cc_size_rotation.z), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture2D(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }\n` + "vert": `\nprecision mediump float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if 1 || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if 1\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nuniform vec4 cc_size_rotation;\nvec4 vs_main() {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n vec2 vertOffset = a_texCoord.xy - 0.5;\n computeVertPos(pos, vertOffset, quaternionFromEuler(0., 0., cc_size_rotation.z), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\n pos = cc_matViewProj * pos;\n uv = a_texCoord.xy;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture2D(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ @@ -53,14 +53,14 @@ export default [ "shaders": [ { "name": "builtin-particle-trail|particle-trail:vs_main|tinted-fs:add", - "hash": 207867717, + "hash": 2489155218, "glsl3": { - "vert": `\nprecision mediump float;\nuniform Constants{\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp mat4 cc_matWorlds[10];\n};\nvec4 quaternionFromAxisAngle(float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis(vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler(vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT(vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS(vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix(inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply(vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat(inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis(vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace(vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner(inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec4 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n out vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n#if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n#endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n#if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n#endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }\n`, - "frag": `\n precision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n in vec2 uv;\n in vec4 color;\n #if CC_DRAW_WIRE_FRAME\n in vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform FragConstants {\n vec4 tintColor;\n };\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\n vec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., col.a);\n }\n#endif\n return CCFragOutput(col);\n }\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }\n` + "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec4 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n out vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n #endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n #if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "frag": `\n precision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n in vec2 uv;\n in vec4 color;\n #if CC_DRAW_WIRE_FRAME\n in vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform FragConstants {\n vec4 tintColor;\n };\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\n vec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., col.a);\n }\n#endif\n return CCFragOutput(col);\n }\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxisAngle(float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis(vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler(vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT(vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS(vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix(inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply(vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat(inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis(vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace(vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner(inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec4 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n#if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n#endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n#if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n#endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }\n`, - "frag": `\n precision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n varying vec2 uv;\n varying vec4 color;\n #if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform vec4 tintColor;\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\n vec4 multiply () {\n vec4 col;\n vec4 texColor = texture2D(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., col.a);\n }\n#endif\n return CCFragOutput(col);\n }\nvoid main() { gl_FragColor = add(); }\n` + "vert": `\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec4 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n#endif\nvec4 vs_main() {\n highp vec4 pos = vec4(a_position, 1);\n vec4 velocity = vec4(a_texCoord1.xyz, 0);\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n velocity = cc_matWorld * velocity;\n #endif\n float vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\n vec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\n pos.xyz += camUp * vertOffset;\n pos = cc_matViewProj * pos;\n uv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\n color = a_color;\n #if CC_DRAW_WIRE_FRAME\n vBarycentric = a_texCoord2;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vs_main(); }`, + "frag": `\n precision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n varying vec2 uv;\n varying vec4 color;\n #if CC_DRAW_WIRE_FRAME\n varying vec3 vBarycentric;\n #endif\n uniform sampler2D mainTexture;\n uniform vec4 tintColor;\n vec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., 1.);\n }\n#endif\n return CCFragOutput(col);\n }\n vec4 multiply () {\n vec4 col;\n vec4 texColor = texture2D(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n#if CC_DRAW_WIRE_FRAME\n if (any(lessThan(vBarycentric, vec3(0.02)))) {\n col = vec4(0., 1., 1., col.a);\n }\n#endif\n return CCFragOutput(col);\n }\nvoid main() { gl_FragColor = add(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ @@ -97,14 +97,14 @@ export default [ "shaders": [ { "name": "builtin-particle|particle-vs-legacy:lpvs_main|tinted-fs:add", - "hash": 1044134572, + "hash": 1910301377, "glsl3": { - "vert": `\nprecision highp float;\nvec4 quaternionFromAxisAngle(float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis(vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler(vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT(vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS(vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix(inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply(vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat(inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis(vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace(vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner(inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nuniform Constants{\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp mat4 cc_matWorlds[10];\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_USE_STRETCHED_BILLBOARD\n in vec3 a_color1;\n#endif\n#if CC_USE_MESH\n in vec3 a_texCoord3;\n in vec3 a_normal;\n in vec4 a_color1;\n#endif\nvec4 lpvs_main() {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n#if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n#if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n#else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n#endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n`, - "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }\n` + "vert": `\nprecision highp float;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n vec4 scale;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_USE_STRETCHED_BILLBOARD\n in vec3 a_color1;\n#endif\n#if CC_USE_MESH\n in vec3 a_texCoord3;\n in vec3 a_normal;\n in vec4 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, + "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nuniform FragConstants {\n vec4 tintColor;\n};\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nvec4 quaternionFromAxisAngle(float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis(vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler(vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT(vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS(vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix(inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply(vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat(inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis(vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace(vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner(inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_USE_STRETCHED_BILLBOARD\n attribute vec3 a_color1;\n#endif\n#if CC_USE_MESH\n attribute vec3 a_texCoord3;\n attribute vec3 a_normal;\n attribute vec4 a_color1;\n#endif\nvec4 lpvs_main() {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n#if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n#if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n#else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n#endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n`, - "frag": `\nprecision highp float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture2D(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }\n` + "vert": `\nprecision highp float;\nvec4 quaternionFromAxisAngle (float angle, vec3 axis){\n angle /= 2.;\n float s = sin(angle);\n vec4 res;\n res.xyz = s * axis;\n res.w = cos(angle);\n return res;\n}\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\n mat3 m = mat3(xAxis,yAxis,zAxis);\n float trace = m[0][0] + m[1][1] + m[2][2];\n vec4 quat;\n if (trace > 0.) {\n float s = 0.5 / sqrt(trace + 1.0);\n quat.w = 0.25 / s;\n quat.x = (m[2][1] - m[1][2]) * s;\n quat.y = (m[0][2] - m[2][0]) * s;\n quat.z = (m[1][0] - m[0][1]) * s;\n } else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\n float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\n quat.w = (m[2][1] - m[1][2]) / s;\n quat.x = 0.25 * s;\n quat.y = (m[0][1] + m[1][0]) / s;\n quat.z = (m[0][2] + m[2][0]) / s;\n } else if (m[1][1] > m[2][2]) {\n float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\n quat.w = (m[0][2] - m[2][0]) / s;\n quat.x = (m[0][1] + m[1][0]) / s;\n quat.y = 0.25 * s;\n quat.z = (m[1][2] + m[2][1]) / s;\n } else {\n float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\n quat.w = (m[1][0] - m[0][1]) / s;\n quat.x = (m[0][2] + m[2][0]) / s;\n quat.y = (m[1][2] + m[2][1]) / s;\n quat.z = 0.25 * s;\n }\n float len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\n if (len > 0.) {\n len = 1. / sqrt(len);\n quat.x = quat.x * len;\n quat.y = quat.y * len;\n quat.z = quat.z * len;\n quat.w = quat.w * len;\n }\n return quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\n float x = angle.x / 2.;\n float y = angle.y / 2.;\n float z = angle.z / 2.;\n float sx = sin(x);\n float cx = cos(x);\n float sy = sin(y);\n float cy = cos(y);\n float sz = sin(z);\n float cz = cos(z);\n vec4 quat = vec4(0);\n quat.x = sx * cy * cz + cx * sy * sz;\n quat.y = cx * sy * cz + sx * cy * sz;\n quat.z = cx * cy * sz - sx * sy * cz;\n quat.w = cx * cy * cz - sx * sy * sz;\n return quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\n float x2 = q.x + q.x;\n float y2 = q.y + q.y;\n float z2 = q.z + q.z;\n float xx = q.x * x2;\n float xy = q.x * y2;\n float xz = q.x * z2;\n float yy = q.y * y2;\n float yz = q.y * z2;\n float zz = q.z * z2;\n float wx = q.w * x2;\n float wy = q.w * y2;\n float wz = q.w * z2;\n return mat4(\n 1. - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1. - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1. - (xx + yy), 0,\n p.x, p.y, p.z, 1\n );\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\n float x = q.x, y = q.y, z = q.z, w = q.w;\n float x2 = x + x;\n float y2 = y + y;\n float z2 = z + z;\n float xx = x * x2;\n float xy = x * y2;\n float xz = x * z2;\n float yy = y * y2;\n float yz = y * z2;\n float zz = z * z2;\n float wx = w * x2;\n float wy = w * y2;\n float wz = w * z2;\n float sx = s.x;\n float sy = s.y;\n float sz = s.z;\n return mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\n t.x, t.y, t.z, 1);\n}\nvoid scaleMatrix (inout mat4 m, float s){\n m[0].xyz *= s;\n m[1].xyz *= s;\n m[2].xyz *= s;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\n vec4 quat;\n quat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\n quat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\n quat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\n quat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n return quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\n float ix = q.w * v.x + q.y * v.z - q.z * v.y;\n float iy = q.w * v.y + q.z * v.x - q.x * v.z;\n float iz = q.w * v.z + q.x * v.y - q.y * v.x;\n float iw = -q.x * v.x - q.y * v.y - q.z * v.z;\n v.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\n v.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\n v.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateVecFromAxis (vec3 v, vec3 axis, float theta){\n return cos(theta) * v + sin(theta) * cross(v, axis) + (1. - cos(theta)) * dot(v, axis) * axis;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\n vec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\n vec4 rotQuat = quatMultiply(viewQuat, q);\n rotateVecFromQuat(pos, rotQuat);\n return pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , mat4 viewInv\n#endif\n#if CC_USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float xIndex\n#endif\n) {\n#if CC_USE_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\n vec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\n vec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_USE_HORIZONTAL_BILLBOARD\n vec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\n vec3 camX = vec3(1, 0, 0);\n vec3 camY = vec3(0, 0, -1);\n pos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_USE_VERTICAL_BILLBOARD\n vec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\n rotateCorner(viewSpaceVert, q.z);\n vec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\n vec3 camY = vec3(0, 1, 0);\n vec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\n pos.xyz += offset;\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if !CC_USE_MESH\n vertIndex.y = 1. - vertIndex.y;\n#endif\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_USE_STRETCHED_BILLBOARD\n attribute vec3 a_color1;\n#endif\n#if CC_USE_MESH\n attribute vec3 a_texCoord3;\n attribute vec3 a_normal;\n attribute vec4 a_color1;\n#endif\nvec4 lpvs_main () {\n vec3 compScale = scale.xyz * a_texCoord1;\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n #endif\n #if !CC_USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if CC_USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n #endif\n #if !CC_USE_MESH\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n #if CC_USE_BILLBOARD\n vec3 rotEuler = a_texCoord2;\n #elif CC_USE_STRETCHED_BILLBOARD\n vec3 rotEuler = vec3(0.);\n #else\n vec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n #endif\n computeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n #if CC_USE_BILLBOARD || CC_USE_VERTICAL_BILLBOARD\n , cc_matViewInv\n #endif\n #if CC_USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord.x\n #endif\n );\n color = a_color;\n #else\n mat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\n mat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\n pos = xform * vec4(a_texCoord3, 1);\n vec4 normal = xformNoScale * vec4(a_normal, 0);\n color = a_color * a_color1;\n #endif\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n pos = cc_matViewProj * pos;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }`, + "frag": `\nprecision highp float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\n vec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n return CCFragOutput(col);\n}\nvec4 multiply () {\n vec4 col;\n vec4 texColor = texture2D(mainTexture, uv);\n col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);\n col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0);\n return CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ @@ -140,19 +140,20 @@ export default [ "shaders": [ { "name": "builtin-sprite|sprite-vs:vert|sprite-fs:frag", - "hash": 1678704147, + "hash": 1146191949, "glsl3": { - "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if USE_LOCAL\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp mat4 cc_matWorlds[10];\n};\n#endif\nin vec3 a_position;\nin vec4 a_color;\nout vec4 color;\nin vec2 a_texCoord;\nout vec2 uv0;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_LOCAL\n pos = cc_matViewProj * cc_matWorld * pos;\n #else\n pos = cc_matViewProj * pos;\n #endif\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nin vec4 color;\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, uv0);\n #endif\n o *= color;\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if USE_LOCAL\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nin vec3 a_position;\nin vec4 a_color;\nout vec4 color;\nin vec2 a_texCoord;\nout vec2 uv0;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_LOCAL\n pos = cc_matViewProj * cc_matWorld * pos;\n #else\n pos = cc_matViewProj * pos;\n #endif\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nin vec4 color;\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, uv0);\n #if IS_GRAY\n float gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\n o.r = o.g = o.b = gray;\n #endif\n #endif\n o *= color;\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform mat4 cc_matViewProj;\n#if USE_LOCAL\nuniform highp mat4 cc_matWorld;\n#endif\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 color;\nattribute vec2 a_texCoord;\nvarying vec2 uv0;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_LOCAL\n pos = cc_matViewProj * cc_matWorld * pos;\n #else\n pos = cc_matViewProj * pos;\n #endif\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nvarying vec4 color;\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform mat4 cc_matViewProj;\n#if USE_LOCAL\nuniform highp mat4 cc_matWorld;\n#endif\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 color;\nattribute vec2 a_texCoord;\nvarying vec2 uv0;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_LOCAL\n pos = cc_matViewProj * cc_matWorld * pos;\n #else\n pos = cc_matViewProj * pos;\n #endif\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nvarying vec4 color;\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #if IS_GRAY\n float gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\n o.r = o.g = o.b = gray;\n #endif\n #endif\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":["USE_LOCAL"]}], "samplers":[]}}, "defines": [ {"name":"USE_LOCAL", "type":"boolean"}, - {"name":"USE_TEXTURE", "type":"boolean"} + {"name":"USE_TEXTURE", "type":"boolean"}, + {"name":"IS_GRAY", "type":"boolean"} ], "blocks": [], "samplers": [ @@ -164,45 +165,47 @@ export default [ { "name": "builtin-standard", "techniques": [ - {"name":"opaque", "passes":[{"program":"builtin-standard|standard-vs:vert|standard-fs:frag", "properties":{"tilingOffset":{"value":[1, 1, 0, 0], "type":16}, "albedo":{"value":[1, 1, 1, 1], "type":16}, "albedoScale":{"value":[1, 1, 1, 0], "type":16}, "pbrParams":{"value":[0.8, 0.6, 1, 1], "type":16}, "pbrScale":{"value":[1, 1, 1, 1], "type":16}, "emissive":{"value":[0, 0, 0, 1], "type":16}, "emissiveScale":{"value":[1, 1, 1, 1], "type":16}, "albedoMap":{"value":"grey", "type":28}, "normalMap":{"value":"normal", "type":28}, "pbrMap":{"value":"grey", "type":28}, "metallicRoughnessMap":{"value":"grey", "type":28}, "occlusionMap":{"value":"white", "type":28}, "emissiveMap":{"value":"grey", "type":28}}}]} + {"name":"opaque", "passes":[{"program":"builtin-standard|standard-vs:vert|standard-fs:frag", "properties":{"tilingOffset":{"value":[1, 1, 0, 0], "type":16}, "mainColor":{"value":[1, 1, 1, 1], "type":16, "handleInfo":["albedo", 0, 16]}, "albedoScale":{"value":[1, 1, 1], "type":15, "handleInfo":["albedoScaleAndCutoff", 0, 15]}, "alphaThreshold":{"value":[0.5], "type":13, "handleInfo":["albedoScaleAndCutoff", 3, 13]}, "occlusion":{"value":[1], "type":13, "handleInfo":["pbrParams", 0, 13]}, "roughness":{"value":[0.8], "type":13, "handleInfo":["pbrParams", 1, 13]}, "metallic":{"value":[0.6], "type":13, "handleInfo":["pbrParams", 2, 13]}, "normalStrenth":{"value":[1], "type":13, "handleInfo":["pbrParams", 3, 13]}, "emissive":{"value":[0, 0, 0, 1], "type":16}, "emissiveScale":{"value":[1, 1, 1, 1], "type":16}, "mainTexture":{"value":"grey", "type":28, "handleInfo":["albedoMap", 0, 28]}, "normalMap":{"value":"normal", "type":28}, "pbrMap":{"value":"grey", "type":28}, "metallicRoughnessMap":{"value":"grey", "type":28}, "occlusionMap":{"value":"white", "type":28}, "emissiveMap":{"value":"grey", "type":28}, "albedo":{"type":16, "value":[1, 1, 1, 1]}, "albedoScaleAndCutoff":{"type":16, "value":[1, 1, 1, 0.5]}, "pbrParams":{"type":16, "value":[1, 0.8, 0.6, 1]}, "albedoMap":{"type":28, "value":"grey"}}}]} ], "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", - "hash": 2079211605, + "hash": 339559055, "glsl3": { - "vert": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp mat4 cc_matWorlds[10];\n};\nstruct StandardAttributes {\n vec4 position;\n vec3 normal;\n vec4 tangent;\n int index;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if USE_BATCHING\nin float a_index;\n#endif\nvoid CCDecode (out StandardAttributes attr) {\n attr.position = vec4(a_position, 1.0);\n attr.normal = a_normal;\n attr.tangent = a_tangent;\n#if USE_BATCHING\n attr.index = int(a_index + 0.5);\n#endif\n}\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinningTexture {\n highp vec4 cc_jointsTextureInfo;\n};\nuniform CCSkinningAnimation {\n highp vec4 cc_jointsAnimInfo;\n};\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32(highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n Qt = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n S = vec3(\n decode32(texture(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 10.5) * invSize, y)))\n );\n }\n#elif CC_USE_SKINNING == 2\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n Qt = texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n S = texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y)).xyz;\n }\n#endif\nvoid skinRTS(out vec4 R, out vec3 T, out vec3 S) {\n vec4 r, t, Qt = vec4(0.0); vec3 s;\n R = vec4(0.0); S = vec3(0.0);\n for (int i = 0; i < 4; i++) {\n float w = a_weights[i];\n getJointDQ(a_joints[i], r, t, s);\n S += s * w; R += r * w; Qt += t * w;\n }\n float invNorm = 1.0 / length(R); R *= invNorm; Qt *= invNorm;\n T = 2.0 * (R.w * Qt.xyz - Qt.w * R.xyz + cross(R.xyz, Qt.xyz));\n}\nvec3 VectorTransformQuat(vec3 v, vec4 Q) {\n return v + 2.0 * cross(Q.xyz, cross(Q.xyz, v) + Q.w * v);\n}\nvoid CCSkin(inout vec4 position) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n position.xyz = VectorTransformQuat(position.xyz * S, R) + T;\n}\nvoid CCSkin(inout StandardAttributes attr) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n attr.position.xyz = VectorTransformQuat(attr.position.xyz * S, R) + T;\n attr.normal = VectorTransformQuat(attr.normal, R);\n attr.tangent.xyz = VectorTransformQuat(attr.tangent.xyz, R);\n}\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n int index;\n};\nvoid CCAttrToInput (in StandardAttributes attr, out StandardVertInput In) {\n In.position = attr.position;\n In.normal = attr.normal;\n In.tangent = attr.tangent;\n In.index = attr.index;\n}\nvoid CCVertInput (out StandardVertInput In) {\n StandardAttributes attr;\n CCDecode(attr);\n #if CC_USE_SKINNING\n CCSkin(attr);\n #endif\n CCAttrToInput(attr, In);\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScale;\n vec4 pbrParams;\n vec4 pbrScale;\n vec4 emissive;\n vec4 emissiveScale;\n};\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP || USE_METALLIC_ROUGHNESS_MAP || USE_OCCLUSION_MAP\n in vec2 a_texCoord;\n out vec2 v_uv;\n#endif\nvec4 vert () {\n StandardVertInput In;\n CCVertInput(In);\n #if USE_BATCHING\n mat4 matWorld = cc_matWorlds[In.index];\n mat4 matWorldIT = transposeMat4(matWorld);\n #else\n mat4 matWorld = cc_matWorld;\n mat4 matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n #if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP || USE_METALLIC_ROUGHNESS_MAP || USE_OCCLUSION_MAP\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return cc_matViewProj * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt2(float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float factor2 = factor * factor;\n float factor3 = factor2 * factor2;\n float smoothFactor = clamp(1.0 - factor3 * factor3, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt(float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt(vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile(float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular(float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting(vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = textureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap(vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = ACESToneMap(color.rgb);\n color.rgb = LinearToSRGB(color.rgb);\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScale;\n vec4 pbrParams;\n vec4 pbrScale;\n vec4 emissive;\n vec4 emissiveScale;\n};\nin vec3 v_position;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP || USE_METALLIC_ROUGHNESS_MAP || USE_OCCLUSION_MAP\n in vec2 v_uv;\n#endif\nin vec3 v_normal;\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, v_uv);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScale.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScale.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrScale.w) * normalize(v_tangent) +\n (nmmp.y * pbrScale.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n pbr = texture(pbrMap, v_uv);\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, v_uv);\n pbr.METALLIC_CHANNEL = metallicRoughness.METALLIC_CHANNEL;\n pbr.ROUGHNESS_CHANNEL = metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.OCCLUSION_CHANNEL = texture(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n pbr *= pbrScale;\n s.roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n s.metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 0.96);\n s.occlusion = pbr.OCCLUSION_CHANNEL;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, v_uv).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "vert": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinningTexture {\n highp vec4 cc_jointsTextureInfo;\n};\nuniform CCSkinningAnimation {\n highp vec4 cc_jointsAnimInfo;\n};\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScale;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nhighp vec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n highp mat4 matWorld, matWorldIT;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n highp vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt2 (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float factor2 = factor * factor;\n float factor3 = factor2 * factor2;\n float smoothFactor = clamp(1.0 - factor3 * factor3, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = textureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScale;\n};\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\n in vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture(pbrMap, v_uv);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, v_uv);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\nuniform highp mat4 cc_matWorlds[10];\nstruct StandardAttributes {\n vec4 position;\n vec3 normal;\n vec4 tangent;\n int index;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if USE_BATCHING\nattribute float a_index;\n#endif\nvoid CCDecode (out StandardAttributes attr) {\n attr.position = vec4(a_position, 1.0);\n attr.normal = a_normal;\n attr.tangent = a_tangent;\n#if USE_BATCHING\n attr.index = int(a_index + 0.5);\n#endif\n}\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform highp vec4 cc_jointsTextureInfo;\nuniform highp vec4 cc_jointsAnimInfo;\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32(highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n Qt = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n S = vec3(\n decode32(texture2D(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 10.5) * invSize, y)))\n );\n }\n#elif CC_USE_SKINNING == 2\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n Qt = texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n S = texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y)).xyz;\n }\n#endif\nvoid skinRTS(out vec4 R, out vec3 T, out vec3 S) {\n vec4 r, t, Qt = vec4(0.0); vec3 s;\n R = vec4(0.0); S = vec3(0.0);\n for (int i = 0; i < 4; i++) {\n float w = a_weights[i];\n getJointDQ(a_joints[i], r, t, s);\n S += s * w; R += r * w; Qt += t * w;\n }\n float invNorm = 1.0 / length(R); R *= invNorm; Qt *= invNorm;\n T = 2.0 * (R.w * Qt.xyz - Qt.w * R.xyz + cross(R.xyz, Qt.xyz));\n}\nvec3 VectorTransformQuat(vec3 v, vec4 Q) {\n return v + 2.0 * cross(Q.xyz, cross(Q.xyz, v) + Q.w * v);\n}\nvoid CCSkin(inout vec4 position) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n position.xyz = VectorTransformQuat(position.xyz * S, R) + T;\n}\nvoid CCSkin(inout StandardAttributes attr) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n attr.position.xyz = VectorTransformQuat(attr.position.xyz * S, R) + T;\n attr.normal = VectorTransformQuat(attr.normal, R);\n attr.tangent.xyz = VectorTransformQuat(attr.tangent.xyz, R);\n}\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n int index;\n};\nvoid CCAttrToInput (in StandardAttributes attr, out StandardVertInput In) {\n In.position = attr.position;\n In.normal = attr.normal;\n In.tangent = attr.tangent;\n In.index = attr.index;\n}\nvoid CCVertInput (out StandardVertInput In) {\n StandardAttributes attr;\n CCDecode(attr);\n #if CC_USE_SKINNING\n CCSkin(attr);\n #endif\n CCAttrToInput(attr, In);\n}\nuniform vec4 tilingOffset;\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP || USE_METALLIC_ROUGHNESS_MAP || USE_OCCLUSION_MAP\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n#endif\nvec4 vert () {\n StandardVertInput In;\n CCVertInput(In);\n #if USE_BATCHING\n mat4 matWorld = cc_matWorlds[In.index];\n mat4 matWorldIT = transposeMat4(matWorld);\n #else\n mat4 matWorld = cc_matWorld;\n mat4 matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n #if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP || USE_METALLIC_ROUGHNESS_MAP || USE_OCCLUSION_MAP\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return cc_matViewProj * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\n#if CC_USE_IBL\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\n#endif\nprecision highp float;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt2(float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float factor2 = factor * factor;\n float factor3 = factor2 * factor2;\n float smoothFactor = clamp(1.0 - factor3 * factor3, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat SmoothDistAtt(float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt(float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt(vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile(float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular(float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting(vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n #ifdef GL_EXT_shader_texture_lod\n vec4 envmap = textureCubeLodEXT(cc_environment, R, s.roughness * cc_ambientGround.w);\n #else\n vec4 envmap = textureCube(cc_environment, R);\n #endif\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap(vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = ACESToneMap(color.rgb);\n color.rgb = LinearToSRGB(color.rgb);\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_position;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP || USE_METALLIC_ROUGHNESS_MAP || USE_OCCLUSION_MAP\n varying vec2 v_uv;\n#endif\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, v_uv);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScale.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScale.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrScale.w) * normalize(v_tangent) +\n (nmmp.y * pbrScale.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n pbr = texture2D(pbrMap, v_uv);\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, v_uv);\n pbr.METALLIC_CHANNEL = metallicRoughness.METALLIC_CHANNEL;\n pbr.ROUGHNESS_CHANNEL = metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.OCCLUSION_CHANNEL = texture2D(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n pbr *= pbrScale;\n s.roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n s.metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 0.96);\n s.occlusion = pbr.OCCLUSION_CHANNEL;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, v_uv).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "vert": `\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matProj;\n#if CC_USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform highp vec4 cc_jointsTextureInfo;\nuniform highp vec4 cc_jointsAnimInfo;\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nhighp vec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n highp mat4 matWorld, matWorldIT;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n highp vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorldIT * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\n#if CC_USE_IBL\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\n#endif\nprecision highp float;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt2 (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float factor2 = factor * factor;\n float factor3 = factor2 * factor2;\n float smoothFactor = clamp(1.0 - factor3 * factor3, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n #ifdef GL_EXT_shader_texture_lod\n vec4 envmap = textureCubeLodEXT(cc_environment, R, s.roughness * cc_ambientGround.w);\n #else\n vec4 envmap = textureCube(cc_environment, R);\n #endif\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb) * cc_ambientSky.w;\n #endif\n finalColor += env * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\n varying vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, v_uv).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture2D(pbrMap, v_uv);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, v_uv);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture2D(occlusionMap, v_uv).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScale.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` }, - "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[{"name":"cc_environment", "defines":["CC_USE_IBL"]}]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}, {"name":"CCSkinningTexture", "defines":["CC_USE_SKINNING"]}, {"name":"CCSkinningAnimation", "defines":["CC_USE_SKINNING"]}, {"name":"CCForwardLight", "defines":[]}], "samplers":[{"name":"cc_jointsTexture", "defines":["CC_USE_SKINNING"]}]}}, + "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[{"name":"cc_environment", "defines":["CC_USE_IBL"]}]}, "locals":{"blocks":[{"name":"CCLocalBatched", "defines":["CC_USE_BATCHING"]}, {"name":"CCLocal", "defines":[]}, {"name":"CCSkinningTexture", "defines":["CC_USE_SKINNING"]}, {"name":"CCSkinningAnimation", "defines":["CC_USE_SKINNING"]}, {"name":"CCForwardLight", "defines":[]}], "samplers":[{"name":"cc_jointsTexture", "defines":["CC_USE_SKINNING"]}]}}, "defines": [ - {"name":"USE_BATCHING", "type":"boolean"}, + {"name":"CC_USE_BATCHING", "type":"boolean"}, {"name":"CC_USE_SKINNING", "type":"number", "range":[0, 2]}, + {"name":"USE_VERTEX_COLOR", "type":"boolean"}, {"name":"USE_NORMAL_MAP", "type":"boolean"}, - {"name":"USE_ALBEDO_MAP", "type":"boolean"}, {"name":"CC_USE_IBL", "type":"number", "range":[0, 2]}, {"name":"CC_USE_HDR", "type":"boolean"}, + {"name":"USE_ALBEDO_MAP", "type":"boolean"}, + {"name":"ALBEDO_UV", "type":"string", "options":["v_uv", "v_uv1"]}, {"name":"USE_PBR_MAP", "type":"boolean"}, {"name":"USE_METALLIC_ROUGHNESS_MAP", "type":"boolean"}, {"name":"USE_OCCLUSION_MAP", "type":"boolean"}, {"name":"USE_EMISSIVE_MAP", "type":"boolean"}, - {"name":"ROUGHNESS_CHANNEL", "type":"string", "options":["r", "g", "b"]}, - {"name":"METALLIC_CHANNEL", "type":"string", "options":["g", "r", "b"]}, - {"name":"OCCLUSION_CHANNEL", "type":"string", "options":["b", "r", "g"]}, + {"name":"EMISSIVE_UV", "type":"string", "options":["v_uv", "v_uv1"]}, + {"name":"OCCLUSION_CHANNEL", "type":"string", "options":["r", "g", "b"]}, + {"name":"ROUGHNESS_CHANNEL", "type":"string", "options":["g", "b", "r"]}, + {"name":"METALLIC_CHANNEL", "type":"string", "options":["b", "r", "g"]}, {"name":"USE_ALPHA_TEST", "type":"boolean"}, - {"name":"ALPHA_TEST_CHANNEL", "type":"string", "options":["a", "r", "g", "b"]} + {"name":"ALPHA_TEST_CHANNEL", "type":"string", "options":["a", "r"]} ], "blocks": [ {"name": "Constants", "defines": [], "binding": 0, "members": [ {"name":"tilingOffset", "type":16, "count":1}, {"name":"albedo", "type":16, "count":1}, - {"name":"albedoScale", "type":16, "count":1}, + {"name":"albedoScaleAndCutoff", "type":16, "count":1}, {"name":"pbrParams", "type":16, "count":1}, - {"name":"pbrScale", "type":16, "count":1}, {"name":"emissive", "type":16, "count":1}, {"name":"emissiveScale", "type":16, "count":1} ]} @@ -226,14 +229,14 @@ export default [ "shaders": [ { "name": "builtin-terrain|terrain-vs:vert|terrain-fs:frag", - "hash": 2907199317, + "hash": 2398639853, "glsl3": { - "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp mat4 cc_matWorlds[10];\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nout vec2 uvw;\nout vec2 uv0;\nout vec2 uv1;\nout vec2 uv2;\nout vec2 uv3;\nout vec3 diffuse;\nuniform TexCoords {\n vec4 UVScale;\n};\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n pos = cc_matViewProj * pos;\n uvw = a_texCoord;\n uv0 = a_position.xz * UVScale.x;\n uv1 = a_position.xz * UVScale.y;\n uv2 = a_position.xz * UVScale.z;\n uv3 = a_position.xz * UVScale.w;\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 N = a_normal;\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n diffuse = ambDiff + vec3(dot(N, L));\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n in vec2 uvw;\n in vec2 uv0;\n in vec2 uv1;\n in vec2 uv2;\n in vec2 uv3;\n in vec3 diffuse;\n uniform sampler2D weightMap;\n uniform sampler2D detailMap0;\n uniform sampler2D detailMap1;\n uniform sampler2D detailMap2;\n uniform sampler2D detailMap3;\nvec4 frag () {\n vec4 color = vec4(0, 0, 0, 0);\n #if LAYERS == 1\n color = texture(detailMap0, uv0);\n #elif LAYERS == 2\n vec4 w = texture(weightMap, uvw);\n color += texture(detailMap0, uv0) * w.r;\n color += texture(detailMap1, uv1) * w.g;\n #elif LAYERS == 3\n vec4 w = texture(weightMap, uvw);\n color += texture(detailMap0, uv0) * w.r;\n color += texture(detailMap1, uv1) * w.g;\n color += texture(detailMap2, uv2) * w.b;\n #elif LAYERS == 4\n vec4 w = texture(weightMap, uvw);\n color += texture(detailMap0, uv0) * w.r;\n color += texture(detailMap1, uv1) * w.g;\n color += texture(detailMap2, uv2) * w.b;\n color += texture(detailMap3, uv3) * w.a;\n #else\n color = texture(detailMap0, uv0);\n #endif\n color.rgb *= diffuse;\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nout vec2 uvw;\nout vec2 uv0;\nout vec2 uv1;\nout vec2 uv2;\nout vec2 uv3;\nout vec3 diffuse;\nuniform TexCoords {\n vec4 UVScale;\n};\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n pos = cc_matViewProj * pos;\n uvw = a_texCoord;\n uv0 = a_position.xz * UVScale.x;\n uv1 = a_position.xz * UVScale.y;\n uv2 = a_position.xz * UVScale.z;\n uv3 = a_position.xz * UVScale.w;\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 N = a_normal;\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n diffuse = ambDiff + vec3(dot(N, L));\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n in vec2 uvw;\n in vec2 uv0;\n in vec2 uv1;\n in vec2 uv2;\n in vec2 uv3;\n in vec3 diffuse;\n uniform sampler2D weightMap;\n uniform sampler2D detailMap0;\n uniform sampler2D detailMap1;\n uniform sampler2D detailMap2;\n uniform sampler2D detailMap3;\nvec4 frag () {\n vec4 color = vec4(0, 0, 0, 0);\n #if LAYERS == 1\n color = texture(detailMap0, uv0);\n #elif LAYERS == 2\n vec4 w = texture(weightMap, uvw);\n color += texture(detailMap0, uv0) * w.r;\n color += texture(detailMap1, uv1) * w.g;\n #elif LAYERS == 3\n vec4 w = texture(weightMap, uvw);\n color += texture(detailMap0, uv0) * w.r;\n color += texture(detailMap1, uv1) * w.g;\n color += texture(detailMap2, uv2) * w.b;\n #elif LAYERS == 4\n vec4 w = texture(weightMap, uvw);\n color += texture(detailMap0, uv0) * w.r;\n color += texture(detailMap1, uv1) * w.g;\n color += texture(detailMap2, uv2) * w.b;\n color += texture(detailMap3, uv3) * w.a;\n #else\n color = texture(detailMap0, uv0);\n #endif\n color.rgb *= diffuse;\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform highp mat4 cc_matWorld;\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nvarying vec2 uvw;\nvarying vec2 uv0;\nvarying vec2 uv1;\nvarying vec2 uv2;\nvarying vec2 uv3;\nvarying vec3 diffuse;\nuniform vec4 UVScale;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n pos = cc_matViewProj * pos;\n uvw = a_texCoord;\n uv0 = a_position.xz * UVScale.x;\n uv1 = a_position.xz * UVScale.y;\n uv2 = a_position.xz * UVScale.z;\n uv3 = a_position.xz * UVScale.w;\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 N = a_normal;\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n diffuse = ambDiff + vec3(dot(N, L));\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n varying vec2 uvw;\n varying vec2 uv0;\n varying vec2 uv1;\n varying vec2 uv2;\n varying vec2 uv3;\n varying vec3 diffuse;\n uniform sampler2D weightMap;\n uniform sampler2D detailMap0;\n uniform sampler2D detailMap1;\n uniform sampler2D detailMap2;\n uniform sampler2D detailMap3;\nvec4 frag () {\n vec4 color = vec4(0, 0, 0, 0);\n #if LAYERS == 1\n color = texture2D(detailMap0, uv0);\n #elif LAYERS == 2\n vec4 w = texture2D(weightMap, uvw);\n color += texture2D(detailMap0, uv0) * w.r;\n color += texture2D(detailMap1, uv1) * w.g;\n #elif LAYERS == 3\n vec4 w = texture2D(weightMap, uvw);\n color += texture2D(detailMap0, uv0) * w.r;\n color += texture2D(detailMap1, uv1) * w.g;\n color += texture2D(detailMap2, uv2) * w.b;\n #elif LAYERS == 4\n vec4 w = texture2D(weightMap, uvw);\n color += texture2D(detailMap0, uv0) * w.r;\n color += texture2D(detailMap1, uv1) * w.g;\n color += texture2D(detailMap2, uv2) * w.b;\n color += texture2D(detailMap3, uv3) * w.a;\n #else\n color = texture2D(detailMap0, uv0);\n #endif\n color.rgb *= diffuse;\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform highp mat4 cc_matWorld;\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nvarying vec2 uvw;\nvarying vec2 uv0;\nvarying vec2 uv1;\nvarying vec2 uv2;\nvarying vec2 uv3;\nvarying vec3 diffuse;\nuniform vec4 UVScale;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n pos = cc_matViewProj * pos;\n uvw = a_texCoord;\n uv0 = a_position.xz * UVScale.x;\n uv1 = a_position.xz * UVScale.y;\n uv2 = a_position.xz * UVScale.z;\n uv3 = a_position.xz * UVScale.w;\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 N = a_normal;\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n diffuse = ambDiff + vec3(dot(N, L));\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n varying vec2 uvw;\n varying vec2 uv0;\n varying vec2 uv1;\n varying vec2 uv2;\n varying vec2 uv3;\n varying vec3 diffuse;\n uniform sampler2D weightMap;\n uniform sampler2D detailMap0;\n uniform sampler2D detailMap1;\n uniform sampler2D detailMap2;\n uniform sampler2D detailMap3;\nvec4 frag () {\n vec4 color = vec4(0, 0, 0, 0);\n #if LAYERS == 1\n color = texture2D(detailMap0, uv0);\n #elif LAYERS == 2\n vec4 w = texture2D(weightMap, uvw);\n color += texture2D(detailMap0, uv0) * w.r;\n color += texture2D(detailMap1, uv1) * w.g;\n #elif LAYERS == 3\n vec4 w = texture2D(weightMap, uvw);\n color += texture2D(detailMap0, uv0) * w.r;\n color += texture2D(detailMap1, uv1) * w.g;\n color += texture2D(detailMap2, uv2) * w.b;\n #elif LAYERS == 4\n vec4 w = texture2D(weightMap, uvw);\n color += texture2D(detailMap0, uv0) * w.r;\n color += texture2D(detailMap1, uv1) * w.g;\n color += texture2D(detailMap2, uv2) * w.b;\n color += texture2D(detailMap3, uv3) * w.a;\n #else\n color = texture2D(detailMap0, uv0);\n #endif\n color.rgb *= diffuse;\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, "defines": [ @@ -258,35 +261,38 @@ export default [ { "name": "builtin-unlit", "techniques": [ - {"name":"opaque", "passes":[{"program":"builtin-unlit|unlit-vs:vert|unlit-fs:frag", "properties":{"color":{"value":[1, 1, 1, 1], "type":16}, "tilingOffset":{"value":[1, 1, 0, 0], "type":16}, "mainTexture":{"value":"grey", "type":28}}}]} + {"name":"opaque", "passes":[{"program":"builtin-unlit|unlit-vs:vert|unlit-fs:frag", "properties":{"mainTexture":{"value":"grey", "type":28}, "tilingOffset":{"value":[1, 1, 0, 0], "type":16}, "mainColor":{"value":[1, 1, 1, 1], "type":16}, "colorScale":{"value":[1, 1, 1], "type":15, "handleInfo":["colorScaleAndCutoff", 0, 15]}, "alphaThreshold":{"value":[0.5], "type":13, "handleInfo":["colorScaleAndCutoff", 3, 13]}, "color":{"type":16, "handleInfo":["mainColor", 0, 16]}, "colorScaleAndCutoff":{"type":16, "value":[1, 1, 1, 0.5]}}}]} ], "shaders": [ { "name": "builtin-unlit|unlit-vs:vert|unlit-fs:frag", - "hash": 2096712480, + "hash": 3618668090, "glsl3": { - "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp mat4 cc_matWorlds[10];\n};\nin vec3 a_position;\nvoid CCDecode (out vec4 position) {\n position = vec4(a_position, 1.0);\n}\n#if CC_USE_SKINNING\nstruct StandardAttributes {\n vec4 position;\n vec3 normal;\n vec4 tangent;\n int index;\n};\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinningTexture {\n highp vec4 cc_jointsTextureInfo;\n};\nuniform CCSkinningAnimation {\n highp vec4 cc_jointsAnimInfo;\n};\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32(highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n Qt = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n S = vec3(\n decode32(texture(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 10.5) * invSize, y)))\n );\n }\n#elif CC_USE_SKINNING == 2\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n Qt = texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n S = texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y)).xyz;\n }\n#endif\nvoid skinRTS(out vec4 R, out vec3 T, out vec3 S) {\n vec4 r, t, Qt = vec4(0.0); vec3 s;\n R = vec4(0.0); S = vec3(0.0);\n for (int i = 0; i < 4; i++) {\n float w = a_weights[i];\n getJointDQ(a_joints[i], r, t, s);\n S += s * w; R += r * w; Qt += t * w;\n }\n float invNorm = 1.0 / length(R); R *= invNorm; Qt *= invNorm;\n T = 2.0 * (R.w * Qt.xyz - Qt.w * R.xyz + cross(R.xyz, Qt.xyz));\n}\nvec3 VectorTransformQuat(vec3 v, vec4 Q) {\n return v + 2.0 * cross(Q.xyz, cross(Q.xyz, v) + Q.w * v);\n}\nvoid CCSkin(inout vec4 position) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n position.xyz = VectorTransformQuat(position.xyz * S, R) + T;\n}\nvoid CCSkin(inout StandardAttributes attr) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n attr.position.xyz = VectorTransformQuat(attr.position.xyz * S, R) + T;\n attr.normal = VectorTransformQuat(attr.normal, R);\n attr.tangent.xyz = VectorTransformQuat(attr.tangent.xyz, R);\n}\n#endif\nvoid CCVertInput (out highp vec4 position) {\n CCDecode(position);\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n}\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nhighp vec4 vert () {\n vec4 position;\n CCVertInput(position);\n highp vec4 pos = cc_matViewProj * cc_matWorld * position;\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_TEXTURE\n in vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform Constant {\n vec4 color;\n };\n#endif\n#if USE_VERTEX_COLOR\n in vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, v_uv);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n return CCFragOutput(o);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nin vec3 a_position;\n#if CC_USE_SKINNING\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinningTexture {\n highp vec4 cc_jointsTextureInfo;\n};\nuniform CCSkinningAnimation {\n highp vec4 cc_jointsAnimInfo;\n};\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nhighp vec4 vert () {\n highp vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n highp mat4 matWorld;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n in vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform Constant {\n vec4 mainColor;\n vec4 colorScaleAndCutoff;\n};\n#if USE_VERTEX_COLOR\n in vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nattribute vec3 a_position;\nvoid CCDecode (out vec4 position) {\n position = vec4(a_position, 1.0);\n}\n#if CC_USE_SKINNING\nstruct StandardAttributes {\n vec4 position;\n vec3 normal;\n vec4 tangent;\n int index;\n};\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform highp vec4 cc_jointsTextureInfo;\nuniform highp vec4 cc_jointsAnimInfo;\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32(highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n Qt = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n S = vec3(\n decode32(texture2D(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 10.5) * invSize, y)))\n );\n }\n#elif CC_USE_SKINNING == 2\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n Qt = texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n S = texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y)).xyz;\n }\n#endif\nvoid skinRTS(out vec4 R, out vec3 T, out vec3 S) {\n vec4 r, t, Qt = vec4(0.0); vec3 s;\n R = vec4(0.0); S = vec3(0.0);\n for (int i = 0; i < 4; i++) {\n float w = a_weights[i];\n getJointDQ(a_joints[i], r, t, s);\n S += s * w; R += r * w; Qt += t * w;\n }\n float invNorm = 1.0 / length(R); R *= invNorm; Qt *= invNorm;\n T = 2.0 * (R.w * Qt.xyz - Qt.w * R.xyz + cross(R.xyz, Qt.xyz));\n}\nvec3 VectorTransformQuat(vec3 v, vec4 Q) {\n return v + 2.0 * cross(Q.xyz, cross(Q.xyz, v) + Q.w * v);\n}\nvoid CCSkin(inout vec4 position) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n position.xyz = VectorTransformQuat(position.xyz * S, R) + T;\n}\nvoid CCSkin(inout StandardAttributes attr) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n attr.position.xyz = VectorTransformQuat(attr.position.xyz * S, R) + T;\n attr.normal = VectorTransformQuat(attr.normal, R);\n attr.tangent.xyz = VectorTransformQuat(attr.tangent.xyz, R);\n}\n#endif\nvoid CCVertInput (out highp vec4 position) {\n CCDecode(position);\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n}\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nhighp vec4 vert () {\n vec4 position;\n CCVertInput(position);\n highp vec4 pos = cc_matViewProj * cc_matWorld * position;\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_TEXTURE\n varying vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\n#if USE_VERTEX_COLOR\n varying vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, v_uv);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n return CCFragOutput(o);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matProj;\n#if CC_USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nattribute vec3 a_position;\n#if CC_USE_SKINNING\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform highp vec4 cc_jointsTextureInfo;\nuniform highp vec4 cc_jointsAnimInfo;\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nhighp vec4 vert () {\n highp vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n highp mat4 matWorld;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n varying vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform vec4 mainColor;\nuniform vec4 colorScaleAndCutoff;\n#if USE_VERTEX_COLOR\n varying vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture2D(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nvoid main() { gl_FragColor = frag(); }` }, - "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}, {"name":"CCSkinningTexture", "defines":["CC_USE_SKINNING"]}, {"name":"CCSkinningAnimation", "defines":["CC_USE_SKINNING"]}], "samplers":[{"name":"cc_jointsTexture", "defines":["CC_USE_SKINNING"]}]}}, + "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocalBatched", "defines":["CC_USE_BATCHING"]}, {"name":"CCLocal", "defines":[]}, {"name":"CCSkinningTexture", "defines":["CC_USE_SKINNING"]}, {"name":"CCSkinningAnimation", "defines":["CC_USE_SKINNING"]}], "samplers":[{"name":"cc_jointsTexture", "defines":["CC_USE_SKINNING"]}]}}, "defines": [ + {"name":"CC_USE_BATCHING", "type":"boolean"}, {"name":"CC_USE_SKINNING", "type":"number", "range":[0, 2]}, {"name":"USE_VERTEX_COLOR", "type":"boolean"}, {"name":"USE_TEXTURE", "type":"boolean"}, {"name":"FLIP_UV", "type":"boolean"}, {"name":"CC_USE_HDR", "type":"boolean"}, - {"name":"USE_COLOR", "type":"boolean"} + {"name":"USE_ALPHA_TEST", "type":"boolean"}, + {"name":"ALPHA_TEST_CHANNEL", "type":"string", "options":["a", "r", "g", "b"]} ], "blocks": [ {"name": "TexCoords", "defines": ["USE_TEXTURE"], "binding": 0, "members": [ {"name":"tilingOffset", "type":16, "count":1} ]}, - {"name": "Constant", "defines": ["USE_COLOR"], "binding": 1, "members": [ - {"name":"color", "type":16, "count":1} + {"name": "Constant", "defines": [], "binding": 1, "members": [ + {"name":"mainColor", "type":16, "count":1}, + {"name":"colorScaleAndCutoff", "type":16, "count":1} ]} ], "samplers": [ @@ -295,41 +301,6 @@ export default [ } ] }, - { - "name": "editor/terrain-circle-brush", - "techniques": [ - {"name":"transparent", "passes":[{"blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "program":"editor/terrain-circle-brush|terrain-brush-vs:vert|terrain-brush-fs:frag", "depthStencilState":{"depthTest":true, "depthWrite":false}, "properties":{"BrushPos":{"value":[0, 0, 0, 1], "type":16}, "BrushParams":{"value":[2.5, 2.5, 0, 0], "type":16}}}]} - ], - "shaders": [ - { - "name": "editor/terrain-circle-brush|terrain-brush-vs:vert|terrain-brush-fs:frag", - "hash": 394086792, - "glsl3": { - "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp mat4 cc_matWorlds[10];\n};\nin vec3 a_position;\nout vec4 wposition;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n wposition = cc_matWorld * pos;\n wposition.y += 0.01;\n pos = cc_matViewProj * wposition;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec4 wposition;\nuniform TexCoords {\n vec4 BrushPos;\n vec4 BrushParams;\n};\nvec4 frag () {\n float Radius = BrushParams.x;\n float Falloff = BrushParams.y;\n float Distance = length(wposition.xz - BrushPos.xz);\n float k = 0.0;\n #if LINEAR\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n k = max(0.0, 1.0 - (Distance - Radius) / Falloff);\n }\n #elif SMOOTH\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n float y = (Distance - Radius) / Falloff;\n k = sqrt(1.0 - y * y);\n }\n #elif SPHERICAL\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n k = max(0.0, 1.0 - (Distance - Radius) / Falloff);\n }\n k = k*k*(3 - 2 * k);\n #elif TIP\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n float y = (Falloff + Radius - Distance) / Falloff;\n k = 1.0 - sqrt(1.0 - y * y);\n }\n #endif\n vec4 color = vec4(0, 0, 0, 0);\n color.rgb = vec3(100, 100, 135) / 255.0;\n color.a = 0.85 * k;\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` - }, - "glsl1": { - "vert": `\nprecision mediump float;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nattribute vec3 a_position;\nvarying vec4 wposition;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n wposition = cc_matWorld * pos;\n wposition.y += 0.01;\n pos = cc_matViewProj * wposition;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec4 wposition;\nuniform vec4 BrushPos;\nuniform vec4 BrushParams;\nvec4 frag () {\n float Radius = BrushParams.x;\n float Falloff = BrushParams.y;\n float Distance = length(wposition.xz - BrushPos.xz);\n float k = 0.0;\n #if LINEAR\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n k = max(0.0, 1.0 - (Distance - Radius) / Falloff);\n }\n #elif SMOOTH\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n float y = (Distance - Radius) / Falloff;\n k = sqrt(1.0 - y * y);\n }\n #elif SPHERICAL\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n k = max(0.0, 1.0 - (Distance - Radius) / Falloff);\n }\n k = k*k*(3 - 2 * k);\n #elif TIP\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n float y = (Falloff + Radius - Distance) / Falloff;\n k = 1.0 - sqrt(1.0 - y * y);\n }\n #endif\n vec4 color = vec4(0, 0, 0, 0);\n color.rgb = vec3(100, 100, 135) / 255.0;\n color.a = 0.85 * k;\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }\n` - }, - "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, - "defines": [ - {"name":"CC_USE_HDR", "type":"boolean"}, - {"name":"LINEAR", "type":"boolean"}, - {"name":"SMOOTH", "type":"boolean"}, - {"name":"SPHERICAL", "type":"boolean"}, - {"name":"TIP", "type":"boolean"} - ], - "blocks": [ - {"name": "TexCoords", "defines": [], "binding": 0, "members": [ - {"name":"BrushPos", "type":16, "count":1}, - {"name":"BrushParams", "type":16, "count":1} - ]} - ], - "samplers": [] - } - ] - }, { "name": "pipeline/planar-shadow", "techniques": [ @@ -338,17 +309,18 @@ export default [ "shaders": [ { "name": "pipeline/planar-shadow|planar-shadow-vs:vert|planar-shadow-fs:frag", - "hash": 2934695859, + "hash": 593635975, "glsl3": { - "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp mat4 cc_matWorlds[10];\n};\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nin vec3 a_position;\nvoid CCDecode (out vec4 position) {\n position = vec4(a_position, 1.0);\n}\n#if CC_USE_SKINNING\nstruct StandardAttributes {\n vec4 position;\n vec3 normal;\n vec4 tangent;\n int index;\n};\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinningTexture {\n highp vec4 cc_jointsTextureInfo;\n};\nuniform CCSkinningAnimation {\n highp vec4 cc_jointsAnimInfo;\n};\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32(highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n Qt = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n S = vec3(\n decode32(texture(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 10.5) * invSize, y)))\n );\n }\n#elif CC_USE_SKINNING == 2\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n Qt = texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n S = texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y)).xyz;\n }\n#endif\nvoid skinRTS(out vec4 R, out vec3 T, out vec3 S) {\n vec4 r, t, Qt = vec4(0.0); vec3 s;\n R = vec4(0.0); S = vec3(0.0);\n for (int i = 0; i < 4; i++) {\n float w = a_weights[i];\n getJointDQ(a_joints[i], r, t, s);\n S += s * w; R += r * w; Qt += t * w;\n }\n float invNorm = 1.0 / length(R); R *= invNorm; Qt *= invNorm;\n T = 2.0 * (R.w * Qt.xyz - Qt.w * R.xyz + cross(R.xyz, Qt.xyz));\n}\nvec3 VectorTransformQuat(vec3 v, vec4 Q) {\n return v + 2.0 * cross(Q.xyz, cross(Q.xyz, v) + Q.w * v);\n}\nvoid CCSkin(inout vec4 position) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n position.xyz = VectorTransformQuat(position.xyz * S, R) + T;\n}\nvoid CCSkin(inout StandardAttributes attr) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n attr.position.xyz = VectorTransformQuat(attr.position.xyz * S, R) + T;\n attr.normal = VectorTransformQuat(attr.normal, R);\n attr.tangent.xyz = VectorTransformQuat(attr.tangent.xyz, R);\n}\n#endif\nvoid CCVertInput (out highp vec4 position) {\n CCDecode(position);\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n}\nhighp vec4 vert () {\n highp vec4 position;\n CCVertInput(position);\n position = cc_matViewProj * cc_matLightPlaneProj * cc_matWorld * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#if CC_USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nin vec3 a_position;\n#if CC_USE_SKINNING\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinningTexture {\n highp vec4 cc_jointsTextureInfo;\n};\nuniform CCSkinningAnimation {\n highp vec4 cc_jointsAnimInfo;\n};\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nhighp vec4 vert () {\n highp vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n highp mat4 matWorld;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matLightPlaneProj;\nattribute vec3 a_position;\nvoid CCDecode (out vec4 position) {\n position = vec4(a_position, 1.0);\n}\n#if CC_USE_SKINNING\nstruct StandardAttributes {\n vec4 position;\n vec3 normal;\n vec4 tangent;\n int index;\n};\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform highp vec4 cc_jointsTextureInfo;\nuniform highp vec4 cc_jointsAnimInfo;\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32(highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n Qt = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n S = vec3(\n decode32(texture2D(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 10.5) * invSize, y)))\n );\n }\n#elif CC_USE_SKINNING == 2\n void getJointDQ(float i, out vec4 Qr, out vec4 Qt, out vec3 S) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n Qr = texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n Qt = texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n S = texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y)).xyz;\n }\n#endif\nvoid skinRTS(out vec4 R, out vec3 T, out vec3 S) {\n vec4 r, t, Qt = vec4(0.0); vec3 s;\n R = vec4(0.0); S = vec3(0.0);\n for (int i = 0; i < 4; i++) {\n float w = a_weights[i];\n getJointDQ(a_joints[i], r, t, s);\n S += s * w; R += r * w; Qt += t * w;\n }\n float invNorm = 1.0 / length(R); R *= invNorm; Qt *= invNorm;\n T = 2.0 * (R.w * Qt.xyz - Qt.w * R.xyz + cross(R.xyz, Qt.xyz));\n}\nvec3 VectorTransformQuat(vec3 v, vec4 Q) {\n return v + 2.0 * cross(Q.xyz, cross(Q.xyz, v) + Q.w * v);\n}\nvoid CCSkin(inout vec4 position) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n position.xyz = VectorTransformQuat(position.xyz * S, R) + T;\n}\nvoid CCSkin(inout StandardAttributes attr) {\n vec4 R; vec3 T, S;\n skinRTS(R, T, S);\n attr.position.xyz = VectorTransformQuat(attr.position.xyz * S, R) + T;\n attr.normal = VectorTransformQuat(attr.normal, R);\n attr.tangent.xyz = VectorTransformQuat(attr.tangent.xyz, R);\n}\n#endif\nvoid CCVertInput (out highp vec4 position) {\n CCDecode(position);\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n}\nhighp vec4 vert () {\n highp vec4 position;\n CCVertInput(position);\n position = cc_matViewProj * cc_matLightPlaneProj * cc_matWorld * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_shadowColor;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matProj;\n#if CC_USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nattribute vec3 a_position;\n#if CC_USE_SKINNING\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform highp vec4 cc_jointsTextureInfo;\nuniform highp vec4 cc_jointsAnimInfo;\nuniform sampler2D cc_jointsTexture;\n#if CC_USE_SKINNING == 1\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n#endif\n#if CC_USE_SKINNING == 1\n mat4 getJointMatrix (float i) {\n highp float j = 12.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointsTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointsTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#elif CC_USE_SKINNING == 2\n mat4 getJointMatrix (float i) {\n highp float j = 3.0 * (cc_jointsAnimInfo.x * i + cc_jointsAnimInfo.y) + cc_jointsTextureInfo.z;\n highp float invSize = cc_jointsTextureInfo.y;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointsTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointsTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nhighp vec4 vert () {\n highp vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n highp mat4 matWorld;\n #if CC_USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id + 0.5)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform vec4 cc_shadowColor;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nvoid main() { gl_FragColor = frag(); }` }, - "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}, {"name":"CCShadow", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}, {"name":"CCSkinningTexture", "defines":["CC_USE_SKINNING"]}, {"name":"CCSkinningAnimation", "defines":["CC_USE_SKINNING"]}], "samplers":[{"name":"cc_jointsTexture", "defines":["CC_USE_SKINNING"]}]}}, + "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}, {"name":"CCShadow", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocalBatched", "defines":["CC_USE_BATCHING"]}, {"name":"CCLocal", "defines":[]}, {"name":"CCSkinningTexture", "defines":["CC_USE_SKINNING"]}, {"name":"CCSkinningAnimation", "defines":["CC_USE_SKINNING"]}], "samplers":[{"name":"cc_jointsTexture", "defines":["CC_USE_SKINNING"]}]}}, "defines": [ + {"name":"CC_USE_BATCHING", "type":"boolean"}, {"name":"CC_USE_SKINNING", "type":"number", "range":[0, 2]}, {"name":"CC_USE_HDR", "type":"boolean"} ], @@ -365,14 +337,14 @@ export default [ "shaders": [ { "name": "pipeline/skybox|sky-vs:vert|sky-fs:frag", - "hash": 491422960, + "hash": 2397009238, "glsl3": { - "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nin vec3 a_position;\nvoid CCDecode (out vec4 position) {\n position = vec4(a_position, 1.0);\n}\nout vec4 viewDir;\nhighp vec4 vert () {\n CCDecode(viewDir);\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n highp vec4 pos = matViewRotOnly * viewDir;\n highp vec2 f = cc_matProj[3][3] > 0.0 ? vec2(4.8, 2.4) : vec2(cc_matProj[1][1]);\n pos.xy *= vec2(cc_screenSize.y * cc_screenSize.z, 1.0) * f;\n pos.zw = vec2(-0.99999 * pos.z, -pos.z);\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform samplerCube cc_environment;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec3 ACESToneMap(vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = ACESToneMap(color.rgb);\n color.rgb = LinearToSRGB(color.rgb);\n #endif\n return color;\n}\nin vec4 viewDir;\nvec4 frag () {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(texture(cc_environment, viewDir.xyz));\n #else\n vec3 c = SRGBToLinear(texture(cc_environment, viewDir.xyz).rgb) * cc_ambientSky.w;\n #endif\n return CCFragOutput(vec4(c, 1.0));\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nin vec3 a_position;\nout vec4 viewDir;\nhighp vec4 vert () {\n viewDir = vec4(a_position, 1.0);\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n highp vec4 pos = matViewRotOnly * viewDir;\n highp vec2 f = cc_matProj[3][3] > 0.0 ? vec2(4.8, 2.4) : vec2(cc_matProj[1][1]);\n pos.xy *= vec2(cc_screenSize.y * cc_screenSize.z, 1.0) * f;\n pos.zw = vec2(-0.99999 * pos.z, -pos.z);\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nin vec4 viewDir;\nvec4 frag () {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(texture(cc_environment, viewDir.xyz));\n #else\n vec3 c = SRGBToLinear(texture(cc_environment, viewDir.xyz).rgb) * cc_ambientSky.w;\n #endif\n return CCFragOutput(vec4(c, 1.0));\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform vec4 cc_screenSize;\nuniform mat4 cc_matView;\nuniform mat4 cc_matProj;\nattribute vec3 a_position;\nvoid CCDecode (out vec4 position) {\n position = vec4(a_position, 1.0);\n}\nvarying vec4 viewDir;\nhighp vec4 vert () {\n CCDecode(viewDir);\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n highp vec4 pos = matViewRotOnly * viewDir;\n highp vec2 f = cc_matProj[3][3] > 0.0 ? vec2(4.8, 2.4) : vec2(cc_matProj[1][1]);\n pos.xy *= vec2(cc_screenSize.y * cc_screenSize.z, 1.0) * f;\n pos.zw = vec2(-0.99999 * pos.z, -pos.z);\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_ambientSky;\nuniform samplerCube cc_environment;\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec3 ACESToneMap(vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = ACESToneMap(color.rgb);\n color.rgb = LinearToSRGB(color.rgb);\n #endif\n return color;\n}\nvarying vec4 viewDir;\nvec4 frag () {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cc_environment, viewDir.xyz));\n #else\n vec3 c = SRGBToLinear(textureCube(cc_environment, viewDir.xyz).rgb) * cc_ambientSky.w;\n #endif\n return CCFragOutput(vec4(c, 1.0));\n}\nvoid main() { gl_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform vec4 cc_screenSize;\nuniform highp mat4 cc_matView;\nuniform mat4 cc_matProj;\nattribute vec3 a_position;\nvarying vec4 viewDir;\nhighp vec4 vert () {\n viewDir = vec4(a_position, 1.0);\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n highp vec4 pos = matViewRotOnly * viewDir;\n highp vec2 f = cc_matProj[3][3] > 0.0 ? vec2(4.8, 2.4) : vec2(cc_matProj[1][1]);\n pos.xy *= vec2(cc_screenSize.y * cc_screenSize.z, 1.0) * f;\n pos.zw = vec2(-0.99999 * pos.z, -pos.z);\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform vec4 cc_ambientSky;\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec3 ACESToneMap (vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nvarying vec4 viewDir;\nvec4 frag () {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cc_environment, viewDir.xyz));\n #else\n vec3 c = SRGBToLinear(textureCube(cc_environment, viewDir.xyz).rgb) * cc_ambientSky.w;\n #endif\n return CCFragOutput(vec4(c, 1.0));\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[{"name":"cc_environment", "defines":[]}]}, "locals":{"blocks":[], "samplers":[]}}, "defines": [ @@ -385,100 +357,22 @@ export default [ } ] }, - { - "name": "pipeline/smaa", - "techniques": [ - {"name":"smaa", "passes":[{"program":"pipeline/smaa|smaa-edge-vs:vert|smaa-edge-fs:frag", "depthStencilState":{"depthTest":false, "depthWrite":false}, "properties":{"u_texSampler":{"type":28, "samplerHash":66186}}}, {"program":"pipeline/smaa|smaa-blend-vs:vert|smaa-blend-fs:frag", "depthStencilState":{"depthTest":false, "depthWrite":false}, "properties":{"u_edgeTexSampler":{"type":28, "samplerHash":66186}, "u_areaTexSampler":{"type":28, "samplerHash":66186}, "u_searchTexSampler":{"type":28, "samplerHash":66181}}}]} - ], - "shaders": [ - { - "name": "pipeline/smaa|smaa-edge-vs:vert|smaa-edge-fs:frag", - "hash": 2008336459, - "glsl3": { - "vert": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_uv;\nout vec4 v_offsets[3];\nvec4 vert () {\n vec4 pos = vec4(a_position, 0.0, 1.0);\n v_uv = a_texCoord * cc_screenScale.xy;\n v_offsets[0] = v_uv.xyxy + cc_nativeSize.zwzw * vec4(-1.0, 0.0, 0.0, 1.0);\n v_offsets[1] = v_uv.xyxy + cc_nativeSize.zwzw * vec4( 1.0, 0.0, 0.0, -1.0);\n v_offsets[2] = v_uv.xyxy + cc_nativeSize.zwzw * vec4(-2.0, 0.0, 0.0, 2.0);\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec3 ACESToneMap(vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nin vec2 v_uv;\nin vec4 v_offsets[3];\nuniform sampler2D u_texSampler;\nvec3 ToLDR(vec3 color) {\n#if CC_USE_HDR\n color *= cc_exposure.x * 1024.0;\n color = ACESToneMap(color);\n color = LinearToSRGB(color);\n#endif\n return color;\n}\nvec4 frag () {\n vec2 threshold = vec2(0.1, 0.1);\n vec4 delta;\n vec3 C = ToLDR(texture(u_texSampler, v_uv).rgb);\n vec3 Cleft = ToLDR(texture(u_texSampler, v_offsets[0].xy).rgb);\n vec3 t = abs(C - Cleft);\n delta.x = max(max(t.r, t.g), t.b);\n vec3 Ctop = ToLDR(texture(u_texSampler, v_offsets[0].zw).rgb);\n t = abs(C - Ctop);\n delta.y = max(max(t.r, t.g), t.b);\n vec2 edges = step(threshold, delta.xy);\n if (dot(edges, vec2(1.0, 1.0)) == 0.0)\n discard;\n vec3 Cright = ToLDR(texture(u_texSampler, v_offsets[1].xy).rgb);\n t = abs(C - Cright);\n delta.z = max(max(t.r, t.g), t.b);\n vec3 Cbottom = ToLDR(texture(u_texSampler, v_offsets[1].zw).rgb);\n t = abs(C - Cbottom);\n delta.w = max(max(t.r, t.g), t.b);\n float maxDelta = max(max(max(delta.x, delta.y), delta.z), delta.w);\n vec3 Cleftleft = ToLDR(texture(u_texSampler, v_offsets[2].xy).rgb);\n t = abs(C - Cleftleft);\n delta.z = max(max(t.r, t.g), t.b);\n vec3 Ctoptop = ToLDR(texture(u_texSampler, v_offsets[2].zw).rgb);\n t = abs(C - Ctoptop);\n delta.w = max(max(t.r, t.g), t.b);\n maxDelta = max(max(maxDelta, delta.z), delta.w);\n edges.xy *= step(0.5 * maxDelta, delta.xy);\n vec4 o = vec4(edges, 0.0, 0.0);\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` - }, - "glsl1": { - "vert": `\nprecision highp float;\nuniform vec4 cc_screenScale;\nuniform vec4 cc_nativeSize;\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nvarying vec4 v_offsets[3];\nvec4 vert () {\n vec4 pos = vec4(a_position, 0.0, 1.0);\n v_uv = a_texCoord * cc_screenScale.xy;\n v_offsets[0] = v_uv.xyxy + cc_nativeSize.zwzw * vec4(-1.0, 0.0, 0.0, 1.0);\n v_offsets[1] = v_uv.xyxy + cc_nativeSize.zwzw * vec4( 1.0, 0.0, 0.0, -1.0);\n v_offsets[2] = v_uv.xyxy + cc_nativeSize.zwzw * vec4(-2.0, 0.0, 0.0, 2.0);\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform vec4 cc_exposure;\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec3 ACESToneMap(vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvarying vec2 v_uv;\nvarying vec4 v_offsets[3];\nuniform sampler2D u_texSampler;\nvec3 ToLDR(vec3 color) {\n#if CC_USE_HDR\n color *= cc_exposure.x * 1024.0;\n color = ACESToneMap(color);\n color = LinearToSRGB(color);\n#endif\n return color;\n}\nvec4 frag () {\n vec2 threshold = vec2(0.1, 0.1);\n vec4 delta;\n vec3 C = ToLDR(texture2D(u_texSampler, v_uv).rgb);\n vec3 Cleft = ToLDR(texture2D(u_texSampler, v_offsets[0].xy).rgb);\n vec3 t = abs(C - Cleft);\n delta.x = max(max(t.r, t.g), t.b);\n vec3 Ctop = ToLDR(texture2D(u_texSampler, v_offsets[0].zw).rgb);\n t = abs(C - Ctop);\n delta.y = max(max(t.r, t.g), t.b);\n vec2 edges = step(threshold, delta.xy);\n if (dot(edges, vec2(1.0, 1.0)) == 0.0)\n discard;\n vec3 Cright = ToLDR(texture2D(u_texSampler, v_offsets[1].xy).rgb);\n t = abs(C - Cright);\n delta.z = max(max(t.r, t.g), t.b);\n vec3 Cbottom = ToLDR(texture2D(u_texSampler, v_offsets[1].zw).rgb);\n t = abs(C - Cbottom);\n delta.w = max(max(t.r, t.g), t.b);\n float maxDelta = max(max(max(delta.x, delta.y), delta.z), delta.w);\n vec3 Cleftleft = ToLDR(texture2D(u_texSampler, v_offsets[2].xy).rgb);\n t = abs(C - Cleftleft);\n delta.z = max(max(t.r, t.g), t.b);\n vec3 Ctoptop = ToLDR(texture2D(u_texSampler, v_offsets[2].zw).rgb);\n t = abs(C - Ctoptop);\n delta.w = max(max(t.r, t.g), t.b);\n maxDelta = max(max(maxDelta, delta.z), delta.w);\n edges.xy *= step(0.5 * maxDelta, delta.xy);\n vec4 o = vec4(edges, 0.0, 0.0);\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n` - }, - "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, - "defines": [ - {"name":"CC_USE_HDR", "type":"boolean"} - ], - "blocks": [], - "samplers": [ - {"name":"u_texSampler", "type":28, "count":1, "defines":[], "binding":30} - ] - }, - { - "name": "pipeline/smaa|smaa-blend-vs:vert|smaa-blend-fs:frag", - "hash": 1697076750, - "glsl3": { - "vert": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_uv;\nout vec4 v_offsets[3];\nout vec2 v_pixCoord;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0.0, 1.0);\n v_uv = a_texCoord * cc_screenScale.xy;\n v_pixCoord = v_uv * cc_nativeSize.xy;\n v_offsets[0] = v_uv.xyxy + cc_nativeSize.zwzw * vec4(-0.25, 0.125, 1.25, 0.125);\n v_offsets[1] = v_uv.xyxy + cc_nativeSize.zwzw * vec4(-0.125, 0.25, -0.125, -1.25);\n v_offsets[2] = vec4(v_offsets[0].xz, v_offsets[1].yw) + vec4(-2.0, 2.0, -2.0, 2.0) * cc_nativeSize.zzww * float(8);\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nin vec2 v_uv;\nin vec4 v_offsets[3];\nin vec2 v_pixCoord;\nuniform sampler2D u_edgeTexSampler;\nuniform sampler2D u_areaTexSampler;\nuniform sampler2D u_searchTexSampler;\nfloat SMAASearchLength(vec2 e, float bias, float scale) {\n e.r = bias + e.r * scale;\n return 255.0 * texture(u_searchTexSampler, e).r;\n}\nfloat SMAASearchXLeft(vec2 texcoord, float end) {\n vec2 e = vec2(0.0, 1.0);\n for (int i = 0; i < 8; ++i) {\n e = texture(u_edgeTexSampler, texcoord).rg;\n texcoord -= vec2( 2.0, 0.0 ) * cc_nativeSize.zw;\n if (!(texcoord.x > end && e.g > 0.8281 && e.r == 0.0))\n break;\n }\n texcoord.x += 0.25 * cc_nativeSize.z;\n texcoord.x += cc_nativeSize.z;\n texcoord.x += 2.0 * cc_nativeSize.z;\n texcoord.x -= cc_nativeSize.z * SMAASearchLength(e, 0.0, 0.5);\n return texcoord.x;\n}\nfloat SMAASearchXRight(vec2 texcoord, float end) {\n vec2 e = vec2(0.0, 1.0);\n for (int i = 0; i < 8; ++i) {\n e = texture(u_edgeTexSampler, texcoord).rg;\n texcoord += vec2( 2.0, 0.0 ) * cc_nativeSize.zw;\n if (!(texcoord.x < end && e.g > 0.8281 && e.r == 0.0))\n break;\n }\n texcoord.x -= 0.25 * cc_nativeSize.z;\n texcoord.x -= cc_nativeSize.z;\n texcoord.x -= 2.0 * cc_nativeSize.z;\n texcoord.x += cc_nativeSize.z * SMAASearchLength(e, 0.5, 0.5);\n return texcoord.x;\n}\nfloat SMAASearchYUp(vec2 texcoord, float end) {\n vec2 e = vec2(1.0, 0.0);\n for (int i = 0; i < 8; ++i) {\n e = texture(u_edgeTexSampler, texcoord).rg;\n texcoord += vec2( 0.0, 2.0 ) * cc_nativeSize.zw;\n if (!(texcoord.y > end && e.r > 0.8281 && e.g == 0.0))\n break;\n }\n texcoord.y -= 0.25 * cc_nativeSize.w;\n texcoord.y -= cc_nativeSize.w;\n texcoord.y -= 2.0 * cc_nativeSize.w;\n texcoord.y += cc_nativeSize.w * SMAASearchLength(e.gr, 0.0, 0.5);\n return texcoord.y;\n}\nfloat SMAASearchYDown(vec2 texcoord, float end) {\n vec2 e = vec2(1.0, 0.0);\n for (int i = 0; i < 8; ++i) {\n e = texture(u_edgeTexSampler, texcoord).rg;\n texcoord -= vec2( 0.0, 2.0 ) * cc_nativeSize.zw;\n if (!(texcoord.y < end && e.r > 0.8281 && e.g == 0.0))\n break;\n }\n texcoord.y += 0.25 * cc_nativeSize.w;\n texcoord.y += cc_nativeSize.w;\n texcoord.y += 2.0 * cc_nativeSize.w;\n texcoord.y -= cc_nativeSize.w * SMAASearchLength(e.gr, 0.5, 0.5);\n return texcoord.y;\n}\nvec2 Round(vec2 x) {\n return sign(x) * floor(abs(x) + 0.5);\n}\nvec2 SMAAArea(vec2 dist, float e1, float e2) {\n vec2 texcoord = float(16) * Round(4.0 * vec2(e1, e2)) + dist;\n texcoord = (1.0 / vec2(160.0, 560.0)) * texcoord + 0.5 * (1.0 / vec2(160.0, 560.0));\n return texture(u_areaTexSampler, texcoord).rg;\n}\nvec4 frag () {\n vec4 weights = vec4(0.0);\n vec2 e = texture(u_edgeTexSampler, v_uv).rg;\n vec2 d;\n vec2 coords;\n if ( e.g > 0.0 ) {\n coords.x = SMAASearchXLeft(v_offsets[0].xy, v_offsets[2].x);\n coords.y = v_offsets[1].y;\n d.x = coords.x;\n float e1 = texture(u_edgeTexSampler, coords).r;\n coords.x = SMAASearchXRight(v_offsets[0].zw, v_offsets[2].y);\n d.y = coords.x;\n d = d / cc_nativeSize.z - v_pixCoord.x;\n vec2 sqrt_d = sqrt(abs(d));\n coords.y -= 1.0 * cc_nativeSize.w;\n float e2 = texture(u_edgeTexSampler, coords + vec2(cc_nativeSize.z, 0.0)).r;\n weights.rg = SMAAArea(sqrt_d, e1, e2);\n }\n if ( e.r > 0.0 ) {\n coords.y = SMAASearchYUp(v_offsets[1].xy, v_offsets[2].z);\n coords.x = v_offsets[0].x;\n d.x = coords.y;\n float e1 = texture(u_edgeTexSampler, coords).g;\n coords.y = SMAASearchYDown(v_offsets[1].zw, v_offsets[2].w);\n d.y = coords.y;\n d = d / cc_nativeSize.w - v_pixCoord.y;\n vec2 sqrt_d = sqrt(abs(d));\n coords.y -= 1.0 * cc_nativeSize.w;\n float e2 = texture(u_edgeTexSampler, coords + vec2(0.0, cc_nativeSize.w)).g;\n weights.ba = SMAAArea(sqrt_d, e1, e2);\n }\n return weights;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` - }, - "glsl1": { - "vert": `\nprecision highp float;\nuniform vec4 cc_screenScale;\nuniform vec4 cc_nativeSize;\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nvarying vec4 v_offsets[3];\nvarying vec2 v_pixCoord;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0.0, 1.0);\n v_uv = a_texCoord * cc_screenScale.xy;\n v_pixCoord = v_uv * cc_nativeSize.xy;\n v_offsets[0] = v_uv.xyxy + cc_nativeSize.zwzw * vec4(-0.25, 0.125, 1.25, 0.125);\n v_offsets[1] = v_uv.xyxy + cc_nativeSize.zwzw * vec4(-0.125, 0.25, -0.125, -1.25);\n v_offsets[2] = vec4(v_offsets[0].xz, v_offsets[1].yw) + vec4(-2.0, 2.0, -2.0, 2.0) * cc_nativeSize.zzww * float(8);\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform vec4 cc_nativeSize;\nvarying vec2 v_uv;\nvarying vec4 v_offsets[3];\nvarying vec2 v_pixCoord;\nuniform sampler2D u_edgeTexSampler;\nuniform sampler2D u_areaTexSampler;\nuniform sampler2D u_searchTexSampler;\nfloat SMAASearchLength(vec2 e, float bias, float scale) {\n e.r = bias + e.r * scale;\n return 255.0 * texture2D(u_searchTexSampler, e).r;\n}\nfloat SMAASearchXLeft(vec2 texcoord, float end) {\n vec2 e = vec2(0.0, 1.0);\n for (int i = 0; i < 8; ++i) {\n e = texture2D(u_edgeTexSampler, texcoord).rg;\n texcoord -= vec2( 2.0, 0.0 ) * cc_nativeSize.zw;\n if (!(texcoord.x > end && e.g > 0.8281 && e.r == 0.0))\n break;\n }\n texcoord.x += 0.25 * cc_nativeSize.z;\n texcoord.x += cc_nativeSize.z;\n texcoord.x += 2.0 * cc_nativeSize.z;\n texcoord.x -= cc_nativeSize.z * SMAASearchLength(e, 0.0, 0.5);\n return texcoord.x;\n}\nfloat SMAASearchXRight(vec2 texcoord, float end) {\n vec2 e = vec2(0.0, 1.0);\n for (int i = 0; i < 8; ++i) {\n e = texture2D(u_edgeTexSampler, texcoord).rg;\n texcoord += vec2( 2.0, 0.0 ) * cc_nativeSize.zw;\n if (!(texcoord.x < end && e.g > 0.8281 && e.r == 0.0))\n break;\n }\n texcoord.x -= 0.25 * cc_nativeSize.z;\n texcoord.x -= cc_nativeSize.z;\n texcoord.x -= 2.0 * cc_nativeSize.z;\n texcoord.x += cc_nativeSize.z * SMAASearchLength(e, 0.5, 0.5);\n return texcoord.x;\n}\nfloat SMAASearchYUp(vec2 texcoord, float end) {\n vec2 e = vec2(1.0, 0.0);\n for (int i = 0; i < 8; ++i) {\n e = texture2D(u_edgeTexSampler, texcoord).rg;\n texcoord += vec2( 0.0, 2.0 ) * cc_nativeSize.zw;\n if (!(texcoord.y > end && e.r > 0.8281 && e.g == 0.0))\n break;\n }\n texcoord.y -= 0.25 * cc_nativeSize.w;\n texcoord.y -= cc_nativeSize.w;\n texcoord.y -= 2.0 * cc_nativeSize.w;\n texcoord.y += cc_nativeSize.w * SMAASearchLength(e.gr, 0.0, 0.5);\n return texcoord.y;\n}\nfloat SMAASearchYDown(vec2 texcoord, float end) {\n vec2 e = vec2(1.0, 0.0);\n for (int i = 0; i < 8; ++i) {\n e = texture2D(u_edgeTexSampler, texcoord).rg;\n texcoord -= vec2( 0.0, 2.0 ) * cc_nativeSize.zw;\n if (!(texcoord.y < end && e.r > 0.8281 && e.g == 0.0))\n break;\n }\n texcoord.y += 0.25 * cc_nativeSize.w;\n texcoord.y += cc_nativeSize.w;\n texcoord.y += 2.0 * cc_nativeSize.w;\n texcoord.y -= cc_nativeSize.w * SMAASearchLength(e.gr, 0.5, 0.5);\n return texcoord.y;\n}\nvec2 Round(vec2 x) {\n return sign(x) * floor(abs(x) + 0.5);\n}\nvec2 SMAAArea(vec2 dist, float e1, float e2) {\n vec2 texcoord = float(16) * Round(4.0 * vec2(e1, e2)) + dist;\n texcoord = (1.0 / vec2(160.0, 560.0)) * texcoord + 0.5 * (1.0 / vec2(160.0, 560.0));\n return texture2D(u_areaTexSampler, texcoord).rg;\n}\nvec4 frag () {\n vec4 weights = vec4(0.0);\n vec2 e = texture2D(u_edgeTexSampler, v_uv).rg;\n vec2 d;\n vec2 coords;\n if ( e.g > 0.0 ) {\n coords.x = SMAASearchXLeft(v_offsets[0].xy, v_offsets[2].x);\n coords.y = v_offsets[1].y;\n d.x = coords.x;\n float e1 = texture2D(u_edgeTexSampler, coords).r;\n coords.x = SMAASearchXRight(v_offsets[0].zw, v_offsets[2].y);\n d.y = coords.x;\n d = d / cc_nativeSize.z - v_pixCoord.x;\n vec2 sqrt_d = sqrt(abs(d));\n coords.y -= 1.0 * cc_nativeSize.w;\n float e2 = texture2D(u_edgeTexSampler, coords + vec2(cc_nativeSize.z, 0.0)).r;\n weights.rg = SMAAArea(sqrt_d, e1, e2);\n }\n if ( e.r > 0.0 ) {\n coords.y = SMAASearchYUp(v_offsets[1].xy, v_offsets[2].z);\n coords.x = v_offsets[0].x;\n d.x = coords.y;\n float e1 = texture2D(u_edgeTexSampler, coords).g;\n coords.y = SMAASearchYDown(v_offsets[1].zw, v_offsets[2].w);\n d.y = coords.y;\n d = d / cc_nativeSize.w - v_pixCoord.y;\n vec2 sqrt_d = sqrt(abs(d));\n coords.y -= 1.0 * cc_nativeSize.w;\n float e2 = texture2D(u_edgeTexSampler, coords + vec2(0.0, cc_nativeSize.w)).g;\n weights.ba = SMAAArea(sqrt_d, e1, e2);\n }\n return weights;\n}\nvoid main() { gl_FragColor = frag(); }\n` - }, - "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, - "defines": [], - "blocks": [], - "samplers": [ - {"name":"u_edgeTexSampler", "type":28, "count":1, "defines":[], "binding":30}, - {"name":"u_areaTexSampler", "type":28, "count":1, "defines":[], "binding":31}, - {"name":"u_searchTexSampler", "type":28, "count":1, "defines":[], "binding":32} - ] - } - ] - }, - { - "name": "pipeline/tonemap", - "techniques": [ - {"name":"tonemap", "passes":[{"program":"pipeline/tonemap|tonemap-vs:vert|tonemap-fs:frag", "depthStencilState":{"depthTest":false, "depthWrite":false}, "properties":{"u_texSampler":{"type":28, "samplerHash":66186}, "u_blendTexSampler":{"type":28, "samplerHash":66186}}}]} - ], - "shaders": [ - { - "name": "pipeline/tonemap|tonemap-vs:vert|tonemap-fs:frag", - "hash": 2708165168, - "glsl3": { - "vert": `\nprecision highp float;\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_uv;\nout vec4 v_offset;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0, 1);\n v_uv = a_texCoord * cc_screenScale.xy;\n v_offset = v_uv.xyxy + cc_nativeSize.zwzw * vec4(1.0, 0.0, 0.0, -1.0);\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec3 ACESToneMap(vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nin vec2 v_uv;\nin vec4 v_offset;\nuniform sampler2D u_texSampler;\nuniform sampler2D u_blendTexSampler;\nvec3 ToLDR(vec3 color) {\n #if CC_USE_HDR\n color *= cc_exposure.x * 1024.0;\n color = ACESToneMap(color);\n color = LinearToSRGB(color);\n #endif\n return color;\n}\nvec4 frag () {\n #if CC_USE_SMAA\n vec4 a;\n a.rb = texture(u_blendTexSampler, v_uv).rb;\n a.g = texture(u_blendTexSampler, v_offset.zw).g;\n a.a = texture(u_blendTexSampler, v_offset.xy).a;\n if (dot(a, vec4(1.0)) < 1e-5) {\n vec4 o = texture(u_texSampler, v_uv);\n o.rgb = ToLDR(o.rgb);\n return o;\n } else {\n vec2 offset;\n offset.x = a.a > a.b ? a.a : -a.b;\n offset.y = a.g > a.r ? -a.g : a.r;\n if (abs(offset.x) > abs(offset.y)) {\n offset.y = 0.0;\n } else {\n offset.x = 0.0;\n }\n vec4 C = texture(u_texSampler, v_uv);\n C.rgb = ToLDR(C.rgb);\n vec2 uv = v_uv + sign(offset) * cc_nativeSize.zw;\n vec4 Cop = texture(u_texSampler, uv);\n Cop.rgb = ToLDR(Cop.rgb);\n float s = abs(offset.x) > abs(offset.y) ? abs(offset.x) : abs(offset.y);\n C.rgb = pow(C.rgb, vec3(2.2));\n Cop.rgb = pow(Cop.rgb, vec3(2.2));\n vec4 mixed = mix(C, Cop, s);\n mixed.rgb = pow(mixed.rgb, vec3(1.0 / 2.2));\n return mixed;\n }\n #else\n vec4 o = texture(u_texSampler, v_uv);\n o.rgb = ToLDR(o.rgb);\n return o;\n #endif\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` - }, - "glsl1": { - "vert": `\nprecision highp float;\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nuniform vec4 cc_screenScale;\nuniform vec4 cc_nativeSize;\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nvarying vec4 v_offset;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0, 1);\n v_uv = a_texCoord * cc_screenScale.xy;\n v_offset = v_uv.xyxy + cc_nativeSize.zwzw * vec4(1.0, 0.0, 0.0, -1.0);\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform vec4 cc_nativeSize;\nuniform vec4 cc_exposure;\n#define saturate(a) clamp( a, 0.0, 1.0 )\nhighp mat4 transposeMat4(in highp mat4 mat) {\n highp vec4 i0 = mat[0];\n highp vec4 i1 = mat[1];\n highp vec4 i2 = mat[2];\n highp vec4 i3 = mat[3];\n return mat4(vec4(i0.x, i1.x, i2.x, i3.x),\n vec4(i0.y, i1.y, i2.y, i3.y),\n vec4(i0.z, i1.z, i2.z, i3.z),\n vec4(i0.w, i1.w, i2.w, i3.w));\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec3 ACESToneMap(vec3 color) {\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvarying vec2 v_uv;\nvarying vec4 v_offset;\nuniform sampler2D u_texSampler;\nuniform sampler2D u_blendTexSampler;\nvec3 ToLDR(vec3 color) {\n #if CC_USE_HDR\n color *= cc_exposure.x * 1024.0;\n color = ACESToneMap(color);\n color = LinearToSRGB(color);\n #endif\n return color;\n}\nvec4 frag () {\n #if CC_USE_SMAA\n vec4 a;\n a.rb = texture2D(u_blendTexSampler, v_uv).rb;\n a.g = texture2D(u_blendTexSampler, v_offset.zw).g;\n a.a = texture2D(u_blendTexSampler, v_offset.xy).a;\n if (dot(a, vec4(1.0)) < 1e-5) {\n vec4 o = texture2D(u_texSampler, v_uv);\n o.rgb = ToLDR(o.rgb);\n return o;\n } else {\n vec2 offset;\n offset.x = a.a > a.b ? a.a : -a.b;\n offset.y = a.g > a.r ? -a.g : a.r;\n if (abs(offset.x) > abs(offset.y)) {\n offset.y = 0.0;\n } else {\n offset.x = 0.0;\n }\n vec4 C = texture2D(u_texSampler, v_uv);\n C.rgb = ToLDR(C.rgb);\n vec2 uv = v_uv + sign(offset) * cc_nativeSize.zw;\n vec4 Cop = texture2D(u_texSampler, uv);\n Cop.rgb = ToLDR(Cop.rgb);\n float s = abs(offset.x) > abs(offset.y) ? abs(offset.x) : abs(offset.y);\n C.rgb = pow(C.rgb, vec3(2.2));\n Cop.rgb = pow(Cop.rgb, vec3(2.2));\n vec4 mixed = mix(C, Cop, s);\n mixed.rgb = pow(mixed.rgb, vec3(1.0 / 2.2));\n return mixed;\n }\n #else\n vec4 o = texture2D(u_texSampler, v_uv);\n o.rgb = ToLDR(o.rgb);\n return o;\n #endif\n}\nvoid main() { gl_FragColor = frag(); }\n` - }, - "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, - "defines": [ - {"name":"CC_USE_HDR", "type":"boolean"}, - {"name":"CC_USE_SMAA", "type":"boolean"} - ], - "blocks": [], - "samplers": [ - {"name":"u_texSampler", "type":28, "count":1, "defines":[], "binding":30}, - {"name":"u_blendTexSampler", "type":28, "count":1, "defines":[], "binding":31} - ] - } - ] - }, { "name": "util/profiler", "techniques": [ - {"passes":[{"blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "rasterizerState":{"cullMode":0}, "program":"util/profiler|profiler-vs:vert|profiler-fs:frag", "depthStencilState":{"depthTest":false, "depthWrite":false}, "properties":{"mainTexture":{"value":"grey", "type":28}, "offset":{"type":16}}}]} + {"passes":[{"blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "rasterizerState":{"cullMode":0}, "program":"util/profiler|profiler-vs:vert|profiler-fs:frag", "depthStencilState":{"depthTest":false, "depthWrite":false}}]} ], "shaders": [ { "name": "util/profiler|profiler-vs:vert|profiler-fs:frag", - "hash": 3710757766, + "hash": 1026877894, "glsl3": { - "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nin vec3 a_position;\nvoid CCDecode (out vec4 position) {\n position = vec4(a_position, 1.0);\n}\nin vec2 a_texCoord;\nout vec2 v_uv;\nuniform Constants {\n vec4 offset;\n};\nvec4 vert () {\n vec4 position;\n CCDecode(position);\n position.x *= cc_screenSize.y * cc_screenSize.z;\n position.xy += offset.xy + abs(position.xy);\n v_uv = a_texCoord;\n return position;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 v_uv;\nuniform sampler2D mainTexture;\nvec4 frag () {\n return CCFragOutput(texture(mainTexture, v_uv));\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nin vec3 a_position;\nin vec4 a_color;\nout vec2 v_uv;\nuniform Constants {\n vec4 offset;\n vec4 symbols[4];\n};\nuniform PerFrameInfo {\n vec4 digits[8 * 9 / 4];\n};\nfloat getComponent(vec4 v, float i) {\n if (i < 1.0) { return v[0]; }\n else if (i < 2.0) { return v[1]; }\n else if (i < 3.0) { return v[2]; }\n else { return v[3]; }\n}\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n position.x *= cc_screenSize.y * cc_screenSize.z;\n position.xy += offset.xy + abs(position.xy);\n v_uv = a_color.xy;\n if (a_color.z >= 0.0) {\n float n = getComponent(digits[int(a_color.z)], a_color.w);\n float row = floor(n / 4.0), col = n - row * 4.0;\n v_uv += vec2(getComponent(symbols[int(row)], col), 0.0);\n }\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n highp mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec2 v_uv;\nuniform sampler2D mainTexture;\nvec4 frag () {\n return CCFragOutput(texture(mainTexture, v_uv));\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform vec4 cc_screenSize;\nattribute vec3 a_position;\nvoid CCDecode (out vec4 position) {\n position = vec4(a_position, 1.0);\n}\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nuniform vec4 offset;\nvec4 vert () {\n vec4 position;\n CCDecode(position);\n position.x *= cc_screenSize.y * cc_screenSize.z;\n position.xy += offset.xy + abs(position.xy);\n v_uv = a_texCoord;\n return position;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 v_uv;\nuniform sampler2D mainTexture;\nvec4 frag () {\n return CCFragOutput(texture2D(mainTexture, v_uv));\n}\nvoid main() { gl_FragColor = frag(); }\n` + "vert": `\nprecision mediump float;\nuniform vec4 cc_screenSize;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying vec2 v_uv;\nuniform vec4 offset;\nuniform vec4 symbols[4];\nuniform vec4 digits[18];\nfloat getComponent(vec4 v, float i) {\n if (i < 1.0) { return v[0]; }\n else if (i < 2.0) { return v[1]; }\n else if (i < 3.0) { return v[2]; }\n else { return v[3]; }\n}\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n position.x *= cc_screenSize.y * cc_screenSize.z;\n position.xy += offset.xy + abs(position.xy);\n v_uv = a_color.xy;\n if (a_color.z >= 0.0) {\n float n = getComponent(digits[int(a_color.z)], a_color.w);\n float row = floor(n / 4.0), col = n - row * 4.0;\n v_uv += vec2(getComponent(symbols[int(row)], col), 0.0);\n }\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec2 v_uv;\nuniform sampler2D mainTexture;\nvec4 frag () {\n return CCFragOutput(texture2D(mainTexture, v_uv));\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, "defines": [ @@ -486,7 +380,11 @@ export default [ ], "blocks": [ {"name": "Constants", "defines": [], "binding": 0, "members": [ - {"name":"offset", "type":16, "count":1} + {"name":"offset", "type":16, "count":1}, + {"name":"symbols", "type":16, "count":4} + ]}, + {"name": "PerFrameInfo", "defines": [], "binding": 1, "members": [ + {"name":"digits", "type":16, "count":18} ]} ], "samplers": [ diff --git a/cocos/core/3d/builtin/init.ts b/cocos/core/3d/builtin/init.ts index ee58cb005a..d18b7b1711 100644 --- a/cocos/core/3d/builtin/init.ts +++ b/cocos/core/3d/builtin/init.ts @@ -4,7 +4,7 @@ import { SpriteFrame } from '../../assets/sprite-frame'; import { Texture2D } from '../../assets/texture-2d'; import { TextureCube } from '../../assets/texture-cube'; import { GFXDevice } from '../../gfx/device'; -import { selectJointsMediumType } from '../../renderer/models/joints-texture-utils'; +import { selectJointsMediumType } from '../../renderer/models/skeletal-animation-utils'; import effects from './effects'; class BuiltinResMgr { @@ -171,9 +171,15 @@ class BuiltinResMgr { // sprite material const spriteColorMtl = new cc.Material(); spriteColorMtl._uuid = 'ui-sprite-material'; - spriteColorMtl.initialize({ defines: { USE_TEXTURE: true }, effectName: 'builtin-sprite' }); + spriteColorMtl.initialize({ defines: { USE_TEXTURE: true, IS_GRAY: false }, effectName: 'builtin-sprite' }); resources[spriteColorMtl._uuid] = spriteColorMtl; + // sprite gray material + const spriteGrayMtl = new cc.Material(); + spriteGrayMtl._uuid = 'ui-sprite-gray-material'; + spriteGrayMtl.initialize({ defines: { USE_TEXTURE: true, IS_GRAY: true }, effectName: 'builtin-sprite' }); + resources[spriteGrayMtl._uuid] = spriteGrayMtl; + // default particle material const defaultParticleMtl = new cc.Material(); defaultParticleMtl._uuid = 'default-particle-material'; diff --git a/cocos/core/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts index 17addea0ef..f4fe42c2d3 100644 --- a/cocos/core/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -98,11 +98,19 @@ export class SkinningModelUnit { @menu('Components/BatchedSkinningModel') export class BatchedSkinningModelComponent extends SkinningModelComponent { - @property + @property({ + tooltip: '合图生成的最终图集的边长', + }) public atlasSize: number = 1024; - @property({ type: [CCString] }) + @property({ + type: [CCString], + tooltip: '材质中真正参与合图的贴图属性,不参与的属性统一使用第一个 unit 的贴图', + }) public batchableTextureNames: string[] = []; - @property({ type: [SkinningModelUnit] }) + @property({ + type: [SkinningModelUnit], + tooltip: '合批前的子蒙皮模型数组,最主要的数据来源', + }) public units: SkinningModelUnit[] = []; private _textures: Record = {}; @@ -143,6 +151,11 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { super.onDestroy(); } + public _onMaterialModified (idx: number, material: Material | null) { + this.cookMaterials(); + super._onMaterialModified(idx, this.getMaterial(idx)); + } + public cook () { this.cookMaterials(); this.cookSkeletons(); diff --git a/cocos/core/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts index 847be01954..b28295dfac 100644 --- a/cocos/core/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -117,6 +117,7 @@ export class CameraComponent extends Component { */ @property({ type: ProjectionType, + tooltip:'相机的投影类型', }) get projection () { return this._projection; @@ -131,7 +132,9 @@ export class CameraComponent extends Component { * @en The priority of the camera, it cannot be modified at runtime, instead, it should be set in editor. * @zh 相机的优先级顺序,只能在编辑器中设置,动态设置无效。 */ - @property + @property({ + tooltip:'相机的优先级顺序,只能在编辑器中设置,动态设置无效', + }) get priority () { return this._priority; } @@ -147,7 +150,9 @@ export class CameraComponent extends Component { * @en The camera field of view * @zh 相机的视角大小。 */ - @property + @property({ + tooltip:'相机的视角大小', + }) get fov () { return this._fov; } @@ -161,7 +166,9 @@ export class CameraComponent extends Component { * @en The camera height when in orthogonal mode * @zh 正交模式下的相机视角大小。 */ - @property + @property({ + tooltip:'正交模式下的相机视角大小', + }) get orthoHeight () { return this._orthoHeight; } @@ -175,7 +182,9 @@ export class CameraComponent extends Component { * @en The near clipping distance of the camera * @zh 相机的近平面。 */ - @property + @property({ + tooltip:'相机的近平面', + }) get near () { return this._near; } @@ -189,7 +198,9 @@ export class CameraComponent extends Component { * @en The far clipping distance of the camera * @zh 相机的远平面。 */ - @property + @property({ + tooltip:'相机的远平面', + }) get far () { return this._far; } @@ -203,7 +214,9 @@ export class CameraComponent extends Component { * @en The color clearing value of the camera * @zh 相机的颜色缓冲默认值。 */ - @property + @property({ + tooltip:'相机的颜色缓冲默认值', + }) // @constget get color (): Readonly { return this._color; @@ -223,7 +236,9 @@ export class CameraComponent extends Component { * @en The depth clearing value of the camera * @zh 相机的深度缓冲默认值。 */ - @property + @property({ + tooltip:'相机的深度缓冲默认值', + }) get depth () { return this._depth; } @@ -237,7 +252,9 @@ export class CameraComponent extends Component { * @en The stencil clearing value of the camera * @zh 相机的模板缓冲默认值。 */ - @property + @property({ + tooltip:'相机的模板缓冲默认值', + }) get stencil () { return this._stencil; } @@ -253,6 +270,7 @@ export class CameraComponent extends Component { */ @property({ type: CameraClearFlag, + tooltip:'相机的缓冲清除标志位', }) get clearFlags () { return this._clearFlags; @@ -267,7 +285,9 @@ export class CameraComponent extends Component { * @en The screen viewport of the camera wrt. sceen size * @zh 相机相对屏幕的 viewport。 */ - @property + @property({ + tooltip:'相机相对屏幕的 viewport', + }) get rect () { return this._rect; } @@ -297,6 +317,7 @@ export class CameraComponent extends Component { */ @property({ type: Layers.BitMask, + tooltip:'设置摄像机可见掩码,与 Component 中的 visibility 同时使用,用于过滤摄像机不需要渲染的物体', }) get visibility () { return this._visibility; @@ -314,6 +335,7 @@ export class CameraComponent extends Component { */ @property({ type: RenderTexture, + tooltip:'设置摄像机 RenderTexture', }) get targetTexture () { return this._targetTexture; diff --git a/cocos/core/3d/framework/directional-light-component.ts b/cocos/core/3d/framework/directional-light-component.ts index d6a0b494eb..ed59cd9aa2 100644 --- a/cocos/core/3d/framework/directional-light-component.ts +++ b/cocos/core/3d/framework/directional-light-component.ts @@ -34,7 +34,7 @@ import { RenderScene } from '../../renderer/scene/render-scene'; import { LightComponent } from './light-component'; @ccclass('cc.DirectionalLightComponent') -@menu('Components/DirectionalLight') +@menu('Light/DirectionalLight') @executeInEditMode export class DirectionalLightComponent extends LightComponent { @@ -50,7 +50,10 @@ export class DirectionalLightComponent extends LightComponent { * @zh * 光源强度。 */ - @property({ unit: 'lx' }) + @property({ + unit: 'lx', + tooltip:'光源强度' + }) get illuminance () { return this._illuminance; } diff --git a/cocos/core/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts index a0a21444b5..643a5ef366 100644 --- a/cocos/core/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -61,7 +61,9 @@ export class LightComponent extends Component { * @zh * 光源颜色。 */ - @property + @property({ + tooltip:'光源颜色', + }) // @constget get color (): Readonly { return this._color; @@ -81,7 +83,9 @@ export class LightComponent extends Component { * @zh * 是否启用光源色温。 */ - @property + @property({ + tooltip:'是否启用光源色温' + }) get useColorTemperature () { return this._useColorTemperature; } @@ -99,6 +103,7 @@ export class LightComponent extends Component { @property({ slide: true, range: [1000, 15000, 1], + tooltip:'光源色温' }) get colorTemperature () { return this._colorTemperature; diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index bd5897608a..000d880839 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -66,6 +66,7 @@ export class ModelComponent extends RenderableComponent { */ @property({ type: Mesh, + tooltip: '模型网格', }) get mesh () { return this._mesh; @@ -84,6 +85,7 @@ export class ModelComponent extends RenderableComponent { */ @property({ type: ModelShadowCastingMode, + tooltip: '投射阴影方式', }) get shadowCastingMode () { return this._shadowCastingMode; @@ -115,37 +117,25 @@ export class ModelComponent extends RenderableComponent { /** * @zh 是否启用动态合批? */ - @property + @property({ + tooltip: '是否启用动态合批', + }) set enableDynamicBatching (enable: boolean) { + if (this._enableDynamicBatching === enable) { return; } this._enableDynamicBatching = enable; if (this._mesh) { - if (enable) { - this._mesh.createFlatBuffers(); - } else { - this._mesh.destroyFlatBuffers(); - } + if (enable) { this._mesh.createFlatBuffers(); } + else { this._mesh.destroyFlatBuffers(); } } if (this._model) { this._model.isDynamicBatching = enable; - if (this._model.isDynamicBatching) { - for (let i = 0; i < this._model.subModels.length; ++i) { - const subModel = this._model.subModels[i]; - for (let p = 0; p < subModel.passes.length; ++p) { - const pass = subModel.passes[p]; - if (!pass.batchedBuffer) { - pass.createBatchedBuffer(); - } - } - } - } else { - for (let i = 0; i < this._model.subModels.length; ++i) { - const subModel = this._model.subModels[i]; - for (let p = 0; p < subModel.passes.length; ++p) { - const pass = subModel.passes[p]; - if (pass.batchedBuffer) { - pass.clearBatchedBuffer(); - } - } + this._model.onPipelineChange(); // update material + for (let i = 0; i < this._model.subModels.length; ++i) { + const subModel = this._model.subModels[i]; + for (let p = 0; p < subModel.passes.length; ++p) { + const pass = subModel.passes[p]; + if (enable) { pass.createBatchedBuffer(); } + else { pass.clearBatchedBuffer(); } } } } @@ -196,14 +186,11 @@ export class ModelComponent extends RenderableComponent { if (this._model) { this._model.scene.destroyModel(this._model); this._model = null; + this._models.length = 0; } } - public _getModel (): Model | null { - return this._model; - } - - public recreateModel () { + public _changeSceneInModel () { if (this.isValid) { if (this._model) { this._model.destroy(); @@ -219,19 +206,14 @@ export class ModelComponent extends RenderableComponent { return; } - if (this._model && this._model.inited) { - this._model.destroy(); - } else { - this._createModel(); - } - - this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); + this._createModel(); this._updateModelParams(); if (this._model) { + this._model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); this._model.enabled = true; - this._model.isDynamicBatching = this._enableDynamicBatching; + if (this._enableDynamicBatching) { if (!this._mesh.hasFlatBuffers) { this._mesh.createFlatBuffers(); @@ -246,15 +228,17 @@ export class ModelComponent extends RenderableComponent { } } } - } } protected _createModel () { if (!this.node.scene) { return; } const scene = this._getRenderScene(); + if (this._model) { scene.destroyModel(this._model); } this._model = scene.createModel(this._getModelConstructor(), this.node); this._model.visFlags = this.visibility; + this._models.length = 0; + this._models.push(this._model); } protected _getModelConstructor () { @@ -266,6 +250,7 @@ export class ModelComponent extends RenderableComponent { return; } this.node.hasChangedFlags = this._model.transform.hasChangedFlags = TransformDirtyBit.POSITION; + this._model.isDynamicBatching = this._enableDynamicBatching; // should pass this in before create PSO const meshCount = this._mesh ? this._mesh.subMeshCount : 0; for (let i = 0; i < meshCount; ++i) { const material = this.getSharedMaterial(i); diff --git a/cocos/core/3d/framework/renderable-component.ts b/cocos/core/3d/framework/renderable-component.ts index d157620053..e0ad6ba24b 100644 --- a/cocos/core/3d/framework/renderable-component.ts +++ b/cocos/core/3d/framework/renderable-component.ts @@ -12,12 +12,17 @@ const { ccclass, property } = _decorator; @ccclass('cc.RenderableComponent') export class RenderableComponent extends Component { - @property({ type: [Material] }) + @property({ + type: [Material], + tooltip: '材质', + }) protected _materials: Array = []; @property protected _visFlags = Layers.Enum.NONE; + protected _models: Model[] = []; + constructor () { super(); } @@ -25,6 +30,7 @@ export class RenderableComponent extends Component { @property({ type: Material, displayName: 'Materials', + tooltip: '源材质', }) get sharedMaterials () { // if we don't create an array copy, the editor will modify the original array directly. @@ -123,11 +129,11 @@ export class RenderableComponent extends Component { } } - public _getModel (): Model | null { - return null; + public _collectModels (): Model[] { + return this._models; } - public recreateModel () { + public _changeSceneInModel () { } diff --git a/cocos/core/3d/framework/skinning-model-component.ts b/cocos/core/3d/framework/skinning-model-component.ts index c91c792284..6f4d128181 100644 --- a/cocos/core/3d/framework/skinning-model-component.ts +++ b/cocos/core/3d/framework/skinning-model-component.ts @@ -31,8 +31,6 @@ import { AnimationClip } from '../../animation'; import { Material } from '../../assets/material'; import { Skeleton } from '../../assets/skeleton'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator'; -import { GFXDevice } from '../../gfx/device'; -import { selectJointsMediumType } from '../../renderer/models/joints-texture-utils'; import { SkinningModel } from '../../renderer/models/skinning-model'; import { Node } from '../../scene-graph/node'; import { INode } from '../../utils/interfaces'; @@ -55,11 +53,15 @@ export class SkinningModelComponent extends ModelComponent { @property(Node) protected _skinningRoot: INode | null = null; + protected _clip: AnimationClip | null = null; + /** - * @en The bone nodes - * @zh 骨骼节点。 + * @en The skeleton resource + * @zh 骨骼资源。 */ - @property({ type: Skeleton }) + @property({ + type: Skeleton, + }) get skeleton () { return this._skeleton; } @@ -72,7 +74,9 @@ export class SkinningModelComponent extends ModelComponent { /** * 骨骼根节点的引用。 */ - @property({ type: Node }) + @property({ + type: Node, + }) get skinningRoot (): INode | null { return this._skinningRoot; } @@ -87,6 +91,7 @@ export class SkinningModelComponent extends ModelComponent { } public uploadAnimation (clip: AnimationClip | null) { + this._clip = clip; if (this._model) { (this._model as SkinningModel).uploadAnimation(clip); } } @@ -96,14 +101,6 @@ export class SkinningModelComponent extends ModelComponent { super._updateModelParams(); } - protected _onMaterialModified (index: number, material: Material | null) { - const device: GFXDevice = cc.director.root!.device; - const type = selectJointsMediumType(device); - const mat = this.getMaterial(index) || this._getBuiltinMaterial(); - mat.recompileShaders({ CC_USE_SKINNING: type }); - super._onMaterialModified(index, mat); - } - protected _getModelConstructor () { return SkinningModel; } @@ -114,7 +111,10 @@ export class SkinningModelComponent extends ModelComponent { } private _update () { - if (this._model) { (this._model as SkinningModel).bindSkeleton(this._skeleton, this._skinningRoot); } - this._materials.forEach((material, index) => material && this._onMaterialModified(index, material)); + if (this._model) { + const model = (this._model as SkinningModel); + model.bindSkeleton(this._skeleton, this._skinningRoot, this._mesh); + model.uploadAnimation(this._clip); + } } } diff --git a/cocos/core/3d/framework/sphere-light-component.ts b/cocos/core/3d/framework/sphere-light-component.ts index 0e4f19e13e..a78b54b9d3 100644 --- a/cocos/core/3d/framework/sphere-light-component.ts +++ b/cocos/core/3d/framework/sphere-light-component.ts @@ -33,7 +33,7 @@ import { SphereLight } from '../../renderer/scene/sphere-light'; import { LightComponent, PhotometricTerm } from './light-component'; @ccclass('cc.SphereLightComponent') -@menu('Components/SphereLight') +@menu('Light/SphereLight') @executeInEditMode export class SphereLightComponent extends LightComponent { @@ -52,7 +52,10 @@ export class SphereLightComponent extends LightComponent { /** * 光通量。 */ - @property({ unit: 'lm' }) + @property({ + unit: 'lm', + tooltip:'光通量', + }) get luminousPower () { return this._luminance * nt2lm(this._size); } @@ -64,7 +67,10 @@ export class SphereLightComponent extends LightComponent { /** * 亮度。 */ - @property({ unit: 'cd/m²' }) + @property({ + unit: 'cd/m²', + tooltip:'亮度', + }) get luminance () { return this._luminance; } @@ -76,7 +82,10 @@ export class SphereLightComponent extends LightComponent { /** * 指定光通量或亮度。 */ - @property({ type: PhotometricTerm }) + @property({ + type: PhotometricTerm, + tooltip:'指定光通量或亮度', + }) get term () { return this._term; } @@ -90,7 +99,9 @@ export class SphereLightComponent extends LightComponent { * @zh * 针对聚光灯和点光源设置光源大小。 */ - @property + @property({ + tooltip:'针对聚光灯和点光源设置光源大小' + }) get size () { return this._size; } @@ -105,7 +116,9 @@ export class SphereLightComponent extends LightComponent { * @zh * 针对聚光灯和点光源设置光源范围。 */ - @property + @property({ + tooltip:'针对聚光灯和点光源设置光源范围', + }) get range () { return this._range; } diff --git a/cocos/core/3d/framework/spot-light-component.ts b/cocos/core/3d/framework/spot-light-component.ts index 73a83ee1c0..1002d6059a 100644 --- a/cocos/core/3d/framework/spot-light-component.ts +++ b/cocos/core/3d/framework/spot-light-component.ts @@ -35,7 +35,7 @@ import { SpotLight } from '../../renderer/scene/spot-light'; import { LightComponent, PhotometricTerm } from './light-component'; @ccclass('cc.SpotLightComponent') -@menu('Components/SpotLight') +@menu('Light/SpotLight') @executeInEditMode export class SpotLightComponent extends LightComponent { @@ -56,7 +56,10 @@ export class SpotLightComponent extends LightComponent { /** * 光通量。 */ - @property({ unit: 'lm' }) + @property({ + unit: 'lm', + tooltip:'光通量', + }) get luminousPower () { return this._luminance * nt2lm(this._size); } @@ -68,7 +71,10 @@ export class SpotLightComponent extends LightComponent { /** * 亮度。 */ - @property({ unit: 'cd/m²' }) + @property({ + unit: 'cd/m²', + tooltip:'亮度', + }) get luminance () { return this._luminance; } @@ -80,7 +86,10 @@ export class SpotLightComponent extends LightComponent { /** * 指定光通量或亮度。 */ - @property({ type: PhotometricTerm }) + @property({ + type: PhotometricTerm, + tooltip:'指定光通量或亮度', + }) get term () { return this._term; } @@ -94,7 +103,9 @@ export class SpotLightComponent extends LightComponent { * @zh * 针对聚光灯和点光源设置光源大小。 */ - @property + @property({ + tooltip:'针对聚光灯和点光源设置光源大小', + }) get size () { return this._size; } @@ -109,7 +120,9 @@ export class SpotLightComponent extends LightComponent { * @zh * 针对聚光灯和点光源设置光源范围。 */ - @property + @property({ + tooltip:'针对聚光灯和点光源设置光源范围', + }) get range () { return this._range; } @@ -127,6 +140,7 @@ export class SpotLightComponent extends LightComponent { @property({ slide: true, range: [2, 180, 1], + tooltip:'聚光灯锥角', }) get spotAngle () { return this._spotAngle; diff --git a/cocos/core/3d/misc/utils.ts b/cocos/core/3d/misc/utils.ts index 4c7fca5d27..d9b1c009bf 100644 --- a/cocos/core/3d/misc/utils.ts +++ b/cocos/core/3d/misc/utils.ts @@ -1,16 +1,10 @@ import { GFXAttributeName, GFXFormat, GFXFormatInfos, GFXFormatType, GFXPrimitiveMode, IGFXFormatInfo } from '../../gfx/define'; export { find } from '../../scene-graph/find'; -import { SkelAnimDataHub } from '../../animation/skeletal-animation-data-hub'; import { Mesh } from '../../assets/mesh'; -import { Skeleton } from '../../assets/skeleton'; -import { aabb } from '../../geom-utils'; import { IGFXAttribute } from '../../gfx/input-assembler'; -import { Mat4, Vec3 } from '../../math'; +import { Vec3 } from '../../math'; import { IGeometry } from '../../primitive/define'; -import { JointsAnimationInfo } from '../../renderer/models/skinning-model'; -import { INode } from '../../utils/interfaces'; -import { SkinningModelComponent } from '../framework'; import { BufferBlob } from './buffer-blob'; /** @@ -343,148 +337,3 @@ export function mapBuffer ( } return out; } - -// get the lowest common ancestor -const _path: INode[] = []; -export const LCA = (a: INode, b: INode) => { - if (a === b) { return a; } - let cur: INode | null = b; - _path.length = 0; - while (cur) { _path.push(cur); cur = cur.parent; } - cur = a; - while (cur) { - if (_path.find((n) => n === cur)) { return cur; } - cur = cur.parent; - } - return null; -}; - -const v3_2 = new Vec3(); -function calculateBoneSpaceBounds (mesh: Mesh, skeleton: Skeleton) { - const result = new Array< { max: Vec3, min: Vec3, hasValue: boolean } >(skeleton.joints.length); - for (let i = 0; i < result.length; ++i) { - result[i] = { - hasValue: false, - min: new Vec3(Infinity, Infinity, Infinity), - max: new Vec3(-Infinity, -Infinity, -Infinity), - }; - } - - for (let iPrimitive = 0; iPrimitive < mesh.struct.primitives.length; ++iPrimitive) { - const joints = mesh.readAttribute(iPrimitive, GFXAttributeName.ATTR_JOINTS); - if (!joints) { - continue; - } - const weights = mesh.readAttribute(iPrimitive, GFXAttributeName.ATTR_WEIGHTS); - if (!weights) { - continue; - } - const positions = mesh.readAttribute(iPrimitive, GFXAttributeName.ATTR_POSITION); - if (!positions) { - continue; - } - const vertexCount = Math.min(joints.length / 4, weights.length / 4, positions.length / 3); - for (let iVertex = 0; iVertex < vertexCount; ++iVertex) { - Vec3.set(v3_1, positions[3 * iVertex + 0], positions[3 * iVertex + 1], positions[3 * iVertex + 2]); - for (let i = 0; i < 4; ++i) { - const weight = weights[4 * iVertex + i]; - if (weight === 0) { - continue; - } - const refJointIndex = joints[4 * iVertex + i]; - if (refJointIndex >= skeleton.joints.length) { - continue; - } - - if (skeleton.bindposes) { Vec3.transformMat4(v3_2, v3_1, skeleton.bindposes[refJointIndex]); } - else { Vec3.copy(v3_2, v3_1); } - - const jointBounds = result[refJointIndex]; - jointBounds.hasValue = true; - Vec3.min(jointBounds.min, jointBounds.min, v3_2); - Vec3.max(jointBounds.max, jointBounds.max, v3_2); - } - } - } - return result.map((bounds) => bounds.hasValue ? aabb.fromPoints(new aabb(), bounds.min, bounds.max) : null); -} -interface ICachedBoneSpaceBounds { - bounds: Array; - referenceCount: number; -} -class BoneSpaceBoundsManager { - private _cached = new Map>(); - - public use (mesh: Mesh, skeleton: Skeleton) { - let bucket = this._cached.get(mesh); - if (!bucket) { - bucket = new Map(); - this._cached.set(mesh, bucket); - } - - let cached = bucket.get(skeleton); - if (!cached) { - cached = { - bounds: calculateBoneSpaceBounds(mesh, skeleton), - referenceCount: 0, - }; - bucket.set(skeleton, cached); - } - ++cached.referenceCount; - return cached.bounds; - } - - public unuse (mesh: Mesh, skeleton: Skeleton) { - const bucket = this._cached.get(mesh); - if (bucket) { - const cached = bucket.get(skeleton); - if (cached) { - --cached.referenceCount; - if (cached.referenceCount === 0) { - bucket.delete(skeleton); - } - } - if (bucket.size === 0) { - this._cached.delete(mesh); - } - } - } -} -const boneSpaceBoundsManager = new BoneSpaceBoundsManager(); -const m4_1 = new Mat4(); -const m4_2 = new Mat4(); -const ab_1 = new aabb(); -const v3_3 = new Vec3(); -const v3_4 = new Vec3(); -export function calculateSkinnedBounds (out: aabb, comp: SkinningModelComponent) { - if (!comp.model || !comp.mesh) { return; } - const skeleton = comp.skeleton; - const root = comp.skinningRoot; - const clip = comp.model.uploadedAnim; - const animInfo = root && JointsAnimationInfo.get(root.uuid); - if (!skeleton || !root || !clip || !animInfo) { - if (!comp.model.worldBounds) { return; } - aabb.copy(out, comp.model.worldBounds); - return true; - } - Vec3.set(v3_3, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); - Vec3.set(v3_4, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); - root.getWorldMatrix(m4_1); - const boundList = boneSpaceBoundsManager.use(comp.mesh, skeleton); - const len = skeleton.joints.length; - const data = SkelAnimDataHub.getOrExtract(clip); - const fid = animInfo.data[1]; - for (let i = 0; i < len; ++i) { - const bounds = boundList[i]; - const nodeData = data[skeleton.joints[i]]; - if (!bounds || !nodeData || !nodeData.props) { continue; } - const matrix = nodeData.props.worldMatrix.values[fid]; - Mat4.multiply(m4_2, m4_1, matrix); - aabb.transform(ab_1, bounds, m4_2); - ab_1.getBoundary(v3_1, v3_2); - Vec3.min(v3_3, v3_3, v3_1); - Vec3.max(v3_4, v3_4, v3_2); - } - aabb.fromPoints(out, v3_3, v3_4); - return true; -} diff --git a/cocos/core/animation/animation-clip.ts b/cocos/core/animation/animation-clip.ts index 3d8faba307..2bcee20c8f 100644 --- a/cocos/core/animation/animation-clip.ts +++ b/cocos/core/animation/animation-clip.ts @@ -6,13 +6,15 @@ import { Asset } from '../assets/asset'; import { SpriteFrame } from '../assets/sprite-frame'; import { ccclass, property } from '../data/class-decorator'; +import { CompactValueTypeArray } from '../data/utils/compact-value-type-array'; import { errorID } from '../platform/debug'; +import { DataPoolManager } from '../renderer/data-pool-manager'; import binarySearchEpsilon from '../utils/binary-search'; import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; import { AnimCurve, CurveValueAdapter, IPropertyCurveData, RatioSampler } from './animation-curve'; +import { SkelAnimDataHub } from './skeletal-animation-data-hub'; import { ComponentModifier, HierachyModifier, TargetModifier } from './target-modifier'; import { WrapMode as AnimationWrapMode } from './types'; -import { CompactValueTypeArray } from '../data/utils/compact-value-type-array'; export interface IObjectCurveData { [propertyName: string]: IPropertyCurveData; @@ -314,6 +316,12 @@ export class AnimationClip extends Asset { return this.events.length !== 0; } + public destroy () { + (cc.director.root.dataPoolManager as DataPoolManager).releaseAnimationClip(this); + SkelAnimDataHub.destroy(this); + return super.destroy(); + } + protected _createPropertyCurves () { this._ratioSamplers = this._keys.map( (keys) => new RatioSampler( diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index b483a84aa4..f46362efa7 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -97,7 +97,10 @@ export class AnimationComponent extends Component implements IEventTarget { * 获取此动画组件的自有动画剪辑。 * 动画组件开始运行时会为每个自有动画剪辑创建动画状态。 */ - @property({ type: [AnimationClip] }) + @property({ + type: [AnimationClip], + tooltip:'此动画组件的自有动画剪辑', + }) get clips () { return this._clips; } @@ -137,7 +140,10 @@ export class AnimationComponent extends Component implements IEventTarget { * 获取默认动画剪辑。 * @see [[playOnLoad]] */ - @property({ type: AnimationClip }) + @property({ + type: AnimationClip, + tooltip:'默认动画剪辑', + }) get defaultClip () { return this._defaultClip; } @@ -162,7 +168,9 @@ export class AnimationComponent extends Component implements IEventTarget { /** * 是否在动画组件开始运行时自动播放默认动画剪辑。 */ - @property + @property({ + tooltip:'是否在动画组件开始运行时自动播放默认动画剪辑', + }) public playOnLoad = false; public _callbackTable: ICallbackTable = createMap(true); diff --git a/cocos/core/animation/curve-value-adapters/uniform.ts b/cocos/core/animation/curve-value-adapters/uniform.ts index 68cdfc59d0..017a2e0c66 100644 --- a/cocos/core/animation/curve-value-adapters/uniform.ts +++ b/cocos/core/animation/curve-value-adapters/uniform.ts @@ -8,7 +8,8 @@ import { SpriteFrame } from '../../assets/sprite-frame'; import { TextureBase } from '../../assets/texture-base'; import { ccclass, property } from '../../data/class-decorator'; import { GFXBindingType } from '../../gfx/define'; -import { _type2default, Pass } from '../../renderer/core/pass'; +import { Pass } from '../../renderer/core/pass'; +import { type2default } from '../../renderer/core/pass-utils'; import { samplerLib } from '../../renderer/core/sampler-lib'; import { CurveValueAdapter } from '../animation-curve'; @@ -44,7 +45,7 @@ export class UniformCurveValueAdapter extends CurveValueAdapter { } else if (bindingType === GFXBindingType.SAMPLER) { const binding = Pass.getBindingFromHandle(handle); const prop = pass.properties[this.uniformName]; - const texName = prop && prop.value ? prop.value + '-texture' : _type2default[prop.type]; + const texName = prop && prop.value ? prop.value + '-texture' : type2default[prop.type]; let dftTex = builtinResMgr.get(texName); if (!dftTex) { console.warn('illegal texture default value: ' + texName); diff --git a/cocos/core/animation/skeletal-animation-clip.ts b/cocos/core/animation/skeletal-animation-clip.ts deleted file mode 100644 index a2cd8d77e8..0000000000 --- a/cocos/core/animation/skeletal-animation-clip.ts +++ /dev/null @@ -1,178 +0,0 @@ -/* - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -/** - * @category animation - */ - -import { SkinningModelComponent } from '../3d/framework/skinning-model-component'; -import { ccclass } from '../data/class-decorator'; -import { Mat4 } from '../math'; -import { INode } from '../utils/interfaces'; -import { AnimationClip, IObjectCurveData, IRuntimeCurve } from './animation-clip'; -import { IPropertyCurveData } from './animation-curve'; -import { ComponentModifier, HierachyModifier, isCustomTargetModifier, isPropertyModifier } from './target-modifier'; - -type ConvertedData = Record; -}>; - -/** - * 骨骼动画剪辑。 - */ -@ccclass('cc.SkeletalAnimationClip') -export class SkeletalAnimationClip extends AnimationClip { - - public originalKeys: number[][] = []; - public convertedData: ConvertedData = {}; - protected _converted = false; - - public getPropertyCurves (root: INode): ReadonlyArray { - // tslint:disable-next-line: no-unused-expression - this.hash; // calculate hash before conversion - if (root.getComponent(cc.SkeletalAnimationComponent)) { - this._convertToSkeletalCurves(root); - } else { - console.warn('skeletal clip in non-skeletal component'); - } - return super.getPropertyCurves(root); - } - - private _convertToSkeletalCurves (root: INode) { - if (this._converted) { return; } - const convertedData: ConvertedData = {}; - this.curves.forEach((curve) => { - if (!curve.valueAdapter && - isCustomTargetModifier(curve.modifiers[0], HierachyModifier) && - isPropertyModifier(curve.modifiers[1])) { - const path = (curve.modifiers[0] as HierachyModifier).path; - let cs = convertedData[path]; - if (!cs) { cs = convertedData[path] = { props: {} }; } - const property = curve.modifiers[1] as string; - cs.props[property] = curve.data; - } - }); - this.convertedData = convertedData; this.curves = []; - // lazy eval the conversion due to memory-heavy ops - // many animation paths may not be actually in-use - for (const path of Object.keys(convertedData)) { - const props = convertedData[path] && convertedData[path].props; - if (!props) { continue; } - Object.defineProperty(props, 'worldMatrix', { - get: () => { - if (!props._worldMatrix) { - const { position, rotation, scale } = props; - // fixed step pre-sample - this._convertToUniformSample(position); - this._convertToUniformSample(rotation); - this._convertToUniformSample(scale); - // transform to world space - this._convertToWorldSpace(path, props); - } - return props._worldMatrix; - }, - }); - } - const values: number[] = new Array(Math.ceil(this.sample * this._duration / this.speed) + 1); - for (let i = 0; i < values.length; i++) { values[i] = i; } - // create frameID animation - const curves: AnimationClip.Curve[] = [{ - modifiers: [ - new HierachyModifier(''), - new ComponentModifier('cc.SkeletalAnimationComponent'), - 'frameID', - ], - data: { keys: 0, values, interpolate: false }, - }]; - this.curves = curves; - this.originalKeys = this._keys; - this._keys = [values.map((_, i) => i * this.speed / this.sample)]; - this._duration = this._keys[0][values.length - 1]; - this._converted = true; - if (!root) { return; } - // try eval for the existing skinning models - const comps = root.getComponentsInChildren(SkinningModelComponent); - for (let i = 0; i < comps.length; ++i) { - const comp = comps[i] as SkinningModelComponent; - if (comp.skinningRoot === root && comp.skeleton) { - for (const path of comp.skeleton.joints) { - const data = convertedData[path]; - // tslint:disable-next-line: no-unused-expression - data && data.props && data.props.worldMatrix; - } - } - } - } - - private _convertToUniformSample (curve: IPropertyCurveData) { - const keys = this.originalKeys[curve.keys]; curve.keys = 0; - const len = this._keys[0].length; - const values: any[] = []; - if (!keys || keys.length === 1) { - for (let i = 0; i < len; i++) { - values[i] = curve.values[0].clone(); // never forget to clone - } - } else { - for (let i = 0, idx = 0; i < len; i++) { - let time = i * this.speed / this.sample; - while (keys[idx] <= time) { idx++; } - if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; } - else if (idx === 0) { idx = 1; } - const from = curve.values[idx - 1].clone(); - from.lerp(curve.values[idx], (time - keys[idx - 1]) / (keys[idx] - keys[idx - 1])); - values[i] = from; - } - } - curve.values = values; - } - - private _convertToWorldSpace (path: string, props: IObjectCurveData) { - const oPos = props.position.values; - const oRot = props.rotation.values; - const oScale = props.scale.values; - const matrix = oPos.map(() => new Mat4()); - const idx = path.lastIndexOf('/'); - let pMatrix: Mat4[] | null = null; - if (idx > 0) { - const name = path.substring(0, idx); - const data = this.convertedData[name]; - if (!data || !data.props) { console.warn('no data for parent bone?'); return; } - pMatrix = data.props.worldMatrix.values; - } - // all props should have the same length now - for (let i = 0; i < oPos.length; i++) { - const oT = oPos[i]; - const oR = oRot[i]; - const oS = oScale[i]; - const m = matrix[i]; - Mat4.fromRTS(m, oR, oT, oS); - if (pMatrix) { Mat4.multiply(m, pMatrix[i], m); } - } - Object.keys(props).forEach((k) => delete props[k]); - props._worldMatrix = { keys: 0, interpolate: false, values: matrix }; - } -} - -cc.SkeletalAnimationClip = SkeletalAnimationClip; diff --git a/cocos/core/animation/skeletal-animation-component.ts b/cocos/core/animation/skeletal-animation-component.ts index 5f5f3ef89e..79aa5d447c 100644 --- a/cocos/core/animation/skeletal-animation-component.ts +++ b/cocos/core/animation/skeletal-animation-component.ts @@ -29,7 +29,7 @@ import { ccclass, executeInEditMode, executionOrder, menu, property } from '../data/class-decorator'; import { Mat4 } from '../math'; -import { IJointsAnimInfo, JointsAnimationInfo } from '../renderer/models/skinning-model'; +import { IAnimInfo, JointsAnimationInfo } from '../renderer/models/skeletal-animation-utils'; import { Node } from '../scene-graph/node'; import { INode } from '../utils/interfaces'; import { AnimationClip } from './animation-clip'; @@ -77,8 +77,12 @@ export class SkeletalAnimationComponent extends AnimationComponent { @property({ type: [Socket] }) public _sockets: Socket[] = []; + protected _animMgr: JointsAnimationInfo = null!; - @property({ type: [Socket] }) + @property({ + type: [Socket], + tooltip: 'Joint Sockets', + }) get sockets () { return this._sockets; } @@ -87,25 +91,28 @@ export class SkeletalAnimationComponent extends AnimationComponent { this.rebuildSocketAnimations(); } - protected _animInfo: IJointsAnimInfo | null = null; + protected _animInfo: IAnimInfo | null = null; set frameID (fid: number) { - if (!this._animInfo) { return; } - const { data, buffer } = this._animInfo; - data[1] = fid; buffer.update(data); + const info = this._animInfo; + if (!info) { return; } + info.data[1] = fid; + info.dirty = true; } get frameID () { - return this._animInfo && this._animInfo.data[1] || 0; + const info = this._animInfo; + return info && info.data[1] || 0; } public onLoad () { super.onLoad(); - this._animInfo = JointsAnimationInfo.create(this.node.uuid); + this._animMgr = cc.director.root.dataPoolManager.jointsAnimationInfo; + this._animInfo = this._animMgr.create(this.node.uuid); } public onDestroy () { if (this._animInfo) { - JointsAnimationInfo.destroy(this.node.uuid); + this._animMgr.destroy(this.node.uuid); this._animInfo = null; } super.onDestroy(); diff --git a/cocos/core/animation/skeletal-animation-data-hub.ts b/cocos/core/animation/skeletal-animation-data-hub.ts index 7fa206fc17..908c93ace2 100644 --- a/cocos/core/animation/skeletal-animation-data-hub.ts +++ b/cocos/core/animation/skeletal-animation-data-hub.ts @@ -42,13 +42,17 @@ type ConvertedData = Record(); - public static getOrExtract (clip: AnimationClip) { let data = SkelAnimDataHub.pool.get(clip); if (!data) { data = convertToSkeletalCurves(clip); SkelAnimDataHub.pool.set(clip, data); } return data; } + + public static destroy (clip: AnimationClip) { + SkelAnimDataHub.pool.delete(clip); + } + + protected static pool = new Map(); } function convertToSkeletalCurves (clip: AnimationClip) { diff --git a/cocos/core/animation/skeletal-animation-state.ts b/cocos/core/animation/skeletal-animation-state.ts index f9e11a5c0e..6b3feac2e6 100644 --- a/cocos/core/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -58,7 +58,7 @@ export class SkeletalAnimationState extends AnimationState { super.onPlay(); const comps = this._targetNode!.getComponentsInChildren(SkinningModelComponent); for (let i = 0; i < comps.length; ++i) { - const comp = comps[i] as SkinningModelComponent; + const comp = comps[i]; if (comp.skinningRoot === this._targetNode) { comp.uploadAnimation(this.clip); } diff --git a/cocos/core/assets/asset.ts b/cocos/core/assets/asset.ts index da17998894..a9860bc21b 100644 --- a/cocos/core/assets/asset.ts +++ b/cocos/core/assets/asset.ts @@ -28,7 +28,7 @@ * @category asset */ -import { ccclass, property } from '../data/class-decorator'; +import { ccclass, property, string } from '../data/class-decorator'; import { Event } from '../event'; import { CallbacksInvoker } from '../event/callbacks-invoker'; import { EventTarget } from '../event/event-target'; @@ -106,7 +106,7 @@ export class Asset extends RawAsset implements IEventTarget { * 用于本机资产的可序列化URL。供内部使用。 * @default "" */ - @property(cc.String) + @property public _native: string = ''; private _file: any = null; diff --git a/cocos/core/assets/effect-asset.ts b/cocos/core/assets/effect-asset.ts index a1501cb9fa..4b7a4c445c 100644 --- a/cocos/core/assets/effect-asset.ts +++ b/cocos/core/assets/effect-asset.ts @@ -43,6 +43,7 @@ export interface IPropertyInfo { samplerHash?: number; // auto-generated from 'sampler' value?: number[] | string; } +// Pass instance itself are compliant to IPassStates too export interface IPassStates { priority?: number; primitive?: GFXPrimitiveMode; @@ -50,9 +51,9 @@ export interface IPassStates { rasterizerState?: GFXRasterizerState; depthStencilState?: GFXDepthStencilState; blendState?: GFXBlendState; - dynamics?: GFXDynamicState[]; + dynamicStates?: GFXDynamicState[]; customizations?: string[]; - phase?: string; + phase?: string | number; } export interface IPassInfo extends IPassStates { program: string; // auto-generated from 'vert' and 'frag' @@ -176,7 +177,7 @@ export class EffectAsset extends Asset { */ public onLoaded () { this.shaders.forEach((s) => programLib.define(s)); - cc.game.once(cc.Game.EVENT_ENGINE_INITED, this._precompile, this); + if (!CC_EDITOR) { cc.game.once(cc.Game.EVENT_ENGINE_INITED, this._precompile, this); } EffectAsset.register(this); } diff --git a/cocos/core/assets/material.ts b/cocos/core/assets/material.ts index 438ddeec09..e1dc304ebf 100644 --- a/cocos/core/assets/material.ts +++ b/cocos/core/assets/material.ts @@ -314,14 +314,14 @@ export class Material extends Asset { const len = propsArray.length; for (let i = 0; i < len; i++) { const props = propsArray[i]; - for (const p of Object.keys(props)) { + for (const p in props) { if (p === name) { return props[p]; } } } } else { if (passIdx >= this._props.length) { console.warn(`illegal pass index: ${passIdx}.`); return null; } const props = this._props[passIdx]; - for (const p of Object.keys(props)) { + for (const p in props) { if (p === name) { return props[p]; } } } @@ -380,9 +380,7 @@ export class Material extends Asset { this._passes.forEach((pass, i) => { let props = this._props[pass.idxInTech]; if (!props) { props = this._props[i] = {}; } - for (const p of Object.keys(props)) { - const val = props[p]; - if (!val) { continue; } + for (const p in props) { this._uploadProperty(pass, p, props[p]); } }); @@ -428,7 +426,7 @@ export class Material extends Asset { protected _onPassesChange () { let str = ''; for (const pass of this._passes) { - str += pass.serializePipelineStates(); + str += Pass.getPSOHash(pass); } this._hash = murmurhash2_32_gc(str, 666); if (this._owner) { diff --git a/cocos/core/assets/mesh.ts b/cocos/core/assets/mesh.ts index 85d49e34c9..f5ecc7caf4 100644 --- a/cocos/core/assets/mesh.ts +++ b/cocos/core/assets/mesh.ts @@ -33,7 +33,6 @@ import { BufferBlob } from '../3d/misc/buffer-blob'; import { GFXBuffer } from '../gfx/buffer'; import { GFXAttributeName, - GFXBufferFlagBit, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, @@ -43,7 +42,8 @@ import { } from '../gfx/define'; import { GFXDevice } from '../gfx/device'; import { IGFXAttribute } from '../gfx/input-assembler'; -import { Root } from '../root'; +import { DataPoolManager } from '../renderer/data-pool-manager'; +import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; import { Asset } from './asset'; import { postLoadMesh } from './utils/mesh-utils'; @@ -84,7 +84,7 @@ export interface IGeometricInfo { export interface IFlatBuffer { stride: number; count: number; - buffer: ArrayBuffer; + buffer: Uint8Array; } /** @@ -336,6 +336,11 @@ export class Mesh extends Asset { return this._data; } + get hash () { + if (!this._hash && this._data) { this._hash = murmurhash2_32_gc(this._data, 666); } + return this._hash; + } + /** * 是否具有平铺的缓冲。 */ @@ -350,7 +355,10 @@ export class Mesh extends Asset { }; @property - private _dataLength: number = 0; + private _dataLength = 0; + + @property + private _hash = 0; private _data: Uint8Array | null = null; private _initialized = false; @@ -445,6 +453,7 @@ export class Mesh extends Asset { */ public destroy () { this.destroyRenderingMesh(); + (cc.director.root.dataPoolManager as DataPoolManager).releaseMesh(this); return super.destroy(); } @@ -481,6 +490,7 @@ export class Mesh extends Asset { this.destroyRenderingMesh(); this._struct = info.struct; this._data = info.data; + this._hash = 0; this.loaded = true; this.emit('load'); } @@ -995,13 +1005,13 @@ export class Mesh extends Asset { subMesh.flatBuffers.push({ stride: vbStride, count: vbCount, - buffer: vbView.buffer, + buffer: vbView, }); } else { subMesh.flatBuffers.push({ stride: vbStride, count: vbCount, - buffer: view.buffer, + buffer: view, }); } } diff --git a/cocos/core/assets/skeleton.ts b/cocos/core/assets/skeleton.ts index 80db26ae53..5c0de0d2fc 100644 --- a/cocos/core/assets/skeleton.ts +++ b/cocos/core/assets/skeleton.ts @@ -31,6 +31,8 @@ import { ccclass, property } from '../../core/data/class-decorator'; import { CCString } from '../../core/data/utils/attribute'; import { Mat4, Quat, Vec3 } from '../../core/math'; import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc'; +import { aabb } from '../geom-utils'; +import { DataPoolManager } from '../renderer/data-pool-manager'; import { Asset } from './asset'; export interface IBindTRS { @@ -39,6 +41,11 @@ export interface IBindTRS { scale: Vec3; } +const m4_1 = new Mat4(); +const v3_1 = new Vec3(); +const v3_min = new Vec3(); +const v3_max = new Vec3(); + /** * 骨骼资源。 * 骨骼资源记录了每个关节(相对于`SkinningModelComponent.skinningRoot`)的路径以及它的绑定姿势矩阵。 @@ -52,9 +59,8 @@ export class Skeleton extends Asset { @property([Mat4]) private _bindposes: Mat4[] = []; - private _bindTRS: IBindTRS[] = []; - private _hash = 0; + private _bounds = new aabb(); /** * 所有关节的绑定姿势矩阵。该数组的长度始终与 `this.joints` 的长度相同。 @@ -65,23 +71,23 @@ export class Skeleton extends Asset { set bindposes (value) { this._bindposes = value; - this._bindTRS = value.map((m) => { - const position = new Vec3(); - const rotation = new Quat(); - const scale = new Vec3(); - Mat4.toRTS(m, rotation, position, scale); - return { position, rotation, scale }; - }); - this._hash = murmurhash2_32_gc(this.bindposes.reduce((acc, cur) => acc + - cur.m00.toPrecision(2) + ' ' + cur.m01.toPrecision(2) + ' ' + cur.m02.toPrecision(2) + ' ' + cur.m03.toPrecision(2) + ' ' + - cur.m04.toPrecision(2) + ' ' + cur.m05.toPrecision(2) + ' ' + cur.m06.toPrecision(2) + ' ' + cur.m07.toPrecision(2) + ' ' + - cur.m08.toPrecision(2) + ' ' + cur.m09.toPrecision(2) + ' ' + cur.m10.toPrecision(2) + ' ' + cur.m11.toPrecision(2) + ' ' + - cur.m12.toPrecision(2) + ' ' + cur.m13.toPrecision(2) + ' ' + cur.m14.toPrecision(2) + ' ' + cur.m15.toPrecision(2) + '\n' - , ''), 666); - } - - get bindTRS () { - return this._bindTRS; + let str = ''; + Vec3.set(v3_min, Infinity, Infinity, Infinity); + Vec3.set(v3_max, -Infinity, -Infinity, -Infinity); + for (let i = 0; i < value.length; i++) { + const ibm = value[i]; + str += + ibm.m00.toPrecision(2) + ' ' + ibm.m01.toPrecision(2) + ' ' + ibm.m02.toPrecision(2) + ' ' + ibm.m03.toPrecision(2) + ' ' + + ibm.m04.toPrecision(2) + ' ' + ibm.m05.toPrecision(2) + ' ' + ibm.m06.toPrecision(2) + ' ' + ibm.m07.toPrecision(2) + ' ' + + ibm.m08.toPrecision(2) + ' ' + ibm.m09.toPrecision(2) + ' ' + ibm.m10.toPrecision(2) + ' ' + ibm.m11.toPrecision(2) + ' ' + + ibm.m12.toPrecision(2) + ' ' + ibm.m13.toPrecision(2) + ' ' + ibm.m14.toPrecision(2) + ' ' + ibm.m15.toPrecision(2) + '\n'; + Mat4.invert(m4_1, ibm); + Vec3.set(v3_1, m4_1.m12, m4_1.m13, m4_1.m14); + Vec3.min(v3_min, v3_min, v3_1); + Vec3.max(v3_max, v3_max, v3_1); + } + this._hash = murmurhash2_32_gc(str, 666); + aabb.fromPoints(this._bounds, v3_min, v3_max); } /** @@ -99,9 +105,18 @@ export class Skeleton extends Asset { return this._hash; } + get bounds () { + return this._bounds; + } + public onLoaded () { this.bindposes = this._bindposes; } + + public destroy () { + (cc.director.root.dataPoolManager as DataPoolManager).releaseSkeleton(this); + return super.destroy(); + } } cc.Skeleton = Skeleton; diff --git a/cocos/core/assets/sprite-frame.ts b/cocos/core/assets/sprite-frame.ts index d91bfe8d74..80a22ed4bf 100644 --- a/cocos/core/assets/sprite-frame.ts +++ b/cocos/core/assets/sprite-frame.ts @@ -643,8 +643,8 @@ export class SpriteFrame extends Asset { uvSliced.length = 0; if (this._rotated) { temp_uvs[0].u = (rect.x + rect.height) / atlasWidth; - temp_uvs[1].u = (rect.x + bottomHeight + centerHeight) / atlasWidth; - temp_uvs[2].u = (rect.x + bottomHeight) / atlasWidth; + temp_uvs[1].u = (rect.x + topHeight + centerHeight) / atlasWidth; + temp_uvs[2].u = (rect.x + topHeight) / atlasWidth; temp_uvs[3].u = (rect.x) / atlasWidth; temp_uvs[3].v = (rect.y + rect.width) / atlasHeight; temp_uvs[2].v = (rect.y + leftWidth + centerWidth) / atlasHeight; diff --git a/cocos/core/assets/texture-base.ts b/cocos/core/assets/texture-base.ts index f607946937..21d9cf7884 100644 --- a/cocos/core/assets/texture-base.ts +++ b/cocos/core/assets/texture-base.ts @@ -100,7 +100,7 @@ export class TextureBase extends Asset { protected _wrapR: number = WrapMode.REPEAT; @property - protected _anisotropy = 16; + protected _anisotropy = 8; protected _width: number = 0; protected _height: number = 0; @@ -192,7 +192,7 @@ export class TextureBase extends Asset { public setMipFilter (mipFilter: Filter) { this._mipFilter = mipFilter; this._samplerInfo[SamplerInfoIndex.mipFilter] = mipFilter; - this._samplerInfo[SamplerInfoIndex.maxLOD] = mipFilter === Filter.NONE ? 0 : 1000; // WebGL2 on some platform need this + this._samplerInfo[SamplerInfoIndex.maxLOD] = mipFilter === Filter.NONE ? 0 : 15; // WebGL2 on some platform need this this._samplerHash = genSamplerHash(this._samplerInfo); } diff --git a/cocos/core/assets/ttf-font.ts b/cocos/core/assets/ttf-font.ts index 5384d3f4e1..81b07c74b9 100644 --- a/cocos/core/assets/ttf-font.ts +++ b/cocos/core/assets/ttf-font.ts @@ -28,7 +28,7 @@ * @category asset */ -import {ccclass, property} from '../data/class-decorator'; +import {ccclass, property, string} from '../data/class-decorator'; import { Font } from './font'; /** @@ -45,9 +45,9 @@ export class TTFFont extends Font { public _fontFamily: any = null; @property({ - type: cc.String, override: true, }) + @string get _nativeAsset () { return this._fontFamily; } diff --git a/cocos/core/components/ui-base/canvas-component.ts b/cocos/core/components/ui-base/canvas-component.ts index 9f2af1dc8d..7b98992021 100644 --- a/cocos/core/components/ui-base/canvas-component.ts +++ b/cocos/core/components/ui-base/canvas-component.ts @@ -74,6 +74,7 @@ const RenderMode = Enum({ export class CanvasComponent extends Component { @property({ type: CanvasClearFlag, + tooltip:'清理屏幕缓冲标记', }) get clearFlag () { return this._clearFlag; @@ -86,7 +87,9 @@ export class CanvasComponent extends Component { } } - @property + @property({ + tooltip:'清理颜色缓冲区后的颜色', + }) get color () { return this._color; } @@ -103,6 +106,7 @@ export class CanvasComponent extends Component { @property({ type: RenderMode, + tooltip:'Canvas 渲染模式,intersperse 下可以指定 Canvas 与场景中的相机的渲染顺序,overlay 下 Canvas 会在所有场景相机渲染完成后渲染。\n注意:启用 intersperse 模式,如果 3D 场景的相机内容显示上要在 Canvas 前面,相机的 clearFlags 也要为 none', }) get renderMode () { return this._renderMode; @@ -121,7 +125,9 @@ export class CanvasComponent extends Component { * * @param value - 渲染优先级。 */ - @property() + @property({ + tooltip:'相机排序优先级。当 RenderMode 为 intersperse 时,指定与其它相机的渲染顺序,当 RenderMode 为 overlay 时,指定跟其余 Canvas 做排序使用', + }) get priority () { return this._priority; } @@ -138,6 +144,7 @@ export class CanvasComponent extends Component { */ @property({ type: RenderTexture, + tooltip:'目标渲染纹理', }) get targetTexture (){ return this._targetTexture; diff --git a/cocos/core/components/ui-base/ui-component.ts b/cocos/core/components/ui-base/ui-component.ts index d5b9ec619c..8336abbeaf 100644 --- a/cocos/core/components/ui-base/ui-component.ts +++ b/cocos/core/components/ui-base/ui-component.ts @@ -27,11 +27,11 @@ * @category ui */ -import { Component } from '../component'; import { ccclass, disallowMultiple, executeInEditMode, executionOrder, property } from '../../../core/data/class-decorator'; import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; import { INode } from '../../../core/utils/interfaces'; import { UI } from '../../renderer/ui/ui'; +import { Component } from '../component'; import { CanvasComponent } from './canvas-component'; /** @@ -48,7 +48,9 @@ export class UIComponent extends Component { * @zh * 渲染先后顺序,按照广度渲染排列,按同级节点下进行一次排列。 */ - @property + @property({ + tooltip:'渲染排序优先级' + }) get priority () { return this._priority; } @@ -67,7 +69,7 @@ export class UIComponent extends Component { * 查找被渲染相机。 */ get visibility () { - if(!this._screen){ + if (!this._screen){ return -1; } @@ -109,13 +111,13 @@ export class UIComponent extends Component { } } - public updateAssembler(render: UI) { + public updateAssembler (render: UI) { } - public postUpdateAssembler(render: UI) { + public postUpdateAssembler (render: UI) { } - public _setScreen(value: CanvasComponent){ + public _setScreen (value: CanvasComponent){ this._followScreen = value; } diff --git a/cocos/core/components/ui-base/ui-render-component.ts b/cocos/core/components/ui-base/ui-render-component.ts index 4cda352f75..edf3c1fa13 100644 --- a/cocos/core/components/ui-base/ui-render-component.ts +++ b/cocos/core/components/ui-base/ui-render-component.ts @@ -45,7 +45,6 @@ import { RenderableComponent } from '../../../core/3d/framework/renderable-compo import { IAssembler, IAssemblerManager } from '../../renderer/ui/base'; import { UIComponent } from './ui-component'; import { UITransformComponent } from './ui-transform-component'; -import { director } from '../../director'; // hack ccenum(GFXBlendFactor); @@ -66,6 +65,12 @@ export enum InstanceMaterialType { * 着色器带颜色和贴图属性。 */ ADDCOLORANDTEXTURE = 1, + + /** + * @zh + * 着色器带颜色和贴图属性,并使用灰度模式。 + */ + GRAYSCALE = 2, } /** @@ -92,6 +97,7 @@ export class UIRenderComponent extends UIComponent { @property({ type: GFXBlendFactor, displayOrder: 0, + tooltip:'原图混合模式', }) get srcBlendFactor () { return this._srcBlendFactor; @@ -119,6 +125,7 @@ export class UIRenderComponent extends UIComponent { @property({ type: GFXBlendFactor, displayOrder: 1, + tooltip:'目标混合模式', }) get dstBlendFactor () { return this._dstBlendFactor; @@ -141,6 +148,7 @@ export class UIRenderComponent extends UIComponent { */ @property({ displayOrder: 2, + tooltip:'渲染颜色', }) // @constget get color (): Readonly { @@ -166,6 +174,7 @@ export class UIRenderComponent extends UIComponent { @property({ type: Material, displayOrder: 3, + tooltip:'源材质', }) get sharedMaterial () { return this._sharedMaterial; @@ -323,7 +332,7 @@ export class UIRenderComponent extends UIComponent { } } - public postUpdateAssembler(render: UI) { + public postUpdateAssembler (render: UI) { super.postUpdateAssembler(render); if (this._renderFlag) { this._postRender(render); @@ -331,10 +340,10 @@ export class UIRenderComponent extends UIComponent { } // 开始提交渲染数据给中转站 - protected _render(render: UI) { } + protected _render (render: UI) { } // 开始提交渲染数据给中转站 - protected _postRender(render: UI) { } + protected _postRender (render: UI) { } // 像组装器更新渲染数据 protected _checkAndUpdateRenderData (){ @@ -403,6 +412,9 @@ export class UIRenderComponent extends UIComponent { case InstanceMaterialType.ADDCOLORANDTEXTURE: mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false); break; + case InstanceMaterialType.GRAYSCALE: + mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-gray-material'), new RenderableComponent(), CC_EDITOR ? true : false); + break; } } diff --git a/cocos/core/components/ui-base/ui-transform-component.ts b/cocos/core/components/ui-base/ui-transform-component.ts index dc9d706414..e541b15c96 100644 --- a/cocos/core/components/ui-base/ui-transform-component.ts +++ b/cocos/core/components/ui-base/ui-transform-component.ts @@ -30,7 +30,7 @@ import { Component } from '../component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator'; import { SystemEventType } from '../../platform/event-manager/event-enum'; -import { EventListener, ILinstenerMask } from '../../platform/event-manager/event-listener'; +import { EventListener, IListenerMask } from '../../platform/event-manager/event-listener'; import { Mat4, Rect, Size, Vec2, Vec3 } from '../../math'; import { aabb } from '../../geom-utils'; import { CanvasComponent } from './canvas-component'; @@ -60,6 +60,7 @@ export class UITransformComponent extends Component { */ @property({ displayOrder: 0, + tooltip:'内容尺寸', }) // @constget get contentSize (): Readonly { @@ -138,6 +139,7 @@ export class UITransformComponent extends Component { */ @property({ displayOrder: 1, + tooltip:'锚点位置', }) // @constget get anchorPoint (): Readonly { @@ -328,7 +330,7 @@ export class UITransformComponent extends Component { if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) { if (listener && listener.mask) { - const mask = listener.mask as ILinstenerMask; + const mask = listener.mask as IListenerMask; let parent: any = this.node; // find mask parent, should hit test it for (let i = 0; parent && i < mask.index; ++i, parent = parent.parent) { diff --git a/cocos/core/data/class-decorator.ts b/cocos/core/data/class-decorator.ts index 6602aa6ae8..49ddba21fa 100644 --- a/cocos/core/data/class-decorator.ts +++ b/cocos/core/data/class-decorator.ts @@ -52,7 +52,7 @@ import * as js from '../utils/js'; import './class'; import { IExposedAttributes } from './utils/attribute-defines'; import { doValidateMethodWithProps_DEV, getFullFormOfProperty } from './utils/preprocess-class'; -import { CCString, CCInteger, CCFloat, CCBoolean } from './utils/attribute'; +import { CCString, CCInteger, CCFloat, CCBoolean, PrimitiveType } from './utils/attribute'; // caches for class construction const CACHE_KEY = '__ccclassCache__'; @@ -605,3 +605,37 @@ export function mixins (...constructors: Function[]) { } }; } + +/** + * 将该属性标记为 cc 整数。 + */ +export const integer = type(CCInteger); + +/** + * 将该属性标记为 cc 浮点数。 + */ +export const float = type(CCFloat); + +/** + * 将该属性标记为 cc 布尔值。 + */ +export const boolean = type(CCBoolean); + +/** + * 将该属性标记为 cc 字符串。 + */ +export const string = type(CCString); + +/** + * 标记该属性的类型。 + * @param type 指定类型。 + */ +export function type (type: Function): PropertyDecorator; + +export function type (type: PrimitiveType): PropertyDecorator; + +export function type (type: PrimitiveType | Function): PropertyDecorator { + return property({ + type, + }); +} \ No newline at end of file diff --git a/cocos/core/geom-utils/aabb.ts b/cocos/core/geom-utils/aabb.ts index b17e7adbb7..593510e7a5 100644 --- a/cocos/core/geom-utils/aabb.ts +++ b/cocos/core/geom-utils/aabb.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Mat3, Mat4, Quat, Vec3 } from '../../core/math'; @@ -91,8 +91,10 @@ export default class aabb { * @returns {aabb} out 接受操作的 aabb。 */ public static fromPoints (out: aabb, minPos: Vec3, maxPos: Vec3): aabb { - Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp, minPos, maxPos), 0.5); - Vec3.multiplyScalar(out.halfExtents, Vec3.subtract(_v3_tmp2, maxPos, minPos), 0.5); + Vec3.add(_v3_tmp, maxPos, minPos); + Vec3.subtract(_v3_tmp2, maxPos, minPos); + Vec3.multiplyScalar(out.center, _v3_tmp, 0.5); + Vec3.multiplyScalar(out.halfExtents, _v3_tmp2, 0.5); return out; } diff --git a/cocos/core/geom-utils/curve.ts b/cocos/core/geom-utils/curve.ts index 5f08caf7e6..a2c301ec38 100644 --- a/cocos/core/geom-utils/curve.ts +++ b/cocos/core/geom-utils/curve.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import CCClass from '../../core/data/class'; diff --git a/cocos/core/geom-utils/deprecated.ts b/cocos/core/geom-utils/deprecated.ts index 95c2e08dc9..9f9f32c673 100644 --- a/cocos/core/geom-utils/deprecated.ts +++ b/cocos/core/geom-utils/deprecated.ts @@ -2,8 +2,9 @@ * @hidden */ -import { replaceProperty } from '../utils/deprecated'; +import { replaceProperty, removeProperty } from '../utils/deprecated'; import line from './line'; +import intersect from './intersect'; replaceProperty(line.prototype, 'line', [ { @@ -15,3 +16,9 @@ replaceProperty(line.prototype, 'line', [ newName: 'len', }, ]); + +removeProperty(intersect, 'intersect', [ + { + name: 'line_quad' + } +]) \ No newline at end of file diff --git a/cocos/core/geom-utils/distance.ts b/cocos/core/geom-utils/distance.ts index 1f94ffab01..1f41fee16e 100644 --- a/cocos/core/geom-utils/distance.ts +++ b/cocos/core/geom-utils/distance.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Vec3 } from '../math'; diff --git a/cocos/core/geom-utils/enums.ts b/cocos/core/geom-utils/enums.ts index 3277242c55..9af97fb244 100644 --- a/cocos/core/geom-utils/enums.ts +++ b/cocos/core/geom-utils/enums.ts @@ -1,6 +1,6 @@ /** * 几何工具模块 - * @category gemotry-utils + * @category geometry */ /** diff --git a/cocos/core/geom-utils/frustum.ts b/cocos/core/geom-utils/frustum.ts index 4367550a7f..578158f8f6 100644 --- a/cocos/core/geom-utils/frustum.ts +++ b/cocos/core/geom-utils/frustum.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Mat4, Vec3 } from '../math'; diff --git a/cocos/core/geom-utils/index.ts b/cocos/core/geom-utils/index.ts index c49f474614..88cebe1279 100644 --- a/cocos/core/geom-utils/index.ts +++ b/cocos/core/geom-utils/index.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ export { default as enums } from './enums'; diff --git a/cocos/core/geom-utils/intersect.ts b/cocos/core/geom-utils/intersect.ts index 4100b13fc8..f16965fbaa 100644 --- a/cocos/core/geom-utils/intersect.ts +++ b/cocos/core/geom-utils/intersect.ts @@ -1,6 +1,6 @@ /** * 几何工具模块 - * @category gemotry-utils + * @category geometry */ import { Mat3, Vec3 } from '../math'; @@ -40,24 +40,6 @@ const ray_plane = (function () { }; })(); -/** - * line-plane intersect
- * 线段与平面的相交性检测。 - * @param {line} line 线段 - * @param {plane} plane 平面 - * @return {number} 0 或 非 0 - */ -const line_plane = (function () { - const ab = new Vec3(0, 0, 0); - - return function (line: line, plane: plane): number { - Vec3.subtract(ab, line.e, line.s); - const t = (plane.d - Vec3.dot(line.s, plane.n)) / Vec3.dot(ab, plane.n); - if (t < 0 || t > 1) { return 0; } - return t; - }; -})(); - // based on http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/raytri/ /** * ray-triangle intersect
@@ -97,160 +79,6 @@ const ray_triangle = (function () { }; })(); -/** - * line-triangle intersect
- * 线段与三角形的相交性检测。 - * @param {line} line 线段 - * @param {triangle} triangle 三角形 - * @param {Vec3} outPt 可选,相交点 - * @return {number} 0 或 非 0 - */ -const line_triangle = (function () { - const ab = new Vec3(0, 0, 0); - const ac = new Vec3(0, 0, 0); - const qp = new Vec3(0, 0, 0); - const ap = new Vec3(0, 0, 0); - const n = new Vec3(0, 0, 0); - const e = new Vec3(0, 0, 0); - - return function (line: line, triangle: triangle, outPt: Vec3): number { - Vec3.subtract(ab, triangle.b, triangle.a); - Vec3.subtract(ac, triangle.c, triangle.a); - Vec3.subtract(qp, line.s, line.e); - - Vec3.cross(n, ab, ac); - const det = Vec3.dot(qp, n); - - if (det <= 0.0) { - return 0; - } - - Vec3.subtract(ap, line.s, triangle.a); - const t = Vec3.dot(ap, n); - if (t < 0 || t > det) { - return 0; - } - - Vec3.cross(e, qp, ap); - let v = Vec3.dot(ac, e); - if (v < 0 || v > det) { - return 0; - } - - let w = -Vec3.dot(ab, e); - if (w < 0.0 || v + w > det) { - return 0; - } - - if (outPt) { - const invDet = 1.0 / det; - v *= invDet; - w *= invDet; - const u = 1.0 - v - w; - - // outPt = u*a + v*d + w*c; - Vec3.set(outPt, - triangle.a.x * u + triangle.b.x * v + triangle.c.x * w, - triangle.a.y * u + triangle.b.y * v + triangle.c.y * w, - triangle.a.z * u + triangle.b.z * v + triangle.c.z * w, - ); - } - - return 1; - }; -})(); - -/** - * line-quad intersect
- * 线段与四边形的相交性检测。 - * @param {Vec3} p 线段的一点 - * @param {Vec3} q 线段的另一点 - * @param {Vec3} a 四边形的 a 点 - * @param {Vec3} b 四边形的 b 点 - * @param {Vec3} c 四边形的 c 点 - * @param {Vec3} d 四边形的 d 点 - * @param {Vec3} outPt 可选,相交点 - * @return {number} 0 或 非 0 - */ -const line_quad = (function () { - const pq = new Vec3(0, 0, 0); - const pa = new Vec3(0, 0, 0); - const pb = new Vec3(0, 0, 0); - const pc = new Vec3(0, 0, 0); - const pd = new Vec3(0, 0, 0); - const m = new Vec3(0, 0, 0); - const tmp = new Vec3(0, 0, 0); - - return function (p: Vec3, q: Vec3, a: Vec3, b: Vec3, c: Vec3, d: Vec3, outPt: Vec3): number { - Vec3.subtract(pq, q, p); - Vec3.subtract(pa, a, p); - Vec3.subtract(pb, b, p); - Vec3.subtract(pc, c, p); - - // Determine which triangle to test against by testing against diagonal first - Vec3.cross(m, pc, pq); - let v = Vec3.dot(pa, m); - - if (v >= 0) { - // Test intersection against triangle abc - let u = -Vec3.dot(pb, m); - if (u < 0) { - return 0; - } - - let w = Vec3.dot(Vec3.cross(tmp, pq, pb), pa); - if (w < 0) { - return 0; - } - - // outPt = u*a + v*b + w*c; - if (outPt) { - const denom = 1.0 / (u + v + w); - u *= denom; - v *= denom; - w *= denom; - - Vec3.set(outPt, - a.x * u + b.x * v + c.x * w, - a.y * u + b.y * v + c.y * w, - a.z * u + b.z * v + c.z * w, - ); - } - } else { - // Test intersection against triangle dac - Vec3.subtract(pd, d, p); - - let u = Vec3.dot(pd, m); - if (u < 0) { - return 0; - } - - let w = Vec3.dot(Vec3.cross(tmp, pq, pa), pd); - if (w < 0) { - return 0; - } - - // outPt = u*a + v*d + w*c; - if (outPt) { - v = -v; - - const denom = 1.0 / (u + v + w); - u *= denom; - v *= denom; - w *= denom; - - Vec3.set(outPt, - a.x * u + d.x * v + c.x * w, - a.y * u + d.y * v + c.y * w, - a.z * u + d.z * v + c.z * w, - ); - } - } - - return 1; - }; -})(); - /** * ray-sphere intersect
* 射线和球的相交性检测。 @@ -384,6 +212,148 @@ const ray_obb = (function () { }; })(); +/** + * line-plane intersect
+ * 线段与平面的相交性检测。 + * @param {line} line 线段 + * @param {plane} plane 平面 + * @return {number} 0 或 非 0 + */ +const line_plane = (function () { + const ab = new Vec3(0, 0, 0); + + return function (line: line, plane: plane): number { + Vec3.subtract(ab, line.e, line.s); + const t = (plane.d - Vec3.dot(line.s, plane.n)) / Vec3.dot(ab, plane.n); + if (t < 0 || t > 1) { return 0; } + return t; + }; +})(); + +/** + * line-triangle intersect
+ * 线段与三角形的相交性检测。 + * @param {line} line 线段 + * @param {triangle} triangle 三角形 + * @param {Vec3} outPt 可选,相交点 + * @return {number} 0 或 非 0 + */ +const line_triangle = (function () { + const ab = new Vec3(0, 0, 0); + const ac = new Vec3(0, 0, 0); + const qp = new Vec3(0, 0, 0); + const ap = new Vec3(0, 0, 0); + const n = new Vec3(0, 0, 0); + const e = new Vec3(0, 0, 0); + + return function (line: line, triangle: triangle, outPt?: Vec3): number { + Vec3.subtract(ab, triangle.b, triangle.a); + Vec3.subtract(ac, triangle.c, triangle.a); + Vec3.subtract(qp, line.s, line.e); + + Vec3.cross(n, ab, ac); + const det = Vec3.dot(qp, n); + + if (det <= 0.0) { + return 0; + } + + Vec3.subtract(ap, line.s, triangle.a); + const t = Vec3.dot(ap, n); + if (t < 0 || t > det) { + return 0; + } + + Vec3.cross(e, qp, ap); + let v = Vec3.dot(ac, e); + if (v < 0 || v > det) { + return 0; + } + + let w = -Vec3.dot(ab, e); + if (w < 0.0 || v + w > det) { + return 0; + } + + if (outPt) { + const invDet = 1.0 / det; + v *= invDet; + w *= invDet; + const u = 1.0 - v - w; + + // outPt = u*a + v*d + w*c; + Vec3.set(outPt, + triangle.a.x * u + triangle.b.x * v + triangle.c.x * w, + triangle.a.y * u + triangle.b.y * v + triangle.c.y * w, + triangle.a.z * u + triangle.b.z * v + triangle.c.z * w, + ); + } + + return 1; + }; +})(); + +const r_t = new ray(); +/** + * @zh + * 线段与轴对齐包围盒的相交性检测 + * @param line 线段 + * @param aabb 轴对齐包围盒 + * @return {number} 0 或 非 0 + */ +function line_aabb (line: line, aabb: aabb): number { + r_t.o.set(line.s); + Vec3.subtract(r_t.d, line.e, line.s); + r_t.d.normalize(); + const min = ray_aabb(r_t, aabb); + const len = line.length(); + if (min <= len) { + return min; + } else { + return 0; + } +} + +/** + * @zh + * 线段与方向包围盒的相交性检测 + * @param line 线段 + * @param obb 方向包围盒 + * @return {number} 0 或 非 0 + */ +function line_obb (line: line, obb: obb): number { + r_t.o.set(line.s); + Vec3.subtract(r_t.d, line.e, line.s); + r_t.d.normalize(); + const min = ray_obb(r_t, obb); + const len = line.length(); + if (min <= len) { + return min; + } else { + return 0; + } +} + +/** + * @zh + * 线段与球的相交性检测 + * @param line 线段 + * @param sphere 球 + * @return {number} 0 或 非 0 + */ +function line_sphere (line: line, sphere: sphere): number { + r_t.o.set(line.s); + Vec3.subtract(r_t.d, line.e, line.s); + r_t.d.normalize(); + const min = ray_sphere(r_t, sphere); + const len = line.length(); + if (min <= len) { + return min; + } else { + return 0; + } +} + /** * aabb-aabb intersect
* 轴对齐包围盒和轴对齐包围盒的相交性检测。 @@ -885,9 +855,12 @@ const intersect = { ray_obb, ray_plane, ray_triangle, + + line_sphere, + line_aabb, + line_obb, line_plane, line_triangle, - line_quad, sphere_sphere, sphere_aabb, @@ -928,6 +901,10 @@ intersect[enums.SHAPE_RAY | enums.SHAPE_AABB] = ray_aabb; intersect[enums.SHAPE_RAY | enums.SHAPE_OBB] = ray_obb; intersect[enums.SHAPE_RAY | enums.SHAPE_PLANE] = ray_plane; intersect[enums.SHAPE_RAY | enums.SHAPE_TRIANGLE] = ray_triangle; + +intersect[enums.SHAPE_LINE | enums.SHAPE_SPHERE] = line_sphere; +intersect[enums.SHAPE_LINE | enums.SHAPE_AABB] = line_aabb; +intersect[enums.SHAPE_LINE | enums.SHAPE_OBB] = line_obb; intersect[enums.SHAPE_LINE | enums.SHAPE_PLANE] = line_plane; intersect[enums.SHAPE_LINE | enums.SHAPE_TRIANGLE] = line_triangle; diff --git a/cocos/core/geom-utils/line.ts b/cocos/core/geom-utils/line.ts index 899cb182b9..7079eb28e7 100644 --- a/cocos/core/geom-utils/line.ts +++ b/cocos/core/geom-utils/line.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Vec3 } from '../math'; diff --git a/cocos/core/geom-utils/obb.ts b/cocos/core/geom-utils/obb.ts index a927c3ea86..23f02f4d68 100644 --- a/cocos/core/geom-utils/obb.ts +++ b/cocos/core/geom-utils/obb.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Mat3, Mat4, Quat, Vec3 } from '../math'; diff --git a/cocos/core/geom-utils/octree.ts b/cocos/core/geom-utils/octree.ts index 6243533b4d..577ce829e4 100644 --- a/cocos/core/geom-utils/octree.ts +++ b/cocos/core/geom-utils/octree.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Vec3 } from '../math'; diff --git a/cocos/core/geom-utils/plane.ts b/cocos/core/geom-utils/plane.ts index 32158899c9..78fdc413d5 100644 --- a/cocos/core/geom-utils/plane.ts +++ b/cocos/core/geom-utils/plane.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Mat4, Vec3, Vec4 } from '../math'; diff --git a/cocos/core/geom-utils/ray.ts b/cocos/core/geom-utils/ray.ts index 06ee594091..d737e9a994 100644 --- a/cocos/core/geom-utils/ray.ts +++ b/cocos/core/geom-utils/ray.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Vec3 } from '../math'; diff --git a/cocos/core/geom-utils/sphere.ts b/cocos/core/geom-utils/sphere.ts index 7d1c597089..febde946c6 100644 --- a/cocos/core/geom-utils/sphere.ts +++ b/cocos/core/geom-utils/sphere.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Mat4, Quat, Vec3 } from '../math'; @@ -77,7 +77,7 @@ export default class sphere { /** * @en Set the components of a sphere to the given values * @zh 将球体的属性设置为给定的值。 - * + * * @param {sphere} out 接受操作的 sphere。 * @param cx 形状的相对于原点的 X 坐标。 * @param cy 形状的相对于原点的 Y 坐标。 diff --git a/cocos/core/geom-utils/triangle.ts b/cocos/core/geom-utils/triangle.ts index ef8ef9f01e..f884c6dcb6 100644 --- a/cocos/core/geom-utils/triangle.ts +++ b/cocos/core/geom-utils/triangle.ts @@ -1,5 +1,5 @@ /** - * @category gemotry-utils + * @category geometry */ import { Vec3 } from '../math'; diff --git a/cocos/core/gfx/binding-layout.ts b/cocos/core/gfx/binding-layout.ts index a340709812..05a4039dc0 100644 --- a/cocos/core/gfx/binding-layout.ts +++ b/cocos/core/gfx/binding-layout.ts @@ -14,7 +14,7 @@ import { GFXTextureView } from './texture-view'; */ export interface IGFXBinding { binding: number; - type: GFXBindingType; + bindingType: GFXBindingType; name: string; } diff --git a/cocos/core/gfx/pipeline-state.ts b/cocos/core/gfx/pipeline-state.ts index e4c8e46d23..e7888a483d 100644 --- a/cocos/core/gfx/pipeline-state.ts +++ b/cocos/core/gfx/pipeline-state.ts @@ -169,13 +169,14 @@ export class GFXInputState { export interface IGFXPipelineStateInfo { primitive: GFXPrimitiveMode; shader: GFXShader; - is: GFXInputState; - rs: GFXRasterizerState; - dss: GFXDepthStencilState; - bs: GFXBlendState; + inputState: GFXInputState; + rasterizerState: GFXRasterizerState; + depthStencilState: GFXDepthStencilState; + blendState: GFXBlendState; dynamicStates?: GFXDynamicState[]; layout: GFXPipelineLayout; renderPass: GFXRenderPass; + hash: number; } /** @@ -224,6 +225,14 @@ export abstract class GFXPipelineState extends GFXObject { return this._bs as GFXBlendState; } + /** + * @zh + * GFX输入状态。 + */ + public get inputState (): GFXInputState { + return this._is as GFXInputState; + } + /** * @zh * GFX动态状态数组。 @@ -248,6 +257,14 @@ export abstract class GFXPipelineState extends GFXObject { return this._renderPass as GFXRenderPass; } + /** + * @zh + * 此管线状态的 hash。 + */ + public get hash (): number { + return this._hash; + } + /** * @zh * GFX设备。 @@ -308,6 +325,12 @@ export abstract class GFXPipelineState extends GFXObject { */ protected _renderPass: GFXRenderPass | null = null; + /** + * @zh + * 此管线状态的 hash。 + */ + protected _hash: number = 0; + /** * 构造函数。 * @param device GFX设备。 diff --git a/cocos/core/gfx/webgl/webgl-binding-layout.ts b/cocos/core/gfx/webgl/webgl-binding-layout.ts index 4064b9fdc0..175267a27d 100644 --- a/cocos/core/gfx/webgl/webgl-binding-layout.ts +++ b/cocos/core/gfx/webgl/webgl-binding-layout.ts @@ -25,7 +25,7 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout { const binding = info.bindings[i]; this._bindingUnits[i] = { binding: binding.binding, - type: binding.type, + type: binding.bindingType, name: binding.name, buffer: null, texView: null, @@ -41,7 +41,7 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout { const binding = info.bindings[i]; this._gpuBindingLayout.gpuBindings[i] = { binding: binding.binding, - type: binding.type, + type: binding.bindingType, name: binding.name, gpuBuffer: null, gpuTexView: null, diff --git a/cocos/core/gfx/webgl/webgl-buffer.ts b/cocos/core/gfx/webgl/webgl-buffer.ts index 7f4c43158d..0cb9bb7634 100644 --- a/cocos/core/gfx/webgl/webgl-buffer.ts +++ b/cocos/core/gfx/webgl/webgl-buffer.ts @@ -128,7 +128,7 @@ export class WebGLGFXBuffer extends GFXBuffer { } else { buffSize = (buffer as ArrayBuffer).byteLength; } - if (this._bufferView) { + if (this._bufferView && buffer !== this._bufferView.buffer) { const view = new Uint8Array(buffer as ArrayBuffer, 0, size); this._bufferView.set(view, offset); } diff --git a/cocos/core/gfx/webgl/webgl-command-buffer.ts b/cocos/core/gfx/webgl/webgl-command-buffer.ts index cd5d1af767..7868aa3a99 100644 --- a/cocos/core/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/core/gfx/webgl/webgl-command-buffer.ts @@ -349,16 +349,17 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { this.cmdPackage.cmds.push(WebGLCmd.DRAW); ++this._numDrawCalls; + const indexCount = inputAssembler.indexCount || inputAssembler.vertexCount; if (this._curGPUPipelineState) { const glPrimitive = this._curGPUPipelineState.glPrimitive; switch (glPrimitive) { case 0x0004: { // WebGLRenderingContext.TRIANGLES - this._numTris += inputAssembler.indexCount / 3 * Math.max(inputAssembler.instanceCount, 1); + this._numTris += indexCount / 3 * Math.max(inputAssembler.instanceCount, 1); break; } case 0x0005: // WebGLRenderingContext.TRIANGLE_STRIP case 0x0006: { // WebGLRenderingContext.TRIANGLE_FAN - this._numTris += (inputAssembler.indexCount - 2) * Math.max(inputAssembler.instanceCount, 1); + this._numTris += (indexCount - 2) * Math.max(inputAssembler.instanceCount, 1); break; } } diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index 016844cc0d..56b3451f9e 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -2207,6 +2207,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web if (device.useVAO) { const vao = device.OES_vertex_array_object!; + const ia = device.ANGLE_instanced_arrays; // check vao let glVAO = gpuInputAssembler.glVAOs.get(gpuShader.glProgram!); @@ -2244,7 +2245,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web cache.glCurrentAttribLocs[glLoc] = true; gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset); - // gl.vertexAttribDivisor(glLoc, glAttrib.isInstanced ? 1 : 0); + if (ia) { ia.vertexAttribDivisorANGLE(glLoc, glAttrib.isInstanced ? 1 : 0); } } } } diff --git a/cocos/core/gfx/webgl/webgl-device.ts b/cocos/core/gfx/webgl/webgl-device.ts index b9c8ceb108..3e6a0dad30 100644 --- a/cocos/core/gfx/webgl/webgl-device.ts +++ b/cocos/core/gfx/webgl/webgl-device.ts @@ -1,3 +1,4 @@ +import sys from '../../platform/sys'; import { GFXBindingLayout, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXBuffer, IGFXBufferInfo } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; @@ -314,7 +315,6 @@ export class WebGLGFXDevice extends GFXDevice { this._features.fill(false); - // if (cc.sys.platform !== cc.sys.WECHAT_GAME) { if (this._WEBGL_color_buffer_float) { this._features[GFXFeature.COLOR_FLOAT] = true; } @@ -373,7 +373,7 @@ export class WebGLGFXDevice extends GFXDevice { this._features[GFXFeature.MSAA] = false; if (this._OES_vertex_array_object) { - this._useVAO = true; + if (sys.platform !== sys.WECHAT_GAME || sys.os !== sys.OS_IOS) { this._useVAO = true; } } console.info('RENDERER: ' + this._renderer); diff --git a/cocos/core/gfx/webgl/webgl-pipeline-state.ts b/cocos/core/gfx/webgl/webgl-pipeline-state.ts index 72fb9e7865..c8b0048f02 100644 --- a/cocos/core/gfx/webgl/webgl-pipeline-state.ts +++ b/cocos/core/gfx/webgl/webgl-pipeline-state.ts @@ -39,11 +39,12 @@ export class WebGLGFXPipelineState extends GFXPipelineState { this._primitive = info.primitive; this._shader = info.shader; - this._is = info.is; - this._rs = info.rs; - this._dss = info.dss; - this._bs = info.bs; + this._is = info.inputState; + this._rs = info.rasterizerState; + this._dss = info.depthStencilState; + this._bs = info.blendState; this._dynamicStates = info.dynamicStates || []; + this._hash = info.hash; this._layout = info.layout; this._renderPass = info.renderPass; @@ -51,9 +52,9 @@ export class WebGLGFXPipelineState extends GFXPipelineState { this._gpuPipelineState = { glPrimitive: WebGLPrimitives[info.primitive], gpuShader: (info.shader as WebGLGFXShader).gpuShader, - rs: info.rs, - dss: info.dss, - bs: info.bs, + rs: info.rasterizerState, + dss: info.depthStencilState, + bs: info.blendState, dynamicStates: (info.dynamicStates !== undefined ? info.dynamicStates : []), gpuLayout: (info.layout as WebGLGFXPipelineLayout).gpuPipelineLayout, gpuRenderPass: (info.renderPass as WebGLGFXRenderPass).gpuRenderPass, diff --git a/cocos/core/gfx/webgl2/webgl2-binding-layout.ts b/cocos/core/gfx/webgl2/webgl2-binding-layout.ts index 2ccfa44e34..3d6d3f06dc 100644 --- a/cocos/core/gfx/webgl2/webgl2-binding-layout.ts +++ b/cocos/core/gfx/webgl2/webgl2-binding-layout.ts @@ -25,7 +25,7 @@ export class WebGL2GFXBindingLayout extends GFXBindingLayout { const binding = info.bindings[i]; this._bindingUnits[i] = { binding: binding.binding, - type: binding.type, + type: binding.bindingType, name: binding.name, buffer: null, texView: null, @@ -41,7 +41,7 @@ export class WebGL2GFXBindingLayout extends GFXBindingLayout { const binding = info.bindings[i]; this._gpuBindingLayout.gpuBindings[i] = { binding: binding.binding, - type: binding.type, + type: binding.bindingType, name: binding.name, gpuBuffer: null, gpuTexView: null, diff --git a/cocos/core/gfx/webgl2/webgl2-buffer.ts b/cocos/core/gfx/webgl2/webgl2-buffer.ts index 6f36ba2036..fa1350296a 100644 --- a/cocos/core/gfx/webgl2/webgl2-buffer.ts +++ b/cocos/core/gfx/webgl2/webgl2-buffer.ts @@ -113,7 +113,7 @@ export class WebGL2GFXBuffer extends GFXBuffer { } else { buffSize = (buffer as ArrayBuffer).byteLength; } - if (this._bufferView) { + if (this._bufferView && buffer !== this._bufferView.buffer) { const view = new Uint8Array(buffer as ArrayBuffer, 0, size); this._bufferView.set(view, offset); } diff --git a/cocos/core/gfx/webgl2/webgl2-command-buffer.ts b/cocos/core/gfx/webgl2/webgl2-command-buffer.ts index 8571b99fd9..1d349dd850 100644 --- a/cocos/core/gfx/webgl2/webgl2-command-buffer.ts +++ b/cocos/core/gfx/webgl2/webgl2-command-buffer.ts @@ -348,16 +348,17 @@ export class WebGL2GFXCommandBuffer extends GFXCommandBuffer { this.cmdPackage.cmds.push(WebGL2Cmd.DRAW); ++this._numDrawCalls; + const indexCount = inputAssembler.indexCount || inputAssembler.vertexCount; if (this._curGPUPipelineState) { const glPrimitive = this._curGPUPipelineState.glPrimitive; switch (glPrimitive) { - case WebGL2RenderingContext.TRIANGLES: { - this._numTris += inputAssembler.indexCount / 3 * Math.max(inputAssembler.instanceCount, 1); + case 0x0004: { // WebGLRenderingContext.TRIANGLES + this._numTris += indexCount / 3 * Math.max(inputAssembler.instanceCount, 1); break; } - case WebGL2RenderingContext.TRIANGLE_STRIP: - case WebGL2RenderingContext.TRIANGLE_FAN: { - this._numTris += (inputAssembler.indexCount - 2) * Math.max(inputAssembler.instanceCount, 1); + case 0x0005: // WebGLRenderingContext.TRIANGLE_STRIP + case 0x0006: { // WebGLRenderingContext.TRIANGLE_FAN + this._numTris += (indexCount - 2) * Math.max(inputAssembler.instanceCount, 1); break; } } diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index a1dcfca0dc..9ce2e56c51 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -54,10 +54,10 @@ import { } from './webgl2-gpu-objects'; const WebGLWraps: GLenum[] = [ - WebGLRenderingContext.REPEAT, - WebGLRenderingContext.MIRRORED_REPEAT, - WebGLRenderingContext.CLAMP_TO_EDGE, - WebGLRenderingContext.CLAMP_TO_EDGE, + 0x2901, // WebGLRenderingContext.REPEAT + 0x8370, // WebGLRenderingContext.MIRRORED_REPEAT + 0x812F, // WebGLRenderingContext.CLAMP_TO_EDGE + 0x812F, // WebGLRenderingContext.CLAMP_TO_EDGE ]; const SAMPLES: number[] = [ @@ -1262,9 +1262,9 @@ export function WebGL2CmdFuncCreateSampler (device: WebGL2GFXDevice, gpuSampler: } if (gpuSampler.magFilter === GFXFilter.LINEAR || gpuSampler.magFilter === GFXFilter.ANISOTROPIC) { - gpuSampler.glMagFilter = WebGLRenderingContext.LINEAR; + gpuSampler.glMagFilter = gl.LINEAR; } else { - gpuSampler.glMagFilter = WebGLRenderingContext.NEAREST; + gpuSampler.glMagFilter = gl.NEAREST; } gpuSampler.glWrapS = WebGLWraps[gpuSampler.addressU]; diff --git a/cocos/core/gfx/webgl2/webgl2-gpu-objects.ts b/cocos/core/gfx/webgl2/webgl2-gpu-objects.ts index 2ee5d8348b..e527ef5097 100644 --- a/cocos/core/gfx/webgl2/webgl2-gpu-objects.ts +++ b/cocos/core/gfx/webgl2/webgl2-gpu-objects.ts @@ -118,11 +118,11 @@ export class WebGL2GPUSampler { public minLOD: number = 0; public maxLOD: number = 1000; - public glMinFilter: GLenum = WebGL2RenderingContext.NONE; - public glMagFilter: GLenum = WebGL2RenderingContext.NONE; - public glWrapS: GLenum = WebGL2RenderingContext.NONE; - public glWrapT: GLenum = WebGL2RenderingContext.NONE; - public glWrapR: GLenum = WebGL2RenderingContext.NONE; + public glMinFilter: GLenum = 0; + public glMagFilter: GLenum = 0; + public glWrapS: GLenum = 0; + public glWrapT: GLenum = 0; + public glWrapR: GLenum = 0; } export class WebGL2GPUInput { @@ -199,7 +199,7 @@ export class WebGL2GPUPipelineLayout { export class WebGL2GPUPipelineState { - public glPrimitive: GLenum = WebGL2RenderingContext.TRIANGLES; + public glPrimitive: GLenum = 0x0004; // WebGLRenderingContext.TRIANGLES public gpuShader: WebGL2GPUShader | null = null; public rs: GFXRasterizerState = new GFXRasterizerState(); public dss: GFXDepthStencilState = new GFXDepthStencilState(); diff --git a/cocos/core/gfx/webgl2/webgl2-pipeline-state.ts b/cocos/core/gfx/webgl2/webgl2-pipeline-state.ts index 0bedf804b4..f8ee9aad57 100644 --- a/cocos/core/gfx/webgl2/webgl2-pipeline-state.ts +++ b/cocos/core/gfx/webgl2/webgl2-pipeline-state.ts @@ -39,11 +39,12 @@ export class WebGL2GFXPipelineState extends GFXPipelineState { this._primitive = info.primitive; this._shader = info.shader; - this._is = info.is; - this._rs = info.rs; - this._dss = info.dss; - this._bs = info.bs; + this._is = info.inputState; + this._rs = info.rasterizerState; + this._dss = info.depthStencilState; + this._bs = info.blendState; this._dynamicStates = info.dynamicStates || []; + this._hash = info.hash; this._layout = info.layout; this._renderPass = info.renderPass; @@ -51,9 +52,9 @@ export class WebGL2GFXPipelineState extends GFXPipelineState { this._gpuPipelineState = { glPrimitive: WebGLPrimitives[info.primitive], gpuShader: (info.shader as WebGL2GFXShader).gpuShader, - rs: info.rs, - dss: info.dss, - bs: info.bs, + rs: info.rasterizerState, + dss: info.depthStencilState, + bs: info.blendState, dynamicStates: (info.dynamicStates !== undefined ? info.dynamicStates : []), gpuLayout: (info.layout as WebGL2GFXPipelineLayout).gpuPipelineLayout, gpuRenderPass: (info.renderPass as WebGL2GFXRenderPass).gpuRenderPass, diff --git a/cocos/core/gfx/webgl2/webgl2-sampler.ts b/cocos/core/gfx/webgl2/webgl2-sampler.ts index e40fd63b44..7e225f5947 100644 --- a/cocos/core/gfx/webgl2/webgl2-sampler.ts +++ b/cocos/core/gfx/webgl2/webgl2-sampler.ts @@ -84,11 +84,11 @@ export class WebGL2GFXSampler extends GFXSampler { minLOD: this._state.minLOD, maxLOD: this._state.maxLOD, - glMinFilter: WebGL2RenderingContext.NONE, - glMagFilter: WebGL2RenderingContext.NONE, - glWrapS: WebGL2RenderingContext.NONE, - glWrapT: WebGL2RenderingContext.NONE, - glWrapR: WebGL2RenderingContext.NONE, + glMinFilter: 0, + glMagFilter: 0, + glWrapS: 0, + glWrapT: 0, + glWrapR: 0, }; WebGL2CmdFuncCreateSampler(this._device as WebGL2GFXDevice, this._gpuSampler); diff --git a/cocos/core/pipeline/batched-buffer.ts b/cocos/core/pipeline/batched-buffer.ts index cbda7d804f..2c0e7696a7 100644 --- a/cocos/core/pipeline/batched-buffer.ts +++ b/cocos/core/pipeline/batched-buffer.ts @@ -9,31 +9,29 @@ import { GFXPipelineState } from '../gfx/pipeline-state'; import { Mat4 } from '../math'; import { Pass } from '../renderer'; import { SubModel } from '../renderer/scene/submodel'; -import { IRenderObject, UBOLocal, UniformBinding } from './define'; +import { IRenderObject, UBOLocalBatched } from './define'; export interface IBatchedItem { vbs: GFXBuffer[]; + vbDatas: Uint8Array[]; vbIdx: GFXBuffer; + vbIdxData: Float32Array; vbCount: number; mergeCount: number; ia: GFXInputAssembler; - uboLocal: UBOLocal; + ubo: GFXBuffer; + uboData: UBOLocalBatched; + pso: GFXPipelineState; } +const _localBatched = new UBOLocalBatched(); + export class BatchedBuffer { public batches: IBatchedItem[] = []; - public pso: GFXPipelineState | null = null; - public ubo: GFXBuffer; public pass: Pass; - private _limitCount = 10; constructor (pass: Pass) { this.pass = pass; - this.ubo = pass.device.createBuffer({ - usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, - memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: UBOLocal.SIZE, - }); } public destroy () { @@ -44,24 +42,22 @@ export class BatchedBuffer { } batch.vbIdx.destroy(); batch.ia.destroy(); + batch.ubo.destroy(); } this.batches.splice(0); - this.pso = null; - this.ubo.destroy(); } - public merge (subModel: SubModel, ro: IRenderObject) { + public merge (subModel: SubModel, ro: IRenderObject, pso: GFXPipelineState) { const flatBuffers = subModel.subMeshData.flatBuffers; - if (flatBuffers.length === 0) { - return ; - } + if (flatBuffers.length === 0) { return; } let vbSize = 0; let vbIdxSize = 0; const vbCount = flatBuffers[0].count; + const bindingLayout = pso.pipelineLayout.layouts[0]; let isBatchExist = false; for (let i = 0; i < this.batches.length; ++i) { const batch = this.batches[i]; - if (batch.vbs.length === flatBuffers.length && batch.mergeCount <= this._limitCount) { + if (batch.vbs.length === flatBuffers.length && batch.mergeCount < UBOLocalBatched.BATCHING_COUNT) { isBatchExist = true; for (let j = 0; j < batch.vbs.length; ++j) { const vb = batch.vbs[j]; @@ -75,27 +71,43 @@ export class BatchedBuffer { for (let j = 0; j < batch.vbs.length; ++j) { const flatBuff = flatBuffers[j]; const batchVB = batch.vbs[j]; + let vbBuf = batch.vbDatas[j]; vbSize = (vbCount + batch.vbCount) * flatBuff.stride; if (vbSize > batchVB.size) { batchVB.resize(vbSize); + vbBuf = batch.vbDatas[j] = new Uint8Array(batchVB.bufferView!.buffer); } - batchVB.update(flatBuff.buffer, batch.vbCount * flatBuff.stride); + vbBuf.set(flatBuff.buffer, batch.vbCount * flatBuff.stride); } vbIdxSize = (vbCount + batch.vbCount) * 4; if (vbIdxSize > batch.vbIdx.size) { batch.vbIdx.resize(vbIdxSize); + batch.vbIdxData = new Float32Array(batch.vbIdx.bufferView!.buffer); + } + + const start = batch.vbCount; + const end = start + vbCount; + const vbIdxBuf = batch.vbIdxData; + const mergeCount = batch.mergeCount; + if (vbIdxBuf[start] !== mergeCount || vbIdxBuf[end - 1] !== mergeCount) { + for (let j = start; j < end; j++) { + vbIdxBuf[j] = mergeCount; + } } - const vbIdxView = new Float32Array(flatBuffers[0].count); - vbIdxView.fill(batch.mergeCount); - batch.vbIdx.update(vbIdxView.buffer, batch.vbCount * 4); // update world matrix - Mat4.toArray(batch.uboLocal.view, ro.model.transform.worldMatrix, UBOLocal.MAT_WORLDS_OFFSET + batch.mergeCount * 16); + Mat4.toArray(batch.uboData.view, ro.model.transform.worldMatrix, UBOLocalBatched.MAT_WORLDS_OFFSET + batch.mergeCount * 16); + if (!batch.mergeCount && batch.pso !== pso) { + bindingLayout.bindBuffer(UBOLocalBatched.BLOCK.binding, batch.ubo); + bindingLayout.update(); + batch.pso = pso; + } ++batch.mergeCount; batch.vbCount += vbCount; batch.ia.vertexCount += vbCount; + return; } } @@ -104,7 +116,8 @@ export class BatchedBuffer { const device = this.pass.device; // Create a new batch - const newVBs: GFXBuffer[] = []; + const vbs: GFXBuffer[] = []; + const vbDatas: Uint8Array[] = []; const totalVBS: GFXBuffer[] = []; for (let i = 0; i < flatBuffers.length; ++i) { const flatBuff = flatBuffers[i]; @@ -115,8 +128,9 @@ export class BatchedBuffer { stride: flatBuff.stride, flags: GFXBufferFlagBit.BAKUP_BUFFER, }); - newVB.update(flatBuff.buffer); - newVBs.push(newVB); + newVB.update(flatBuff.buffer.buffer); + vbs.push(newVB); + vbDatas.push(new Uint8Array(newVB.bufferView!.buffer)); totalVBS.push(newVB); } @@ -131,6 +145,7 @@ export class BatchedBuffer { vbIndices.fill(0); vbIdx.update(vbIndices); totalVBS.push(vbIdx); + const vbIdxData = new Float32Array(vbIdx.bufferView!.buffer); const attributes = subModel.inputAssembler!.attributes; const attrs = new Array(attributes.length + 1); @@ -138,7 +153,7 @@ export class BatchedBuffer { attrs[a] = attributes[a]; } attrs[attributes.length] = { - name: 'a_index', + name: 'a_dyn_batch_id', format: GFXFormat.R32F, stream: flatBuffers.length, }; @@ -148,27 +163,22 @@ export class BatchedBuffer { vertexBuffers: totalVBS, }); - const newBatch: IBatchedItem = { - vbs: newVBs, - vbIdx, - vbCount, + const ubo = this.pass.device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: UBOLocalBatched.SIZE, + }); + + bindingLayout.bindBuffer(UBOLocalBatched.BLOCK.binding, ubo); + bindingLayout.update(); + + const uboData = new UBOLocalBatched(); + Mat4.toArray(uboData.view, ro.model.transform.worldMatrix, UBOLocalBatched.MAT_WORLDS_OFFSET); + + this.batches.push({ mergeCount: 1, - ia, - uboLocal: new UBOLocal(), - }; - - // newBatch.subModels.push(subModel); - - Mat4.toArray(newBatch.uboLocal.view, ro.model.transform.worldMatrix, UBOLocal.MAT_WORLDS_OFFSET); - - this.batches.push(newBatch); - this.pass.bindBuffer(UniformBinding.UBO_LOCAL, this.ubo); - this.pass.update(); - if (!this.pso) { - this.pso = subModel.psos![this.pass.idxInTech]; - const bindingLayout = this.pso.pipelineLayout.layouts[0]; - bindingLayout.update(); - } + vbs, vbDatas, vbIdx, vbIdxData, vbCount, ia, ubo, uboData, pso, + }); } public clear () { @@ -179,4 +189,11 @@ export class BatchedBuffer { batch.ia.vertexCount = 0; } } + + public clearUBO () { + for (let i = 0; i < this.batches.length; ++i) { + const batch = this.batches[i]; + batch.ubo.update(_localBatched.view.buffer); + } + } } diff --git a/cocos/core/pipeline/define.ts b/cocos/core/pipeline/define.ts index 92ea8be9ae..3a02500e36 100644 --- a/cocos/core/pipeline/define.ts +++ b/cocos/core/pipeline/define.ts @@ -85,11 +85,10 @@ export enum UniformBinding { UBO_SHADOW = MAX_BINDING_SUPPORTED - 2, UBO_LOCAL = MAX_BINDING_SUPPORTED - 3, - UBO_LOCAL_BATCHED = MAX_BINDING_SUPPORTED - 4, - UBO_FORWARD_LIGHTS = MAX_BINDING_SUPPORTED - 5, - UBO_SKINNING_ANIMATION = MAX_BINDING_SUPPORTED - 6, - UBO_SKINNING_TEXTURE = MAX_BINDING_SUPPORTED - 7, - UBO_UI = MAX_BINDING_SUPPORTED - 8, + UBO_FORWARD_LIGHTS = MAX_BINDING_SUPPORTED - 4, + UBO_SKINNING_ANIMATION = MAX_BINDING_SUPPORTED - 5, + UBO_SKINNING_TEXTURE = MAX_BINDING_SUPPORTED - 6, + UBO_UI = MAX_BINDING_SUPPORTED - 7, // samplers SAMPLER_JOINTS = MAX_BINDING_SUPPORTED + 1, @@ -184,18 +183,15 @@ export const localBindingsDesc: Map = new Map { const phases: Map = new Map(); let phaseNum = 0; - return (phaseName: string) => { + return (phaseName: string | number) => { + if (typeof phaseName === 'number') { return phaseName; } if (!phases.has(phaseName)) { phases.set(phaseName, 1 << phaseNum); phaseNum++; diff --git a/cocos/core/pipeline/pipeline-funcs.ts b/cocos/core/pipeline/pipeline-funcs.ts index 7a92e3ca05..6452031973 100644 --- a/cocos/core/pipeline/pipeline-funcs.ts +++ b/cocos/core/pipeline/pipeline-funcs.ts @@ -9,11 +9,13 @@ import { IGFXColor } from '../gfx/define'; * SRGB颜色空间转换为线性空间。 * @param gamma SRGB颜色空间下的GAMMA值。 */ -export function SRGBToLinear (gamma: IGFXColor): IGFXColor { - const r = Math.pow(gamma.r, 2.2); - const g = Math.pow(gamma.g, 2.2); - const b = Math.pow(gamma.b, 2.2); - return { r, g, b, a: 1.0 }; +export function SRGBToLinear (out: IGFXColor, gamma: IGFXColor) { + // out.r = Math.pow(gamma.r, 2.2); + // out.g = Math.pow(gamma.g, 2.2); + // out.b = Math.pow(gamma.b, 2.2); + out.r = gamma.r * gamma.r; + out.g = gamma.g * gamma.g; + out.b = gamma.b * gamma.b; } /** @@ -21,9 +23,11 @@ export function SRGBToLinear (gamma: IGFXColor): IGFXColor { * 线性空间转换为SRGB颜色空间。 * @param linear 线性空间下的颜色值。 */ -export function LinearToSRGB (linear: IGFXColor): IGFXColor { - const r = Math.pow(linear.r, 0.454545); - const g = Math.pow(linear.g, 0.454545); - const b = Math.pow(linear.b, 0.454545); - return { r, g, b, a: 1.0 }; +export function LinearToSRGB (out: IGFXColor, linear: IGFXColor) { + // out.r = Math.pow(linear.r, 0.454545); + // out.g = Math.pow(linear.g, 0.454545); + // out.b = Math.pow(linear.b, 0.454545); + out.r = Math.sqrt(linear.r); + out.g = Math.sqrt(linear.g); + out.b = Math.sqrt(linear.b); } diff --git a/cocos/core/pipeline/ppfx/tonemap-stage.ts b/cocos/core/pipeline/ppfx/tonemap-stage.ts index cb75e14d82..fa41ab09dd 100644 --- a/cocos/core/pipeline/ppfx/tonemap-stage.ts +++ b/cocos/core/pipeline/ppfx/tonemap-stage.ts @@ -3,12 +3,16 @@ */ import { GFXBindingLayout } from '../../gfx/binding-layout'; -import { GFXClearFlag, GFXCommandBufferType } from '../../gfx/define'; +import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { GFXClearFlag, GFXCommandBufferType, IGFXColor } from '../../gfx/define'; import { UBOGlobal } from '../define'; import { RenderFlow } from '../render-flow'; import { IRenderStageInfo, RenderStage } from '../render-stage'; import { RenderView } from '../render-view'; +const colors: IGFXColor[] = [ { r: 0, g: 0, b: 0, a: 1 } ]; +const bufs: GFXCommandBuffer[] = []; + /** * @zh * 色调映射渲染阶段。 @@ -89,7 +93,7 @@ export class ToneMapStage extends RenderStage { this._cmdBuff.begin(); this._cmdBuff.beginRenderPass(framebuffer, this._renderArea, - GFXClearFlag.ALL, [{ r: 0.0, g: 0.0, b: 0.0, a: 1.0 }], 1.0, 0); + GFXClearFlag.ALL, colors, 1.0, 0); this._cmdBuff.bindPipelineState(this._pso!); this._cmdBuff.bindBindingLayout(this._pso!.pipelineLayout.layouts[0]); this._cmdBuff.bindInputAssembler(this._pipeline.quadIA); @@ -98,7 +102,8 @@ export class ToneMapStage extends RenderStage { this._cmdBuff.end(); } - this._device.queue.submit([this._cmdBuff!]); + bufs[0] = this._cmdBuff!; + this._device.queue.submit(bufs); // this._pipeline.swapFBOs(); } diff --git a/cocos/core/pipeline/render-batched-queue.ts b/cocos/core/pipeline/render-batched-queue.ts index 0419d0d0e9..61d13ca4e7 100644 --- a/cocos/core/pipeline/render-batched-queue.ts +++ b/cocos/core/pipeline/render-batched-queue.ts @@ -29,7 +29,7 @@ export class RenderBatchedQueue { * 清空渲染队列。 */ public clear () { - for (const batchedBuff of this.queue.values()){ + for (const batchedBuff of this.queue.values()) { batchedBuff.clear(); } this.queue.clear(); @@ -40,15 +40,18 @@ export class RenderBatchedQueue { * 记录命令缓冲。 */ public recordCommandBuffer (cmdBuff: GFXCommandBuffer) { - for (const batchedBuffer of this.queue.values()){ - if (batchedBuffer.pso) { - cmdBuff.bindPipelineState(batchedBuffer.pso); - cmdBuff.bindBindingLayout(batchedBuffer.pso.pipelineLayout.layouts[0]); - } - + for (const batchedBuffer of this.queue.values()) { + let boundPSO = false; for (let b = 0; b < batchedBuffer.batches.length; ++b) { const batch = batchedBuffer.batches[b]; - batchedBuffer.ubo.update(batch.uboLocal.view); + if (!batch.mergeCount) { continue; } + for (let v = 0; v < batch.vbs.length; ++v) { + batch.vbs[v].update(batch.vbDatas[v]); + } + batch.vbIdx.update(batch.vbIdxData.buffer); + batch.ubo.update(batch.uboData.view); + if (!boundPSO) { cmdBuff.bindPipelineState(batch.pso); boundPSO = true; } + cmdBuff.bindBindingLayout(batch.pso.pipelineLayout.layouts[0]); cmdBuff.bindInputAssembler(batch.ia); cmdBuff.draw(batch.ia); } diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index 19f35c3c2c..100ff1aa2a 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -1128,6 +1128,8 @@ export abstract class RenderPipeline { // update UBOGlobal fv[UBOGlobal.TIME_OFFSET] = this._root.cumulativeTime; + fv[UBOGlobal.TIME_OFFSET + 1] = this._root.frameTime; + fv[UBOGlobal.TIME_OFFSET + 2] = cc.director.getTotalFrames(); fv[UBOGlobal.SCREEN_SIZE_OFFSET] = device.width; fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = device.height; @@ -1251,7 +1253,7 @@ export abstract class RenderPipeline { } if (planarShadows.enabled) { - planarShadows.updateCommandBuffers(); + planarShadows.updateCommandBuffers(camera.frustum); } } diff --git a/cocos/core/pipeline/render-queue.ts b/cocos/core/pipeline/render-queue.ts index 07a9763b84..f863a67699 100644 --- a/cocos/core/pipeline/render-queue.ts +++ b/cocos/core/pipeline/render-queue.ts @@ -5,6 +5,7 @@ import { GFXCommandBuffer } from '../gfx/command-buffer'; import { CachedArray } from '../memop/cached-array'; import { IRenderObject, IRenderPass, IRenderQueueDesc } from './define'; +import { getPhaseID } from './pass-phase'; /** * @en diff --git a/cocos/core/pipeline/ui/ui-stage.ts b/cocos/core/pipeline/ui/ui-stage.ts index dd6a52fd58..a693bbf094 100644 --- a/cocos/core/pipeline/ui/ui-stage.ts +++ b/cocos/core/pipeline/ui/ui-stage.ts @@ -3,7 +3,7 @@ */ import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXClearFlag, GFXCommandBufferType } from '../../gfx/define'; +import { GFXCommandBufferType, IGFXColor } from '../../gfx/define'; import { getPhaseID } from '../pass-phase'; import { RenderFlow } from '../render-flow'; import { RenderQueue, transparentCompareFn } from '../render-queue'; @@ -11,6 +11,7 @@ import { IRenderStageInfo, RenderStage } from '../render-stage'; import { RenderView } from '../render-view'; const bufs: GFXCommandBuffer[] = []; +const colors: IGFXColor[] = []; /** * @zh @@ -88,9 +89,11 @@ export class UIStage extends RenderStage { this._renderArea.width = vp.width * camera.width; this._renderArea.height = vp.height * camera.height; + colors[0] = camera.clearColor; + cmdBuff.begin(); cmdBuff.beginRenderPass(framebuffer, this._renderArea, - camera.clearFlag, [camera.clearColor], camera.clearDepth, camera.clearStencil); + camera.clearFlag, colors, camera.clearDepth, camera.clearStencil); cmdBuff.execute(this._uiQueue.cmdBuffs.array, this._uiQueue.cmdBuffCount); diff --git a/cocos/core/platform/SubContextView.ts b/cocos/core/platform/SubContextView.ts index ccb2e97128..6cb0a5fb37 100644 --- a/cocos/core/platform/SubContextView.ts +++ b/cocos/core/platform/SubContextView.ts @@ -1,3 +1,27 @@ +/* + Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ import { Component } from '../components/component'; import { property, ccclass, menu, executionOrder } from '../data/class-decorator'; @@ -34,7 +58,9 @@ import { Rect } from '../math'; @executionOrder(110) @menu('Components/SubContextView') export class SubContextView extends Component { - @property + @property({ + tooltip:'帧数', + }) get fps (){ return this._fps; } @@ -47,7 +73,7 @@ export class SubContextView extends Component { this._updateSubContextFrameRate(); } - @property({ type: Number }) + @property private _fps = 60; private _sprite: SpriteComponent | null; private _imageAsset: ImageAsset; diff --git a/cocos/core/platform/event-manager/event-listener.ts b/cocos/core/platform/event-manager/event-listener.ts index c3171d0fa8..9c6c3c4da7 100644 --- a/cocos/core/platform/event-manager/event-listener.ts +++ b/cocos/core/platform/event-manager/event-listener.ts @@ -38,7 +38,7 @@ export interface IEventListenerCreateInfo { [x: string]: any; } -export interface ILinstenerMask { +export interface IListenerMask { index: number; node: INode; } @@ -148,7 +148,7 @@ export class EventListener { // hack: How to solve the problem of uncertain attribute // callback's this object public owner: Object | null = null; - public mask: ILinstenerMask | null = null; + public mask: IListenerMask | null = null; public _previousIn?: boolean = false; public _target: any = null; diff --git a/cocos/core/platform/sys.ts b/cocos/core/platform/sys.ts index 26be9add06..4578243431 100644 --- a/cocos/core/platform/sys.ts +++ b/cocos/core/platform/sys.ts @@ -762,7 +762,13 @@ else { osVersion = uaResult[2] || ''; osMainVersion = parseInt(osVersion) || 0; } - else if (/(iPhone|iPad|iPod)/.exec(nav.platform)) { + // refer to https://github.com/cocos-creator/engine/pull/5542 , thanks for contribition from @krapnikkk + // ipad OS 13 safari identifies itself as "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko)" + // so use maxTouchPoints to check whether it's desktop safari or not. + // reference: https://stackoverflow.com/questions/58019463/how-to-detect-device-name-in-safari-on-ios-13-while-it-doesnt-show-the-correct + // FIXME: should remove it when touch-enabled mac are available + // TODO: due to compatibility issues, it is still determined to be ios, and a new operating system type ipados may be added later? + else if (/(iPhone|iPad|iPod)/.exec(nav.platform) || (nav.platform === 'MacIntel' && nav.maxTouchPoints && nav.maxTouchPoints > 1)) { iOS = true; osVersion = ''; osMainVersion = 0; @@ -920,7 +926,6 @@ else { else if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { _supportWebGL = true; } - // @ts-ignore else if (win.WebGLRenderingContext) { // @ts-ignore if (create3DContext(document.createElement('CANVAS'))) { diff --git a/cocos/core/primitive/utils.ts b/cocos/core/primitive/utils.ts index acba94ae4c..1a3159e377 100644 --- a/cocos/core/primitive/utils.ts +++ b/cocos/core/primitive/utils.ts @@ -76,7 +76,7 @@ export function toWavefrontOBJ (primitive: IGeometry, scale = 1) { /** * @deprecated */ -export function normals (positions: number[], normals: number[], length = 1) { +export function normals (positions: number[], nms: number[], length = 1) { const verts = new Array(2 * positions.length); for (let i = 0; i < positions.length / 3; ++i) { @@ -89,9 +89,9 @@ export function normals (positions: number[], normals: number[], length = 1) { verts[i6 + 2] = positions[i3 + 2]; // line end - verts[i6 + 3] = positions[i3 + 0] + normals[i3 + 0] * length; - verts[i6 + 4] = positions[i3 + 1] + normals[i3 + 1] * length; - verts[i6 + 5] = positions[i3 + 2] + normals[i3 + 2] * length; + verts[i6 + 3] = positions[i3 + 0] + nms[i3 + 0] * length; + verts[i6 + 4] = positions[i3 + 1] + nms[i3 + 1] * length; + verts[i6 + 5] = positions[i3 + 2] + nms[i3 + 2] * length; } return verts; diff --git a/cocos/core/renderer/core/pass-utils.ts b/cocos/core/renderer/core/pass-utils.ts new file mode 100644 index 0000000000..aa4ca44004 --- /dev/null +++ b/cocos/core/renderer/core/pass-utils.ts @@ -0,0 +1,87 @@ +/* + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** + * @category material + */ + +import { GFXBindingType, GFXType } from '../../gfx/define'; +import { Mat3, Mat4, Vec2, Vec3, Vec4 } from '../../math'; + +const btMask = 0xf0000000; // 4 bits => 16 binding types +const typeMask = 0x0fc00000; // 6 bits => 64 types +const bindingMask = 0x003fc000; // 8 bits => 256 bindings +const offsetMask = 0x00003fff; // 14 bits => 4096 vectors + +export const genHandle = (bt: GFXBindingType, binding: number, type: GFXType, offset: number = 0) => + ((bt << 28) & btMask) | ((type << 22) & typeMask) | ((binding << 14) & bindingMask) | (offset & offsetMask); +export const getBindingTypeFromHandle = (handle: number) => (handle & btMask) >>> 28; +export const getTypeFromHandle = (handle: number) => (handle & typeMask) >>> 22; +export const getBindingFromHandle = (handle: number) => (handle & bindingMask) >>> 14; +export const getOffsetFromHandle = (handle: number) => (handle & offsetMask); +export const customizeType = (handle: number, type: GFXType) => (handle & ~typeMask) | ((type << 22) & typeMask); + +export const type2reader = { + [GFXType.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'), + [GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx], + [GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx), + [GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx), + [GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx), + [GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx], + [GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx), + [GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx), + [GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx), + [GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.fromArray(v, a, idx), + [GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.fromArray(v, a, idx), +}; + +export const type2writer = { + [GFXType.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'), + [GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, + [GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx), + [GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx), + [GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx), + [GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, + [GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx), + [GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx), + [GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx), + [GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.toArray(a, v, idx), + [GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.toArray(a, v, idx), +}; + +export const type2default = { + [GFXType.INT]: [0], + [GFXType.INT2]: [0, 0], + [GFXType.INT3]: [0, 0, 0], + [GFXType.INT4]: [0, 0, 0, 0], + [GFXType.FLOAT]: [0], + [GFXType.FLOAT2]: [0, 0], + [GFXType.FLOAT3]: [0, 0, 0], + [GFXType.FLOAT4]: [0, 0, 0, 0], + [GFXType.MAT3]: [1, 0, 0, 0, 1, 0, 0, 0, 1], + [GFXType.MAT4]: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + [GFXType.SAMPLER2D]: 'default-texture', + [GFXType.SAMPLER_CUBE]: 'default-cube-texture', +}; diff --git a/cocos/core/renderer/core/pass.ts b/cocos/core/renderer/core/pass.ts index 7094c62dab..b06b343bdc 100644 --- a/cocos/core/renderer/core/pass.ts +++ b/cocos/core/renderer/core/pass.ts @@ -28,26 +28,28 @@ */ import { builtinResMgr } from '../../3d/builtin/init'; -import { EffectAsset, IPassInfo, IPassStates, IPropertyInfo, IShaderInfo } from '../../assets/effect-asset'; +import { EffectAsset, IPassInfo, IPassStates, IPropertyInfo } from '../../assets/effect-asset'; import { TextureBase } from '../../assets/texture-base'; -import { GFXBindingLayout, IGFXBinding } from '../../gfx/binding-layout'; -import { GFXBuffer } from '../../gfx/buffer'; +import { GFXBindingLayout, IGFXBinding, IGFXBindingLayoutInfo } from '../../gfx/binding-layout'; +import { GFXBuffer, IGFXBufferInfo } from '../../gfx/buffer'; import { GFXBindingType, GFXBufferUsageBit, GFXDynamicState, GFXGetTypeSize, GFXMemoryUsageBit, GFXPrimitiveMode, GFXType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; -import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; +import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from '../../gfx/pipeline-layout'; import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, - GFXInputState, GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state'; + GFXInputState, GFXPipelineState, GFXRasterizerState, IGFXPipelineStateInfo } from '../../gfx/pipeline-state'; import { GFXRenderPass } from '../../gfx/render-pass'; import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; -import { Mat3, Mat4, Vec2, Vec3, Vec4 } from '../../math'; import { BatchedBuffer } from '../../pipeline/batched-buffer'; -import { isBuiltinBinding, RenderPassStage, RenderPriority, UBOLocal } from '../../pipeline/define'; +import { isBuiltinBinding, RenderPassStage, RenderPriority } from '../../pipeline/define'; import { getPhaseID } from '../../pipeline/pass-phase'; import { Root } from '../../root'; -import { programLib } from './program-lib'; +import { murmurhash2_32_gc } from '../../utils/murmurhash2_gc'; +import { customizeType, getBindingFromHandle, getBindingTypeFromHandle, + getOffsetFromHandle, getTypeFromHandle, type2default, type2reader, type2writer } from './pass-utils'; +import { IProgramInfo, programLib } from './program-lib'; import { samplerLib } from './sampler-lib'; export interface IDefineMap { [name: string]: number | boolean | string; } @@ -59,62 +61,7 @@ export interface IPassInfoFull extends IPassInfo { } export type PassOverrides = RecursivePartial; -const _type2writer = { - [GFXType.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'), - [GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, - [GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx), - [GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx), - [GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx), - [GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, - [GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx), - [GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx), - [GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx), - [GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.toArray(a, v, idx), - [GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.toArray(a, v, idx), -}; - -const _type2reader = { - [GFXType.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'), - [GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx], - [GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx), - [GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx), - [GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx), - [GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx], - [GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx), - [GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx), - [GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx), - [GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.fromArray(v, a, idx), - [GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.fromArray(v, a, idx), -}; - -export const _type2default = { - [GFXType.INT]: [0], - [GFXType.INT2]: [0, 0], - [GFXType.INT3]: [0, 0, 0], - [GFXType.INT4]: [0, 0, 0, 0], - [GFXType.FLOAT]: [0], - [GFXType.FLOAT2]: [0, 0], - [GFXType.FLOAT3]: [0, 0, 0], - [GFXType.FLOAT4]: [0, 0, 0, 0], - [GFXType.MAT3]: [1, 0, 0, 0, 1, 0, 0, 0, 1], - [GFXType.MAT4]: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], - [GFXType.SAMPLER2D]: 'default-texture', - [GFXType.SAMPLER_CUBE]: 'default-cube-texture', -}; - -const btMask = 0xf0000000; // 4 bits => 16 binding types -const typeMask = 0x0fc00000; // 6 bits => 64 types -const bindingMask = 0x003fc000; // 8 bits => 256 bindings -const offsetMask = 0x00003fff; // 14 bits => 4096 vectors -const genHandle = (bt: GFXBindingType, binding: number, type: GFXType, index: number = 0) => - ((bt << 28) & btMask) | ((type << 22) & typeMask) | ((binding << 14) & bindingMask) | (index & offsetMask); -const getBindingTypeFromHandle = (handle: number) => (handle & btMask) >>> 28; -const getTypeFromHandle = (handle: number) => (handle & typeMask) >>> 22; -const getBindingFromHandle = (handle: number) => (handle & bindingMask) >>> 14; -const getOffsetFromHandle = (handle: number) => (handle & offsetMask); -const customizeType = (handle: number, type: GFXType) => (handle & ~typeMask) | ((type << 22) & typeMask); - -interface IBlock { +export interface IBlock { buffer: ArrayBuffer; view: Float32Array; dirty: boolean; @@ -127,7 +74,7 @@ interface IPassResources { } interface IPassDynamics { - [type: string]: { + [type: number]: { dirty: boolean, value: number[], }; @@ -139,6 +86,48 @@ interface IEffectInfo { states: PassOverrides[]; } +interface IPSOHashInfo { + program: string; + defines: IDefineMap; + stage: RenderPassStage; + primitive: GFXPrimitiveMode; + rasterizerState: GFXRasterizerState; + depthStencilState: GFXDepthStencilState; + blendState: GFXBlendState; + dynamicStates: GFXDynamicState[]; +} + +const _bfInfo: IGFXBufferInfo = { + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: 0, + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, +}; + +const _blInfo: IGFXBindingLayoutInfo = { + bindings: null!, +}; + +const _plInfo: IGFXPipelineLayoutInfo = { + layouts: null!, +}; + +const _psoInfo: IGFXPipelineStateInfo & IPSOHashInfo = { + primitive: 0, + shader: null!, + inputState: new GFXInputState(), + rasterizerState: null!, + depthStencilState: null!, + blendState: null!, + dynamicStates: null!, + layout: null!, + renderPass: null!, + hash: 0, + + program: '', + defines: null!, + stage: 0, +}; + /** * @zh * 渲染 pass,储存实际描述绘制过程的各项资源。 @@ -179,6 +168,42 @@ export class Pass { return passes; } + public static fillinPipelineInfo (target: Pass, info: PassOverrides) { + if (info.priority !== undefined) { target._priority = info.priority; } + if (info.primitive !== undefined) { target._primitive = info.primitive; } + if (info.stage !== undefined) { target._stage = info.stage; } + if (info.dynamicStates !== undefined) { target._dynamicStates = info.dynamicStates as GFXDynamicState[]; } + if (info.customizations) { target._customizations = info.customizations as string[]; } + if (info.phase) { target._phase = getPhaseID(info.phase); } + + const bs = target._bs; + if (info.blendState) { + const bsInfo = Object.assign({}, info.blendState); + if (bsInfo.targets) { + bsInfo.targets.forEach((t, i) => Object.assign( + bs.targets[i] || (bs.targets[i] = new GFXBlendTarget()), t)); + } + delete bsInfo.targets; + Object.assign(bs, bsInfo); + } + Object.assign(target._rs, info.rasterizerState); + Object.assign(target._dss, info.depthStencilState); + } + + /** + * @zh + * 根据指定 PSO 信息计算 hash + * @param psoInfo 用于计算 PSO hash 的最小必要信息 + */ + public static getPSOHash (psoInfo: IPSOHashInfo) { + const shaderKey = programLib.getKey(psoInfo.program, psoInfo.defines); + let res = `${shaderKey},${psoInfo.stage},${psoInfo.primitive}`; + res += serializeBlendState(psoInfo.blendState); + res += serializeDepthStencilState(psoInfo.depthStencilState); + res += serializeRasterizerState(psoInfo.rasterizerState); + return murmurhash2_32_gc(res, 666); + } + protected static getOffsetFromHandle = getOffsetFromHandle; // internal resources protected _buffers: Record = {}; @@ -186,7 +211,7 @@ export class Pass { protected _textureViews: Record = {}; protected _resources: IPassResources[] = []; // internal data - protected _phase: number = 0; + protected _phase = getPhaseID('default'); protected _idxInTech = 0; protected _programName = ''; protected _priority: RenderPriority = RenderPriority.DEFAULT; @@ -201,7 +226,7 @@ export class Pass { protected _customizations: string[] = []; protected _handleMap: Record = {}; protected _blocks: IBlock[] = []; - protected _shaderInfo: IShaderInfo = null!; + protected _shaderInfo: IProgramInfo = null!; protected _defines: IDefineMap = {}; protected _properties: Record = {}; // external references @@ -227,41 +252,30 @@ export class Pass { this._properties = info.properties || this._properties; // pipeline state const device = this._device; - this._fillinPipelineInfo(info); - this._fillinPipelineInfo(info.states); - - for (const u of this._shaderInfo.blocks) { - if (isBuiltinBinding(u.binding)) { continue; } - const blockSize = u.members.reduce((s, m) => s + GFXGetTypeSize(m.type) * m.count, 0); + Pass.fillinPipelineInfo(this, info); + Pass.fillinPipelineInfo(this, info.states); + const blocks = this._shaderInfo.blocks; + for (let i = 0; i < blocks.length; i++) { + const { size, binding } = blocks[i]; + if (isBuiltinBinding(binding)) { continue; } // create gfx buffer resource - this._buffers[u.binding] = device.createBuffer({ - memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: Math.ceil(blockSize / 16) * 16, // https://bugs.chromium.org/p/chromium/issues/detail?id=988988 - usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, - }); + _bfInfo.size = Math.ceil(size / 16) * 16; // https://bugs.chromium.org/p/chromium/issues/detail?id=988988 + this._buffers[binding] = device.createBuffer(_bfInfo); // non-builtin UBO data pools, note that the effect compiler // guarantees these bindings to be consecutive, starting from 0 - const buffer = new ArrayBuffer(blockSize); - this._blocks[u.binding] = { buffer, dirty: false, view: new Float32Array(buffer) }; - - u.members.reduce((acc, cur) => { - // store handle map - this._handleMap[cur.name] = genHandle(GFXBindingType.UNIFORM_BUFFER, u.binding, cur.type, acc); - // proceed the counter - return acc + (GFXGetTypeSize(cur.type) >> 2) * cur.count; - }, 0); + const buffer = new ArrayBuffer(size); + this._blocks[binding] = { buffer, dirty: false, view: new Float32Array(buffer) }; } - // store indirect property handles - for (const name of Object.keys(this._properties)) { + // store handles + const directHandleMap = this._handleMap = this._shaderInfo.handleMap; + const indirectHandleMap: Record = {}; + for (const name in this._properties) { const prop = this._properties[name]; if (!prop.handleInfo) { continue; } - this._handleMap[name] = this.getHandle.apply(this, prop.handleInfo)!; - } - // store sampler handles - for (const u of this._shaderInfo.samplers) { - this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.binding, u.type); + indirectHandleMap[name] = this.getHandle.apply(this, prop.handleInfo)!; } + Object.assign(directHandleMap, indirectHandleMap); this.resetUBOs(); this.resetTextures(); @@ -286,8 +300,7 @@ export class Pass { * ``` */ public getHandle (name: string, offset = 0, targetType = GFXType.UNKNOWN): number | undefined { - let handle = this._handleMap[name]; - if (!handle) { return; } + let handle = this._handleMap[name]; if (!handle) { return; } if (targetType) { handle = customizeType(handle, targetType); } else if (offset) { handle = customizeType(handle, getTypeFromHandle(handle) - offset); } return handle + offset; @@ -315,7 +328,7 @@ export class Pass { const type = Pass.getTypeFromHandle(handle); const ofs = Pass.getOffsetFromHandle(handle); const block = this._blocks[binding]; - _type2writer[type](block.view, value, ofs); + type2writer[type](block.view, value, ofs); block.dirty = true; } @@ -330,7 +343,7 @@ export class Pass { const type = Pass.getTypeFromHandle(handle); const ofs = Pass.getOffsetFromHandle(handle); const block = this._blocks[binding]; - return _type2reader[type](block.view, out, ofs); + return type2reader[type](block.view, out, ofs); } /** @@ -347,7 +360,7 @@ export class Pass { let ofs = Pass.getOffsetFromHandle(handle); for (let i = 0; i < value.length; i++, ofs += stride) { if (value[i] === null) { continue; } - _type2writer[type](block.view, value[i], ofs); + type2writer[type](block.view, value[i], ofs); } block.dirty = true; } @@ -422,8 +435,8 @@ export class Pass { this._bs = new GFXBlendState(); this._dss = new GFXDepthStencilState(); this._rs = new GFXRasterizerState(); - this._fillinPipelineInfo(original); - this._fillinPipelineInfo(overrides); + Pass.fillinPipelineInfo(this, original); + Pass.fillinPipelineInfo(this, overrides); } /** @@ -482,7 +495,7 @@ export class Pass { const cur = u.members[i]; const inf = this._properties[cur.name]; const givenDefault = inf && inf.value; - const value = givenDefault ? givenDefault : _type2default[cur.type]; + const value = givenDefault ? givenDefault : type2default[cur.type]; const stride = GFXGetTypeSize(cur.type) >> 2; for (let j = 0; j < cur.count; j++) { block.view.set(value, ofs + j * stride); } ofs += stride * cur.count; @@ -499,7 +512,7 @@ export class Pass { for (const u of this._shaderInfo.samplers) { if (isBuiltinBinding(u.binding)) { continue; } const inf = this._properties[u.name]; - const texName = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; + const texName = inf && inf.value ? inf.value + '-texture' : type2default[u.type]; const texture = builtinResMgr.get(texName); const textureView = texture && texture.getGFXTextureView(); if (!textureView) { console.warn('illegal texture default value: ' + texName); continue; } @@ -519,46 +532,67 @@ export class Pass { * 尝试编译 shader 并获取相关资源引用。 * @param defineOverrides shader 预处理宏定义重载 */ - public tryCompile (defineOverrides?: IDefineMap) { - if (defineOverrides) { Object.assign(this._defines, defineOverrides); } + public tryCompile (defineOverrides?: IDefineMap, saveOverrides = true) { const pipeline = (cc.director.root as Root).pipeline; - if (!pipeline) { return false; } + if (!pipeline) { return null; } this._renderPass = pipeline.getRenderPass(this._stage); - if (!this._renderPass) { console.warn(`illegal pass stage.`); return false; } - this._shader = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline); - if (!this._shader) { console.warn(`create shader ${this._programName} failed`); return false; } - this._bindings = this._shaderInfo.blocks.reduce((acc, cur) => { - if (cur.defines.every((d) => this._defines[d])) { - acc.push({ name: cur.name, binding: cur.binding, type: GFXBindingType.UNIFORM_BUFFER }); + if (!this._renderPass) { console.warn(`illegal pass stage.`); return null; } + let defines = this._defines; + if (defineOverrides) { + if (saveOverrides) { Object.assign(this._defines, defineOverrides); } + else { Object.assign(defineOverrides, this._defines); defines = defineOverrides; } + } + const shader = programLib.getGFXShader(this._device, this._programName, defines, pipeline); + if (!shader) { console.warn(`create shader ${this._programName} failed`); return null; } + if (saveOverrides) { this._shader = shader; } + + const { blocks, samplers } = this._shaderInfo; + this._bindings.length = 0; + let lastBinding = -1; + blocks: + for (let i = 0; i < blocks.length; i++) { + const block = blocks[i]; + if (block.binding === lastBinding) { continue; } + for (let j = 0; j < block.defines.length; j++) { + if (!defines[block.defines[j]]) { continue blocks; } } - return acc; - }, [] as IGFXBinding[]).concat(this._shaderInfo.samplers.reduce((acc, cur) => { - if (cur.defines.every((d) => this._defines[d])) { - acc.push({ name: cur.name, binding: cur.binding, type: GFXBindingType.SAMPLER }); + lastBinding = block.binding; + this._bindings.push(block); + } + samplers: + for (let i = 0; i < samplers.length; i++) { + const sampler = samplers[i]; + if (sampler.binding === lastBinding) { continue; } + for (let j = 0; j < sampler.defines.length; j++) { + if (!defines[sampler.defines[j]]) { continue samplers; } } - return acc; - }, [] as IGFXBinding[])); - return true; + lastBinding = sampler.binding; + this._bindings.push(sampler); + } + return shader; } /** * @zh * 根据当前 pass 持有的信息创建 [[GFXPipelineState]]。 */ - public createPipelineState (): GFXPipelineState | null { + public createPipelineState (defineOverrides?: IDefineMap, stateOverrides?: IPassStates): GFXPipelineState | null { if ((!this._renderPass || !this._shader || !this._bindings.length) && !this.tryCompile()) { console.warn(`pass resources not complete, create PSO failed`); return null; } + let shader = this._shader!; + if (defineOverrides) { shader = this.tryCompile(defineOverrides, false)!; } // bind resources - const bindingLayout = this._device.createBindingLayout({ bindings: this._bindings }); - for (const b of Object.keys(this._buffers)) { + _blInfo.bindings = this._bindings; + const bindingLayout = this._device.createBindingLayout(_blInfo); + for (const b in this._buffers) { bindingLayout.bindBuffer(parseInt(b), this._buffers[b]); } - for (const s of Object.keys(this._samplers)) { + for (const s in this._samplers) { bindingLayout.bindSampler(parseInt(s), this._samplers[s]); } - for (const t of Object.keys(this._textureViews)) { + for (const t in this._textureViews) { bindingLayout.bindTextureView(parseInt(t), this._textureViews[t]); } // bind pipeline builtins @@ -575,20 +609,22 @@ export class Pass { if (info.sampler) { bindingLayout.bindSampler(info.samplerInfo!.binding, info.sampler); } bindingLayout.bindTextureView(info.samplerInfo!.binding, info.textureView!); } - + _plInfo.layouts = [bindingLayout]; + const pipelineLayout = this._device.createPipelineLayout(_plInfo); // create pipeline state - const pipelineLayout = this._device.createPipelineLayout({ layouts: [bindingLayout] }); - const pipelineState = this._device.createPipelineState({ - bs: this._bs, - dss: this._dss, - dynamicStates: this._dynamicStates, - is: new GFXInputState(), - layout: pipelineLayout, - primitive: this._primitive, - renderPass: this._renderPass!, - rs: this._rs, - shader: this._shader!, - }); + _psoInfo.primitive = stateOverrides && stateOverrides.primitive || this._primitive; + _psoInfo.shader = shader; + _psoInfo.rasterizerState = stateOverrides && stateOverrides.rasterizerState || this._rs; + _psoInfo.depthStencilState = stateOverrides && stateOverrides.depthStencilState || this._dss; + _psoInfo.blendState = stateOverrides && stateOverrides.blendState || this._bs; + _psoInfo.dynamicStates = stateOverrides && stateOverrides.dynamicStates || this._dynamicStates; + _psoInfo.layout = pipelineLayout; + _psoInfo.renderPass = this._renderPass!; + _psoInfo.program = this._programName; + _psoInfo.defines = defineOverrides || this._defines; + _psoInfo.stage = this._stage; + _psoInfo.hash = Pass.getPSOHash(_psoInfo); + const pipelineState = this._device.createPipelineState(_psoInfo); this._resources.push({ bindingLayout, pipelineLayout, pipelineState }); return pipelineState; } @@ -606,19 +642,6 @@ export class Pass { } } - /** - * @zh - * 返回这个 pass 的序列化信息,用于计算 hash。 - */ - public serializePipelineStates () { - const shaderKey = programLib.getKey(this._programName, this._defines); - let res = `${shaderKey},${this._stage},${this._primitive}`; - res += serializeBlendState(this._bs); - res += serializeDepthStencilState(this._dss); - res += serializeRasterizerState(this._rs); - return res; - } - /** * @zh * 创建合批缓冲。 @@ -629,91 +652,61 @@ export class Pass { } } - /** - * @zh - * 销毁合批缓冲。 - */ - public destroyBatchedBuffer () { - if (this._batchedBuffer) { - this._batchedBuffer.destroy(); - this._batchedBuffer = null; - } - } - /** * @zh * 清空合批缓冲。 */ public clearBatchedBuffer () { if (this._batchedBuffer) { - const uboLocal = new UBOLocal(); - this._batchedBuffer.ubo.update(uboLocal.view.buffer); + this._batchedBuffer.clearUBO(); } } - protected _fillinPipelineInfo (info: PassOverrides) { - if (info.priority !== undefined) { this._priority = info.priority; } - if (info.primitive !== undefined) { this._primitive = info.primitive; } - if (info.stage !== undefined) { this._stage = info.stage; } - if (info.dynamics !== undefined) { this._dynamicStates = info.dynamics as GFXDynamicState[]; } - if (info.customizations) { this._customizations = info.customizations as string[]; } - if (this._phase === 0) { - const phaseName = info.phase || 'default'; - this._phase = getPhaseID(phaseName); - } - - const bs = this._bs; - if (info.blendState) { - const bsInfo = Object.assign({}, info.blendState); - if (bsInfo.targets) { - bsInfo.targets.forEach((t, i) => Object.assign( - bs.targets[i] || (bs.targets[i] = new GFXBlendTarget()), t)); - } - delete bsInfo.targets; - Object.assign(bs, bsInfo); - } - Object.assign(this._rs, info.rasterizerState); - Object.assign(this._dss, info.depthStencilState); - } - - get device () { return this._device; } - get idxInTech () { return this._idxInTech; } - get programName () { return this._programName; } + // states get priority () { return this._priority; } get primitive () { return this._primitive; } get stage () { return this._stage; } - get phase () { return this._phase; } - get bindings () { return this._bindings; } - get blendState () { return this._bs; } - get depthStencilState () { return this._dss; } get rasterizerState () { return this._rs; } - get dynamics () { return this._dynamics; } + get depthStencilState () { return this._dss; } + get blendState () { return this._bs; } + get dynamicStates () { return this._dynamicStates; } get customizations () { return this._customizations; } - get shader (): GFXShader { return this._shader!; } - get batchedBuffer (): BatchedBuffer | null { return this._batchedBuffer; } + get phase () { return this._phase; } + // infos get shaderInfo () { return this._shaderInfo; } + get program () { return this._programName; } get properties () { return this._properties; } + get defines () { return this._defines; } + get idxInTech () { return this._idxInTech; } + // resources + get device () { return this._device; } + get bindings () { return this._bindings; } + get shader () { return this._shader!; } + get renderPass () { return this._renderPass!; } + get dynamics () { return this._dynamics; } + get batchedBuffer () { return this._batchedBuffer; } + get blocks () { return this._blocks; } } -const serializeBlendState = (bs: GFXBlendState) => { +function serializeBlendState (bs: GFXBlendState) { let res = `,bs,${bs.isA2C},${bs.blendColor}`; for (const t of bs.targets) { res += `,bt,${t.blend},${t.blendEq},${t.blendAlphaEq},${t.blendColorMask}`; res += `,${t.blendSrc},${t.blendDst},${t.blendSrcAlpha},${t.blendDstAlpha}`; } return res; -}; +} -const serializeRasterizerState = (rs: GFXRasterizerState) => { +function serializeRasterizerState (rs: GFXRasterizerState) { const res = `,rs,${rs.cullMode},${rs.depthBias},${rs.isFrontFaceCCW}`; return res; -}; +} -const serializeDepthStencilState = (dss: GFXDepthStencilState) => { +function serializeDepthStencilState (dss: GFXDepthStencilState) { let res = `,dss,${dss.depthTest},${dss.depthWrite},${dss.depthFunc}`; res += `,${dss.stencilTestFront},${dss.stencilFuncFront},${dss.stencilRefFront},${dss.stencilReadMaskFront}`; res += `,${dss.stencilFailOpFront},${dss.stencilZFailOpFront},${dss.stencilPassOpFront},${dss.stencilWriteMaskFront}`; res += `,${dss.stencilTestBack},${dss.stencilFuncBack},${dss.stencilRefBack},${dss.stencilReadMaskBack}`; res += `,${dss.stencilFailOpBack},${dss.stencilZFailOpBack},${dss.stencilPassOpBack},${dss.stencilWriteMaskBack}`; return res; -}; +} diff --git a/cocos/core/renderer/core/program-lib.ts b/cocos/core/renderer/core/program-lib.ts index 079e5c657e..30f584ecb6 100644 --- a/cocos/core/renderer/core/program-lib.ts +++ b/cocos/core/renderer/core/program-lib.ts @@ -27,33 +27,45 @@ * @category material */ -import { IBuiltinInfo, IDefineInfo, IShaderInfo } from '../../assets/effect-asset'; -import { GFXBindingType, GFXShaderType } from '../../gfx/define'; +import { IBlockInfo, IBuiltinInfo, IDefineInfo, ISamplerInfo, IShaderInfo } from '../../assets/effect-asset'; +import { IGFXBinding } from '../../gfx/binding-layout'; +import { GFXBindingType, GFXGetTypeSize, GFXShaderType } from '../../gfx/define'; import { GFXAPI, GFXDevice } from '../../gfx/device'; -import { GFXShader } from '../../gfx/shader'; +import { GFXShader, GFXUniformBlock } from '../../gfx/shader'; import { IInternalBindingDesc, localBindingsDesc } from '../../pipeline/define'; import { RenderPipeline } from '../../pipeline/render-pipeline'; import { IDefineMap } from './pass'; +import { genHandle } from './pass-utils'; -let _shdID = 0; interface IDefineRecord extends IDefineInfo { _map: (value: any) => number; _offset: number; } -interface IProgramInfo extends IShaderInfo { - id: number; +interface IBlockInfoRT extends IBlockInfo, IGFXBinding { + size: number; +} +interface ISamplerInfoRT extends ISamplerInfo, IGFXBinding { +} +export interface IProgramInfo extends IShaderInfo { + blocks: IBlockInfoRT[]; + samplers: ISamplerInfoRT[]; defines: IDefineRecord[]; + handleMap: Record; + offsets: number[][]; globalsInited: boolean; localsInited: boolean; } export interface IMacroInfo { name: string; value: string; + isDefault: boolean; } -const getBitCount = (cnt: number) => Math.ceil(Math.log2(Math.max(cnt, 2))); +function getBitCount (cnt: number) { + return Math.ceil(Math.log2(Math.max(cnt, 2))); +} -const mapDefine = (info: IDefineInfo, def: number | string | boolean) => { +function mapDefine (info: IDefineInfo, def: number | string | boolean) { switch (info.type) { case 'boolean': return def as boolean ? '1' : '0'; case 'string': return def !== undefined ? def as string : info.options![0]; @@ -61,39 +73,70 @@ const mapDefine = (info: IDefineInfo, def: number | string | boolean) => { } console.warn(`unknown define type '${info.type}'`); return '-1'; // should neven happen -}; +} -const prepareDefines = (defs: IDefineMap, tDefs: IDefineInfo[]) => { +function prepareDefines (defs: IDefineMap, tDefs: IDefineInfo[]) { const macros: IMacroInfo[] = []; for (const tmpl of tDefs) { const name = tmpl.name; - const value = mapDefine(tmpl, defs[name]); - macros.push({ name, value }); + const v = defs[name]; + const value = mapDefine(tmpl, v); + const isDefault = !v || v === '0'; + macros.push({ name, value, isDefault }); } return macros; -}; +} -const getShaderInstanceName = (name: string, macros: IMacroInfo[]) => { - return name + macros.reduce((acc, cur) => cur.value !== '0' ? `${acc}|${cur.name}${cur.value}` : acc, ''); -}; +function getShaderInstanceName (name: string, macros: IMacroInfo[]) { + return name + macros.reduce((acc, cur) => cur.isDefault ? acc : `${acc}|${cur.name}${cur.value}`, ''); +} -const insertBuiltinBindings = (tmpl: IProgramInfo, source: Map, type: string) => { +function insertBuiltinBindings (tmpl: IProgramInfo, source: Map, type: string) { const target = tmpl.builtins[type] as IBuiltinInfo; const blocks = tmpl.blocks; for (const b of target.blocks) { const info = source.get(b.name); if (!info || info.type !== GFXBindingType.UNIFORM_BUFFER) { console.warn(`builtin UBO '${b.name}' not available!`); continue; } - const builtin = Object.assign({ defines: b.defines }, info.blockInfo); + const builtin: IBlockInfoRT = Object.assign({ + defines: b.defines, + size: getSize(info.blockInfo!), + bindingType: GFXBindingType.UNIFORM_BUFFER, + }, info.blockInfo!); blocks.push(builtin); } const samplers = tmpl.samplers; for (const s of target.samplers) { const info = source.get(s.name); if (!info || info.type !== GFXBindingType.SAMPLER) { console.warn(`builtin sampler '${s.name}' not available!`); continue; } - const builtin = Object.assign({ defines: s.defines }, info.samplerInfo); + const builtin = Object.assign({ defines: s.defines, bindingType: GFXBindingType.SAMPLER }, info.samplerInfo); samplers.push(builtin); } -}; +} + +function getSize (block: GFXUniformBlock) { + return block.members.reduce((s, m) => s + GFXGetTypeSize(m.type) * m.count, 0); +} + +function genHandles (tmpl: IProgramInfo) { + const handleMap: Record = {}; + // block member handles + for (let i = 0; i < tmpl.blocks.length; i++) { + const block = tmpl.blocks[i]; + const members = block.members; + let offset = 0; + for (let j = 0; j < members.length; j++) { + const uniform = members[j]; + handleMap[uniform.name] = genHandle(GFXBindingType.UNIFORM_BUFFER, block.binding, uniform.type, offset); + offset += (GFXGetTypeSize(uniform.type) >> 2) * uniform.count; + } + } + // sampler handles + for (let i = 0; i < tmpl.samplers.length; i++) { + const sampler = tmpl.samplers[i]; + handleMap[sampler.name] = genHandle(GFXBindingType.SAMPLER, sampler.binding, sampler.type); + } + return handleMap; +} /** * @zh @@ -111,31 +154,11 @@ class ProgramLib { /** * @zh * 根据 effect 信息注册 shader 模板。 - * @example - * ```typescript - * // this object is auto-generated from your actual shaders - * let program = { - * name: 'foobar', - * glsl1: { vert: '...', frag: '...' }, - * glsl3: { vert: '...', frag: '...' }, - * defines: [ - * { name: 'shadow', type: 'boolean', defines: [] }, - * { name: 'lightCount', type: 'number', range: [1, 4], defines: [] } - * ], - * blocks: [{ name: 'Constants', binding: 0, members: [ - * { name: 'color', type: 'vec4', count: 1, size: 16 }], defines: [], size: 16 } - * ], - * samplers: [], - * }; - * programLib.define(program); - * ``` */ public define (prog: IShaderInfo) { - const cur = this._templates[prog.name]; - if (cur && cur.hash === prog.hash) { return; } - const tmpl = Object.assign({ id: ++_shdID }, prog) as IProgramInfo; - if (!tmpl.localsInited) { insertBuiltinBindings(tmpl, localBindingsDesc, 'locals'); tmpl.localsInited = true; } - + const curTmpl = this._templates[prog.name]; + if (curTmpl && curTmpl.hash === prog.hash) { return; } + const tmpl = prog as IProgramInfo; // calculate option mask offset let offset = 0; for (const def of tmpl.defines) { @@ -153,6 +176,10 @@ class ProgramLib { def._offset = offset; offset += cnt; } + tmpl.blocks.forEach((b) => (b.size = getSize(b), b.bindingType = GFXBindingType.UNIFORM_BUFFER)); + tmpl.samplers.forEach((s) => (s.bindingType = GFXBindingType.SAMPLER)); + tmpl.handleMap = genHandles(tmpl); + if (!tmpl.localsInited) { insertBuiltinBindings(tmpl, localBindingsDesc, 'locals'); tmpl.localsInited = true; } // store it this._templates[prog.name] = tmpl; } @@ -190,7 +217,7 @@ class ProgramLib { const offset = tmplDef._offset; key |= mapped << offset; } - return `${key.toString(16)}|${tmpl.id}`; + return `${key.toString(16)}|${tmpl.hash}`; } /** diff --git a/cocos/core/renderer/core/sampler-lib.ts b/cocos/core/renderer/core/sampler-lib.ts index 4219b82d41..7a7afd5ab8 100644 --- a/cocos/core/renderer/core/sampler-lib.ts +++ b/cocos/core/renderer/core/sampler-lib.ts @@ -54,11 +54,12 @@ const defaultInfo = [ GFXAddress.WRAP, GFXAddress.WRAP, GFXAddress.WRAP, - 16, + 8, GFXComparisonFunc.NEVER, 0, 0, 0, 0, 0, 0, 0, ]; +const defaultHash = genSamplerHash(defaultInfo); const gfxInfo: IGFXSamplerInfo = {}; @@ -99,13 +100,10 @@ class SamplerLib { * @param info 目标 sampler 属性 */ public getSampler (device: GFXDevice, hash: number) { + if (hash === 0) { hash = defaultHash; } const cache = this._cache[hash]; if (cache) { return cache; } - if (hash === 0) { - hash = genSamplerHash(defaultInfo); - } - gfxInfo.minFilter = (hash & 3); gfxInfo.magFilter = ((hash >> 2) & 3); gfxInfo.mipFilter = ((hash >> 4) & 3); @@ -117,7 +115,7 @@ class SamplerLib { gfxInfo.minLOD = ((hash >> 20) & 15); gfxInfo.maxLOD = ((hash >> 24) & 15); gfxInfo.mipLODBias = ((hash >> 28) & 15); - gfxInfo.borderColor = { r: 0, g: 0, b: 0, a: 0 }; + gfxInfo.borderColor = { r: 0, g: 0, b: 0, a: 0 }; const sampler = this._cache[hash] = device.createSampler(gfxInfo); return sampler; diff --git a/cocos/core/renderer/core/texture-buffer-pool.ts b/cocos/core/renderer/core/texture-buffer-pool.ts index 7150225f94..31d4efc2ab 100644 --- a/cocos/core/renderer/core/texture-buffer-pool.ts +++ b/cocos/core/renderer/core/texture-buffer-pool.ts @@ -2,8 +2,7 @@ * @hidden */ -import { GFXFormat } from '../../gfx'; -import { GFXBufferTextureCopy, GFXFormatInfos, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define'; +import { GFXBufferTextureCopy, GFXFormat, GFXFormatInfos, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXTexture } from '../../gfx/texture'; import { GFXTextureView } from '../../gfx/texture-view'; diff --git a/cocos/core/renderer/data-pool-manager.ts b/cocos/core/renderer/data-pool-manager.ts new file mode 100644 index 0000000000..a126429690 --- /dev/null +++ b/cocos/core/renderer/data-pool-manager.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +import { AnimationClip } from '../animation/animation-clip'; +import { Mesh, Skeleton } from '../assets'; +import { GFXDevice } from '../gfx/device'; +import { AnimatedBoundsInfo, JointsAnimationInfo, JointsTexturePool } from './models/skeletal-animation-utils'; + +export class DataPoolManager { + public jointsTexturePool: JointsTexturePool; + public jointsAnimationInfo: JointsAnimationInfo; + public animatedBoundsInfo: AnimatedBoundsInfo; + + constructor (device: GFXDevice) { + this.jointsTexturePool = new JointsTexturePool(device); + this.jointsAnimationInfo = new JointsAnimationInfo(device); + this.animatedBoundsInfo = new AnimatedBoundsInfo(); + } + + public releaseMesh (mesh: Mesh) { + this.animatedBoundsInfo.releaseMesh(mesh); + } + + public releaseSkeleton (skeleton: Skeleton) { + this.jointsTexturePool.releaseSkeleton(skeleton); + this.animatedBoundsInfo.releaseSkeleton(skeleton); + } + + public releaseAnimationClip (clip: AnimationClip) { + this.jointsTexturePool.releaseAnimationClip(clip); + this.animatedBoundsInfo.releaseAnimationClip(clip); + } + + public clear () { + this.jointsTexturePool.clear(); + this.jointsAnimationInfo.clear(); + this.animatedBoundsInfo.clear(); + } +} diff --git a/cocos/core/renderer/index.ts b/cocos/core/renderer/index.ts index 8898abbc9d..f87a8843e3 100644 --- a/cocos/core/renderer/index.ts +++ b/cocos/core/renderer/index.ts @@ -17,6 +17,7 @@ export { Camera } from './scene/camera'; export { Model } from './scene/model'; export { SkinningModel } from './models/skinning-model'; -export * from './models/joints-texture-utils'; +export * from './models/skeletal-animation-utils'; -import './scene/deprecated'; \ No newline at end of file +import './scene/deprecated'; +import './ui/render-data'; diff --git a/cocos/core/renderer/models/joints-texture-utils.ts b/cocos/core/renderer/models/joints-texture-utils.ts deleted file mode 100644 index 3e6199d70c..0000000000 --- a/cocos/core/renderer/models/joints-texture-utils.ts +++ /dev/null @@ -1,206 +0,0 @@ -/* - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -/** - * @hidden - */ - -import { AnimationClip } from '../../animation/animation-clip'; -import { SkelAnimDataHub } from '../../animation/skeletal-animation-data-hub'; -import { Skeleton } from '../../assets/skeleton'; -import { GFXFormat, GFXFormatInfos } from '../../gfx/define'; -import { GFXDevice, GFXFeature } from '../../gfx/device'; -import { Mat4, Quat, Vec3 } from '../../math'; -import { ITextureBufferHandle, TextureBufferPool } from '../core/texture-buffer-pool'; - -// change here and cc-skinning.inc to use other skinning algorithms -const uploadJointData = uploadJointDataDQS; - -export enum JointsMediumType { - NONE, // for non-skinning models only - RGBA8, - RGBA32F, -} - -export function selectJointsMediumType (device: GFXDevice) { - if (device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { - return JointsMediumType.RGBA32F; - } else { - return JointsMediumType.RGBA8; - } -} - -const id_m4 = Object.freeze(new Mat4()); -const m4_1 = new Mat4(); -const dq_0 = new Quat(); -const dq_1 = new Quat(); -const v3_1 = new Vec3(); -const qt_1 = new Quat(); -const v3_2 = new Vec3(); - -// negative zeros cannot be decoded correctly at GLSL 100 minimum highp float precision, 1/1024 -// and it has a significant effect on the final transformation -function makeStable (n: number) { return n ? n : 0; } - -// Linear Blending Skinning -function uploadJointDataLBS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) { - out[base + 0] = makeStable(mat.m00); - out[base + 1] = makeStable(mat.m01); - out[base + 2] = makeStable(mat.m02); - out[base + 3] = makeStable(mat.m12); - out[base + 4] = makeStable(mat.m04); - out[base + 5] = makeStable(mat.m05); - out[base + 6] = makeStable(mat.m06); - out[base + 7] = makeStable(mat.m13); - out[base + 8] = makeStable(mat.m08); - out[base + 9] = makeStable(mat.m09); - out[base + 10] = makeStable(mat.m10); - out[base + 11] = makeStable(mat.m14); -} - -// Dual Quaternion Skinning -function uploadJointDataDQS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) { - Mat4.toRTS(mat, qt_1, v3_1, v3_2); - // sign consistency - if (firstBone) { Quat.copy(dq_0, qt_1); } - else if (Quat.dot(dq_0, qt_1) < 0) { Quat.multiplyScalar(qt_1, qt_1, -1); } - // conversion - Quat.set(dq_1, v3_1.x, v3_1.y, v3_1.z, 0); - Quat.multiplyScalar(dq_1, Quat.multiply(dq_1, dq_1, qt_1), 0.5); - // upload - out[base + 0] = makeStable(qt_1.x); - out[base + 1] = makeStable(qt_1.y); - out[base + 2] = makeStable(qt_1.z); - out[base + 3] = makeStable(qt_1.w); - out[base + 4] = makeStable(dq_1.x); - out[base + 5] = makeStable(dq_1.y); - out[base + 6] = makeStable(dq_1.z); - out[base + 7] = makeStable(dq_1.w); - out[base + 8] = makeStable(v3_2.x); - out[base + 9] = makeStable(v3_2.y); - out[base + 10] = makeStable(v3_2.z); -} - -function roundUpTextureSize (targetLength: number, formatSize: number) { - const minSize = 204; - const formatScale = 4 / Math.sqrt(formatSize); - return Math.ceil(Math.max(minSize * formatScale, targetLength) / 12) * 12; -} - -const _jointsFormat = { - [JointsMediumType.RGBA8]: GFXFormat.RGBA8, - [JointsMediumType.RGBA32F]: GFXFormat.RGBA32F, -}; - -export interface IJointsTextureHandle { - pixelOffset: number; - refCount: number; - hash: number; - handle: ITextureBufferHandle; -} - -export class JointsTexturePool { - - private _device: GFXDevice; - private _pool: TextureBufferPool; - private _textureBuffers: Map = new Map(); - private _formatSize = 0; - - constructor (device: GFXDevice) { - this._device = device; - this._pool = new TextureBufferPool(device); - } - - public initialize (maxChunks: number = 8) { - const format = _jointsFormat[selectJointsMediumType(this._device)]; - this._formatSize = GFXFormatInfos[format].size; - const scale = 16 / this._formatSize; - this._pool.initialize({ - format, - maxChunks: maxChunks * scale, - roundUpFn: roundUpTextureSize, - }); - } - - public destroy () { - this._pool.destroy(); - } - - /** - * 获取默认骨骼贴图 - */ - public getDefaultJointsTexture (skeleton?: Skeleton) { - const len = skeleton && skeleton.joints.length || 1; - let texture: IJointsTextureHandle | null = this._textureBuffers.get(len) || null; - if (texture) { texture.refCount++; return texture; } - const handle = this._pool.alloc(len * 12 * Float32Array.BYTES_PER_ELEMENT); - if (!handle) { return null; } - texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, hash: len, handle }; - const textureBuffer = new Float32Array(len * 12); - for (let i = 0; i < len; i++) { - uploadJointData(textureBuffer, 12 * i, id_m4, i === 0); - } - this._pool.update(handle, textureBuffer.buffer); - this._textureBuffers.set(len, texture); - return texture; - } - - /** - * 获取指定动画片段的骨骼贴图 - */ - public getJointsTextureWithAnimation (skeleton: Skeleton, clip: AnimationClip) { - const hash = skeleton.hash ^ clip.hash; - let texture: IJointsTextureHandle | null = this._textureBuffers.get(hash) || null; - if (texture) { texture.refCount++; return texture; } - const frames = clip.keys[0].length; - const bufSize = skeleton.joints.length * 12 * frames; - const handle = this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT); - if (!handle) { return null; } - texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, hash, handle }; - const textureBuffer = new Float32Array(bufSize); - const data = SkelAnimDataHub.getOrExtract(clip); - for (let i = 0; i < skeleton.joints.length; i++) { - const nodeData = data[skeleton.joints[i]]; - if (!nodeData || !nodeData.props) { continue; } - const bindpose = skeleton.bindposes[i]; - const matrix = nodeData.props.worldMatrix.values; - for (let frame = 0; frame < frames; frame++) { - const m = matrix[frame]; - Mat4.multiply(m4_1, m, bindpose); - uploadJointData(textureBuffer, 12 * (frames * i + frame), m4_1, i === 0); - } - } - this._pool.update(handle, textureBuffer.buffer); - this._textureBuffers.set(hash, texture); - return texture; - } - - public releaseTexture (texture: IJointsTextureHandle) { - if (--texture.refCount === 0) { - this._pool.free(texture.handle); - this._textureBuffers.delete(texture.hash); - } - } -} diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts new file mode 100644 index 0000000000..7b63576dc2 --- /dev/null +++ b/cocos/core/renderer/models/skeletal-animation-utils.ts @@ -0,0 +1,449 @@ +/* + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** + * @hidden + */ + +import { AnimationClip } from '../../animation/animation-clip'; +import { SkelAnimDataHub } from '../../animation/skeletal-animation-data-hub'; +import { Mesh } from '../../assets/mesh'; +import { Skeleton } from '../../assets/skeleton'; +import { aabb } from '../../geom-utils'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXAddress, GFXAttributeName, GFXBufferUsageBit, GFXFilter, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXDevice, GFXFeature } from '../../gfx/device'; +import { Mat4, Quat, Vec3 } from '../../math'; +import { UBOSkinningAnimation } from '../../pipeline/define'; +import { genSamplerHash } from '../core/sampler-lib'; +import { ITextureBufferHandle, TextureBufferPool } from '../core/texture-buffer-pool'; + +// change here and cc-skinning.chunk to use other skinning algorithms +const uploadJointData = uploadJointDataLBS; + +export enum JointsMediumType { + NONE, // for non-skinning models only + RGBA8, + RGBA32F, +} + +export function selectJointsMediumType (device: GFXDevice) { + if (device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { + return JointsMediumType.RGBA32F; + } else { + return JointsMediumType.RGBA8; + } +} + +const m4_1 = new Mat4(); +const dq_0 = new Quat(); +const dq_1 = new Quat(); +const v3_1 = new Vec3(); +const qt_1 = new Quat(); +const v3_2 = new Vec3(); + +// negative zeros cannot be decoded correctly at GLSL 100 minimum highp float precision, 1/1024 +// and it has a significant effect on the final transformation +function makeStable (n: number) { return n ? n : 0; } + +// Linear Blending Skinning +function uploadJointDataLBS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) { + out[base + 0] = makeStable(mat.m00); + out[base + 1] = makeStable(mat.m01); + out[base + 2] = makeStable(mat.m02); + out[base + 3] = makeStable(mat.m12); + out[base + 4] = makeStable(mat.m04); + out[base + 5] = makeStable(mat.m05); + out[base + 6] = makeStable(mat.m06); + out[base + 7] = makeStable(mat.m13); + out[base + 8] = makeStable(mat.m08); + out[base + 9] = makeStable(mat.m09); + out[base + 10] = makeStable(mat.m10); + out[base + 11] = makeStable(mat.m14); +} + +// Dual Quaternion Skinning +function uploadJointDataDQS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) { + Mat4.toRTS(mat, qt_1, v3_1, v3_2); + // sign consistency + if (firstBone) { Quat.copy(dq_0, qt_1); } + else if (Quat.dot(dq_0, qt_1) < 0) { Quat.multiplyScalar(qt_1, qt_1, -1); } + // conversion + Quat.set(dq_1, v3_1.x, v3_1.y, v3_1.z, 0); + Quat.multiplyScalar(dq_1, Quat.multiply(dq_1, dq_1, qt_1), 0.5); + // upload + out[base + 0] = makeStable(qt_1.x); + out[base + 1] = makeStable(qt_1.y); + out[base + 2] = makeStable(qt_1.z); + out[base + 3] = makeStable(qt_1.w); + out[base + 4] = makeStable(dq_1.x); + out[base + 5] = makeStable(dq_1.y); + out[base + 6] = makeStable(dq_1.z); + out[base + 7] = makeStable(dq_1.w); + out[base + 8] = makeStable(v3_2.x); + out[base + 9] = makeStable(v3_2.y); + out[base + 10] = makeStable(v3_2.z); +} + +function roundUpTextureSize (targetLength: number, formatSize: number) { + const minSize = 204; + const formatScale = 4 / Math.sqrt(formatSize); + return Math.ceil(Math.max(minSize * formatScale, targetLength) / 12) * 12; +} + +const _jointsFormat = { + [JointsMediumType.RGBA8]: GFXFormat.RGBA8, + [JointsMediumType.RGBA32F]: GFXFormat.RGBA32F, +}; + +export const jointsTextureSamplerHash = genSamplerHash([ + GFXFilter.POINT, + GFXFilter.POINT, + GFXFilter.NONE, + GFXAddress.CLAMP, + GFXAddress.CLAMP, + GFXAddress.CLAMP, +]); + +export interface IJointsTextureHandle { + pixelOffset: number; + refCount: number; + clipHash: number; + skeletonHash: number; + readyToBeDeleted: boolean; + handle: ITextureBufferHandle; +} + +export class JointsTexturePool { + + private _device: GFXDevice; + private _pool: TextureBufferPool; + private _textureBuffers: Map = new Map(); // per skeleton per clip + private _identityBuffer: IJointsTextureHandle | null; + private _maxIdentityJoints = 64; + private _formatSize = 0; + + constructor (device: GFXDevice, maxChunks = 8) { + this._device = device; + this._pool = new TextureBufferPool(device); + const format = _jointsFormat[selectJointsMediumType(this._device)]; + this._formatSize = GFXFormatInfos[format].size; + const scale = 16 / this._formatSize; + this._pool.initialize({ + format, + maxChunks: maxChunks * scale, + roundUpFn: roundUpTextureSize, + }); + this._identityBuffer = this._allocIdentityBuffer(); + } + + public clear () { + this._pool.destroy(); + this._textureBuffers.clear(); + this._identityBuffer = null; + } + + /** + * 获取默认骨骼贴图 + */ + public getDefaultJointsTexture (skeleton?: Skeleton) { + const len = skeleton && skeleton.joints.length || 1; + if (len > this._maxIdentityJoints) { + if (this._identityBuffer) { + this._identityBuffer.readyToBeDeleted = true; + this.releaseHandle(this._identityBuffer, false); + } + this._maxIdentityJoints *= 2; + this._identityBuffer = this._allocIdentityBuffer(); + } + if (!this._identityBuffer) { return null; } + this._identityBuffer.refCount++; + return this._identityBuffer; + } + + /** + * 获取指定动画片段的骨骼贴图 + */ + public getJointsTextureWithAnimation (skeleton: Skeleton, clip: AnimationClip) { + const hash = skeleton.hash ^ clip.hash; + let texture: IJointsTextureHandle | null = this._textureBuffers.get(hash) || null; + if (texture) { texture.refCount++; return texture; } + const frames = clip.keys[0].length; + const bufSize = skeleton.joints.length * 12 * frames; + const handle = this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT); + if (!handle) { return null; } + texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, + skeletonHash: skeleton.hash, clipHash: clip.hash, readyToBeDeleted: false, handle }; + const textureBuffer = new Float32Array(bufSize); + const data = SkelAnimDataHub.getOrExtract(clip); + for (let i = 0; i < skeleton.joints.length; i++) { + const nodeData = data[skeleton.joints[i]]; + if (!nodeData || !nodeData.props) { continue; } + const bindpose = skeleton.bindposes[i]; + const matrix = nodeData.props.worldMatrix.values; + for (let frame = 0; frame < frames; frame++) { + const m = matrix[frame]; + Mat4.multiply(m4_1, m, bindpose); + uploadJointData(textureBuffer, 12 * (frames * i + frame), m4_1, i === 0); + } + } + this._pool.update(handle, textureBuffer.buffer); + this._textureBuffers.set(hash, texture); + return texture; + } + + public releaseHandle (handle: IJointsTextureHandle, decr = true) { + if (decr && handle.refCount > 0) { handle.refCount--; } + if (!handle.refCount && handle.readyToBeDeleted) { + this._pool.free(handle.handle); + this._textureBuffers.delete(handle.skeletonHash ^ handle.clipHash); + } + } + + public releaseSkeleton (skeleton: Skeleton) { + const it = this._textureBuffers.values(); + let res = it.next(); + while (!res.done) { + if (res.value.skeletonHash === skeleton.hash) { + res.value.readyToBeDeleted = true; + this.releaseHandle(res.value, false); + } + res = it.next(); + } + } + + public releaseAnimationClip (clip: AnimationClip) { + const it = this._textureBuffers.values(); + let res = it.next(); + while (!res.done) { + if (res.value.clipHash === clip.hash) { + res.value.readyToBeDeleted = true; + this.releaseHandle(res.value, false); + } + res = it.next(); + } + } + + private _allocIdentityBuffer (len = this._maxIdentityJoints) { + const handle = this._pool.alloc(len * 12 * Float32Array.BYTES_PER_ELEMENT); + if (!handle) { return null; } + const textureBuffer = new Float32Array(len * 12); + for (let i = 0; i < len; i++) { + uploadJointData(textureBuffer, 12 * i, Mat4.IDENTITY, i === 0); + } + this._pool.update(handle, textureBuffer.buffer); + return { pixelOffset: handle.start / this._formatSize, refCount: 0, + skeletonHash: len, clipHash: 0, readyToBeDeleted: false, handle }; + } +} + +export interface IAnimInfo { + buffer: GFXBuffer; + data: Float32Array; + dirty: boolean; +} + +export class JointsAnimationInfo { + private _pool = new Map(); // per node + private _device: GFXDevice; + + constructor (device: GFXDevice) { + this._device = device; + } + + public create (nodeID: string) { + const res = this._pool.get(nodeID); + if (res) { return res; } + const buffer = this._device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: UBOSkinningAnimation.SIZE, + stride: UBOSkinningAnimation.SIZE, + }); + const data = new Float32Array([1, 0, 0, 0]); + buffer.update(data); + const info = { buffer, data, dirty: false }; + this._pool.set(nodeID, info); + return info; + } + + public destroy (nodeID: string) { + const info = this._pool.get(nodeID); + if (!info) { return; } + info.buffer.destroy(); + this._pool.delete(nodeID); + } + + public get (nodeID: string) { + return this._pool.get(nodeID) || this.create(-1 as any); + } + + public switchClip (info: IAnimInfo, clip: AnimationClip | null) { + info.data[0] = clip ? clip.keys[0].length : 1; + info.data[1] = 0; + info.buffer.update(info.data); + info.dirty = false; + return info; + } + + public clear () { + for (const info of this._pool.values()) { + info.buffer.destroy(); + } + this._pool.clear(); + } +} + +const v3_3 = new Vec3(); +const v3_4 = new Vec3(); +const ab_1 = new aabb(); + +export class AnimatedBoundsInfo { + private _perJointBoundsPool = new Map>>(); // per Mesh per Skeleton + private _fullClipBoundsPool = new Map>(); // per Skeleton per AnimationClip + + public get (mesh: Mesh, skeleton: Skeleton, clip: AnimationClip) { + const list: aabb[] = this._getFullClipBounds(skeleton, clip) || []; + if (list.length) { return list; } + let perJointBounds = this._getPerJointBounds(mesh, skeleton); + if (!perJointBounds) { + perJointBounds = this.getBoneSpacePerJointBounds(mesh, skeleton); + this._setPerJointBounds(mesh, skeleton, perJointBounds); + } + const frames = clip.keys[0].length; + for (let fid = 0; fid < frames; fid++) { + list.push(new aabb(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity)); + } + const data = SkelAnimDataHub.getOrExtract(clip); + const joints = skeleton.joints; + // per frame bounding box + for (let i = 0; i < joints.length; i++) { + const nodeData = data[joints[i]]; + const bound = perJointBounds[i]; + if (!bound || !nodeData || !nodeData.props) { continue; } + const matrix = nodeData.props.worldMatrix.values; + for (let fid = 0; fid < frames; fid++) { + const m = matrix[fid]; + const info = list[fid]; + aabb.transform(ab_1, bound, m); + ab_1.getBoundary(v3_3, v3_4); + Vec3.min(info.center, info.center, v3_3); + Vec3.max(info.halfExtents, info.halfExtents, v3_4); + } + } + for (let fid = 0; fid < frames; fid++) { + const { center, halfExtents } = list[fid]; + aabb.fromPoints(list[fid], center, halfExtents); + } + this._setFullClipBounds(skeleton, clip, list); + return list; + } + + public getBoneSpacePerJointBounds (mesh: Mesh, skeleton: Skeleton) { + const bounds: Array = []; + const valid: boolean[] = []; + const bindposes = skeleton.bindposes; + for (let i = 0; i < bindposes.length; i++) { + bounds.push(new aabb(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity)); + valid.push(false); + } + for (let p = 0; p < mesh.struct.primitives.length; p++) { + const joints = mesh.readAttribute(p, GFXAttributeName.ATTR_JOINTS); + const weights = mesh.readAttribute(p, GFXAttributeName.ATTR_WEIGHTS); + const positions = mesh.readAttribute(p, GFXAttributeName.ATTR_POSITION); + if (!joints || !weights || !positions) { continue; } + const vertCount = Math.min(joints.length / 4, weights.length / 4, positions.length / 3); + for (let i = 0; i < vertCount; i++) { + Vec3.set(v3_3, positions[3 * i + 0], positions[3 * i + 1], positions[3 * i + 2]); + for (let j = 0; j < 4; ++j) { + const idx = 4 * i + j; + const joint = joints[idx]; + if (weights[idx] === 0 || joint >= bindposes.length) { continue; } + Vec3.transformMat4(v3_4, v3_3, bindposes[joint]); + valid[joint] = true; + const b = bounds[joint]!; + Vec3.min(b.center, b.center, v3_4); + Vec3.max(b.halfExtents, b.halfExtents, v3_4); + } + } + } + for (let i = 0; i < bindposes.length; i++) { + const b = bounds[i]!; + if (!valid[i]) { bounds[i] = null; } + else { aabb.fromPoints(b, b.center, b.halfExtents); } + } + return bounds; + } + + public clear () { + this._perJointBoundsPool.clear(); + this._fullClipBoundsPool.clear(); + } + + public releaseMesh (mesh: Mesh) { + this._perJointBoundsPool.delete(mesh.hash); + } + + public releaseSkeleton (skeleton: Skeleton) { + const it = this._perJointBoundsPool.values(); + let res = it.next(); + while (!res.done) { + res.value.delete(skeleton.hash); + res = it.next(); + } + this._fullClipBoundsPool.delete(skeleton.hash); + } + + public releaseAnimationClip (clip: AnimationClip) { + const it = this._fullClipBoundsPool.values(); + let res = it.next(); + while (!res.done) { + res.value.delete(clip.hash); + res = it.next(); + } + } + + private _getPerJointBounds (mesh: Mesh, skeleton: Skeleton) { + const m = this._perJointBoundsPool.get(mesh.hash); + return m && m.get(skeleton.hash); + } + + private _getFullClipBounds (skeleton: Skeleton, clip: AnimationClip) { + const m = this._fullClipBoundsPool.get(skeleton.hash); + return m && m.get(clip.hash); + } + + private _setPerJointBounds (mesh: Mesh, skeleton: Skeleton, bounds: Array) { + let m = this._perJointBoundsPool.get(mesh.hash); + if (!m) { m = new Map>(); } + m.set(skeleton.hash, bounds); + } + + private _setFullClipBounds (skeleton: Skeleton, clip: AnimationClip, bounds: aabb[]) { + let m = this._fullClipBoundsPool.get(skeleton.hash); + if (!m) { m = new Map(); } + m.set(clip.hash, bounds); + } +} diff --git a/cocos/core/renderer/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts index a910a12ee3..25a07bb1c0 100644 --- a/cocos/core/renderer/models/skinning-model.ts +++ b/cocos/core/renderer/models/skinning-model.ts @@ -28,74 +28,26 @@ */ import { AnimationClip } from '../../animation/animation-clip'; +import { Mesh } from '../../assets/mesh'; import { Skeleton } from '../../assets/skeleton'; +import { aabb } from '../../geom-utils'; import { GFXBuffer } from '../../gfx/buffer'; -import { GFXAddress, GFXBufferUsageBit, GFXFilter, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { Vec3 } from '../../math'; import { UBOSkinningAnimation, UBOSkinningTexture, UniformJointsTexture } from '../../pipeline/define'; import { INode } from '../../utils/interfaces'; import { Pass } from '../core/pass'; -import { genSamplerHash, samplerLib } from '../core/sampler-lib'; +import { samplerLib } from '../core/sampler-lib'; import { Model } from '../scene/model'; import { RenderScene } from '../scene/render-scene'; -import { IJointsTextureHandle } from './joints-texture-utils'; - -export interface IJointsAnimInfo { - buffer: GFXBuffer; - data: Float32Array; -} - -export class JointsAnimationInfo { - public static create (nodeID: string) { - const res = JointsAnimationInfo.pool.get(nodeID); - if (res) { return res; } - const buffer = cc.director.root.device.createBuffer({ - usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, - memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: UBOSkinningAnimation.SIZE, - stride: UBOSkinningAnimation.SIZE, - }); - const data = new Float32Array([1, 0, 0, 0]); - buffer.update(data); - const info = { buffer, data }; - JointsAnimationInfo.pool.set(nodeID, info); - return info; - } - - public static destroy (nodeID: string) { - const info = JointsAnimationInfo.pool.get(nodeID); - if (!info) { return; } - info.buffer.destroy(); - JointsAnimationInfo.pool.delete(nodeID); - } - - public static switchClip (nodeID: string, clip: AnimationClip | null) { - const info = JointsAnimationInfo.pool.get(nodeID); - if (!info) { return; } - info.data[0] = clip ? clip.keys[0].length : 1; - info.data[1] = 0; - info.buffer.update(info.data); - } - - public static get (nodeID: string) { - return JointsAnimationInfo.pool.get(nodeID) || JointsAnimationInfo.create(-1 as any); - } - - protected static pool = new Map(); -} - -const jointsTextureSamplerHash = genSamplerHash([ - GFXFilter.POINT, - GFXFilter.POINT, - GFXFilter.NONE, - GFXAddress.CLAMP, - GFXAddress.CLAMP, - GFXAddress.CLAMP, -]); +import { IAnimInfo, IJointsTextureHandle, jointsTextureSamplerHash, selectJointsMediumType } from './skeletal-animation-utils'; interface IJointsInfo { buffer: GFXBuffer | null; jointsTextureInfo: Float32Array; texture: IJointsTextureHandle | null; + animInfo: IAnimInfo | null; + boundsInfo: aabb[] | null; } export class SkinningModel extends Model { @@ -104,17 +56,15 @@ export class SkinningModel extends Model { private _jointsMedium: IJointsInfo; private _skeleton: Skeleton | null = null; - - get worldBounds () { - return this.uploadedAnim ? null : this._worldBounds; - } + private _staticModelBounds: aabb | null = null; + private _mesh: Mesh | null = null; constructor (scene: RenderScene, node: INode) { super(scene, node); this._type = 'skinning'; const jointsTextureInfo = new Float32Array(4); - const texture = this._scene.texturePool.getDefaultJointsTexture(); - this._jointsMedium = { buffer: null, jointsTextureInfo, texture }; + const texture = this._scene.root.dataPoolManager.jointsTexturePool.getDefaultJointsTexture(); + this._jointsMedium = { buffer: null, jointsTextureInfo, texture, animInfo: null, boundsInfo: null }; } public destroy () { @@ -125,10 +75,12 @@ export class SkinningModel extends Model { } } - public bindSkeleton (skeleton: Skeleton | null, skinningRoot: INode | null) { + public bindSkeleton (skeleton: Skeleton | null, skinningRoot: INode | null, mesh: Mesh | null) { this._skeleton = skeleton; - if (!skeleton || !skinningRoot) { return; } + this._mesh = mesh; + if (!skeleton || !skinningRoot || !mesh) { return; } this._transform = skinningRoot; + this._jointsMedium.animInfo = this._scene.root.dataPoolManager.jointsAnimationInfo.get(skinningRoot.uuid); if (!this._jointsMedium.buffer) { this._jointsMedium.buffer = this._device.createBuffer({ usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, @@ -137,25 +89,49 @@ export class SkinningModel extends Model { stride: UBOSkinningTexture.SIZE, }); } - this.uploadAnimation(this.uploadedAnim); + } + + public updateTransform () { + super.updateTransform(); + if (!this.uploadedAnim) { return; } + const { animInfo, boundsInfo } = this._jointsMedium; + const skelBound = boundsInfo![animInfo!.data[1]]; + const node = this._transform; + if (this._worldBounds) { + // @ts-ignore TS2339 + skelBound.transform(node._mat, node._pos, node._rot, node._scale, this._worldBounds); + } + } + + // update fid buffer only when visible + public updateUBOs () { + if (!super.updateUBOs()) { return false; } + const info = this._jointsMedium.animInfo!; + if (info.dirty) { info.buffer.update(info.data); info.dirty = false; } + return true; + } + + public createBoundingShape (minPos?: Vec3, maxPos?: Vec3) { + super.createBoundingShape(minPos, maxPos); + this._staticModelBounds = this._modelBounds && aabb.clone(this._modelBounds); } public uploadAnimation (anim: AnimationClip | null) { - if (!this._skeleton) { return; } + if (!this._skeleton || !this._mesh) { return; } this.uploadedAnim = anim; - const texture = this.uploadedAnim ? - this._scene.texturePool.getJointsTextureWithAnimation(this._skeleton, this.uploadedAnim) : - this._scene.texturePool.getDefaultJointsTexture(this._skeleton); - JointsAnimationInfo.switchClip(this._transform.uuid, anim); + const resMgr = this._scene.root.dataPoolManager; + const texture = anim ? resMgr.jointsTexturePool.getJointsTextureWithAnimation(this._skeleton, anim) : + resMgr.jointsTexturePool.getDefaultJointsTexture(this._skeleton); + resMgr.jointsAnimationInfo.switchClip(this._jointsMedium.animInfo!, anim); this._applyJointsTexture(texture); + this._jointsMedium.boundsInfo = anim ? resMgr.animatedBoundsInfo.get(this._mesh, this._skeleton, anim) : null; + this._modelBounds = anim ? this._staticModelBounds : null; // don't calc bounds again in Model } protected _applyJointsTexture (texture: IJointsTextureHandle | null) { if (!texture) { return; } - // we skip freeing the joints texture by default as an aggressive caching strategy - // toggle the following when memory usage becomes more important than stable performance - // const oldTex = this._jointsMedium.texture; - // if (oldTex && oldTex !== texture) { this._scene.texturePool.releaseTexture(oldTex); } + const oldTex = this._jointsMedium.texture; + if (oldTex && oldTex !== texture) { this._scene.root.dataPoolManager.jointsTexturePool.releaseHandle(oldTex); } this._jointsMedium.texture = texture; const { buffer, jointsTextureInfo } = this._jointsMedium; jointsTextureInfo[0] = texture.handle.texture.width; @@ -166,22 +142,29 @@ export class SkinningModel extends Model { for (const submodel of this._subModels) { if (!submodel.psos) { continue; } for (const pso of submodel.psos) { - pso.pipelineLayout.layouts[0].bindTextureView(UniformJointsTexture.binding, texture.handle.texView); - pso.pipelineLayout.layouts[0].bindSampler(UniformJointsTexture.binding, sampler); + const bindingLayout = pso.pipelineLayout.layouts[0]; + bindingLayout.bindTextureView(UniformJointsTexture.binding, texture.handle.texView); + bindingLayout.bindSampler(UniformJointsTexture.binding, sampler); } } + for (const pso of this._implantPSOs) { + const bindingLayout = pso.pipelineLayout.layouts[0]; + bindingLayout.bindTextureView(UniformJointsTexture.binding, texture.handle.texView); + bindingLayout.bindSampler(UniformJointsTexture.binding, sampler); + bindingLayout.update(); + } } protected _doCreatePSO (pass: Pass) { - const pso = super._doCreatePSO(pass); - const { buffer, texture } = this._jointsMedium; - const animInfo = JointsAnimationInfo.get(this._transform.uuid); - pso.pipelineLayout.layouts[0].bindBuffer(UBOSkinningTexture.BLOCK.binding, buffer!); - pso.pipelineLayout.layouts[0].bindBuffer(UBOSkinningAnimation.BLOCK.binding, animInfo.buffer); + const pso = super._doCreatePSO(pass, { CC_USE_SKINNING: selectJointsMediumType(this._device) }); + const { buffer, texture, animInfo } = this._jointsMedium; + const bindingLayout = pso.pipelineLayout.layouts[0]; + bindingLayout.bindBuffer(UBOSkinningTexture.BLOCK.binding, buffer!); + bindingLayout.bindBuffer(UBOSkinningAnimation.BLOCK.binding, animInfo!.buffer); const sampler = samplerLib.getSampler(this._device, jointsTextureSamplerHash); if (texture) { - pso.pipelineLayout.layouts[0].bindTextureView(UniformJointsTexture.binding, texture.handle.texView); - pso.pipelineLayout.layouts[0].bindSampler(UniformJointsTexture.binding, sampler); + bindingLayout.bindTextureView(UniformJointsTexture.binding, texture.handle.texView); + bindingLayout.bindSampler(UniformJointsTexture.binding, sampler); } return pso; } diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index 418e912935..28730003c6 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -1,4 +1,5 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +import { IPassStates } from '../../assets/effect-asset'; import { Material } from '../../assets/material'; import { IRenderingSubmesh } from '../../assets/mesh'; import { aabb } from '../../geom-utils'; @@ -12,7 +13,7 @@ import Pool from '../../memop/pool'; import { IInternalBindingInst, UBOForwardLight, UBOLocal } from '../../pipeline/define'; import { Layers } from '../../scene-graph/layers'; import { INode } from '../../utils/interfaces'; -import { Pass } from '../core/pass'; +import { IDefineMap, Pass } from '../core/pass'; import { customizationManager } from './customization-manager'; import { RenderScene } from './render-scene'; import { SubModel } from './submodel'; @@ -69,18 +70,10 @@ export class Model { return this._enabled; } - /** - * Get the hosting node of this camera - * @returns the hosting node - */ get node () { return this._node; } - /** - * Set the hosting node of this model - * @param {Node} node the hosting node - */ set node (node: INode) { this._node = node; } @@ -154,23 +147,24 @@ export class Model { protected _node: INode; protected _transform: INode; protected _id: number; - protected _enabled: boolean = false; + protected _enabled = false; protected _visFlags = Layers.Enum.NONE; - protected _cameraID: number = -1; - protected _userKey: number = -1; + protected _cameraID = -1; + protected _userKey = -1; protected _worldBounds: aabb | null = null; protected _modelBounds: aabb | null = null; protected _subModels: SubModel[] = []; - protected _matPSORecord: Map; - protected _matRefCount: Map; - protected _uboLocal: UBOLocal; + protected _implantPSOs: GFXPipelineState[] = []; + protected _matPSORecord = new Map(); + protected _matRefCount = new Map(); + protected _uboLocal = new UBOLocal(); protected _localUBO: GFXBuffer | null = null; - protected _localBindings: Map = new Map(); - protected _inited: boolean = false; - protected _uboUpdated: boolean = false; - protected _castShadow: boolean = false; - protected _isDynamicBatching: boolean = false; - private _transformUpdated: boolean = true; + protected _localBindings = new Map(); + protected _inited = false; + protected _uboUpdated = false; + protected _castShadow = false; + protected _isDynamicBatching = false; + protected _transformUpdated = true; /** * Setup a default empty model @@ -178,12 +172,8 @@ export class Model { constructor (scene: RenderScene, node: INode) { this._device = cc.director.root!.device; this._scene = scene; + this._node = this._transform = node; this._id = this._scene.generateModelId(); - this._transform = this._node = node; - - this._matPSORecord = new Map(); - this._matRefCount = new Map(); - this._uboLocal = new UBOLocal(); } public destroy () { @@ -223,7 +213,7 @@ export class Model { node.updateWorldTransform(); this._transformUpdated = true; if (this._modelBounds && this._worldBounds) { - // @ts-ignore + // @ts-ignore TS2339 this._modelBounds.transform(node._mat, node._pos, node._rot, node._scale, this._worldBounds); } } @@ -329,6 +319,15 @@ export class Model { } } + public insertImplantPSO (pso: GFXPipelineState) { + this._implantPSOs.push(pso); + } + + public removeImplantPSO (pso: GFXPipelineState) { + const idx = this._implantPSOs.indexOf(pso); + if (idx >= 0) { this._implantPSOs.splice(idx, 1); } + } + protected createPipelineState (mat: Material): GFXPipelineState[] { const ret = new Array(mat.passes.length); for (let i = 0; i < ret.length; i++) { @@ -347,8 +346,10 @@ export class Model { } } - protected _doCreatePSO (pass: Pass) { - const pso = pass.createPipelineState()!; + protected _doCreatePSO (pass: Pass, defineOverrides?: IDefineMap, stateOverrides?: IPassStates) { + defineOverrides = defineOverrides || {}; + defineOverrides.CC_USE_BATCHING = this._isDynamicBatching; + const pso = pass.createPipelineState(defineOverrides, stateOverrides)!; pso.pipelineLayout.layouts[0].bindBuffer(UBOLocal.BLOCK.binding, this._localBindings.get(UBOLocal.BLOCK.name)!.buffer!); if (this._localBindings.has(UBOForwardLight.BLOCK.name)) { pso.pipelineLayout.layouts[0].bindBuffer(UBOForwardLight.BLOCK.binding, this._localBindings.get(UBOForwardLight.BLOCK.name)!.buffer!); diff --git a/cocos/core/renderer/scene/planar-shadows.ts b/cocos/core/renderer/scene/planar-shadows.ts index 4e0a7715a2..d349c4a4bc 100644 --- a/cocos/core/renderer/scene/planar-shadows.ts +++ b/cocos/core/renderer/scene/planar-shadows.ts @@ -1,6 +1,7 @@ import { EffectAsset } from '../../assets/effect-asset'; -import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { aabb, frustum, intersect } from '../../geom-utils'; +import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../../gfx/command-buffer'; import { GFXCommandBufferType, GFXStatus } from '../../gfx/define'; import { GFXInputAssembler } from '../../gfx/input-assembler'; import { GFXPipelineState } from '../../gfx/pipeline-state'; @@ -8,7 +9,7 @@ import { Color, Mat4, Quat, Vec3 } from '../../math'; import { CachedArray } from '../../memop/cached-array'; import { IInternalBindingInst, UBOShadow } from '../../pipeline/define'; import { Pass } from '../core/pass'; -import { selectJointsMediumType } from '../models/joints-texture-utils'; +import { selectJointsMediumType } from '../models/skeletal-animation-utils'; import { SkinningModel } from '../models/skinning-model'; import { DirectionalLight } from './directional-light'; import { Model } from './model'; @@ -17,7 +18,12 @@ import { SphereLight } from './sphere-light'; const _forward = new Vec3(0, 0, -1); const _v3 = new Vec3(); +const _ab = new aabb(); const _qt = new Quat(); +const _info: IGFXCommandBufferInfo = { + allocator: null!, + type: GFXCommandBufferType.SECONDARY, +}; export class PlanarShadows { @@ -150,11 +156,15 @@ export class PlanarShadows { this._globalBindings.buffer!.update(this.data); } - public updateCommandBuffers () { + public updateCommandBuffers (frstm: frustum) { this._cmdBuffs.clear(); if (!this._scene.mainLight.enabled) { return; } for (const model of this._scene.models) { if (!model.enabled || !model.node || !model.castShadow) { continue; } + if (model.worldBounds) { + aabb.transform(_ab, model.worldBounds, this._matLight); + if (!intersect.aabb_frustum(_ab, frstm)) { continue; } + } let pso = this._psoRecord.get(model); let newOne = false; if (!pso) { pso = this._createPSO(model); this._psoRecord.set(model, pso); newOne = true; } if (!model.UBOUpdated) { model.updateUBOs(); } // for those outside the frustum @@ -213,28 +223,26 @@ export class PlanarShadows { protected _createPSO (model: Model) { const pass = model instanceof SkinningModel ? this._passSkinning : this._passNormal; - // @ts-ignore + // @ts-ignore TS2445 const pso = model._doCreatePSO(pass); + model.insertImplantPSO(pso); // add back to model to sync binding layouts pso.pipelineLayout.layouts[0].update(); return pso; } protected _destroyPSO (model: Model, pso: GFXPipelineState) { const pass = model instanceof SkinningModel ? this._passSkinning : this._passNormal; - return pass.destroyPipelineState(pso); + model.removeImplantPSO(pso); pass.destroyPipelineState(pso); } protected _createOrReuseCommandBuffer (cb?: GFXCommandBuffer) { const device = this._scene.root.device; - const info = { - allocator: device.commandAllocator, - type: GFXCommandBufferType.SECONDARY, - }; + _info.allocator = device.commandAllocator; if (cb) { if (cb.status === GFXStatus.SUCCESS) { cb.destroy(); } - cb.initialize(info); + cb.initialize(_info); } else { - cb = device.createCommandBuffer(info); + cb = device.createCommandBuffer(_info); } return cb; } diff --git a/cocos/core/renderer/scene/render-scene.ts b/cocos/core/renderer/scene/render-scene.ts index ade0a104dc..ac3f39f5a4 100644 --- a/cocos/core/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/scene/render-scene.ts @@ -7,7 +7,6 @@ import { Root } from '../../root'; import { Layers } from '../../scene-graph/layers'; import { Node } from '../../scene-graph/node'; import { INode } from '../../utils/interfaces'; -import { JointsTexturePool } from '../models/joints-texture-utils'; import { Ambient } from './ambient'; import { Camera, ICameraInfo } from './camera'; import { DirectionalLight } from './directional-light'; @@ -78,10 +77,6 @@ export class RenderScene { return this._models; } - get texturePool () { - return this._texturePool; - } - /** * @zh * 获取 raycastAllCanvas 后的检测结果 @@ -111,7 +106,7 @@ export class RenderScene { * 获取 raycastSingleModel 后的检测结果 */ get rayResultSingleModel () { - return this.rayResultSingleModel; + return resultSingleModel; } public static registerCreateFunc (root: Root) { @@ -130,7 +125,6 @@ export class RenderScene { private _spotLights: SpotLight[] = []; private _models: Model[] = []; private _modelId: number = 0; - private _texturePool: JointsTexturePool; constructor (root: Root) { this._root = root; @@ -142,12 +136,10 @@ export class RenderScene { this._ambient = new Ambient(this); this._skybox = new Skybox(this); this._planarShadows = new PlanarShadows(this); - this._texturePool = new JointsTexturePool(root.device); } public initialize (info: IRenderSceneInfo): boolean { this._name = info.name; - this._texturePool.initialize(); return true; } @@ -158,7 +150,6 @@ export class RenderScene { this.destroyModels(); this._skybox.destroy(); this._planarShadows.destroy(); - this._texturePool.destroy(); } public createCamera (info: ICameraInfo): Camera { @@ -272,7 +263,7 @@ export class RenderScene { * @param mask mask 用于标记所有要检测的层,默认为 Default | UI2D * @param distance 射线检测的最大距离, 默认为 Infinity * @returns boolean , 射线是否有击中 - * @nete 通过 this.rayResultAll 可以获取到最近的结果 + * @note 通过 this.rayResultAll 可以获取到最近的结果 */ public raycastAll (worldRay: ray, mask = Layers.Enum.DEFAULT | Layers.Enum.UI_2D, distance = Infinity): boolean { const r_3d = this.raycastAllModels(worldRay, mask, distance); @@ -300,7 +291,7 @@ export class RenderScene { * @param mask 用于标记所有要检测的层,默认为 Default * @param distance 射线检测的最大距离, 默认为 Infinity * @returns boolean , 射线是否有击中 - * @nete 通过 this.rayResultModels 可以获取到最近的结果 + * @note 通过 this.rayResultModels 可以获取到最近的结果 */ public raycastAllModels (worldRay: ray, mask = Layers.Enum.DEFAULT, distance = Infinity): boolean { pool.reset(); @@ -391,10 +382,10 @@ export class RenderScene { * @zh * 传入一条射线检测场景中所有的 Canvas 以及 Canvas 下的 Node * @param worldRay 世界射线 - * @param mask 用于标记所有要检测的层,默认为 UI2D + * @param mask 用于标记所有要检测的层,默认为 UI_2D * @param distance 射线检测的最大距离, 默认为 Infinity * @returns boolean , 射线是否有击中 - * @nete 通过 this.rayResultCanvas 可以获取到最近的结果 + * @note 通过 this.rayResultCanvas 可以获取到最近的结果 */ public raycastAllCanvas (worldRay: ray, mask = Layers.Enum.UI_2D, distance = Infinity): boolean { poolUI.reset(); diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index e181361523..2e63c23140 100644 --- a/cocos/core/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -10,6 +10,7 @@ import { Model } from './model'; import { RenderScene } from './render-scene'; let skybox_mesh: Mesh | null = null; +let skybox_material: Material | null = null; export class Skybox extends Model { @@ -23,8 +24,8 @@ export class Skybox extends Model { set isRGBE (val) { this._isRGBE = val; - this._material.recompileShaders({ USE_RGBE_CUBEMAP: this._isRGBE }); - this.setSubModelMaterial(0, this._material); + skybox_material!.recompileShaders({ USE_RGBE_CUBEMAP: this._isRGBE }); + this.setSubModelMaterial(0, skybox_material); this._updateGlobalBinding(); this._updatePipeline(); } @@ -47,16 +48,18 @@ export class Skybox extends Model { protected _isRGBE = false; protected _useIBL = false; - protected _material = new Material(); protected _globalBinding: IInternalBindingInst; constructor (scene: RenderScene) { super(scene, null!); this._scene = scene; - this._material.initialize({ effectName: 'pipeline/skybox', defines: { USE_RGBE_CUBEMAP: this._isRGBE } }); this._globalBinding = this._scene.root.pipeline.globalBindings.get(UNIFORM_ENVIRONMENT.name)!; + if (!skybox_material) { + skybox_material = new Material(); + skybox_material.initialize({ effectName: 'pipeline/skybox', defines: { USE_RGBE_CUBEMAP: this._isRGBE } }); + } if (!skybox_mesh) { skybox_mesh = createMesh(box({ width: 2, height: 2, length: 2 })); } - this.initSubModel(0, skybox_mesh.renderingMesh.getSubmesh(0), this._material); + this.initSubModel(0, skybox_mesh.renderingMesh.getSubmesh(0), skybox_material); } protected _updatePipeline () { @@ -74,7 +77,7 @@ export class Skybox extends Model { this._globalBinding.textureView = textureView; // update skybox material, need to do this every time pso is created // because skybox.updateUBOs is not called in pipeline per frame - const mat = this._material; + const mat = skybox_material!; mat.passes[0].bindSampler(UNIFORM_ENVIRONMENT.binding, sampler); mat.passes[0].bindTextureView(UNIFORM_ENVIRONMENT.binding, textureView); for (const pso of this._matPSORecord.get(mat)!) { diff --git a/cocos/core/renderer/ui/mesh-buffer.ts b/cocos/core/renderer/ui/mesh-buffer.ts index d912964b14..ccc1335442 100644 --- a/cocos/core/renderer/ui/mesh-buffer.ts +++ b/cocos/core/renderer/ui/mesh-buffer.ts @@ -40,10 +40,6 @@ export class MeshBuffer { public vb: GFXBuffer | null = null; public ib: GFXBuffer | null = null; public ia: GFXInputAssembler | null = null; - // public vbCount: number = 0; - // public vbSize: number = 0; - // public ibCount: number = 0; - // public ibSize: number = 0; public byteStart: number = 0; public byteOffset: number = 0; @@ -93,15 +89,6 @@ export class MeshBuffer { }); this._reallocBuffer(); - - // const batch = this._bufferBatchPool.add(); - // batch.vb = vb; - // batch.ib = ib; - // batch.ia = ia; - // batch.vf32 = null; - // batch.vui16 = null; - // batch.vbSize = vb.size; - // batch.ibSize = ib.size; } public request (vertexCount = 4, indiceCount = 6) { @@ -140,10 +127,6 @@ export class MeshBuffer { } public reset () { - // this._arrOffset = 0; - // this._vb = this._vbArr[0]; - // this._ib = this._ibArr[0]; - this.byteStart = 0; this.byteOffset = 0; this.indiceStart = 0; @@ -155,17 +138,6 @@ export class MeshBuffer { } public destroy () { - // for (const key in this._vbArr) { - // const vb = this._vbArr[key]; - // vb.destroy(); - // } - // this._vbArr = undefined; - - // for (const key in this._ibArr) { - // const ib = this._ibArr[key]; - // ib.destroy(); - // } - // this._ibArr = undefined; this.ib!.destroy(); this.vb!.destroy(); this.ia!.destroy(); @@ -198,7 +170,7 @@ export class MeshBuffer { this._reallocIData(true); } - private _reallocVData (copyOldData) { + private _reallocVData (copyOldData: boolean) { let oldVData; if (this.vData) { oldVData = new Uint8Array(this.vData.buffer); @@ -214,7 +186,7 @@ export class MeshBuffer { } } - private _reallocIData (copyOldData) { + private _reallocIData (copyOldData: boolean) { const oldIData = this.iData; this.iData = new Uint16Array(this._initIDataCount); diff --git a/cocos/core/renderer/ui/render-data.ts b/cocos/core/renderer/ui/render-data.ts index 504eda2e4d..5fe751b517 100644 --- a/cocos/core/renderer/ui/render-data.ts +++ b/cocos/core/renderer/ui/render-data.ts @@ -30,6 +30,8 @@ import { Pool, RecyclePool } from '../../memop'; import { Material } from '../../assets'; import { Color } from '../../math'; +import { GFXTextureView } from '../../gfx'; +import { MeshBuffer } from '../../../ui'; export interface IRenderData { x: number; @@ -126,7 +128,7 @@ export class RenderData extends BaseRenderData { } } -export class IARenderData extends BaseRenderData { +export class MeshRenderData extends BaseRenderData { public vData: Float32Array = new Float32Array(256 * 9 * Float32Array.BYTES_PER_ELEMENT); public iData: Uint16Array = new Uint16Array(256 * 6); public vertexStart = 0; @@ -189,7 +191,7 @@ const _dataPool = new Pool(() => { u: 0, v: 0, color: Color.WHITE.clone(), - } as IRenderData; + }; }, 128); const _pool = new RecyclePool(() => { diff --git a/cocos/core/renderer/ui/ui-batch-model.ts b/cocos/core/renderer/ui/ui-batch-model.ts index 2bba8db22a..ba80c9d690 100644 --- a/cocos/core/renderer/ui/ui-batch-model.ts +++ b/cocos/core/renderer/ui/ui-batch-model.ts @@ -32,7 +32,7 @@ import { GFXPipelineState } from '../../gfx/pipeline-state'; import { Model } from '../scene/model'; import { RenderScene } from '../scene/render-scene'; import { SubModel } from '../scene/submodel'; -import { UIDrawBatch } from './ui'; +import { UIDrawBatch } from './ui-draw-batch'; export class UIBatchModel extends Model { diff --git a/cocos/core/renderer/ui/ui-draw-batch.ts b/cocos/core/renderer/ui/ui-draw-batch.ts new file mode 100644 index 0000000000..90bb4f28a1 --- /dev/null +++ b/cocos/core/renderer/ui/ui-draw-batch.ts @@ -0,0 +1,48 @@ +import { UI } from "./ui"; +import { Camera } from "../scene/camera"; +import { MeshBuffer } from "../../../ui"; +import { Model } from "../scene/model"; +import { Material } from "../../assets"; +import { GFXTextureView, GFXPipelineState } from "../../gfx"; +import { INode } from "../../utils/interfaces"; +import { GFXBindingLayout } from "../../gfx/binding-layout"; + +export class UIDrawBatch { + public camera: Camera | null = null; + public bufferBatch: MeshBuffer | null = null; + public model: Model | null = null; + public material: Material | null = null; + public texView: GFXTextureView | null = null; + public firstIdx: number = 0; + public idxCount: number = 0; + public pipelineState: GFXPipelineState | null = null; + public bindingLayout: GFXBindingLayout | null = null; + public useLocalData: INode | null = null; + public isStatic = false; + + public destroy (ui: UI) { + if (this.pipelineState) { + ui._getUIMaterial(this.material!).revertPipelineState(this.pipelineState); + this.pipelineState = null; + } + + if (this.bindingLayout) { + this.bindingLayout = null; + } + } + + public clear (ui: UI) { + if (this.pipelineState) { + ui._getUIMaterial(this.material!).revertPipelineState(this.pipelineState); + this.pipelineState = null; + } + this.camera = null; + this.bufferBatch = null; + this.material = null; + this.texView = null; + this.firstIdx = 0; + this.idxCount = 0; + this.model = null; + this.isStatic = false; + } +} diff --git a/cocos/core/renderer/ui/ui.ts b/cocos/core/renderer/ui/ui.ts index 491610e927..024aa37c7e 100644 --- a/cocos/core/renderer/ui/ui.ts +++ b/cocos/core/renderer/ui/ui.ts @@ -26,14 +26,13 @@ * @hidden */ +import { UIStaticBatchComponent } from '../../../ui'; import { Material } from '../../assets/material'; import { CanvasComponent, UIComponent, UIRenderComponent } from '../../components/ui-base'; -import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { GFXCommandBufferType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { IGFXAttribute } from '../../gfx/input-assembler'; -import { GFXPipelineState } from '../../gfx/pipeline-state'; import { GFXTextureView } from '../../gfx/texture-view'; import { Pool, RecyclePool } from '../../memop'; import { CachedArray } from '../../memop/cached-array'; @@ -47,47 +46,10 @@ import { INode } from '../../utils/interfaces'; import { MeshBuffer } from './mesh-buffer'; import { StencilManager } from './stencil-manager'; import { UIBatchModel } from './ui-batch-model'; +import { UIDrawBatch } from './ui-draw-batch'; import { UIMaterial } from './ui-material'; import * as UIVertexFormat from './ui-vertex-format'; -export class UIDrawBatch { - public camera: Camera | null = null; - public bufferBatch: MeshBuffer | null = null; - public model: Model | null = null; - public material: Material | null = null; - public texView: GFXTextureView | null = null; - public firstIdx: number = 0; - public idxCount: number = 0; - public pipelineState: GFXPipelineState | null = null; - public bindingLayout: GFXBindingLayout | null = null; - public useLocalData: INode | null = null; - - public destroy (ui: UI) { - if (this.pipelineState) { - ui._getUIMaterial(this.material!).revertPipelineState(this.pipelineState); - this.pipelineState = null; - } - - if (this.bindingLayout) { - this.bindingLayout = null; - } - } - - public clear (ui: UI) { - if (this.pipelineState) { - ui._getUIMaterial(this.material!).revertPipelineState(this.pipelineState); - this.pipelineState = null; - } - this.camera = null; - this.bufferBatch = null; - this.material = null; - this.texView = null; - this.firstIdx = 0; - this.idxCount = 0; - this.model = null; - } -} - /** * @zh * UI 渲染流程 @@ -102,6 +64,18 @@ export class UI { return this._currMeshBuffer; } + set currBufferBatch (value) { + if (!value){ + return; + } + + this._currMeshBuffer = value; + } + + set currStaticRoot (value: UIStaticBatchComponent | null) { + this._currStaticRoot = value; + } + public device: GFXDevice; private _screens: CanvasComponent[] = []; private _bufferBatchPool: RecyclePool = new RecyclePool(() => { @@ -122,10 +96,11 @@ export class UI { private _modelInUse: CachedArray; // batcher private _emptyMaterial = new Material(); - private _currMeshBuffer: MeshBuffer | null = null; private _currMaterial: Material = this._emptyMaterial; private _currTexView: GFXTextureView | null = null; private _currCanvas = -1; + private _currMeshBuffer: MeshBuffer | null = null; + private _currStaticRoot: UIStaticBatchComponent | null = null; constructor (private _root: Root) { this.device = _root.device; @@ -269,7 +244,7 @@ export class UI { camera = this._screens[i].camera; if (camera) { const matRecord = this._canvasMaterials.get(camera.view.visibility)!; - camera.view.visibility -= 1; + camera.view.visibility = Layers.BitMask.UI_2D | (i + 1); this._canvasMaterials.set(camera.view.visibility, matRecord); } } @@ -352,7 +327,7 @@ export class UI { * @param frame - 当前执行组件贴图。 * @param assembler - 当前组件渲染数据组装器。 */ - public commitComp (comp: UIRenderComponent, frame: GFXTextureView | null = null, assembler?: any) { + public commitComp (comp: UIRenderComponent, frame: GFXTextureView | null = null, assembler: any) { const renderComp = comp; const texView = frame; if (this._currMaterial.hash !== renderComp.material!.hash || @@ -414,6 +389,11 @@ export class UI { this._batches.push(curDrawBatch); } + public commitStaticBatch (comp: UIStaticBatchComponent) { + this._batches.append(comp.drawBatchList); + this.finishMergeBatches(); + } + /** * @zh * UI 渲染数据合批 @@ -431,9 +411,9 @@ export class UI { StencilManager.sharedManager!.handleMaterial(mat); - const curDrawBatch = this._drawBatchPool.alloc(); + const curDrawBatch = this._currStaticRoot ? this._currStaticRoot.requireDrawBatch() : this._drawBatchPool.alloc(); curDrawBatch.camera = uiCanvas && uiCanvas.camera; - curDrawBatch.bufferBatch = this._currMeshBuffer; + curDrawBatch.bufferBatch = buffer; curDrawBatch.material = mat; curDrawBatch.texView = this._currTexView!; curDrawBatch.firstIdx = indicsStart; @@ -462,6 +442,12 @@ export class UI { this.autoMergeBatches(); } + public finishMergeBatches (){ + this.autoMergeBatches(); + this._currMaterial = this._emptyMaterial; + this._currTexView = null; + } + private _deleteUIMaterial (mat: Material) { if (this._uiMaterials.has(mat.hash)) { this._uiMaterials.get(mat.hash)!.destroy(); @@ -484,7 +470,7 @@ export class UI { const len = node.children.length; this._preprocess(node); - if (len > 0) { + if (len > 0 && !node._static) { const children = node.children; for (let i = 0; i < children.length; ++i) { const child = children[i]; @@ -531,6 +517,10 @@ export class UI { private _reset () { for (let i = 0; i < this._batches.length; ++i) { const batch = this._batches.array[i]; + if (batch.isStatic) { + continue; + } + batch.clear(this); this._drawBatchPool.free(batch); } diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 03e8f2dbf8..438ccd9b63 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -8,6 +8,7 @@ import { GFXWindow, IGFXWindowInfo } from './gfx/window'; import { ForwardPipeline } from './pipeline/forward/forward-pipeline'; import { RenderPipeline } from './pipeline/render-pipeline'; import { IRenderViewInfo, RenderView } from './pipeline/render-view'; +import { DataPoolManager } from './renderer/data-pool-manager'; import { IRenderSceneInfo, RenderScene } from './renderer/scene/render-scene'; import { UI } from './renderer/ui/ui'; @@ -165,6 +166,10 @@ export class Root { return this._fixedFPS; } + public get dataPoolManager () { + return this._dataPoolMgr; + } + public _createSceneFun; public _createViewFun; @@ -175,6 +180,7 @@ export class Root { private _tempWindow: GFXWindow | null = null; private _pipeline: RenderPipeline | null = null; private _ui: UI | null = null; + private _dataPoolMgr: DataPoolManager; private _scenes: RenderScene[] = []; private _views: RenderView[] = []; private _time: number = 0; @@ -191,6 +197,7 @@ export class Root { */ constructor (device: GFXDevice) { this._device = device; + this._dataPoolMgr = new DataPoolManager(device); RenderScene.registerCreateFunc(this); RenderView.registerCreateFunc(this); @@ -249,6 +256,7 @@ export class Root { this._curWindow = null; this._mainWindow = null; + this.dataPoolManager.clear(); } /** diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index 6e9bad465d..3bf2f7477c 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -30,14 +30,15 @@ import { Component } from '../components/component'; import { ccclass, property } from '../data/class-decorator'; import { CCObject } from '../data/object'; +import { Event } from '../event'; +import { errorID, warnID } from '../platform/debug'; import { SystemEventType } from '../platform/event-manager/event-enum'; import { ISchedulable } from '../scheduler'; import IdGenerator from '../utils/id-generator'; import { IBaseNode } from '../utils/interfaces'; import * as js from '../utils/js'; import { baseNodePolyfill } from './base-node-dev'; -import { Scene } from './scene'; -import { errorID, warnID } from '../platform/debug'; +import { NodeEventProcessor } from './node-event-processor'; /** * @@ -54,12 +55,14 @@ const Deactivating = CCObject.Flags.Deactivating; const Activating = CCObject.Flags.Activating; const ChangingState = Activating | Deactivating; +export const TRANFORM_ON = 1 << 0; + // const CHILD_ADDED = 'child-added'; // const CHILD_REMOVED = 'child-removed'; const idGenerator = new IdGenerator('Node'); -const NullScene = null as unknown as Scene; +const NullScene = null; function getConstructor (typeOrClassName: string | Function): Function | null { if (!typeOrClassName) { @@ -247,9 +250,13 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { return this._scene; } + get eventProcessor () { + return this._eventProcessor; + } + public static _setScene (node: BaseNode) { if (node instanceof cc.Scene) { - node._scene = node as Scene; + node._scene = node; } else { if (node._parent == null) { cc.error('Node %s(%s) has not attached to a scene.', node.name, node.uuid); @@ -360,7 +367,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { * @zh 此节点属于哪个场景。 * @type {cc.Scene}} */ - protected _scene: Scene = NullScene; + protected _scene: any = NullScene; protected _activeInHierarchy = false; @@ -370,6 +377,8 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { protected _name: string; + protected _eventProcessor: NodeEventProcessor = new NodeEventProcessor(this as IBaseNode); + protected _eventMask = 0; /** * Register all related EventTargets, * all event callbacks will be removed in _onPreDestroy @@ -388,6 +397,26 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { this._name = name !== undefined ? name : 'New Node'; } + /** + * @en + * Properties configuration function
+ * All properties in attrs will be set to the node,
+ * when the setter of the node is available,
+ * the property will be set via setter function.
+ * @zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。 + * @param attrs - Properties to be set to node + * @example + * ``` + * var attrs = { key: 0, num: 100 }; + * node.attr(attrs); + * ``` + */ + public attr (attrs: Object) { + js.mixin(this, attrs); + } + + // HIERARCHY METHODS + /** * @en Get parent of the node. * @zh 获取该节点的父节点。 @@ -456,28 +485,6 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { } - // ABSTRACT INTERFACES - - /** - * @en - * Properties configuration function
- * All properties in attrs will be set to the node,
- * when the setter of the node is available,
- * the property will be set via setter function.
- * @zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。 - * @param attrs - Properties to be set to node - * @example - * ``` - * var attrs = { key: 0, num: 100 }; - * node.attr(attrs); - * ``` - */ - public attr (attrs: Object) { - js.mixin(this, attrs); - } - - // composition: GET - /** * @en Returns a child from the container given its uuid. * @zh 通过 uuid 获取节点的子节点。 @@ -555,8 +562,6 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { return lastNode; } - // composition: ADD - public addChild (child: this): void { if (CC_DEV && !(child instanceof cc._BaseNode)) { @@ -589,8 +594,6 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { child.setSiblingIndex(siblingIndex); } - // HIERARCHY METHODS - /** * @en Get the sibling index. * @zh 获取同级索引。 @@ -1099,6 +1102,55 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { } } + // EVENT PROCESSING + + public on (type: string | SystemEventType, callback: Function, target?: Object, useCapture?: any) { + switch (type) { + case SystemEventType.TRANSFORM_CHANGED: + this._eventMask |= TRANFORM_ON; + break; + } + this._eventProcessor.on(type, callback, target, useCapture); + } + + public off (type: string, callback?: Function, target?: Object, useCapture?: any) { + this._eventProcessor.off(type, callback, target, useCapture); + + const hasListeners = this._eventProcessor.hasEventListener(type); + // All listener removed + if (!hasListeners) { + switch (type) { + case SystemEventType.TRANSFORM_CHANGED: + this._eventMask &= ~TRANFORM_ON; + break; + } + } + } + + public once (type: string, callback: Function, target?: Object, useCapture?: any) { + this._eventProcessor.once(type, callback, target, useCapture); + } + + public emit (type: string, ...args: any[]) { + this._eventProcessor.emit(type, ...args); + } + + public dispatchEvent (event: Event) { + this._eventProcessor.dispatchEvent(event); + } + + public hasEventListener (type: string) { + return this._eventProcessor.hasEventListener(type); + } + + public targetOff (target: string | Object) { + this._eventProcessor.targetOff(target); + // Check for event mask reset + if ((this._eventMask & TRANFORM_ON) && !this._eventProcessor.hasEventListener(SystemEventType.TRANSFORM_CHANGED)) { + this._eventMask &= ~TRANFORM_ON; + } + } + public destroy () { if (super.destroy()) { // disable hierarchy @@ -1131,8 +1183,6 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { } } - public emit? (type: string, ...args: any[]): void; - // Do remove component, only used internally. public _removeComponent (component: Component) { if (!component) { @@ -1171,6 +1221,8 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { } } + // PRIVATE + protected _onPostActivated (active: boolean) { return; } @@ -1315,12 +1367,13 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable { if (!destroyByParent) { // remove from parent if (parent) { + this.emit(SystemEventType.PARENT_CHANGED, this); // During destroy process, siblingIndex is not relyable const childIndex = parent._children.indexOf(this); parent._children.splice(childIndex, 1); this._siblingIndex = 0; if (parent.emit) { - parent.emit('child-removed', this); + parent.emit(SystemEventType.CHILD_REMOVED, this); } } } diff --git a/cocos/core/scene-graph/node-event-processor.ts b/cocos/core/scene-graph/node-event-processor.ts index 34d8dddd58..c0b528f964 100644 --- a/cocos/core/scene-graph/node-event-processor.ts +++ b/cocos/core/scene-graph/node-event-processor.ts @@ -35,10 +35,10 @@ import { EventListener } from '../platform/event-manager/event-listener'; import { eventManager } from '../platform/event-manager/event-manager'; import { EventMouse, EventTouch } from '../platform/event-manager/events'; import { Touch } from '../platform/event-manager/touch'; -import { INode } from '../utils/interfaces'; +import { IBaseNode, INode } from '../utils/interfaces'; -const _cachedArray = new Array(16); -let _currentHovered: INode | null = null; +const _cachedArray = new Array(16); +let _currentHovered: IBaseNode | null = null; let pos = new Vec2(); const _touchEvents = [ @@ -59,7 +59,7 @@ const _mouseEvents = [ // TODO: rearrange event function _touchStartHandler (this: EventListener, touch: Touch, event: EventTouch) { - const node = this.owner as INode; + const node = this.owner as IBaseNode; // @ts-ignore if (!node || !node.uiTransfromComp) { return false; @@ -213,8 +213,8 @@ function _mouseWheelHandler (this: EventListener, event: EventMouse) { } } -function _doDispatchEvent (owner: INode, event: Event) { - let target: INode; +function _doDispatchEvent (owner: IBaseNode, event: Event) { + let target: IBaseNode; let i = 0; event.target = owner; @@ -287,7 +287,7 @@ function _searchMaskInParent (node: INode | null) { return null; } -function _checkListeners (node: INode, events: string[]) { +function _checkListeners (node: IBaseNode, events: string[]) { if (!node._persistNode) { let i = 0; if (node.eventProcessor.bubblingTargets) { @@ -314,7 +314,7 @@ function _checkListeners (node: INode, events: string[]) { * 节点事件类。 */ export class NodeEventProcessor { - public get node (): INode { + public get node (): IBaseNode { return this._node; } @@ -340,21 +340,21 @@ export class NodeEventProcessor { */ public mouseListener: EventListener | null = null; - private _node: INode; + private _node: IBaseNode; - constructor (node: INode) { + constructor (node: IBaseNode) { this._node = node; } public reattach (): void { if (this.touchListener) { - const mask = this.touchListener.mask = _searchMaskInParent(this._node); + const mask = this.touchListener.mask = _searchMaskInParent(this._node as INode); if (this.mouseListener) { this.mouseListener.mask = mask; } } else if (this.mouseListener) { - this.mouseListener.mask = _searchMaskInParent(this._node); + this.mouseListener.mask = _searchMaskInParent(this._node as INode); } } @@ -615,7 +615,7 @@ export class NodeEventProcessor { * @param type - 一个监听事件类型的字符串。 * @param array - 接收目标的数组。 */ - public getCapturingTargets (type: string, targets: INode[]) { + public getCapturingTargets (type: string, targets: IBaseNode[]) { let parent = this._node.parent; while (parent) { if (parent.eventProcessor.capturingTargets && parent.eventProcessor.capturingTargets.hasEventListener(type)) { @@ -634,7 +634,7 @@ export class NodeEventProcessor { * @param type - 一个监听事件类型的字符串。 * @param array - 接收目标的数组。 */ - public getBubblingTargets (type: string, targets: INode[]) { + public getBubblingTargets (type: string, targets: IBaseNode[]) { let parent = this._node.parent; while (parent) { if (parent.eventProcessor.bubblingTargets && parent.eventProcessor.bubblingTargets.hasEventListener(type)) { @@ -656,7 +656,7 @@ export class NodeEventProcessor { event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true, owner: this._node, - mask: _searchMaskInParent(this._node), + mask: _searchMaskInParent(this._node as INode), onTouchBegan: _touchStartHandler, onTouchMoved: _touchMoveHandler, onTouchEnded: _touchEndHandler, @@ -672,7 +672,7 @@ export class NodeEventProcessor { event: cc.EventListener.MOUSE, _previousIn: false, owner: this._node, - mask: _searchMaskInParent(this._node), + mask: _searchMaskInParent(this._node as INode), onMouseDown: _mouseDownHandler, onMouseMove: _mouseMoveHandler, onMouseUp: _mouseUpHandler, diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index d44b040bf5..4cd580d3ea 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -29,21 +29,18 @@ import { UIComponent, UITransformComponent } from '../components/ui-base'; import { ccclass, property } from '../data/class-decorator'; -import Event from '../event/event'; import { Mat3, Mat4, Quat, Size, Vec2, Vec3 } from '../math'; import { SystemEventType } from '../platform/event-manager/event-enum'; import { eventManager } from '../platform/event-manager/event-manager'; import { INode } from '../utils/interfaces'; -import { BaseNode } from './base-node'; +import { BaseNode, TRANFORM_ON } from './base-node'; import { Layers } from './layers'; import { NodeSpace, TransformDirtyBit } from './node-enum'; -import { NodeEventProcessor } from './node-event-processor'; const v3_a = new Vec3(); const q_a = new Quat(); const q_b = new Quat(); const array_a = new Array(10); -const TRANFORM_ON = 1 << 0; const qt_1 = new Quat(); const m3_1 = new Mat3(); const m3_scaling = new Mat3(); @@ -77,14 +74,10 @@ export class Node extends BaseNode implements INode { */ public static TransformDirtyBit = TransformDirtyBit; - /** - * @zh - * 指定对象是否是普通的场景节点? - * @param obj 待测试的节点 - */ - public static isNode (obj: object | null): obj is Node { - return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); - } + // UI 部分的脏数据 + public _uiTransfromComp: UITransformComponent | null = null; + public _uiComp: UIComponent | null = null; + public _static = false; // world transform, don't access this directly protected _pos = new Vec3(); @@ -109,11 +102,14 @@ export class Node extends BaseNode implements INode { protected _dirtyFlags = TransformDirtyBit.NONE; // does the world transform need to update? protected _eulerDirty = false; - protected _eventProcessor: NodeEventProcessor = new NodeEventProcessor(this as INode); - protected _eventMask = 0; - private _uiTransfromComp: UITransformComponent | null = null; - // tslint:disable-next-line: member-ordering - public _uiComp: UIComponent | null = null; + /** + * @zh + * 指定对象是否是普通的场景节点? + * @param obj 待测试的节点 + */ + public static isNode (obj: object | null): obj is Node { + return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); + } /** * @zh @@ -236,8 +232,7 @@ export class Node extends BaseNode implements INode { * 当前节点面向的前方方向 */ get forward (): Vec3 { - this.getWorldRotation(q_a); - return Vec3.transformQuat(new Vec3(), Vec3.UNIT_Z, q_a); + return Vec3.transformQuat(new Vec3(), Vec3.UNIT_Z, this.worldRotation); } set forward (dir: Vec3) { const len = dir.length(); @@ -313,10 +308,6 @@ export class Node extends BaseNode implements INode { this.uiTransfromComp!.anchorY = value; } - get eventProcessor () { - return this._eventProcessor; - } - // =============================== // hierarchy // =============================== @@ -389,7 +380,7 @@ export class Node extends BaseNode implements INode { this._lpos.z += v3_a.z; } else if (space === NodeSpace.WORLD) { if (this._parent) { - Quat.invert(q_a, this.worldRotation); + Quat.invert(q_a, this._parent.worldRotation); Vec3.transformQuat(v3_a, trans, q_a); const scale = this.worldScale; this._lpos.x += v3_a.x / scale.x; @@ -948,55 +939,6 @@ export class Node extends BaseNode implements INode { this.uiTransfromComp!.setContentSize(size, height); } - // Event: maybe remove - - public on (type: string | SystemEventType, callback: Function, target?: Object, useCapture?: any) { - switch (type) { - case SystemEventType.TRANSFORM_CHANGED: - this._eventMask |= TRANFORM_ON; - break; - } - this._eventProcessor.on(type, callback, target, useCapture); - } - - public off (type: string, callback?: Function, target?: Object, useCapture?: any) { - this._eventProcessor.off(type, callback, target, useCapture); - - const hasListeners = this._eventProcessor.hasEventListener(type); - // All listener removed - if (!hasListeners) { - switch (type) { - case SystemEventType.TRANSFORM_CHANGED: - this._eventMask &= ~TRANFORM_ON; - break; - } - } - } - - public once (type: string, callback: Function, target?: Object, useCapture?: any) { - this._eventProcessor.once(type, callback, target, useCapture); - } - - public emit (type: string, ...args: any[]) { - this._eventProcessor.emit(type, ...args); - } - - public dispatchEvent (event: Event) { - this._eventProcessor.dispatchEvent(event); - } - - public hasEventListener (type: string) { - return this._eventProcessor.hasEventListener(type); - } - - public targetOff (target: string | Object) { - this._eventProcessor.targetOff(target); - // Check for event mask reset - if ((this._eventMask & TRANFORM_ON) && !this._eventProcessor.hasEventListener(SystemEventType.TRANSFORM_CHANGED)) { - this._eventMask &= ~TRANFORM_ON; - } - } - public pauseSystemEvents (recursive: boolean): void { // @ts-ignore eventManager.pauseTarget(this, recursive); diff --git a/cocos/core/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts index 48042c2d66..243c6dd7f8 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -28,7 +28,7 @@ */ import { TextureCube } from '../assets/texture-cube'; -import { ccclass, property } from '../data/class-decorator'; +import { ccclass, property, float } from '../data/class-decorator'; import { CCBoolean, CCFloat } from '../data/utils/attribute'; import { Color, Quat, Vec3 } from '../math'; import { Ambient } from '../renderer/scene/ambient'; @@ -70,7 +70,7 @@ export class AmbientInfo { /** * @zh 天空亮度 */ - @property({ type: CCFloat }) + @float set skyIllum (val: number) { this._skyIllum = val; if (this._resource) { this._resource.skyIllum = this.skyIllum; } diff --git a/cocos/core/scene-graph/scene.ts b/cocos/core/scene-graph/scene.ts index cb31de0967..dd384a70cf 100644 --- a/cocos/core/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -28,9 +28,10 @@ */ import { ccclass, property } from '../data/class-decorator'; +import { Mat4, Quat, Vec3 } from '../math'; +import { warnID } from '../platform/debug'; import { RenderScene } from '../renderer/scene/render-scene'; import { BaseNode } from './base-node'; -import { Node } from './node'; import { SceneGlobals } from './scene-globals'; /** @@ -38,11 +39,11 @@ import { SceneGlobals } from './scene-globals'; * cc.Scene is a subclass of cc.Node that is used only as an abstract concept.
* cc.Scene and cc.Node are almost identical with the difference that users can not modify cc.Scene manually. * @zh - * cc.Scene 是 cc.Node 的子类,仅作为一个抽象的概念。
- * cc.Scene 和 cc.Node 有点不同,用户不应直接修改 cc.Scene。 + * cc.Scene 是 cc._BaseNode 的子类,仅作为一个抽象的概念。
+ * cc.Scene 和 cc._BaseNode 有点不同,用户不应直接修改 cc.Scene。 */ @ccclass('cc.Scene') -export class Scene extends Node { +export class Scene extends BaseNode { get renderScene () { return this._renderScene; @@ -72,6 +73,13 @@ export class Scene extends Node { protected _inited: boolean; protected _prefabSyncedInLiveReload = false; + // support Node access parent data from Scene + protected _pos = Vec3.ZERO; + protected _rot = Quat.IDENTITY; + protected _scale = Vec3.ONE; + protected _mat = Mat4.IDENTITY; + protected _dirtyFlags = 0; + constructor (name: string) { super(name); this._activeInHierarchy = false; @@ -88,7 +96,48 @@ export class Scene extends Node { return success; } + public addComponent (typeOrClassName: string | Function) { + warnID(3822); + return null; + } + public _onHierarchyChanged () { } + + public _onBatchCreated () { + super._onBatchCreated(); + const len = this._children.length; + for (let i = 0; i < len; ++i) { + this._children[i]._onBatchCreated(); + } + } + + public _onBatchRestored () { + this._onBatchCreated(); + } + + // transform helpers + + public getPosition (out?: Vec3): Vec3 { return Vec3.copy(out || new Vec3(), Vec3.ZERO); } + public getRotation (out?: Quat): Quat { return Quat.copy(out || new Quat(), Quat.IDENTITY); } + public getScale (out?: Vec3): Vec3 { return Vec3.copy(out || new Vec3(), Vec3.ONE); } + public getWorldPosition (out?: Vec3) { return Vec3.copy(out || new Vec3(), Vec3.ZERO); } + public getWorldRotation (out?: Quat) { return Quat.copy(out || new Quat(), Quat.IDENTITY); } + public getWorldScale (out?: Vec3) { return Vec3.copy(out || new Vec3(), Vec3.ONE); } + public getWorldMatrix (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } + public getWorldRS (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } + public getWorldRT (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } + public get position (): Readonly { return Vec3.ZERO; } + public get worldPosition (): Readonly { return Vec3.ZERO; } + public get rotation (): Readonly { return Quat.IDENTITY; } + public get worldRotation (): Readonly { return Quat.IDENTITY; } + public get scale (): Readonly { return Vec3.ONE; } + public get worldScale (): Readonly { return Vec3.ONE; } + public get eulerAngles (): Readonly { return Vec3.ZERO; } + public get worldMatrix (): Readonly { return Mat4.IDENTITY; } + public updateWorldTransform () {} + + // life-cycle call backs + protected _instantiate () { } protected _load () { @@ -99,6 +148,8 @@ export class Scene extends Node { this._onBatchCreated(); this._inited = true; } + // @ts-ignore + // static methode can't use this as parameter type this.walk(BaseNode._setScene); } diff --git a/cocos/core/scheduler.ts b/cocos/core/scheduler.ts index dc6b3b6f1d..7b59e7e883 100644 --- a/cocos/core/scheduler.ts +++ b/cocos/core/scheduler.ts @@ -565,7 +565,7 @@ export class Scheduler extends System { * @param {Number} [delay=0] * @param {Boolean} [paused=fasle] */ - public schedule (callback: Function, target: ISchedulable, interval: number, repeat: number, delay: number, paused?: boolean) { + public schedule (callback: Function, target: ISchedulable, interval: number, repeat?: number, delay?: number, paused?: boolean) { 'use strict'; if (typeof callback !== 'function') { const tmp = callback; @@ -575,7 +575,7 @@ export class Scheduler extends System { } // selector, target, interval, repeat, delay, paused // selector, target, interval, paused - if (arguments.length === 4 || arguments.length === 5) { + if (arguments.length === 3 || arguments.length === 4 || arguments.length === 5) { paused = !!repeat; repeat = cc.macro.REPEAT_FOREVER; delay = 0; @@ -1082,7 +1082,7 @@ export class Scheduler extends System { let targetId = target.uuid || target.id; if (!targetId) { cc.errorID(1510); - return; + return false; } // Custom selectors diff --git a/cocos/core/splash-image.ts b/cocos/core/splash-image.ts index c8f8eb54aa..a2313cdfeb 100644 --- a/cocos/core/splash-image.ts +++ b/cocos/core/splash-image.ts @@ -7,8 +7,10 @@ import { EffectAsset } from './assets/effect-asset'; import { Material } from './assets/material'; import { GFXBuffer } from './gfx/buffer'; import { GFXCommandBuffer } from './gfx/command-buffer'; -import { GFXBufferTextureCopy, GFXBufferUsageBit, GFXClearFlag, GFXCommandBufferType, GFXFormat, - GFXMemoryUsageBit, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType, IGFXRect } from './gfx/define'; +import { + GFXBufferTextureCopy, GFXBufferUsageBit, GFXClearFlag, GFXCommandBufferType, GFXFormat, + GFXMemoryUsageBit, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType, IGFXRect, IGFXColor +} from './gfx/define'; import { GFXDevice } from './gfx/device'; import { GFXFramebuffer } from './gfx/framebuffer'; import { GFXInputAssembler, IGFXAttribute } from './gfx/input-assembler'; @@ -17,20 +19,19 @@ import { GFXTexture } from './gfx/texture'; import { GFXTextureView } from './gfx/texture-view'; import { clamp01 } from './math/utils'; -export type SplashEffectType = 'none' | 'Fade-in-out'; +export type SplashEffectType = 'none' | 'Fade-InOut'; export interface ISplashSetting { readonly totalTime: number; readonly base64src: string; readonly effect: SplashEffectType; - // readonly clearColor: any; + readonly clearColor: IGFXColor; + readonly displayRatio: number; + readonly displayWatermark: boolean; } -// tslint:disable-next-line: max-line-length -const defaultSrcBase64 = 'data:image/png;base64,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'; - export class SplashScreen { - public set splashFinish (v: boolean) { + private set splashFinish (v: boolean) { this._splashFinish = v; this._tryToStart(); } @@ -44,7 +45,7 @@ export class SplashScreen { private cancelAnimate: boolean = false; private startTime: number = -1; private setting!: ISplashSetting; - private image!: HTMLImageElement; + private image!: TexImageSource; private device!: GFXDevice; private cmdBuff!: GFXCommandBuffer; private assmebler!: GFXInputAssembler; @@ -57,26 +58,51 @@ export class SplashScreen { private material!: Material; private texture!: GFXTexture; private textureView!: GFXTextureView; + private clearColors!: IGFXColor[]; private _splashFinish: boolean = false; - private _loadFinish: boolean = false; + /** text */ + private textImg!: TexImageSource; + private textRegion!: GFXBufferTextureCopy; + private textTexture!: GFXTexture; + private textTextureView!: GFXTextureView; + private textVB!: GFXBuffer; + private textIB!: GFXBuffer; + private textAssmebler!: GFXInputAssembler; + private textMaterial!: Material; + private textPSO!: GFXPipelineState; + + /** shader */ + private program!: { name: string, techniques: any[], shaders: any[] }; + private effect!: EffectAsset; + + /** size */ + private screenWidth!: number; + private screenHeight!: number; + public main (device: GFXDevice) { - if (window._CCSettings && window._CCSettings.SplashScreen) { - this.setting = window._CCSettings.SplashScreen; + if (window._CCSettings && window._CCSettings.splashScreen) { + this.setting = window._CCSettings.splashScreen; (this.setting.totalTime as number) = this.setting.totalTime != null ? this.setting.totalTime : 3000; - (this.setting.base64src as string) = this.setting.base64src != null ? this.setting.base64src : defaultSrcBase64; - (this.setting.effect as SplashEffectType) = this.setting.effect != null ? this.setting.effect : 'none'; + (this.setting.base64src as string) = this.setting.base64src != null ? this.setting.base64src : ''; + (this.setting.effect as SplashEffectType) = this.setting.effect != null ? this.setting.effect : 'Fade-InOut'; + (this.setting.clearColor as IGFXColor) = this.setting.clearColor != null ? this.setting.clearColor : { r: 0.88, g: 0.88, b: 0.88, a: 1.0 }; + (this.setting.displayRatio as number) = this.setting.displayRatio != null ? this.setting.displayRatio : 0.4; + (this.setting.displayWatermark as boolean) = this.setting.displayWatermark != null ? this.setting.displayWatermark : true; } else { this.setting = { totalTime: 3000, - base64src: defaultSrcBase64, - effect: 'none', + base64src: '', + effect: 'Fade-InOut', + clearColor: { r: 0.88, g: 0.88, b: 0.88, a: 1.0 }, + displayRatio: 0.4, + displayWatermark: true }; } - if (this.setting.totalTime <= 0) { + if (this.setting.base64src == '' || this.setting.totalTime <= 0) { if (this.callBack) { this.callBack(); } this.callBack = null; (this.setting as any) = null; @@ -87,11 +113,67 @@ export class SplashScreen { cc.director._lateUpdate = performance.now(); }, cc.director); + // this.program = effects.find(function (element) { + // return element.name == 'util/splash-image'; + // }); + + this.program = { + name: 'util/splash-image', + techniques: [ + { + passes: [{ + blendState: { targets: [{ blend: true, blendSrc: 2, blendDst: 4, blendDstAlpha: 4 }] }, + program: 'util/splash-image|splash-vs:vert|splash-fs:frag', + depthStencilState: { depthTest: true, depthWrite: false }, + properties: { mainTexture: { value: 'grey', type: 28 }, u_precent: { type: 13 } } + }], + }, + ], + shaders: [ + { + name: 'util/splash-image|splash-vs:vert|splash-fs:frag', + hash: 2381344969, + glsl3: { + // tslint:disable: max-line-length + vert: `\nprecision mediump float;\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_uv;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0, 1);\n v_uv = a_texCoord;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + frag: `\nprecision mediump float;\nin vec2 v_uv;\nuniform sampler2D mainTexture;\nuniform splashFrag {\n float u_precent;\n};\nvec4 frag () {\n vec4 color = texture(mainTexture, v_uv);\n float precent = clamp(u_precent, 0.0, 1.0);\n color.xyz *= precent;\n return color;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n`, + }, + glsl1: { + vert: `\nprecision mediump float;\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0, 1);\n v_uv = a_texCoord;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + frag: `\nprecision mediump float;\nvarying vec2 v_uv;\nuniform sampler2D mainTexture;\nuniform float u_precent;\nvec4 frag () {\n vec4 color = texture2D(mainTexture, v_uv);\n float precent = clamp(u_precent, 0.0, 1.0);\n color.xyz *= precent;\n return color;\n}\nvoid main() { gl_FragColor = frag(); }\n`, + // tslint:enable: max-line-length + }, + builtins: { globals: { blocks: [], samplers: [] }, locals: { blocks: [], samplers: [] } }, + defines: [], + blocks: [ + { + name: 'splashFrag', defines: [], binding: 0, members: [ + { name: 'u_precent', type: 13, count: 1 }, + ], + }, + ], + samplers: [ + { name: 'mainTexture', type: 28, count: 1, defines: [], binding: 30 }, + ], + dependencies: {}, + }, + ], + }; + + this.effect = new EffectAsset(); + this.effect.name = this.program.name; + this.effect.techniques = this.program.techniques; + this.effect.shaders = this.program.shaders; + this.effect.onLoaded(); + this.callBack = null; this.cancelAnimate = false; this.startTime = -1; - + this.clearColors = [this.setting.clearColor]; this.device = device; + this.screenWidth = this.device.width; + this.screenHeight = this.device.height; + this.image = new Image(); this.image.onload = this.init.bind(this); this.image.src = this.setting.base64src; @@ -116,6 +198,10 @@ export class SplashScreen { this.initIA(); this.initPSO(); + if (this.setting.displayWatermark) { + this.initText(); + } + const animate = (time: number) => { if (this.cancelAnimate) { return; @@ -128,9 +214,15 @@ export class SplashScreen { /** update uniform */ const precent = clamp01(elapsedTime / this.setting.totalTime); - this.material.setProperty('u_precent', easing.cubicOut(precent)); + const u_p = easing.cubicOut(precent); + this.material.setProperty('u_precent', u_p); this.material.passes[0].update(); + if (this.setting.displayWatermark && this.textMaterial) { + this.textMaterial.setProperty('u_precent', u_p); + this.textMaterial.passes[0].update(); + } + this.frame(time); if (elapsedTime > this.setting.totalTime) { @@ -146,24 +238,30 @@ export class SplashScreen { cancelAnimationFrame(this.handle); this.cancelAnimate = true; this.destoy(); - delete SplashScreen._ins; } private frame (time: number) { const device = this.device; - const pso = this.pso; const cmdBuff = this.cmdBuff; const framebuffer = this.framebuffer; const renderArea = this.renderArea; - const assmebler = this.assmebler; cmdBuff.begin(); cmdBuff.beginRenderPass(framebuffer, renderArea, - GFXClearFlag.ALL, [{ r: 0.88, g: 0.88, b: 0.88, a: 1 }], 1.0, 0); - cmdBuff.bindPipelineState(pso); - cmdBuff.bindBindingLayout(pso.pipelineLayout.layouts[0]); - cmdBuff.bindInputAssembler(assmebler); - cmdBuff.draw(assmebler); + GFXClearFlag.ALL, this.clearColors, 1.0, 0); + + cmdBuff.bindPipelineState(this.pso); + cmdBuff.bindBindingLayout(this.pso.pipelineLayout.layouts[0]); + cmdBuff.bindInputAssembler(this.assmebler); + cmdBuff.draw(this.assmebler); + + if (this.setting.displayWatermark && this.textPSO && this.textAssmebler) { + cmdBuff.bindPipelineState(this.textPSO); + cmdBuff.bindBindingLayout(this.textPSO.pipelineLayout.layouts[0]); + cmdBuff.bindInputAssembler(this.textAssmebler); + cmdBuff.draw(this.textAssmebler); + } + cmdBuff.endRenderPass(); cmdBuff.end(); @@ -171,6 +269,126 @@ export class SplashScreen { device.present(); } + private initText () { + /** texure */ + this.textImg = document.createElement('canvas'); + this.textImg.width = 300; + this.textImg.height = 30; + this.textImg.style.width = `${this.textImg.width}`; + this.textImg.style.height = `${this.textImg.height}`; + + const ctx = this.textImg.getContext('2d')!; + ctx.font = `${18}px Arial` + ctx.textBaseline = 'top'; + ctx.textAlign = 'left'; + ctx.fillStyle = '`#424242`'; + ctx.fillText("Powered by Cocos Creator 3D", 30, 8); + + this.textRegion = new GFXBufferTextureCopy(); + this.textRegion.texExtent.width = this.textImg.width; + this.textRegion.texExtent.height = this.textImg.height; + this.textRegion.texExtent.depth = 1; + + this.textTexture = this.device.createTexture({ + type: GFXTextureType.TEX2D, + usage: GFXTextureUsageBit.SAMPLED, + format: GFXFormat.RGBA8, + width: this.textImg.width, + height: this.textImg.height, + mipLevel: 1, + }); + + this.textTextureView = this.device.createTextureView({ + texture: this.textTexture, + type: GFXTextureViewType.TV2D, + format: GFXFormat.RGBA8, + }); + + this.device.copyTexImagesToTexture([this.textImg], this.textTexture, [this.textRegion]); + + + /** PSO */ + this.textMaterial = new Material(); + this.textMaterial.initialize({ + effectAsset: this.effect, + }); + + const pass = this.textMaterial.passes[0]; + const binding = pass.getBinding('mainTexture'); + pass.bindTextureView(binding!, this.textTextureView!); + + this.textPSO = pass.createPipelineState() as GFXPipelineState; + this.textPSO.pipelineLayout.layouts[0].update(); + + /** Assembler */ + // create vertex buffer + const vbStride = Float32Array.BYTES_PER_ELEMENT * 4; + const vbSize = vbStride * 4; + this.textVB = this.device.createBuffer({ + usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: vbSize, + stride: vbStride, + }); + + const verts = new Float32Array(4 * 4); + let w = -this.textImg.width / 2; + let h = -this.textImg!.height / 2; + if (this.screenWidth < this.screenHeight) { + w = -this.screenWidth / 2 * 0.5; + h = w / (this.textImg.width / this.textImg.height); + } else { + w = -this.screenHeight / 2 * 0.5; + h = w / (this.textImg.width / this.textImg.height); + } + let n = 0; + verts[n++] = w; verts[n++] = h; verts[n++] = 0.0; verts[n++] = 1.0; + verts[n++] = -w; verts[n++] = h; verts[n++] = 1.0; verts[n++] = 1.0; + verts[n++] = w; verts[n++] = -h; verts[n++] = 0.0; verts[n++] = 0.0; + verts[n++] = -w; verts[n++] = -h; verts[n++] = 1.0; verts[n++] = 0.0; + + // translate to bottom + for (let i = 0; i < verts.length; i += 4) { + verts[i] = verts[i] + this.screenWidth / 2; + verts[i + 1] = verts[i + 1] + this.screenHeight * 0.1; + } + + // transform to clipspace + for (let i = 0; i < verts.length; i += 4) { + verts[i] = verts[i] / this.screenWidth * 2 - 1; + verts[i + 1] = verts[i + 1] / this.screenHeight * 2 - 1; + } + + this.textVB.update(verts); + + // create index buffer + const ibStride = Uint8Array.BYTES_PER_ELEMENT; + const ibSize = ibStride * 6; + + this.textIB = this.device.createBuffer({ + usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: ibSize, + stride: ibStride, + }); + + const indices = new Uint8Array(6); + indices[0] = 0; indices[1] = 1; indices[2] = 2; + indices[3] = 1; indices[4] = 3; indices[5] = 2; + this.textIB.update(indices); + + const attributes: IGFXAttribute[] = [ + { name: 'a_position', format: GFXFormat.RG32F }, + { name: 'a_texCoord', format: GFXFormat.RG32F }, + ]; + + this.textAssmebler = this.device.createInputAssembler({ + attributes, + vertexBuffers: [this.textVB], + indexBuffer: this.textIB, + }); + } + private initCMD () { const device = this.device as GFXDevice; this.renderArea = { x: 0, y: 0, width: device.width, height: device.height }; @@ -197,8 +415,15 @@ export class SplashScreen { }); const verts = new Float32Array(4 * 4); - const w = -this.image.width / 2; - const h = -this.image!.height / 2; + let w = -this.image.width / 2; + let h = -this.image!.height / 2; + if (this.screenWidth < this.screenHeight) { + w = -this.screenWidth / 2 * this.setting.displayRatio; + h = w / (this.image.width / this.image.height); + } else { + w = -this.screenHeight / 2 * this.setting.displayRatio; + h = w / (this.image.width / this.image.height); + } let n = 0; verts[n++] = w; verts[n++] = h; verts[n++] = 0.0; verts[n++] = 1.0; verts[n++] = -w; verts[n++] = h; verts[n++] = 1.0; verts[n++] = 1.0; @@ -207,14 +432,14 @@ export class SplashScreen { // translate to center for (let i = 0; i < verts.length; i += 4) { - verts[i] = verts[i] + device.width / 2; - verts[i + 1] = verts[i + 1] + device.height / 2; + verts[i] = verts[i] + this.screenWidth / 2; + verts[i + 1] = verts[i + 1] + this.screenHeight / 2; } // transform to clipspace for (let i = 0; i < verts.length; i += 4) { - verts[i] = verts[i] / device.width * 2 - 1; - verts[i + 1] = verts[i + 1] / device.height * 2 - 1; + verts[i] = verts[i] / this.screenWidth * 2 - 1; + verts[i + 1] = verts[i + 1] / this.screenHeight * 2 - 1; } this.vertexBuffers.update(verts); @@ -251,60 +476,9 @@ export class SplashScreen { const device = this.device as GFXDevice; - // const program = effects.find(function (element) { - // return element.name == 'util/splash-image'; - // }); - - const program = { - name: 'util/splash-image', - techniques: [ - { - passes: [{ blendState: { targets: [{ blend: true, blendSrc: 2, blendDst: 4, blendDstAlpha: 4 }] }, - program: 'util/splash-image|splash-vs:vert|splash-fs:frag', - depthStencilState: { depthTest: true, depthWrite: false }, - properties: { mainTexture: { value: 'grey', type: 28 }, u_precent: { type: 13 } } }], - }, - ], - shaders: [ - { - name: 'util/splash-image|splash-vs:vert|splash-fs:frag', - hash: 2381344969, - glsl3: { - // tslint:disable: max-line-length - vert: `\nprecision mediump float;\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_uv;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0, 1);\n v_uv = a_texCoord;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - frag: `\nprecision mediump float;\nin vec2 v_uv;\nuniform sampler2D mainTexture;\nuniform splashFrag {\n float u_precent;\n};\nvec4 frag () {\n vec4 color = texture(mainTexture, v_uv);\n float precent = clamp(u_precent, 0.0, 1.0);\n color.xyz *= precent;\n return color;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n`, - }, - glsl1: { - vert: `\nprecision mediump float;\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0, 1);\n v_uv = a_texCoord;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - frag: `\nprecision mediump float;\nvarying vec2 v_uv;\nuniform sampler2D mainTexture;\nuniform float u_precent;\nvec4 frag () {\n vec4 color = texture2D(mainTexture, v_uv);\n float precent = clamp(u_precent, 0.0, 1.0);\n color.xyz *= precent;\n return color;\n}\nvoid main() { gl_FragColor = frag(); }\n`, - // tslint:enable: max-line-length - }, - builtins: { globals: { blocks: [], samplers: [] }, locals: { blocks: [], samplers: [] } }, - defines: [], - blocks: [ - { - name: 'splashFrag', defines: [], binding: 0, members: [ - { name: 'u_precent', type: 13, count: 1 }, - ], - }, - ], - samplers: [ - { name: 'mainTexture', type: 28, count: 1, defines: [], binding: 30 }, - ], - dependencies: {}, - }, - ], - }; - - const effect = new EffectAsset(); - effect.name = program!.name; - effect.techniques = program!.techniques as any; - effect.shaders = program!.shaders; - effect.onLoaded(); - this.material = new Material(); this.material.initialize({ - effectAsset: effect, + effectAsset: this.effect, }); this.texture = device.createTexture({ @@ -338,12 +512,16 @@ export class SplashScreen { private destoy () { this.callBack = null; - (this.setting as any) = null; + (this.clearColors as any) = null; (this.device as any) = null; (this.image as any) = null; (this.framebuffer as any) = null; (this.renderArea as any) = null; (this.region as any) = null; + (this.program as any) = null; + + this.effect.destroy(); + (this.effect as any) = null; this.cmdBuff.destroy(); (this.cmdBuff as any) = null; @@ -368,6 +546,36 @@ export class SplashScreen { this.indicesBuffers.destroy(); (this.indicesBuffers as any) = null; + + /** text */ + if (this.setting.displayWatermark && this.textImg) { + (this.textImg as any) = null; + (this.textRegion as any) = null; + + this.textPSO.destroy(); + (this.textPSO as any) = null; + + this.textMaterial.destroy(); + (this.textMaterial as any) = null; + + this.textTextureView.destroy(); + (this.textTextureView as any) = null; + + this.textTexture.destroy(); + (this.textTexture as any) = null; + + this.textAssmebler.destroy(); + (this.textAssmebler as any) = null; + + this.textVB.destroy(); + (this.textVB as any) = null; + + this.textIB.destroy(); + (this.textIB as any) = null; + } + + (this.setting as any) = null; + delete SplashScreen._ins; } private static _ins: SplashScreen; diff --git a/cocos/core/utils/id-generator.ts b/cocos/core/utils/id-generator.ts index 78c25a5bd1..41d0d7cbe8 100644 --- a/cocos/core/utils/id-generator.ts +++ b/cocos/core/utils/id-generator.ts @@ -50,7 +50,7 @@ export default class IDGenerator { public getNewId () { if (CC_EDITOR && (this.prefix === 'Node.' || this.prefix === 'Comp.')) { - return Editor.Utils.UuidUtils.uuid(); + return Editor.Utils.UuidUtils.uuid() as string; } return this.prefix + (++this.id); } diff --git a/cocos/core/utils/interfaces.ts b/cocos/core/utils/interfaces.ts index 99188ec1e4..a4199cd5e8 100644 --- a/cocos/core/utils/interfaces.ts +++ b/cocos/core/utils/interfaces.ts @@ -23,13 +23,13 @@ THE SOFTWARE. */ -import { SystemEventType } from '../platform/event-manager/event-enum'; -import { Mat4, Quat, Size, Vec2, Vec3 } from '../math'; -import { Scene } from '../scene-graph/scene'; -import { NodeEventProcessor } from '../scene-graph/node-event-processor'; import { Component } from '../components/component'; import { Event } from '../event'; -import { TransformDirtyBit, NodeSpace } from '../scene-graph/node-enum'; +import { Mat4, Quat, Size, Vec2, Vec3 } from '../math'; +import { SystemEventType } from '../platform/event-manager/event-enum'; +import { NodeSpace, TransformDirtyBit } from '../scene-graph/node-enum'; +import { NodeEventProcessor } from '../scene-graph/node-event-processor'; +import { Scene } from '../scene-graph/scene'; export interface IBaseNode { @@ -143,6 +143,12 @@ export interface IBaseNode { */ components: ReadonlyArray; + /** + * @zh + * 节点事件相关的处理器 + */ + eventProcessor: Readonly; + /** * @en Get parent of the node. * @zh 获取该节点的父节点。 @@ -180,18 +186,6 @@ export interface IBaseNode { */ addChild (child: this): void; - /** - * @zh 移除节点中指定的子节点 - * @param child 孩子节点 - */ - removeChild (child: this, cleanup?: boolean): void; - - /** - * @zh 插入子节点到指定位置 - * @param siblingIndex 指定位置 - */ - insertChild (child: this, siblingIndex: number): void; - /** * @en Returns a child from the container given its uuid. * @zh 通过 uuid 获取节点的子节点。 @@ -288,7 +282,7 @@ export interface IBaseNode { * node.removeChild(newNode); * ``` */ - removeChild (child: this): void; + removeChild (child: this, cleanup?: boolean): void; /** * @en @@ -340,7 +334,6 @@ export interface IBaseNode { */ removeComponent (classConstructor: Constructor): void; removeComponent (classNameOrInstance: string | Component): void; - removeComponent (component: string | Component | any): void; _removeComponent (component: Component): void; @@ -407,6 +400,18 @@ export interface IBaseNode { getComponentsInChildren (className: string): Component[]; getComponentsInChildren (typeOrClassName: string | Function); + /** + * @zh + * 节点事件API,注:未来可能会移除 + */ + on (type: string | SystemEventType, callback: Function, target?: Object, useCapture?: boolean): void; + off (type: string, callback?: Function, target?: Object, useCapture?: boolean): void; + once (type: string, callback: Function, target?: Object, useCapture?: boolean): void; + emit (type: string, ...args: any[]): void; + dispatchEvent (event: Event): void; + hasEventListener (type: string): boolean; + targetOff (target: string | Object): void; + /** * @zh * 销毁实例,实际销毁操作会延迟到当前帧渲染前执行。 @@ -443,12 +448,6 @@ export interface INode extends IBaseNode { */ hasChangedFlags: Readonly; - /** - * @zh - * 节点事件相关的处理器 - */ - eventProcessor: Readonly; - /** * @zh * 本地坐标 @@ -521,6 +520,8 @@ export interface INode extends IBaseNode { uiTransfromComp; + _static: boolean; + /** * @zh * 获取本地坐标 @@ -727,14 +728,7 @@ export interface INode extends IBaseNode { * @zh * 节点事件API,注:未来可能会移除 */ - on (type: string | SystemEventType, callback: Function, target?: Object, useCapture?: boolean): void; - off (type: string, callback?: Function, target?: Object, useCapture?: boolean): void; - once (type: string, callback: Function, target?: Object, useCapture?: boolean): void; - emit (type: string, ...args: any[]): void; - dispatchEvent (event: Event): void; - hasEventListener (type: string): boolean; - targetOff (target: string | Object): void; pauseSystemEvents (recursive: boolean): void; resumeSystemEvents (recursive: boolean): void; - _updateSiblingIndex(): void; + _updateSiblingIndex (): void; } diff --git a/cocos/core/utils/murmurhash2_gc.ts b/cocos/core/utils/murmurhash2_gc.ts index 87f238cf96..13d9b34a9e 100644 --- a/cocos/core/utils/murmurhash2_gc.ts +++ b/cocos/core/utils/murmurhash2_gc.ts @@ -11,17 +11,21 @@ * @return {number} 32-bit positive integer hash */ -export function murmurhash2_32_gc (str: string, seed: number) { - let l = str.length; +const getUint8ForString = String.prototype.charCodeAt; +function getUint8ForArray (this: Uint8Array, idx: number) { return this[idx]; } + +export function murmurhash2_32_gc (input: string | Uint8Array, seed: number) { + let l = input.length; let h = seed ^ l; let i = 0; + const getUint8 = typeof input === 'string' ? getUint8ForString : getUint8ForArray; while (l >= 4) { let k = - ((str.charCodeAt(i) & 0xff)) | - ((str.charCodeAt(++i) & 0xff) << 8) | - ((str.charCodeAt(++i) & 0xff) << 16) | - ((str.charCodeAt(++i) & 0xff) << 24); + ((getUint8.call(input, i) & 0xff)) | + ((getUint8.call(input, ++i) & 0xff) << 8) | + ((getUint8.call(input, ++i) & 0xff) << 16) | + ((getUint8.call(input, ++i) & 0xff) << 24); k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); k ^= k >>> 24; @@ -34,9 +38,9 @@ export function murmurhash2_32_gc (str: string, seed: number) { } switch (l) { - case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; - case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; - case 1: h ^= (str.charCodeAt(i) & 0xff); + case 3: h ^= (getUint8.call(input, i + 2) & 0xff) << 16; + case 2: h ^= (getUint8.call(input, i + 1) & 0xff) << 8; + case 1: h ^= (getUint8.call(input, i) & 0xff); h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); } diff --git a/cocos/core/utils/profiler/counter.ts b/cocos/core/utils/profiler/counter.ts index 0391e12010..408b9746ab 100644 --- a/cocos/core/utils/profiler/counter.ts +++ b/cocos/core/utils/profiler/counter.ts @@ -1,4 +1,3 @@ -import { ccclass } from '../../../core/data/class-decorator'; export interface ICounterOption { desc: string; @@ -9,15 +8,15 @@ export interface ICounterOption { below?: number; over?: number; color?: string; + isInteger?: boolean; } -@ccclass('cc.Counter') export class Counter { - get value (){ + get value () { return this._value; } - set value (val){ + set value (val) { this._value = val; } @@ -40,9 +39,10 @@ export class Counter { this._average(this._value, now); } - public human (isPoint = true) { - const v = this._opts.average ? this._averageValue : this._value; - return isPoint ? Math.round(v * 100) / 100 : Math.round(v); + public human () { + const { average, isInteger } = this._opts; + const v = average ? this._averageValue : this._value; + return isInteger ? Math.round(v) : Math.round(v * 100) / 100; } public alarm () { diff --git a/cocos/core/utils/profiler/profiler.ts b/cocos/core/utils/profiler/profiler.ts index 9c447d494d..2aa3b8868d 100644 --- a/cocos/core/utils/profiler/profiler.ts +++ b/cocos/core/utils/profiler/profiler.ts @@ -27,12 +27,12 @@ import { CameraComponent, ModelComponent } from '../../3d'; import { createMesh } from '../../3d/misc/utils'; import { Material } from '../../assets/material'; -import { director, Director } from '../../director'; import { GFXBufferTextureCopy, GFXClearFlag, GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXTexture } from '../../gfx/texture'; import { GFXTextureView } from '../../gfx/texture-view'; import { Vec4 } from '../../math'; +import { IBlock } from '../../renderer/core/pass'; import { Layers } from '../../scene-graph'; import { Node } from '../../scene-graph/node'; import { ICounterOption } from './counter'; @@ -44,24 +44,54 @@ interface IProfilerState { draws: ICounterOption; tricount: ICounterOption; logic: ICounterOption; - render: ICounterOption; - // mode: ICounterOption; physics: ICounterOption; + render: ICounterOption; textureMemory: ICounterOption; bufferMemory: ICounterOption; } +const _characters = '0123456789. '; + +const _string2offset = { + '0': 0, + '1': 1, + '2': 2, + '3': 3, + '4': 4, + '5': 5, + '6': 6, + '7': 7, + '8': 8, + '9': 9, + '.': 10, +}; + +const _profileInfo = { + frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: 500 }, + fps: { desc: 'Framerate (FPS)', below: 30, average: 500, isInteger: true }, + draws: { desc: 'Draw call', isInteger: true }, + tricount: { desc: 'Triangle', isInteger: true }, + logic: { desc: 'Game Logic (ms)', min: 0, max: 50, average: 500, color: '#080' }, + physics: { desc: 'Physics (ms)', min: 0, max: 50, average: 500 }, + render: { desc: 'Renderer (ms)', min: 0, max: 50, average: 500, color: '#f90' }, + textureMemory: { desc: 'GFX Texture Mem(M)' }, + bufferMemory: { desc: 'GFX Buffer Mem(M)'}, +}; + +const _constants = { + fontSize: 24, + quadHeight: 0.18, + segmentsPerLine: 8, + textureWidth: 256, + textureHeight: 256, +}; + export class Profiler { public _stats: IProfilerState | null = null; + public id = '__Profiler__'; private _showFPS = false; - private readonly _fontSize = 22; - private readonly _lineHeight = this._fontSize + 2; - private readonly _left = 10; - private readonly _right = 10; - private readonly _top = 10; - private readonly _bottom = 10; private _rootNode: Node | null = null; private _device: GFXDevice | null = null; @@ -72,9 +102,20 @@ export class Profiler { private readonly _region: GFXBufferTextureCopy = new GFXBufferTextureCopy(); private readonly _canvasArr: HTMLCanvasElement[] = []; private readonly _regionArr = [this._region]; + private digitsData: IBlock = null!; private _canvasDone = false; private _statsDone = false; + private _inited = false; + + private readonly _lineHeight = _constants.fontSize + 2; + private _wordHeight = 0; + private _eachNumWidth = 0; // profiler each number width + private _totalLines = 0; // total lines to display + + private lastTime = 0; // update use time + + private _uvOffset: Vec4[] = []; constructor () { if (!CC_TEST) { @@ -95,12 +136,12 @@ export class Profiler { this._rootNode.active = false; } - director.off(Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); - director.off(Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); - director.off(Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); - director.off(Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); - director.off(Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); - director.off(Director.EVENT_AFTER_DRAW, this.afterDraw, this); + cc.director.off(cc.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); + cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); + cc.director.off(cc.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); + cc.director.off(cc.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); + cc.director.off(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); + cc.director.off(cc.Director.EVENT_AFTER_DRAW, this.afterDraw, this); this._showFPS = false; } } @@ -110,17 +151,18 @@ export class Profiler { this.initDevice(); this.generateCanvas(); this.generateStats(); + cc.game.on(cc.Game.EVENT_ENGINE_INITED, this.generateNode, this); if (this._rootNode) { this._rootNode.active = true; } - director.on(Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); - director.on(Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); - director.on(Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); - director.on(Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); - director.on(Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); - director.on(Director.EVENT_AFTER_DRAW, this.afterDraw, this); + cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); + cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); + cc.director.on(cc.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); + cc.director.on(cc.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); + cc.director.on(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); + cc.director.on(cc.Director.EVENT_AFTER_DRAW, this.afterDraw, this); this._showFPS = true; this._canvasDone = true; @@ -132,7 +174,7 @@ export class Profiler { if (this._device) { return; } - this._device = director.root!.device; + this._device = cc.director.root!.device; } public generateCanvas () { @@ -141,8 +183,7 @@ export class Profiler { return; } - const textureWidth = 350; - const textureHeight = 200; + const { textureWidth, textureHeight } = _constants; if (!this._ctx || !this._canvas) { return; @@ -153,7 +194,7 @@ export class Profiler { this._canvas.style.width = `${this._canvas.width}`; this._canvas.style.height = `${this._canvas.height}`; - this._ctx.font = `${this._fontSize}px Arial`; + this._ctx.font = `${_constants.fontSize}px Arial`; this._ctx.textBaseline = 'top'; this._ctx.fillStyle = '#fff'; @@ -177,35 +218,46 @@ export class Profiler { } public generateStats () { - if (this._statsDone || !this._ctx) { + if (this._statsDone || !this._ctx || !this._canvas ) { return; } this._stats = null; + this._inited = false; const now = performance.now(); - const opts = { - frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: 500 }, - fps: { desc: 'Framerate (FPS)', below: 30, average: 500 }, - draws: { desc: 'Draw call' }, - tricount: { desc: 'Triangle' }, - logic: { desc: 'Game Logic (ms)', min: 0, max: 50, average: 500, color: '#080' }, - physics: { desc: 'Physics (ms)', min: 0, max: 50, average: 500 }, - render: { desc: 'Renderer (ms)', min: 0, max: 50, average: 500, color: '#f90' }, - textureMemory: { desc: 'GFX Texture Mem(M)' }, - bufferMemory: { desc: 'GFX Buffer Mem(M)'}, - }; - this._ctx.textAlign = 'left'; let i = 0; - for (const id of Object.keys(opts)) { - this._ctx.fillText(opts[id].desc, this._left, this._top + i * this._lineHeight); - opts[id].counter = new PerfCounter(id, opts[id], now); + for (const id in _profileInfo) { + const element = _profileInfo[id]; + this._ctx.fillText(element.desc, 0, i * this._lineHeight); + element.counter = new PerfCounter(id, element, now); i++; } - this._ctx.textAlign = 'end'; + this._totalLines = i; + this._wordHeight = this._totalLines * this._lineHeight / this._canvas.height; - this._stats = opts as IProfilerState; + this._eachNumWidth = this._ctx.measureText('0').width / this._canvas.width; // each number uv width + const canvasNumWidth = this._eachNumWidth * this._canvas.width; // each number width in canvas + + const offsets = new Array(); + let offset = 0; + offsets[0] = 0; + for (let j = 0; j < _characters.length; ++j) { + this._ctx.fillText(_characters[j], j * canvasNumWidth, this._totalLines * this._lineHeight); + offset += this._eachNumWidth; + offsets[j + 1] = offset; + } + + const len = Math.ceil(offsets.length / 4); + for (let j = 0; j < len; j++) { + this._uvOffset.push(new Vec4(offsets[j * 4], offsets[j * 4 + 1], offsets[j * 4 + 2], offsets[j * 4 + 3])); + } + + this._stats = _profileInfo as IProfilerState; + this._canvasArr[0] = this._canvas; + this.updateTexture(); + this._inited = true; } public generateNode () { @@ -231,35 +283,64 @@ export class Profiler { const managerNode = new Node('Profiler_Root'); managerNode.parent = this._rootNode; + const height = _constants.quadHeight; + const rowHeight = height / this._totalLines; + const lWidth = height / this._wordHeight; + const scale = rowHeight / _constants.fontSize; + const columnWidth = this._eachNumWidth * this._canvas!.width * scale; + const vertexPos: number[] = [ + 0, height, 0, // top-left + lWidth, height, 0, // top-right + lWidth, 0, 0, // bottom-right + 0, 0, 0, // bottom-left + ]; + const vertexindices: number[] = [ + 0, 2, 1, + 0, 3, 2, + ]; + const vertexUV: number[] = [ + 0, 0, -1, 0, + 1, 0, -1, 0, + 1, this._wordHeight, -1, 0, + 0, this._wordHeight, -1, 0, + ]; + let offset = 0; + for (let i = 0; i < this._totalLines; i++) { + for (let j = 0; j < _constants.segmentsPerLine; j++) { + vertexPos.push(lWidth + j * columnWidth, height - i * rowHeight, 0 ); // tl + vertexPos.push(lWidth + (j + 1) * columnWidth, height - i * rowHeight, 0); // tr + vertexPos.push(lWidth + (j + 1) * columnWidth, height - (i + 1) * rowHeight, 0); // br + vertexPos.push(lWidth + j * columnWidth, height - (i + 1) * rowHeight, 0); // bl + offset = (i * _constants.segmentsPerLine + j + 1) * 4; + vertexindices.push(0 + offset, 2 + offset, 1 + offset, 0 + offset, 3 + offset, 2 + offset); + const idx = i * _constants.segmentsPerLine + j; + const z = Math.floor(idx / 4); + const w = idx - z * 4; + vertexUV.push(0, this._wordHeight, z, w ); // tl + vertexUV.push(this._eachNumWidth, this._wordHeight, z, w ); // tr + vertexUV.push(this._eachNumWidth, 1, z, w ); // br + vertexUV.push(0, 1, z, w ); // bl + } + } + const modelCom = managerNode.addComponent('cc.ModelComponent') as ModelComponent; modelCom.mesh = createMesh({ - positions: [ - -0.35, -0.2, 0, // bottom-left - -0.35, 0.2, 0, // top-left - 0.35, 0.2, 0, // top-right - 0.35, -0.2, 0, // bottom-right - ], - indices: [ - 0, 2, 1, - 0, 3, 2, - ], - uvs: [ - 0, 1, - 0, 0, - 1, 0, - 1, 1, - ], + positions: vertexPos, + indices: vertexindices, + colors: vertexUV, // pack all the necessary info in a_color: { x: u, y: v, z: id.x, w: id.y } }); const _material = new Material(); - _material.initialize({ - effectName: 'util/profiler', - }); + _material.initialize({ effectName: 'util/profiler' }); _material.setProperty('offset', new Vec4(-0.9, -0.9, 0, 0)); + _material.setProperty('symbols', this._uvOffset); const pass = _material.passes[0]; const handle = pass.getBinding('mainTexture'); pass.bindTextureView(handle!, this._textureView!); + const binding = pass.getBinding('digits')!; + this.digitsData = pass.blocks[binding]; + modelCom.material = _material; modelCom.node.layer = Layers.Enum.PROFILER; } @@ -269,8 +350,6 @@ export class Profiler { return; } - this.generateNode(); - const now = performance.now(); this.getCounter('frame').end(now); this.getCounter('frame').start(now); @@ -283,7 +362,7 @@ export class Profiler { } const now = performance.now(); - if (director.isPaused()) { + if (cc.director.isPaused()) { this.getCounter('frame').start(now); } else { this.getCounter('logic').end(now); @@ -318,34 +397,42 @@ export class Profiler { } public afterDraw () { - if (!this._stats || !this._ctx || !this._canvas) { + if (!this._stats || !this._inited) { return; } const now = performance.now(); this.getCounter('fps').frame(now); - this.getCounter('draws').value = this._device!.numDrawCalls; - this.getCounter('bufferMemory').value = this._device!.memoryStatus.bufferSize / (1024 * 1024); - this.getCounter('textureMemory').value = this._device!.memoryStatus.textureSize / (1024 * 1024); - this.getCounter('tricount').value = this._device!.numTris; this.getCounter('render').end(now); - const x = this._left + this._ctx.measureText('GFX Texture Mem(M)').width; - this._ctx.clearRect( x, 0, this._canvas.width - x, this._canvas.height); + if (now - this.lastTime < 500) { + return; + } + this.lastTime = now; + + const device = this._device!; + this.getCounter('draws').value = device.numDrawCalls; + this.getCounter('bufferMemory').value = device.memoryStatus.bufferSize / (1024 * 1024); + this.getCounter('textureMemory').value = device.memoryStatus.textureSize / (1024 * 1024); + this.getCounter('tricount').value = device.numTris; let i = 0; - for (const id of Object.keys(this._stats)) { - const stat = this._stats[id]; + const view = this.digitsData.view; + for (const id in this._stats) { + const stat = this._stats[id] as ICounterOption; stat.counter.sample(now); - this._ctx.fillText( - stat.counter.human(!(stat.desc === 'Framerate (FPS)')), - this._canvas.width - this._right, - this._top + i * this._lineHeight); + const result = stat.counter.human().toString(); + for (let j = _constants.segmentsPerLine - 1; j >= 0; j--) { + const index = i * _constants.segmentsPerLine + j; + const character = result[result.length - (_constants.segmentsPerLine - j)]; + let offset = _string2offset[character]; + if (offset === undefined) { offset = 11; } + view[index] = offset; + } i++; } - this._canvasArr[0] = this._canvas; - this.updateTexture(); + this.digitsData.dirty = true; } public getCounter (s: string) { @@ -354,7 +441,7 @@ export class Profiler { } public updateTexture () { - director.root!.device.copyTexImagesToTexture(this._canvasArr, this._texture!, this._regionArr); + cc.director.root!.device.copyTexImagesToTexture(this._canvasArr, this._texture!, this._regionArr); } } diff --git a/cocos/particle/animator/force-overtime.ts b/cocos/particle/animator/force-overtime.ts index 64488cf196..0eab23fc9a 100644 --- a/cocos/particle/animator/force-overtime.ts +++ b/cocos/particle/animator/force-overtime.ts @@ -32,6 +32,7 @@ export default class ForceOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 2, + tooltip:'X 轴方向上的加速度分量', }) public x = new CurveRange(); @@ -42,6 +43,7 @@ export default class ForceOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 3, + tooltip:'Y 轴方向上的加速度分量', }) public y = new CurveRange(); @@ -52,6 +54,7 @@ export default class ForceOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 4, + tooltip:'Z 轴方向上的加速度分量', }) public z = new CurveRange(); @@ -61,6 +64,7 @@ export default class ForceOvertimeModule { @property({ type: Space, displayOrder: 1, + tooltip:'加速度计算时采用的坐标', }) public space = Space.Local; diff --git a/cocos/particle/animator/limit-velocity-overtime.ts b/cocos/particle/animator/limit-velocity-overtime.ts index 51a0e61e2a..0265861acd 100644 --- a/cocos/particle/animator/limit-velocity-overtime.ts +++ b/cocos/particle/animator/limit-velocity-overtime.ts @@ -4,15 +4,17 @@ */ import { ccclass, property } from '../../core/data/class-decorator'; -import { lerp, pseudoRandom, Vec3 } from '../../core/math'; +import { lerp, pseudoRandom, Vec3, Mat4, Quat } from '../../core/math'; import { Space } from '../enum'; import Particle from '../particle'; import CurveRange from './curve-range'; +import { calculateTransform } from '../particle-general-function'; // tslint:disable: max-line-length const LIMIT_VELOCITY_RAND_OFFSET = 23541; const _temp_v3 = new Vec3(); +const _temp_v3_1 = new Vec3(); @ccclass('cc.LimitVelocityOvertimeModule') export default class LimitVelocityOvertimeModule { @@ -32,6 +34,7 @@ export default class LimitVelocityOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 4, + tooltip:'X 轴方向上的速度下限', }) public limitX = new CurveRange(); @@ -42,6 +45,7 @@ export default class LimitVelocityOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 5, + tooltip:'Y 轴方向上的速度下限', }) public limitY = new CurveRange(); @@ -52,6 +56,7 @@ export default class LimitVelocityOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 6, + tooltip:'Z 轴方向上的速度下限', }) public limitZ = new CurveRange(); @@ -62,6 +67,7 @@ export default class LimitVelocityOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 3, + tooltip:'速度下限', }) public limit = new CurveRange(); @@ -70,6 +76,7 @@ export default class LimitVelocityOvertimeModule { */ @property({ displayOrder: 7, + tooltip:'当前速度与速度下限的插值', }) public dampen = 3; @@ -78,6 +85,7 @@ export default class LimitVelocityOvertimeModule { */ @property({ displayOrder: 2, + tooltip:'是否三个轴分开限制', }) public separateAxes = false; @@ -87,6 +95,7 @@ export default class LimitVelocityOvertimeModule { @property({ type: Space, displayOrder: 1, + tooltip:'计算速度下限时采用的坐标系', }) public space = Space.Local; @@ -96,18 +105,33 @@ export default class LimitVelocityOvertimeModule { public multiplyDragByParticleSize = false; public multiplyDragByParticleVelocity = false; + + private rotation: Quat; + private needTransform: boolean; constructor () { + this.rotation = new Quat(); + this.needTransform = false; + } + + public update (space: number, worldTransform: Mat4) { + this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } public animate (p: Particle) { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const dampedVel = _temp_v3; if (this.separateAxes) { + Vec3.set(_temp_v3_1, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, + this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, + this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!); + if (this.needTransform) { + Vec3.transformQuat(_temp_v3_1, _temp_v3_1, this.rotation); + } Vec3.set(dampedVel, - dampenBeyondLimit(p.ultimateVelocity.x, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen), - dampenBeyondLimit(p.ultimateVelocity.y, this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen), - dampenBeyondLimit(p.ultimateVelocity.z, this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen)); + dampenBeyondLimit(p.ultimateVelocity.x, _temp_v3_1.x, this.dampen), + dampenBeyondLimit(p.ultimateVelocity.y, _temp_v3_1.y, this.dampen), + dampenBeyondLimit(p.ultimateVelocity.z, _temp_v3_1.z, this.dampen)); } else { Vec3.normalize(dampedVel, p.ultimateVelocity); diff --git a/cocos/particle/animator/rotation-overtime.ts b/cocos/particle/animator/rotation-overtime.ts index fb02823cb1..92f514f734 100644 --- a/cocos/particle/animator/rotation-overtime.ts +++ b/cocos/particle/animator/rotation-overtime.ts @@ -30,6 +30,7 @@ export default class RotationOvertimeModule { */ @property({ displayOrder: 1, + tooltip:'是否三个轴分开设定旋转(暂不支持)', }) get separateAxes () { return this._separateAxes; @@ -47,6 +48,7 @@ export default class RotationOvertimeModule { range: [-1, 1], radian: true, displayOrder: 2, + tooltip:'绕 X 轴设定旋转', }) public x = new CurveRange(); @@ -58,17 +60,19 @@ export default class RotationOvertimeModule { range: [-1, 1], radian: true, displayOrder: 3, + tooltip:'绕 Y 轴设定旋转', }) public y = new CurveRange(); /** - * @zh 绕 X 轴设定旋转。 + * @zh 绕 Z 轴设定旋转。 */ @property({ type: CurveRange, range: [-1, 1], radian: true, displayOrder: 4, + tooltip:'绕 Z 轴设定旋转', }) public z = new CurveRange(); diff --git a/cocos/particle/animator/size-overtime.ts b/cocos/particle/animator/size-overtime.ts index 226f8fe31b..00d2586b5c 100644 --- a/cocos/particle/animator/size-overtime.ts +++ b/cocos/particle/animator/size-overtime.ts @@ -27,6 +27,7 @@ export default class SizeOvertimeModule { */ @property({ displayOrder: 1, + tooltip:'决定是否在每个轴上独立控制粒子大小', }) public separateAxes = false; @@ -36,6 +37,7 @@ export default class SizeOvertimeModule { @property({ type: CurveRange, displayOrder: 2, + tooltip:'定义一条曲线来决定粒子在其生命周期中的大小变化', }) public size = new CurveRange(); @@ -45,6 +47,7 @@ export default class SizeOvertimeModule { @property({ type: CurveRange, displayOrder: 3, + tooltip:'定义一条曲线来决定粒子在其生命周期中 X 轴方向上的大小变化', }) public x = new CurveRange(); @@ -54,6 +57,7 @@ export default class SizeOvertimeModule { @property({ type: CurveRange, displayOrder: 4, + tooltip:'定义一条曲线来决定粒子在其生命周期中 Y 轴方向上的大小变化', }) public y = new CurveRange(); @@ -63,6 +67,7 @@ export default class SizeOvertimeModule { @property({ type: CurveRange, displayOrder: 5, + tooltip:'定义一条曲线来决定粒子在其生命周期中 Z 轴方向上的大小变化', }) public z = new CurveRange(); diff --git a/cocos/particle/animator/texture-animation.ts b/cocos/particle/animator/texture-animation.ts index a382ac9407..a7fe168049 100644 --- a/cocos/particle/animator/texture-animation.ts +++ b/cocos/particle/animator/texture-animation.ts @@ -79,6 +79,7 @@ export default class TextureAnimationModule { @property({ type: Mode, displayOrder: 1, + tooltip:'设定粒子贴图动画的类型(暂只支持 Grid 模式)', }) get mode () { return this._mode; @@ -96,6 +97,7 @@ export default class TextureAnimationModule { */ @property({ displayOrder: 2, + tooltip:'X 方向动画帧数', }) public numTilesX = 0; @@ -104,6 +106,7 @@ export default class TextureAnimationModule { */ @property({ displayOrder: 3, + tooltip:'Y 方向动画帧数', }) public numTilesY = 0; @@ -113,6 +116,7 @@ export default class TextureAnimationModule { @property({ type: Animation, displayOrder: 4, + tooltip:'动画播放方式', }) public animation = Animation.WholeSheet; @@ -122,6 +126,7 @@ export default class TextureAnimationModule { @property({ type: CurveRange, displayOrder: 7, + tooltip:'一个周期内动画播放的帧与时间变化曲线', }) public frameOverTime = new CurveRange(); @@ -131,6 +136,7 @@ export default class TextureAnimationModule { @property({ type: CurveRange, displayOrder: 8, + tooltip:'从第几帧开始播放,时间为整个粒子系统的生命周期', }) public startFrame = new CurveRange(); @@ -139,6 +145,7 @@ export default class TextureAnimationModule { */ @property({ displayOrder: 9, + tooltip:'一个生命周期内播放循环的次数', }) public cycleCount = 0; @@ -184,6 +191,7 @@ export default class TextureAnimationModule { */ @property({ displayOrder: 5, + tooltip:'随机从动画贴图中选择一行以生成动画。\n此选项仅在动画播放方式为 SingleRow 时生效' }) public randomRow = false; @@ -193,6 +201,7 @@ export default class TextureAnimationModule { */ @property({ displayOrder: 6, + tooltip:'从动画贴图中选择特定行以生成动画。\n此选项仅在动画播放方式为 SingleRow 时且禁用 randomRow 时可用' }) public rowIndex = 0; diff --git a/cocos/particle/animator/velocity-overtime.ts b/cocos/particle/animator/velocity-overtime.ts index d842f79d20..af6de5fda1 100644 --- a/cocos/particle/animator/velocity-overtime.ts +++ b/cocos/particle/animator/velocity-overtime.ts @@ -35,6 +35,7 @@ export default class VelocityOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 2, + tooltip:'X 轴方向上的速度分量', }) public x = new CurveRange(); @@ -45,6 +46,7 @@ export default class VelocityOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 3, + tooltip:'Y 轴方向上的速度分量', }) public y = new CurveRange(); @@ -55,6 +57,7 @@ export default class VelocityOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 4, + tooltip:'Z 轴方向上的速度分量', }) public z = new CurveRange(); @@ -65,6 +68,7 @@ export default class VelocityOvertimeModule { type: CurveRange, range: [-1, 1], displayOrder: 5, + tooltip:'速度修正系数(只支持 CPU 粒子)', }) public speedModifier = new CurveRange(); @@ -74,6 +78,7 @@ export default class VelocityOvertimeModule { @property({ type: Space, displayOrder: 1, + tooltip:'速度计算时采用的坐标系', }) public space = Space.Local; diff --git a/cocos/particle/billboard-component.ts b/cocos/particle/billboard-component.ts index fa61d6873f..2a9c57b0d4 100644 --- a/cocos/particle/billboard-component.ts +++ b/cocos/particle/billboard-component.ts @@ -29,6 +29,7 @@ export class BillboardComponent extends Component { */ @property({ type: Texture2D, + tooltip:'billboard显示的贴图', }) get texture () { return this._texture; @@ -47,7 +48,9 @@ export class BillboardComponent extends Component { /** * @zh 高度。 */ - @property + @property({ + tooltip:'billboard的高度', + }) get height () { return this._height; } @@ -66,7 +69,9 @@ export class BillboardComponent extends Component { /** * @zh 宽度。 */ - @property + @property({ + tooltip:'billboard的宽度', + }) public get width () { return this._width; } @@ -85,7 +90,9 @@ export class BillboardComponent extends Component { /** * @zh 角度。 */ - @property + @property({ + tooltip:'billboard绕中心点旋转的角度', + }) public get rotation () { return Math.round(toDegree(this._rotation) * 100) / 100; } diff --git a/cocos/particle/emitter/shape-module.ts b/cocos/particle/emitter/shape-module.ts index a81917097b..e0ccbfc7c9 100644 --- a/cocos/particle/emitter/shape-module.ts +++ b/cocos/particle/emitter/shape-module.ts @@ -24,6 +24,7 @@ export default class ShapeModule { */ @property({ displayOrder: 13, + tooltip:'粒子发射器位置', }) get position () { return this._position; @@ -38,6 +39,7 @@ export default class ShapeModule { */ @property({ displayOrder: 14, + tooltip:'粒子发射器旋转角度', }) get rotation () { return this._rotation; @@ -52,6 +54,7 @@ export default class ShapeModule { */ @property({ displayOrder: 15, + tooltip:'粒子发射器缩放比例', }) get scale () { return this._scale; @@ -66,6 +69,7 @@ export default class ShapeModule { */ @property({ displayOrder: 6, + tooltip:'粒子发射器在一个扇形范围内发射', }) get arc () { return toDegree(this._arc); @@ -81,6 +85,7 @@ export default class ShapeModule { */ @property({ displayOrder: 5, + tooltip:'圆锥的轴与母线的夹角\n决定圆锥发射器的开合程度', }) get angle () { return Math.round(toDegree(this._angle) * 100) / 100; @@ -110,6 +115,7 @@ export default class ShapeModule { @property({ type: ShapeType, + tooltip:'粒子发射器类型', }) public get shapeType () { return this._shapeType; @@ -143,6 +149,7 @@ export default class ShapeModule { @property({ type: EmitLocation, displayOrder: 2, + tooltip:'粒子从发射器哪个部位发射', }) public emitFrom = EmitLocation.Volume; @@ -151,6 +158,7 @@ export default class ShapeModule { */ @property({ displayOrder: 16, + tooltip:'根据粒子的初始方向决定粒子的移动方向', }) public alignToDirection = false; @@ -159,6 +167,7 @@ export default class ShapeModule { */ @property({ displayOrder: 17, + tooltip:'粒子生成方向随机设定', }) public randomDirectionAmount = 0; @@ -167,6 +176,7 @@ export default class ShapeModule { */ @property({ displayOrder: 18, + tooltip:'表示当前发射方向与当前位置到结点中心连线方向的插值', }) public sphericalDirectionAmount = 0; @@ -175,6 +185,7 @@ export default class ShapeModule { */ @property({ displayOrder: 19, + tooltip:'粒子生成位置随机设定(设定此值为非 0 会使粒子生成位置超出生成器大小范围)', }) public randomPositionAmount = 0; @@ -183,6 +194,7 @@ export default class ShapeModule { */ @property({ displayOrder: 3, + tooltip:'粒子发射器半径', }) public radius = 1; @@ -194,6 +206,7 @@ export default class ShapeModule { */ @property({ displayOrder: 4, + tooltip:'粒子发射器发射位置(对 Box 类型的发射器无效):\n - 0 表示从表面发射;\n - 1 表示从中心发射;\n - 0 ~ 1 之间表示在中心到表面之间发射。', }) public radiusThickness = 1; @@ -203,6 +216,7 @@ export default class ShapeModule { @property({ type: ArcMode, displayOrder: 7, + tooltip:'粒子在扇形范围内的发射方式', }) public arcMode = ArcMode.Random; @@ -211,6 +225,7 @@ export default class ShapeModule { */ @property({ displayOrder: 9, + tooltip:'控制可能产生粒子的弧周围的离散间隔', }) public arcSpread = 0; @@ -220,6 +235,7 @@ export default class ShapeModule { @property({ type: CurveRange, displayOrder: 10, + tooltip:'粒子沿圆周发射的速度', }) public arcSpeed = new CurveRange(); @@ -229,6 +245,7 @@ export default class ShapeModule { */ @property({ displayOrder: 11, + tooltip:'圆锥顶部截面距离底部的轴长\n决定圆锥发射器的高度', }) public length = 5; @@ -237,6 +254,7 @@ export default class ShapeModule { */ @property({ displayOrder: 12, + tooltip:'粒子发射器发射位置(针对 Box 类型的粒子发射器)', }) public boxThickness = new Vec3(0, 0, 0); diff --git a/cocos/particle/line-component.ts b/cocos/particle/line-component.ts index 6d09ffda53..b136fc08d5 100644 --- a/cocos/particle/line-component.ts +++ b/cocos/particle/line-component.ts @@ -32,6 +32,7 @@ export class LineComponent extends Component { @property({ type: Texture2D, displayOrder: 0, + tooltip:'线段中显示的贴图', }) get texture () { return this._texture; @@ -54,6 +55,7 @@ export class LineComponent extends Component { */ @property({ displayOrder: 1, + tooltip:'线段中各个点的坐标采用哪个坐标系,勾选使用世界坐标系,不选使用本地坐标系', }) get worldSpace () { return this._worldSpace; @@ -81,6 +83,7 @@ export class LineComponent extends Component { @property({ type: [Vec3], displayOrder: 2, + tooltip:'每个线段端点的坐标', }) get positions () { return this._positions; @@ -104,6 +107,7 @@ export class LineComponent extends Component { @property({ type: CurveRange, displayOrder: 3, + tooltip:'线段宽度,如果采用曲线,则表示沿着线段方向上的曲线变化', }) get width () { return this._width; @@ -125,6 +129,7 @@ export class LineComponent extends Component { @property({ type: Vec2, displayOrder: 4, + tooltip:'贴图平铺次数', }) get tile () { return this._tile; @@ -145,6 +150,7 @@ export class LineComponent extends Component { @property({ type: Vec2, displayOrder: 5, + tooltip:'贴图坐标的偏移', }) get offset () { return this._offset; @@ -170,6 +176,7 @@ export class LineComponent extends Component { @property({ type: GradientRange, displayOrder: 6, + tooltip:'线段颜色,如果采用渐变色,则表示沿着线段方向上的颜色渐变', }) get color () { return this._color; diff --git a/cocos/particle/models/line-model.ts b/cocos/particle/models/line-model.ts index cf41cfb750..7eb5929e6d 100644 --- a/cocos/particle/models/line-model.ts +++ b/cocos/particle/models/line-model.ts @@ -3,14 +3,14 @@ */ import { IRenderingSubmesh } from '../../core/assets/mesh'; -import CurveRange from '../animator/curve-range'; -import { Vec3 } from '../../core/math'; +import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../core/gfx/buffer'; import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../core/gfx/define'; +import { Vec3 } from '../../core/math'; import { Model } from '../../core/renderer/scene/model'; import { RenderScene } from '../../core/renderer/scene/render-scene'; -import GradientRange from '../animator/gradient-range'; -import { GFX_DRAW_INFO_SIZE, IGFXIndirectBuffer, GFXBuffer } from '../../core/gfx/buffer'; import { INode } from '../../core/utils/interfaces'; +import CurveRange from '../animator/curve-range'; +import GradientRange from '../animator/gradient-range'; const _vertex_attrs = [ { name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }, // xyz:position @@ -111,7 +111,6 @@ export class LineModel extends Model { indexBuffer.update(indices); - this._iaInfo.drawInfos[0].vertexCount = this._capacity * this._vertCount; this._iaInfo.drawInfos[0].indexCount = (this._capacity - 1) * this._indexCount; this._iaInfoBuffer.update(this._iaInfo); diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index 729f49e07b..a4c59d7144 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -33,10 +33,10 @@ import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../core/gf import { GFXAttributeName, GFXBufferUsageBit, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../core/gfx/define'; import { IGFXAttribute } from '../../core/gfx/input-assembler'; -import { Node } from '../../core/scene-graph'; +import { Color } from '../../core/math/color'; import { Model } from '../../core/renderer/scene/model'; import { RenderScene } from '../../core/renderer/scene/render-scene'; -import { Color } from '../../core/math/color'; +import { Node } from '../../core/scene-graph'; export default class ParticleBatchModel extends Model { diff --git a/cocos/particle/particle-system-component.ts b/cocos/particle/particle-system-component.ts index 854756787c..5cd8d6b8dd 100644 --- a/cocos/particle/particle-system-component.ts +++ b/cocos/particle/particle-system-component.ts @@ -6,12 +6,12 @@ // tslint:disable: max-line-length +import { RenderableComponent } from '../core/3d/framework/renderable-component'; +import { Material } from '../core/assets/material'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../core/data/class-decorator'; import { Mat4, pseudoRandom, Quat, randomRangeInt, Vec2, Vec3 } from '../core/math'; import { INT_MAX } from '../core/math/bits'; import { Model } from '../core/renderer'; -import { Material } from '../core/assets/material'; -import { RenderableComponent } from '../core/3d/framework/renderable-component'; import ColorOverLifetimeModule from './animator/color-overtime'; import CurveRange, { Mode } from './animator/curve-range'; import ForceOvertimeModule from './animator/force-overtime'; @@ -41,6 +41,7 @@ export class ParticleSystemComponent extends RenderableComponent { */ @property({ displayOrder: 1, + tooltip:'粒子系统能生成的最大粒子数量', }) public get capacity () { return this._capacity; @@ -61,17 +62,20 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: GradientRange, displayOrder: 8, + tooltip:'粒子初始颜色', }) public startColor = new GradientRange(); @property({ type: Space, displayOrder: 9, + tooltip:'选择缩放坐标系', }) public scaleSpace = Space.Local; @property({ displayOrder: 10, + tooltip:'粒子初始大小', }) public startSize3D = false; @@ -82,6 +86,7 @@ export class ParticleSystemComponent extends RenderableComponent { type: CurveRange, displayOrder: 10, formerlySerializedAs: 'startSize', + tooltip:'粒子初始大小', }) public startSizeX = new CurveRange(); @@ -91,6 +96,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: CurveRange, displayOrder: 10, + tooltip:'粒子初始大小', }) public startSizeY = new CurveRange(); @@ -100,6 +106,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: CurveRange, displayOrder: 10, + tooltip:'粒子初始大小', }) public startSizeZ = new CurveRange(); @@ -110,11 +117,13 @@ export class ParticleSystemComponent extends RenderableComponent { type: CurveRange, range: [-1, 1], displayOrder: 11, + tooltip:'粒子初始速度', }) public startSpeed = new CurveRange(); @property({ - displayOrder:12, + displayOrder: 12, + tooltip:'粒子初始旋转角度', }) public startRotation3D = false; @@ -126,6 +135,7 @@ export class ParticleSystemComponent extends RenderableComponent { range: [-1, 1], radian: true, displayOrder: 12, + tooltip:'粒子初始旋转角度' }) public startRotationX = new CurveRange(); @@ -137,6 +147,7 @@ export class ParticleSystemComponent extends RenderableComponent { range: [-1, 1], radian: true, displayOrder: 12, + tooltip:'粒子初始旋转角度' }) public startRotationY = new CurveRange(); @@ -149,6 +160,7 @@ export class ParticleSystemComponent extends RenderableComponent { radian: true, displayOrder: 12, formerlySerializedAs: 'startRotation', + tooltip:'粒子初始旋转角度' }) public startRotationZ = new CurveRange(); @@ -158,6 +170,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: CurveRange, displayOrder: 6, + tooltip:'粒子系统开始运行后,延迟粒子发射的时间', }) public startDelay = new CurveRange(); @@ -167,6 +180,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: CurveRange, displayOrder: 7, + tooltip:'粒子生命周期', }) public startLifetime = new CurveRange(); @@ -175,6 +189,7 @@ export class ParticleSystemComponent extends RenderableComponent { */ @property({ displayOrder: 0, + tooltip:'粒子系统运行时间', }) public duration = 5.0; @@ -183,6 +198,7 @@ export class ParticleSystemComponent extends RenderableComponent { */ @property({ displayOrder: 2, + tooltip:'粒子系统是否循环播放', }) public loop = true; @@ -191,6 +207,7 @@ export class ParticleSystemComponent extends RenderableComponent { */ @property({ displayOrder: 3, + tooltip:'选中之后,粒子系统会以已播放完一轮之后的状态开始播放(仅当循环播放启用时有效)', }) get prewarm () { return this._prewarm; @@ -209,6 +226,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: Space, displayOrder: 4, + tooltip:'控制粒子坐标计算所在的坐标系', }) get simulationSpace () { return this._simulationSpace; @@ -227,6 +245,7 @@ export class ParticleSystemComponent extends RenderableComponent { */ @property({ displayOrder: 5, + tooltip:'控制整个粒子系统的更新速度', }) public simulationSpeed = 1.0; @@ -235,6 +254,7 @@ export class ParticleSystemComponent extends RenderableComponent { */ @property({ displayOrder: 2, + tooltip:'粒子系统加载后是否自动开始播放', }) public playOnAwake = true; @@ -245,6 +265,7 @@ export class ParticleSystemComponent extends RenderableComponent { type: CurveRange, range: [-1, 1], displayOrder: 13, + tooltip:'粒子受重力影响的重力系数', }) public gravityModifier = new CurveRange(); @@ -255,6 +276,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: CurveRange, displayOrder: 14, + tooltip:'每秒发射的粒子数', }) public rateOverTime = new CurveRange(); @@ -264,6 +286,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: CurveRange, displayOrder: 15, + tooltip:'每移动单位距离发射的粒子数', }) public rateOverDistance = new CurveRange(); @@ -273,6 +296,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: [Burst], displayOrder: 16, + tooltip:'在某个时间点发射给定数量的粒子' }) public bursts = new Array(); @@ -300,6 +324,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: ColorOverLifetimeModule, displayOrder: 23, + tooltip:'颜色模块', }) public colorOverLifetimeModule = new ColorOverLifetimeModule(); @@ -310,6 +335,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: ShapeModule, displayOrder: 17, + tooltip:'发射器模块', }) public shapeModule = new ShapeModule(); @@ -320,6 +346,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: SizeOvertimeModule, displayOrder: 21, + tooltip:'大小模块', }) public sizeOvertimeModule = new SizeOvertimeModule(); @@ -329,6 +356,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: VelocityOvertimeModule, displayOrder: 18, + tooltip:'速度模块', }) public velocityOvertimeModule = new VelocityOvertimeModule(); @@ -338,6 +366,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: ForceOvertimeModule, displayOrder: 19, + tooltip:'加速度模块', }) public forceOvertimeModule = new ForceOvertimeModule(); @@ -347,6 +376,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: LimitVelocityOvertimeModule, displayOrder: 20, + tooltip:'限速模块', }) public limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); @@ -356,6 +386,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: RotationOvertimeModule, displayOrder: 22, + tooltip:'旋转模块', }) public rotationOvertimeModule = new RotationOvertimeModule(); @@ -365,6 +396,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: TextureAnimationModule, displayOrder: 24, + tooltip:'贴图动画模块', }) public textureAnimationModule = new TextureAnimationModule(); @@ -374,6 +406,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: TrailModule, displayOrder: 25, + tooltip:'拖尾模块', }) public trailModule = new TrailModule(); @@ -381,6 +414,7 @@ export class ParticleSystemComponent extends RenderableComponent { @property({ type: ParticleSystemRenderer, displayOrder: 26, + tooltip:'渲染模块', }) public renderer: ParticleSystemRenderer = new ParticleSystemRenderer(); @@ -458,11 +492,16 @@ export class ParticleSystemComponent extends RenderableComponent { this.renderer._onRebuildPSO(index, material); } - public _getModel (): Model | null { - return (this.renderer as any)._model; + public _collectModels (): Model[] { + this._models.length = 0; + this._models.push((this.renderer as any)._model); + if (this.trailModule.enable && (this.trailModule as any)._trailModel) { + this._models.push((this.trailModule as any)._trailModel); + } + return this._models; } - public recreateModel () { + public _changeSceneInModel () { if (this.isValid) { const r = this.renderer as any; if (r && r._model) { @@ -471,6 +510,12 @@ export class ParticleSystemComponent extends RenderableComponent { r.onEnable(); r._updateModel(); r._updateMaterialParams(); + } + const t = this.trailModule as any; + if (t && t._trailModel) { + t._trailModel.scene.destroyModel(t._trailModel); + t._trailModel = null; + t.enable = t._enable; r._updateTrailMaterial(); } } diff --git a/cocos/particle/renderer/particle-system-renderer.ts b/cocos/particle/renderer/particle-system-renderer.ts index 7b32ef14d0..9071c75492 100644 --- a/cocos/particle/renderer/particle-system-renderer.ts +++ b/cocos/particle/renderer/particle-system-renderer.ts @@ -66,6 +66,7 @@ export default class ParticleSystemRenderer { @property({ type: RenderMode, displayOrder: 0, + tooltip:'设定粒子生成模式', }) public get renderMode () { return this._renderMode; @@ -86,6 +87,7 @@ export default class ParticleSystemRenderer { */ @property({ displayOrder: 1, + tooltip:'在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按速度大小进行拉伸', }) public get velocityScale () { return this._velocityScale; @@ -102,6 +104,7 @@ export default class ParticleSystemRenderer { */ @property({ displayOrder: 2, + tooltip:'在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按粒子大小进行拉伸', }) public get lengthScale () { return this._lengthScale; @@ -146,6 +149,7 @@ export default class ParticleSystemRenderer { @property({ type: Mesh, displayOrder: 7, + tooltip:'粒子发射的模型', }) public get mesh () { return this._mesh; @@ -164,6 +168,7 @@ export default class ParticleSystemRenderer { @property({ type: Material, displayOrder: 8, + tooltip:'粒子使用的材质', }) public get particleMaterial () { if (!this._particleSystem) { @@ -182,6 +187,7 @@ export default class ParticleSystemRenderer { @property({ type: Material, displayOrder: 9, + tooltip:'拖尾使用的材质', }) public get trailMaterial () { if (!this._particleSystem) { @@ -295,6 +301,9 @@ export default class ParticleSystemRenderer { if (this._particleSystem.velocityOvertimeModule.enable) { this._particleSystem.velocityOvertimeModule.update(this._particleSystem._simulationSpace, _tempWorldTrans); } + if (this._particleSystem.limitVelocityOvertimeModule.enable) { + this._particleSystem.limitVelocityOvertimeModule.update(this._particleSystem._simulationSpace, _tempWorldTrans); + } if (this._particleSystem.forceOvertimeModule.enable) { this._particleSystem.forceOvertimeModule.update(this._particleSystem._simulationSpace, _tempWorldTrans); } diff --git a/cocos/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts index fd4face65e..913d215bb8 100644 --- a/cocos/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -31,7 +31,7 @@ const _temp_vec3 = new Vec3(); const _temp_vec3_1 = new Vec3(); const _temp_color = new Color(); -const barycentric = [1,0,0, 0,1,0, 0,0,1]; // +const barycentric = [1,0,0, 0,1,0, 0,0,1]; // let _bcIdx = 0; interface ITrailElement { @@ -135,7 +135,7 @@ class TrailSegment { // public _print () { // let msg = String(); // this.iterateElement(this, (target: object, e: ITrailElement, p: Particle, dt: number) => { - // msg += 'pos:' + e.position.toString() + '\nlifetime:' + e.lifetime + '\nwidth:' + e.width + '\nvelocity:' + e.velocity.toString() + '\n'; + // msg += 'pos:' + e.position.toString() + ' lifetime:' + e.lifetime + ' dir:' + e.direction + ' velocity:' + e.velocity.toString() + '\n'; // return false; // }, null, 0); // console.log(msg); @@ -178,6 +178,7 @@ export default class TrailModule { @property({ type: TrailMode, displayOrder: 1, + tooltip:'Particle在每个粒子的运动轨迹上形成拖尾效果', }) public mode = TrailMode.Particles; @@ -187,6 +188,7 @@ export default class TrailModule { @property({ type: CurveRange, displayOrder: 3, + tooltip:'拖尾的生命周期', }) public lifeTime = new CurveRange(); @@ -198,6 +200,7 @@ export default class TrailModule { */ @property({ displayOrder: 5, + tooltip:'粒子每生成一个拖尾节点所运行的最短距离', }) public get minParticleDistance () { return this._minParticleDistance; @@ -211,6 +214,7 @@ export default class TrailModule { @property({ type: Space, displayOrder: 6, + tooltip:'拖尾所在的坐标系,World在世界坐标系中运行,Local在本地坐标系中运行', }) public get space () { return this._space; @@ -228,6 +232,7 @@ export default class TrailModule { */ @property({ displayOrder: 7, + tooltip:'拖尾是否跟随粒子一起消失', }) public existWithParticles = true; @@ -237,11 +242,13 @@ export default class TrailModule { @property({ type: TextureMode, displayOrder: 8, + tooltip:'贴图在拖尾上的展开形式,Stretch贴图覆盖在整条拖尾上,Repeat贴图覆盖在一段拖尾上', }) public textureMode = TextureMode.Stretch; @property({ displayOrder: 9, + tooltip:'拖尾宽度继承自粒子大小' }) public widthFromParticle = true; @@ -251,23 +258,27 @@ export default class TrailModule { @property({ type: CurveRange, displayOrder: 10, + tooltip:'拖尾宽度,如果继承自粒子则是粒子大小的比例', }) public widthRatio = new CurveRange(); @property({ displayOrder: 11, + tooltip:'拖尾颜色是否继承自粒子' }) public colorFromParticle = false; @property({ type: GradientRange, displayOrder: 12, + tooltip:'拖尾颜色随拖尾自身长度的颜色渐变' }) public colorOverTrail = new GradientRange(); @property({ type: GradientRange, displayOrder: 13, + tooltip:'拖尾颜色随时间的颜色渐变' }) public colorOvertime = new GradientRange(); @@ -510,20 +521,25 @@ export default class TrailModule { const lastThirdTrail = trailSeg.getElement(trailSeg.end - 2)!; Vec3.subtract(_temp_vec3, lastThirdTrail.position, lastSecondTrail.position); Vec3.subtract(_temp_vec3_1, _temp_trailEle.position, lastSecondTrail.position); + Vec3.normalize(_temp_vec3,_temp_vec3); + Vec3.normalize(_temp_vec3_1,_temp_vec3_1); Vec3.subtract(lastSecondTrail.velocity, _temp_vec3_1, _temp_vec3); Vec3.normalize(lastSecondTrail.velocity, lastSecondTrail.velocity); this._checkDirectionReverse(lastSecondTrail, lastThirdTrail); - this._vbF32![this.vbOffset - this._vertSize / 4 - 4] = lastSecondTrail.velocity.x; - this._vbF32![this.vbOffset - this._vertSize / 4 - 3] = lastSecondTrail.velocity.y; - this._vbF32![this.vbOffset - this._vertSize / 4 - 2] = lastSecondTrail.velocity.z; - this._vbF32![this.vbOffset - 4] = lastSecondTrail.velocity.x; - this._vbF32![this.vbOffset - 3] = lastSecondTrail.velocity.y; - this._vbF32![this.vbOffset - 2] = lastSecondTrail.velocity.z; + // refresh last trail segment data + this.vbOffset -= this._vertSize / 4 * 2; + this.ibOffset -= 6; + // _bcIdx = (_bcIdx - 6 + 9) % 9; // + this._fillVertexBuffer(lastSecondTrail, this.colorOverTrail.evaluate(textCoordSeg, 1), indexOffset, textCoordSeg, trailNum - 1, PRE_TRIANGLE_INDEX | NEXT_TRIANGLE_INDEX); Vec3.subtract(_temp_trailEle.velocity, _temp_trailEle.position, lastSecondTrail.position); Vec3.normalize(_temp_trailEle.velocity, _temp_trailEle.velocity); this._checkDirectionReverse(_temp_trailEle, lastSecondTrail); } - _temp_trailEle.width = p.size.x; + if (this.widthFromParticle) { + _temp_trailEle.width = p.size.x * this.widthRatio.evaluate(0, 1)!; + } else { + _temp_trailEle.width = this.widthRatio.evaluate(0, 1)!; + } _temp_trailEle.color = p.color; if (Vec3.equals(_temp_trailEle.velocity, Vec3.ZERO)) { @@ -664,4 +680,17 @@ export default class TrailModule { currElement.direction = prevElement.direction; } } + + // + // private _printVB() { + // let log = new String(); + // for (let i = 0; i < this.vbOffset; i++) { + // log += 'pos:' + this._vbF32![i++].toFixed(2) + ',' + this._vbF32![i++].toFixed(2) + ',' + this._vbF32![i++].toFixed(2) + ' dir:' + this._vbF32![i++].toFixed(0) + ' '; + // i += 6; + // log += 'vel:' + this._vbF32![i++].toFixed(2) + ',' + this._vbF32![i++].toFixed(2) + ',' + this._vbF32![i++].toFixed(2) + '\n'; + // } + // if (log.length > 0) { + // console.log(log); + // } + // } } diff --git a/cocos/physics/components/collider/box-collider-component.ts b/cocos/physics/components/collider/box-collider-component.ts index 5d89885aae..29a4b1218f 100644 --- a/cocos/physics/components/collider/box-collider-component.ts +++ b/cocos/physics/components/collider/box-collider-component.ts @@ -59,7 +59,10 @@ export class BoxColliderComponent extends ColliderComponent { * @zh * 获取或设置盒的大小。 */ - @property({ type: Vec3 }) + @property({ + type: Vec3, + tooltip:'盒的大小,即长、宽、高' + }) public get size () { return this._size; } diff --git a/cocos/physics/components/collider/collider-component.ts b/cocos/physics/components/collider/collider-component.ts index 86264bc8d2..3ffd5047f3 100644 --- a/cocos/physics/components/collider/collider-component.ts +++ b/cocos/physics/components/collider/collider-component.ts @@ -35,6 +35,7 @@ export class ColliderComponent extends PhysicsBasedComponent implements IEventTa type: PhysicMaterial, displayName: 'Material', displayOrder: -1, + tooltip:'源材质', }) public get sharedMaterial () { return this._material; @@ -92,6 +93,7 @@ export class ColliderComponent extends PhysicsBasedComponent implements IEventTa */ @property({ displayOrder: 0, + tooltip:'是否与其它碰撞器产生碰撞,并产生物理行为', }) public get isTrigger () { return this._isTrigger; @@ -120,7 +122,7 @@ export class ColliderComponent extends PhysicsBasedComponent implements IEventTa @property({ type: Vec3, displayOrder: 1, - tooltip: 'The center of the collider, in local space', + tooltip:'形状的中心点(与所在 Node 中心点的相对位置)', }) public get center () { return this._center; diff --git a/cocos/physics/components/collider/sphere-collider-component.ts b/cocos/physics/components/collider/sphere-collider-component.ts index 92e10ee015..4b22e81ea9 100644 --- a/cocos/physics/components/collider/sphere-collider-component.ts +++ b/cocos/physics/components/collider/sphere-collider-component.ts @@ -56,7 +56,9 @@ export class SphereColliderComponent extends ColliderComponent { * @zh * 获取或设置球的半径。 */ - @property + @property({ + tooltip:'球的半径', + }) public get radius () { return this._radius; } diff --git a/cocos/physics/components/constant-force.ts b/cocos/physics/components/constant-force.ts index 39903c7870..14540ac5a9 100644 --- a/cocos/physics/components/constant-force.ts +++ b/cocos/physics/components/constant-force.ts @@ -51,6 +51,7 @@ export class ConstantForce extends Component { */ @property({ displayOrder: 0, + tooltip:'世界朝向的力', }) public get force () { return this._force; @@ -69,6 +70,7 @@ export class ConstantForce extends Component { */ @property({ displayOrder: 1, + tooltip:'本地朝向的力', }) public get localForce () { return this._localForce; @@ -87,6 +89,7 @@ export class ConstantForce extends Component { */ @property({ displayOrder: 2, + tooltip:'世界朝向的扭转力', }) public get torque () { return this._torque; @@ -105,6 +108,7 @@ export class ConstantForce extends Component { */ @property({ displayOrder: 3, + tooltip:'本地朝向的扭转力', }) public get localTorque () { return this._localTorque; diff --git a/cocos/physics/components/detail/physics-based-component.ts b/cocos/physics/components/detail/physics-based-component.ts index fc043f3ea5..4abca0422b 100644 --- a/cocos/physics/components/detail/physics-based-component.ts +++ b/cocos/physics/components/detail/physics-based-component.ts @@ -194,6 +194,7 @@ export class PhysicsBasedComponent extends Component { return rigidbody; } else { if (begin.parent) { + // @ts-ignore if (begin.parent === begin.scene) { return null; } else { diff --git a/cocos/physics/components/physics-system.ts b/cocos/physics/components/physics-system.ts index 6b0988da4c..83d59a623b 100644 --- a/cocos/physics/components/physics-system.ts +++ b/cocos/physics/components/physics-system.ts @@ -149,7 +149,7 @@ export class PhysicsSystem extends System { 'group': -1, 'mask': -1, 'queryTrigger': true, - 'maxDistance': Infinity + 'maxDistance': 10000000 } private readonly raycastResultPool = new RecyclePool(() => { @@ -198,12 +198,12 @@ export class PhysicsSystem extends System { * 检测所有的碰撞盒,并记录所有被检测到的结果,通过 PhysicsSystem.instance.raycastResults 访问结果 * @param worldRay 世界空间下的一条射线 * @param mask 掩码 - * @param maxDistance 最大检测距离 + * @param maxDistance 最大检测距离,目前请勿传入 Infinity 或 Number.MAX_VALUE * @param queryTrigger 是否检测触发器 * @return boolean 表示是否有检测到碰撞盒 * @note 由于目前 Layer 还未完善,mask 暂时失效,请留意更新公告 */ - public raycast (worldRay: ray, mask: number = Layers.Enum.DEFAULT, maxDistance = Infinity, queryTrigger = true): boolean { + public raycast (worldRay: ray, mask: number = Layers.Enum.DEFAULT, maxDistance = 10000000, queryTrigger = true): boolean { this.raycastResultPool.reset(); this.raycastResults.length = 0; this.raycastOptions.mask = mask; @@ -217,12 +217,12 @@ export class PhysicsSystem extends System { * 检测所有的碰撞盒,并记录与射线距离最短的检测结果,通过 PhysicsSystem.instance.raycastClosestResult 访问结果 * @param worldRay 世界空间下的一条射线 * @param mask 掩码 - * @param maxDistance 最大检测距离 + * @param maxDistance 最大检测距离,目前请勿传入 Infinity 或 Number.MAX_VALUE * @param queryTrigger 是否检测触发器 * @return boolean 表示是否有检测到碰撞盒 * @note 由于目前 Layer 还未完善,mask 暂时失效,请留意更新公告 */ - public raycastClosest (worldRay: ray, mask: number = Layers.Enum.DEFAULT, maxDistance = Infinity, queryTrigger = true): boolean { + public raycastClosest (worldRay: ray, mask: number = Layers.Enum.DEFAULT, maxDistance = 10000000, queryTrigger = true): boolean { this.raycastOptions.mask = mask; this.raycastOptions.maxDistance = maxDistance; this.raycastOptions.queryTrigger = queryTrigger; diff --git a/cocos/physics/components/rigid-body-component.ts b/cocos/physics/components/rigid-body-component.ts index 5fa53dbe45..8ea671283d 100644 --- a/cocos/physics/components/rigid-body-component.ts +++ b/cocos/physics/components/rigid-body-component.ts @@ -57,6 +57,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { */ @property({ displayOrder: 0, + tooltip:'刚体的质量', }) public get mass () { return this._mass; @@ -75,6 +76,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { */ @property({ displayOrder: 1, + tooltip:'线性阻尼', }) public get linearDamping () { return this._linearDamping; @@ -93,6 +95,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { */ @property({ displayOrder: 2, + tooltip:'旋转阻尼', }) public get angularDamping () { return this._angularDamping; @@ -111,6 +114,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { */ @property({ displayOrder: 3, + tooltip:'刚体是否由物理系统控制运动', }) public get isKinematic () { return this._isKinematic; @@ -129,6 +133,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { */ @property({ displayOrder: 4, + tooltip:'刚体是否使用重力', }) public get useGravity () { return this._useGravity; @@ -147,6 +152,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { */ @property({ displayOrder: 5, + tooltip:'刚体是否固定旋转', }) public get fixedRotation () { return this._fixedRotation; @@ -165,6 +171,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { */ @property({ displayOrder: 6, + tooltip:'线性速度的因子,可以用来控制每个轴方向上的速度的缩放', }) public get linearFactor () { if (CC_EDITOR) { @@ -187,6 +194,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { */ @property({ displayOrder: 7, + tooltip:'旋转速度的因子,可以用来控制每个轴方向上的旋转速度的缩放', }) public get angularFactor () { if (CC_EDITOR) { diff --git a/cocos/terrain/terrain.ts b/cocos/terrain/terrain.ts index 85559d14c2..016d2c8b95 100644 --- a/cocos/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -41,7 +41,9 @@ export const TERRAIN_HEIGHT_FACTORY = 1.0 / 512.0; */ @ccclass('cc.TerrainInfo') export class TerrainInfo { - @property + @property({ + tooltip:'地形Tile的大小', + }) public tileSize: number = 1; @property public blockCount: number[] = [1, 1]; @@ -77,9 +79,13 @@ export class TerrainInfo { @ccclass('cc.TerrainLayer') export class TerrainLayer { - @property + @property({ + tooltip:'当前Layer的纹理', + }) public detailMap: Texture2D|null = null; - @property + @property({ + tooltip:'纹理的平铺大小,值越小会在同样大小的区域内进行更多次的平铺', + }) public tileSize: number = 1; } diff --git a/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts index d435461c0f..f20bb9793e 100644 --- a/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts +++ b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts @@ -31,7 +31,7 @@ import { Color, Vec3 } from '../../../../core/math'; import { GFXPrimitiveMode } from '../../../../core/gfx'; import { Model } from '../../../../core/renderer'; import { RenderScene } from '../../../../core/renderer/scene/render-scene'; -import { IARenderData } from '../../../../core/renderer/ui/render-data'; +import { MeshRenderData } from '../../../../core/renderer/ui/render-data'; import { UI } from '../../../../core/renderer/ui/ui'; import { createMesh } from '../../../../core/3d/misc/utils'; import { GraphicsComponent } from '../../../components'; @@ -63,7 +63,7 @@ const uvs: number[] = []; const colors: number[] = []; const indices: number[] = []; -let _renderData: IARenderData | null = null; +let _renderData: MeshRenderData | null = null; let _impl: Impl | null = null; const _curColor = new Color(); @@ -109,40 +109,6 @@ export const graphicsAssembler: IAssembler = { }, renderIA (graphics: GraphicsComponent, renderer: UI) { - // const impl = graphics.impl; - // let renderDatas = impl && impl.getRenderDatas(); - // if (!renderDatas) { - // renderDatas = []; - // } - - // let bufferBatch = renderer.currBufferBatch!; - // let vertexId = 0; - // let byteoffset = 0; - // let indicesOffset = 0; - // for (const renderData of renderDatas) { - // if (!graphics.material || renderData.byteCount <= 0 || renderData.indiceCount <= 0) { - // continue; - // } - - // vertexId = bufferBatch.vertexOffset; - // byteoffset = bufferBatch.byteOffset; - // indicesOffset = bufferBatch.indiceOffset; - // bufferBatch.request(renderData.vertexCount, renderData.indiceCount); - // bufferBatch = renderer.currBufferBatch!; - // const vData = bufferBatch.vData!; - // const iData = bufferBatch.iData!; - // // the data format is strictly in accordance with pos uv color - // const vDataCopy = renderData.vData.slice(0, renderData.byteCount >> 2); - // vData.set(vDataCopy, byteoffset >> 2); - - // let iDataCopy = renderData.iData.slice(0, renderData.indiceCount); - // iDataCopy = iDataCopy.map((v) => { - // return v + vertexId; - // }); - // iData.set(iDataCopy, indicesOffset); - - // renderer.forceMergeBatches(graphics.material, null); - // } }, getRenderData (graphics: GraphicsComponent, cverts: number) { @@ -307,7 +273,7 @@ export const graphicsAssembler: IAssembler = { } } - const meshbuffer: IARenderData | null = _renderData = this.getRenderData!(graphics, cverts); + const meshbuffer: MeshRenderData | null = _renderData = this.getRenderData!(graphics, cverts); if (!meshbuffer) { return; } diff --git a/cocos/ui/assembler/graphics/webgl/impl.ts b/cocos/ui/assembler/graphics/webgl/impl.ts index 8c1c71d93e..12610f8740 100644 --- a/cocos/ui/assembler/graphics/webgl/impl.ts +++ b/cocos/ui/assembler/graphics/webgl/impl.ts @@ -1,6 +1,6 @@ import { Color, Vec2 } from '../../../../core/math'; -import { IARenderData } from '../../../../core/renderer/ui/render-data'; +import { MeshRenderData } from '../../../../core/renderer/ui/render-data'; import RecyclePool from '../../../../core/memop/recycle-pool'; import { arc, ellipse, roundRect, tesselateBezier } from '../helper'; import { LineCap, LineJoin, PointFlags} from '../types'; @@ -74,10 +74,10 @@ export class Impl { private _commandy = 0; private _points: Point[] = []; - private _renderDatasPool: RecyclePool = new RecyclePool(() => { - return new IARenderData(); + private _renderDatasPool: RecyclePool = new RecyclePool(() => { + return new MeshRenderData(); }, 16); - private _renderDatas: IARenderData[] = []; + private _renderDatas: MeshRenderData[] = []; private _curPath: Path | null = null; diff --git a/cocos/ui/components/button-component.ts b/cocos/ui/components/button-component.ts index b8de323501..49ce64f4fe 100644 --- a/cocos/ui/components/button-component.ts +++ b/cocos/ui/components/button-component.ts @@ -128,6 +128,7 @@ export class ButtonComponent extends Component { */ @property({ displayOrder: 1, + tooltip:'按钮是否可交互,这一项未选中时,按钮处在禁用状态', }) get interactable () { return this._interactable; @@ -155,19 +156,6 @@ export class ButtonComponent extends Component { } } - /** - * @zh - * 如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰。 - */ - // TODO: - // enableAutoGrayEffect: { - // default: false, - // tooltip: CC_DEV && 'i18n:COMPONENT.button.auto_gray_effect', - // notify() { - // this._updateDisabledState(); - // } - // }, - /** * @zh * 按钮状态改变时过渡方式。 @@ -175,6 +163,7 @@ export class ButtonComponent extends Component { @property({ type: Transition, displayOrder: 2, + tooltip:'按钮状态变化时的过渡类型', }) get transition () { return this._transition; @@ -194,7 +183,9 @@ export class ButtonComponent extends Component { * @zh * 普通状态下按钮所显示的颜色。 */ - @property + @property({ + tooltip:'普通状态的按钮背景颜色', + }) // @constget get normalColor (): Readonly { return this._normalColor; @@ -213,7 +204,9 @@ export class ButtonComponent extends Component { * @zh * 按下状态时按钮所显示的颜色。 */ - @property + @property({ + tooltip:'按下状态的按钮背景颜色', + }) // @constget get pressedColor (): Readonly { return this._pressColor; @@ -231,7 +224,9 @@ export class ButtonComponent extends Component { * @zh * 悬停状态下按钮所显示的颜色。 */ - @property + @property({ + tooltip:'悬停状态的按钮背景颜色', + }) // @constget get hoverColor (): Readonly { return this._hoverColor; @@ -248,7 +243,9 @@ export class ButtonComponent extends Component { * @zh * 禁用状态下按钮所显示的颜色。 */ - @property + @property({ + tooltip:'禁用状态的按钮背景颜色', + }) // @constget get disabledColor (): Readonly { return this._disabledColor; @@ -270,6 +267,7 @@ export class ButtonComponent extends Component { @property({ min: 0, max: 10, + tooltip:'按钮颜色变化或者缩放变化的过渡时间', }) get duration () { return this._duration; @@ -287,7 +285,9 @@ export class ButtonComponent extends Component { * @zh * 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale。 */ - @property + @property({ + tooltip:'当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale。', + }) get zoomScale () { return this._zoomScale; } @@ -307,6 +307,7 @@ export class ButtonComponent extends Component { */ @property({ type: SpriteFrame, + tooltip:'普通状态的按钮背景图资源', }) get normalSprite () { return this._normalSprite; @@ -332,6 +333,7 @@ export class ButtonComponent extends Component { */ @property({ type: SpriteFrame, + tooltip:'按下状态的按钮背景图资源', }) get pressedSprite () { return this._pressedSprite; @@ -352,6 +354,7 @@ export class ButtonComponent extends Component { */ @property({ type: SpriteFrame, + tooltip:'悬停状态的按钮背景图资源', }) get hoverSprite () { return this._hoverSprite; @@ -372,6 +375,7 @@ export class ButtonComponent extends Component { */ @property({ type: SpriteFrame, + tooltip:'禁用状态的按钮背景图资源', }) get disabledSprite () { return this._disabledSprite; @@ -397,6 +401,7 @@ export class ButtonComponent extends Component { @property({ type: Node, displayOrder: 0, + tooltip:'指定 Button 背景节点,Button 状态改变时会修改此节点的 Color 或 Sprite 属性', }) get target () { return this._target; @@ -419,6 +424,7 @@ export class ButtonComponent extends Component { @property({ type: [ComponentEventHandler], displayOrder: 3, + tooltip:'按钮点击事件的列表。先将数量改为1或更多,就可以为每个点击事件设置接受者和处理方法', }) public clickEvents: ComponentEventHandler[] = []; @property @@ -696,7 +702,6 @@ export class ButtonComponent extends Component { protected _updateState () { const state = this._getButtonState(); this._applyTransition(state); - // this._updateDisabledState(); } protected _getButtonState () { @@ -781,19 +786,6 @@ export class ButtonComponent extends Component { } } - // _updateDisabledState() { - // if (this._sprite) { - // if (this.enableAutoGrayEffect) { - // if (!(this._transition === Transition.SPRITE && this._disabledSprite)) { - // if (!this._interactable) { - // this._sprite.setState(cc.SpriteComponent.State.GRAY); - // return; - // } - // } - // } - // this._sprite.setState(cc.SpriteComponent.State.NORMAL); - // } - // } } cc.ButtonComponent = ButtonComponent; diff --git a/cocos/ui/components/editbox/edit-box-component.ts b/cocos/ui/components/editbox/edit-box-component.ts index bfaa9f7b3c..0fc9d3582f 100644 --- a/cocos/ui/components/editbox/edit-box-component.ts +++ b/cocos/ui/components/editbox/edit-box-component.ts @@ -76,7 +76,9 @@ export class EditBoxComponent extends Component { * @zh * 输入框的初始输入内容,如果为空则会显示占位符的文本。 */ - @property + @property({ + tooltip:'输入框的初始输入内容,如果为空则会显示占位符的文本', + }) get string () { return this._string; } @@ -101,6 +103,7 @@ export class EditBoxComponent extends Component { */ @property({ type: SpriteFrame, + tooltip:'输入框的背景图片', }) get backgroundImage () { return this._backgroundImage; @@ -126,6 +129,7 @@ export class EditBoxComponent extends Component { */ @property({ type: KeyboardReturnType, + tooltip:'指定移动设备上面回车按钮的样式', }) get returnType () { return this._returnType; @@ -147,6 +151,7 @@ export class EditBoxComponent extends Component { */ @property({ type: InputFlag, + tooltip:'指定输入标志位,可以指定输入方式为密码或者单词首字母大写' }) get inputFlag () { return this._inputFlag; @@ -169,6 +174,7 @@ export class EditBoxComponent extends Component { */ @property({ type: InputMode, + tooltip:'指定输入模式: ANY 表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式' }) get inputMode () { return this._inputMode; @@ -188,7 +194,9 @@ export class EditBoxComponent extends Component { * @zh * 输入框文本的字体大小。 */ - @property + @property({ + tooltip:'输入框文本的字体大小', + }) get fontSize () { return this._fontSize; } @@ -214,7 +222,9 @@ export class EditBoxComponent extends Component { * @zh * 输入框文本的行高。 */ - @property + @property({ + tooltip:'输入框文本的行高' + }) get lineHeight () { return this._lineHeight; } @@ -239,6 +249,7 @@ export class EditBoxComponent extends Component { */ @property({ type: Color, + tooltip:'输入框文本的颜色', }) get fontColor () { return this._fontColor; @@ -269,7 +280,9 @@ export class EditBoxComponent extends Component { * @zh * 输入框占位符的文本内容。 */ - @property + @property({ + tooltip:'输入框占位符的文本内容', + }) get placeholder () { return this._placeholder; } @@ -295,7 +308,9 @@ export class EditBoxComponent extends Component { * @zh * 输入框占位符的字体大小。 */ - @property + @property({ + tooltip:'输入框占位符的字体大小' + }) get placeholderFontSize () { return this._placeholderFontSize; } @@ -318,7 +333,9 @@ export class EditBoxComponent extends Component { * @zh * 输入框占位符的字体颜色。 */ - @property + @property({ + tooltip:'输入框占位符的字体颜色', + }) get placeholderFontColor () { return this._placeholderFontColor; } @@ -347,7 +364,9 @@ export class EditBoxComponent extends Component { * - 如果值为小于 0 的值,则不会限制输入字符个数。 * - 如果值为 0,则不允许用户进行任何输入。 */ - @property + @property({ + tooltip:'输入框最大允许输入的字符个数', + }) get maxLength () { return this._maxLength; } @@ -370,7 +389,9 @@ export class EditBoxComponent extends Component { * 输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义) * Note: only available on Web at the moment. */ - @property + @property({ + tooltip:'输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义)' + }) get stayOnTop () { return this._stayOnTop; } @@ -389,7 +410,9 @@ export class EditBoxComponent extends Component { * @zh * 修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)。 */ - @property + @property({ + tooltip:'修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)', + }) get tabIndex () { return this._tabIndex; } @@ -414,6 +437,7 @@ export class EditBoxComponent extends Component { */ @property({ type: [ComponentEventHandler], + tooltip:'该事件在用户点击输入框获取焦点的时候被触发', }) public editingDidBegan: ComponentEventHandler[] = []; @@ -426,6 +450,7 @@ export class EditBoxComponent extends Component { */ @property({ type: [ComponentEventHandler], + tooltip:'编辑文本输入框时触发的事件回调' }) public textChanged: ComponentEventHandler[] = []; @@ -438,6 +463,7 @@ export class EditBoxComponent extends Component { */ @property({ type: [ComponentEventHandler], + tooltip:'在单行模式下面,一般是在用户按下回车或者点击屏幕输入框以外的地方调用该函数。 如果是多行输入,一般是在用户点击屏幕输入框以外的地方调用该函数', }) public editingDidEnded: ComponentEventHandler[] = []; @@ -450,6 +476,7 @@ export class EditBoxComponent extends Component { */ @property({ type: [ComponentEventHandler], + tooltip:'该事件在用户按下回车键的时候被触发, 如果是单行输入框,按回车键还会使输入框失去焦点', }) public editingReturn: ComponentEventHandler[] = []; diff --git a/cocos/ui/components/graphics-component.ts b/cocos/ui/components/graphics-component.ts index 18febbc88b..154e5fb20e 100644 --- a/cocos/ui/components/graphics-component.ts +++ b/cocos/ui/components/graphics-component.ts @@ -73,6 +73,7 @@ export class GraphicsComponent extends UIRenderComponent { */ @property({ type: LineJoin, + tooltip:'两条线相交时,所创建的拐角类型', }) get lineJoin () { return this._lineJoin; @@ -93,6 +94,7 @@ export class GraphicsComponent extends UIRenderComponent { */ @property({ type: LineCap, + tooltip:'线条的结束端点样式', }) get lineCap () { return this._lineCap; @@ -111,7 +113,9 @@ export class GraphicsComponent extends UIRenderComponent { * @zh * 线段颜色。 */ - @property + @property({ + tooltip:'笔触的颜色', + }) // @constget get strokeColor (): Readonly { return this._strokeColor; @@ -130,7 +134,9 @@ export class GraphicsComponent extends UIRenderComponent { * @zh * 填充颜色。 */ - @property + @property({ + tooltip:'填充绘画的颜色', + }) // @constget get fillColor (): Readonly { return this._fillColor; @@ -149,7 +155,9 @@ export class GraphicsComponent extends UIRenderComponent { * @zh * 设置斜接面限制比例。 */ - @property + @property({ + tooltip:'最大斜接长度', + }) get miterLimit () { return this._miterLimit; } diff --git a/cocos/ui/components/index.ts b/cocos/ui/components/index.ts index dee67a6804..0844b32957 100644 --- a/cocos/ui/components/index.ts +++ b/cocos/ui/components/index.ts @@ -24,5 +24,6 @@ export { GraphicsComponent } from './graphics-component'; export { UIReorderComponent } from './ui-reorder-component'; export { PageViewComponent } from './page-view-component'; export { PageViewIndicatorComponent } from './page-view-indicator-component'; +export { UIStaticBatchComponent } from './ui-static-batch-component'; export { widgetManager } from './widget-manager'; diff --git a/cocos/ui/components/label-component.ts b/cocos/ui/components/label-component.ts index 1166ac2aff..09bcb1d680 100644 --- a/cocos/ui/components/label-component.ts +++ b/cocos/ui/components/label-component.ts @@ -175,6 +175,7 @@ export class LabelComponent extends UIRenderComponent { @property({ displayOrder: 4, multiline: true, + tooltip:'Label 显示的文本内容字符串', }) get string () { return this._string; @@ -196,6 +197,7 @@ export class LabelComponent extends UIRenderComponent { @property({ type: HorizontalTextAlignment, displayOrder: 5, + tooltip:'文字水平对齐模式', }) get horizontalAlign () { return this._horizontalAlign; @@ -217,6 +219,7 @@ export class LabelComponent extends UIRenderComponent { @property({ type: VerticalTextAlignment, displayOrder: 6, + tooltip:'文字垂直对齐模式', }) get verticalAlign () { return this._verticalAlign; @@ -254,6 +257,7 @@ export class LabelComponent extends UIRenderComponent { */ @property({ displayOrder: 7, + tooltip:'文字尺寸,以 point 为单位', }) get fontSize () { return this._fontSize; @@ -274,6 +278,7 @@ export class LabelComponent extends UIRenderComponent { */ @property({ displayOrder: 8, + tooltip:'文字字体名字', }) get fontFamily () { return this._fontFamily; @@ -294,6 +299,7 @@ export class LabelComponent extends UIRenderComponent { */ @property({ displayOrder: 8, + tooltip:'文字行高,以 point 为单位', }) get lineHeight () { return this._lineHeight; @@ -314,6 +320,7 @@ export class LabelComponent extends UIRenderComponent { @property({ type: Overflow, displayOrder: 9, + tooltip:'文字排版模式,包括以下三种:\n 1. CLAMP: 节点约束框之外的文字会被截断 \n 2. SHRINK: 自动根据节点约束框缩小文字\n 3. RESIZE_HEIGHT: 根据文本内容自动更新节点的 height 属性.', }) get overflow () { return this._overflow; @@ -334,6 +341,7 @@ export class LabelComponent extends UIRenderComponent { */ @property({ displayOrder: 10, + tooltip:'自动换行', }) get enableWrapText () { return this._enableWrapText; @@ -354,6 +362,7 @@ export class LabelComponent extends UIRenderComponent { @property({ type: Font, displayOrder: 11, + tooltip:'Label 使用的字体资源', }) get font () { // return this._N$file; @@ -396,6 +405,7 @@ export class LabelComponent extends UIRenderComponent { */ @property({ displayOrder: 12, + tooltip:'是否使用系统默认字体', }) get useSystemFont () { return this._isSystemFontUsed; @@ -436,6 +446,7 @@ export class LabelComponent extends UIRenderComponent { @property({ type: CacheMode, displayOrder: 13, + tooltip:'文本缓存模式,包括以下三种:\n 1. NONE: 不做任何缓存,文本内容进行一次绘制 \n 2. BITMAP: 将文本作为静态图像加入动态图集进行批次合并,但是不能频繁动态修改文本内容 \n 3. CHAR: 将文本拆分为字符并且把字符纹理缓存到一张字符图集中进行复用,适用于字符内容重复并且频繁更新的文本内容', }) get cacheMode () { return this._cacheMode; @@ -469,6 +480,7 @@ export class LabelComponent extends UIRenderComponent { @property({ // visible: false, displayOrder: 15, + tooltip:'字体加粗', }) get isBold () { return this._isBold; @@ -490,6 +502,7 @@ export class LabelComponent extends UIRenderComponent { @property({ // visible: false, displayOrder: 16, + tooltip:'字体倾斜', }) get isItalic () { return this._isItalic; @@ -511,6 +524,7 @@ export class LabelComponent extends UIRenderComponent { @property({ // visible: false, displayOrder: 17, + tooltip:'字体加下划线', }) get isUnderline () { return this._isUnderline; diff --git a/cocos/ui/components/label-outline-component.ts b/cocos/ui/components/label-outline-component.ts index eb56b577d0..5d63bf39b4 100644 --- a/cocos/ui/components/label-outline-component.ts +++ b/cocos/ui/components/label-outline-component.ts @@ -66,7 +66,9 @@ export class LabelOutlineComponent extends Component { * outline.color = cc.color(0.5, 0.3, 0.7, 1.0); * ``` */ - @property + @property({ + tooltip:'描边的颜色', + }) // @constget get color (): Readonly { return this._color; @@ -90,7 +92,9 @@ export class LabelOutlineComponent extends Component { * outline.width = 3; * ``` */ - @property + @property({ + tooltip:'描边的宽度', + }) get width () { return this._width; } diff --git a/cocos/ui/components/layout-component.ts b/cocos/ui/components/layout-component.ts index fd6f5801e8..3ec93177e5 100644 --- a/cocos/ui/components/layout-component.ts +++ b/cocos/ui/components/layout-component.ts @@ -171,6 +171,7 @@ export class LayoutComponent extends Component { */ @property({ type: Type, + tooltip:'自动布局模式,包括:\n 1. NONE,不会对子节点进行自动布局 \n 2. HORIZONTAL,横向自动排布子物体 \n 3. VERTICAL,垂直自动排布子物体\n 4. GRID, 采用网格方式对子物体自动进行布局', }) get type () { return this._N$layoutType; @@ -193,6 +194,7 @@ export class LayoutComponent extends Component { */ @property({ type: ResizeMode, + tooltip:'缩放模式,包括:\n 1. NONE,不会对子节点和容器进行大小缩放 \n 2. CONTAINER, 对容器的大小进行缩放 \n 3. CHILDREN, 对子节点的大小进行缩放', }) get resizeMode () { return this._resizeMode; diff --git a/cocos/ui/components/mask-component.ts b/cocos/ui/components/mask-component.ts index b7b04f7fcd..eaf5ec268e 100644 --- a/cocos/ui/components/mask-component.ts +++ b/cocos/ui/components/mask-component.ts @@ -99,6 +99,7 @@ export class MaskComponent extends UIRenderComponent { @property({ type: MaskType, displayOrder: 4, + tooltip:'遮罩类型', }) get type () { return this._type; diff --git a/cocos/ui/components/page-view-component.ts b/cocos/ui/components/page-view-component.ts index b50faac3ef..65ddf9d101 100644 --- a/cocos/ui/components/page-view-component.ts +++ b/cocos/ui/components/page-view-component.ts @@ -112,6 +112,7 @@ export class PageViewComponent extends ScrollViewComponent { */ @property({ type: SizeMode, + tooltip:'页面视图中每个页面大小类型', }) get sizeMode () { return this._sizeMode; @@ -132,6 +133,7 @@ export class PageViewComponent extends ScrollViewComponent { */ @property({ type: Direction, + tooltip:'页面视图滚动类型', }) get direction () { return this._direction; @@ -155,6 +157,7 @@ export class PageViewComponent extends ScrollViewComponent { @property({ slide: true, range: [0, 1, 0.01], + tooltip:'滚动临界值,默认单位百分比,当拖拽超出该数值时,松开会自动滚动下一页,小于时则还原', }) get scrollThreshold () { return this._scrollThreshold; @@ -175,6 +178,7 @@ export class PageViewComponent extends ScrollViewComponent { @property({ slide: true, range: [0, 1, 0.01], + tooltip:'设置 PageView PageTurning 事件的发送时机', }) get pageTurningEventTiming () { return this._pageTurningEventTiming; @@ -194,6 +198,7 @@ export class PageViewComponent extends ScrollViewComponent { */ @property({ type: PageViewIndicatorComponent, + tooltip:'页面视图指示器组件', }) get indicator () { return this._indicator; @@ -228,7 +233,9 @@ export class PageViewComponent extends ScrollViewComponent { * 当用户快速滑动时,会根据滑动开始和结束的距离与时间计算出一个速度值, * 该值与此临界值相比较,如果大于临界值,则进行自动翻页。 */ - @property + @property({ + tooltip:'快速滑动翻页临界值\n当用户快速滑动时,会根据滑动开始和结束的距离与时间计算出一个速度值\n该值与此临界值相比较,如果大于临界值,则进行自动翻页' + }) public autoPageTurningThreshold = 100; // override visible false @@ -289,6 +296,7 @@ export class PageViewComponent extends ScrollViewComponent { */ @property({ type: [ComponentEventHandler], + tooltip:'滚动视图的事件回调函数', }) public pageEvents: ComponentEventHandler[] = []; diff --git a/cocos/ui/components/page-view-indicator-component.ts b/cocos/ui/components/page-view-indicator-component.ts index b2a24b6c7d..1682ad3b7a 100644 --- a/cocos/ui/components/page-view-indicator-component.ts +++ b/cocos/ui/components/page-view-indicator-component.ts @@ -76,6 +76,7 @@ export class PageViewIndicatorComponent extends Component { */ @property({ type: SpriteFrame, + tooltip:'每个页面标记显示的图片', }) get spriteFrame () { return this._spriteFrame; @@ -96,6 +97,7 @@ export class PageViewIndicatorComponent extends Component { */ @property({ type: Direction, + tooltip:'页面标记摆放方向', }) get direction () { return this._direction; @@ -115,6 +117,7 @@ export class PageViewIndicatorComponent extends Component { */ @property({ type: Size, + tooltip:'每个页面标记的大小', }) get cellSize () { return this._cellSize; @@ -134,7 +137,9 @@ export class PageViewIndicatorComponent extends Component { * @en The distance between each element. * @zh 每个页面标记之间的边距 */ - @property + @property({ + tooltip:'每个页面标记之间的边距', + }) public spacing = 0; @property public _spriteFrame: SpriteFrame | null = null; diff --git a/cocos/ui/components/progress-bar-component.ts b/cocos/ui/components/progress-bar-component.ts index 15651fee14..6dbc7c2238 100644 --- a/cocos/ui/components/progress-bar-component.ts +++ b/cocos/ui/components/progress-bar-component.ts @@ -93,6 +93,7 @@ export class ProgressBarComponent extends Component { */ @property({ type: SpriteComponent, + tooltip:'进度条显示用的 Sprite 节点,可以动态改变尺寸', }) get barSprite () { return this._barSprite; @@ -113,6 +114,7 @@ export class ProgressBarComponent extends Component { */ @property({ type: Mode, + tooltip:'进度条显示模式,目前支持水平和垂直两种', }) get mode () { return this._mode; @@ -143,7 +145,9 @@ export class ProgressBarComponent extends Component { * @zh * 进度条实际的总长度。 */ - @property + @property({ + tooltip:'进度条在 progress 为 1 时的最大长度', + }) get totalLength () { return this._totalLength; } @@ -163,6 +167,7 @@ export class ProgressBarComponent extends Component { @property({ range: [0, 1, 0.1], slide: true, + tooltip:'当前进度指示,范围从 0 到 1', }) get progress () { return this._progress; @@ -181,7 +186,9 @@ export class ProgressBarComponent extends Component { * @zh * 进度条是否进行反方向变化。 */ - @property + @property({ + tooltip:'是否反向驱动进度条', + }) get reverse () { return this._reverse; } diff --git a/cocos/ui/components/rich-text-component.ts b/cocos/ui/components/rich-text-component.ts index 5d8785526a..18ee59fc71 100644 --- a/cocos/ui/components/rich-text-component.ts +++ b/cocos/ui/components/rich-text-component.ts @@ -177,6 +177,7 @@ export class RichTextComponent extends UIComponent { */ @property({ multiline: true, + tooltip:'富文本显示的文本内容', }) get string () { return this._string; @@ -196,6 +197,7 @@ export class RichTextComponent extends UIComponent { */ @property({ type: HorizontalTextAlignment, + tooltip:'文本内容的水平对齐方式', }) get horizontalAlign () { return this._horizontalAlign; @@ -215,7 +217,9 @@ export class RichTextComponent extends UIComponent { * @zh * 富文本字体大小。 */ - @property + @property({ + tooltip:'富文本字体大小', + }) get fontSize () { return this._fontSize; } @@ -236,6 +240,7 @@ export class RichTextComponent extends UIComponent { */ @property({ type: TTFFont, + tooltip:'富文本定制字体', }) get font () { return this._font; @@ -257,7 +262,9 @@ export class RichTextComponent extends UIComponent { * @zh * 富文本的最大宽度。 */ - @property + @property({ + tooltip:'富文本的最大宽度', + }) get maxWidth () { return this._maxWidth; } @@ -276,7 +283,9 @@ export class RichTextComponent extends UIComponent { * @zh * 富文本行高。 */ - @property + @property({ + tooltip:'富文本行高', + }) get lineHeight () { return this._lineHeight; } @@ -297,6 +306,7 @@ export class RichTextComponent extends UIComponent { */ @property({ type: SpriteAtlas, + tooltip:'对于 img 标签里面的 src 属性名称,都需要在 imageAtlas 里面找到一个有效的 spriteFrame,否则 img tag 会判定为无效', }) get imageAtlas () { return this._imageAtlas; @@ -316,7 +326,9 @@ export class RichTextComponent extends UIComponent { * @zh * 选中此选项后,RichText 将阻止节点边界框中的所有输入事件(鼠标和触摸),从而防止输入事件穿透到底层节点。 */ - @property + @property({ + tooltip:'选中此选项后,RichText 将阻止节点边界框中的所有输入事件(鼠标和触摸),从而防止输入事件穿透到底层节点', + }) get handleTouchEvent () { return this._handleTouchEvent; } diff --git a/cocos/ui/components/scroll-bar-component.ts b/cocos/ui/components/scroll-bar-component.ts index 398b67f68b..ac57ed7573 100644 --- a/cocos/ui/components/scroll-bar-component.ts +++ b/cocos/ui/components/scroll-bar-component.ts @@ -80,6 +80,7 @@ export class ScrollBarComponent extends Component { */ @property({ type: SpriteComponent, + tooltip:'作为当前滚动区域位置显示的滑块 Sprite', }) get handle () { return this._handle; @@ -99,6 +100,7 @@ export class ScrollBarComponent extends Component { */ @property({ type: Direction, + tooltip:'ScrollBar 的滚动方向', }) get direction () { return this._direction; @@ -117,7 +119,9 @@ export class ScrollBarComponent extends Component { * @zh * 是否在没有滚动动作时自动隐藏 ScrollBar。 */ - @property + @property({ + tooltip:'是否在没有滚动动作时自动隐藏 ScrollBar', + }) get enableAutoHide () { return this._enableAutoHide; } @@ -138,7 +142,9 @@ export class ScrollBarComponent extends Component { * 没有滚动动作后经过多久会自动隐藏。
* 注意:只要当 “enableAutoHide” 为 true 时,才有效。 */ - @property + @property({ + tooltip:'没有滚动动作后经过多久会自动隐藏。\n注意:只要当 “enableAutoHide” 为 true 时,才有效。', + }) get autoHideTime () { return this._autoHideTime; } diff --git a/cocos/ui/components/scroll-view-component.ts b/cocos/ui/components/scroll-view-component.ts index 6f9e83050e..d3b290fef6 100644 --- a/cocos/ui/components/scroll-view-component.ts +++ b/cocos/ui/components/scroll-view-component.ts @@ -167,6 +167,7 @@ export class ScrollViewComponent extends ViewGroupComponent { */ @property({ type: Node, + tooltip:'可滚动展示内容的节点', }) get content () { return this._content; @@ -186,6 +187,7 @@ export class ScrollViewComponent extends ViewGroupComponent { */ @property({ type: ScrollBarComponent, + tooltip:'水平滚动的 ScrollBar', }) get horizontalScrollBar () { return this._horizontalScrollBar; @@ -211,6 +213,7 @@ export class ScrollViewComponent extends ViewGroupComponent { */ @property({ type: ScrollBarComponent, + tooltip:'垂直滚动的 ScrollBar', }) get verticalScrollBar () { return this._verticalScrollBar; @@ -242,21 +245,27 @@ export class ScrollViewComponent extends ViewGroupComponent { * @zh * 是否开启水平滚动。 */ - @property + @property({ + tooltip:'是否开启水平滚动', + }) public horizontal = true; /** * @zh * 是否开启垂直滚动。 */ - @property + @property({ + tooltip:'是否开启垂直滚动', + }) public vertical = true; /** * @zh * 是否开启滚动惯性。 */ - @property + @property({ + tooltip:'是否开启滚动惯性', + }) public inertia = true; /** @@ -265,6 +274,7 @@ export class ScrollViewComponent extends ViewGroupComponent { */ @property({ range: [0, 1, 0.1], + tooltip:'开启惯性后,在用户停止触摸后滚动多快停止,0 表示永不停止,1 表示立刻停止', }) public brake = 0.5; @@ -272,7 +282,9 @@ export class ScrollViewComponent extends ViewGroupComponent { * @zh * 是否允许滚动内容超过边界,并在停止触摸后回弹。 */ - @property + @property({ + tooltip:'是否允许滚动内容超过边界,并在停止触摸后回弹', + }) public elastic = true; /** @@ -281,6 +293,7 @@ export class ScrollViewComponent extends ViewGroupComponent { */ @property({ range: [0, 10], + tooltip:'回弹持续的时间,0 表示将立即反弹', }) public bounceDuration = 1; @@ -290,6 +303,7 @@ export class ScrollViewComponent extends ViewGroupComponent { */ @property({ type: [ComponentEventHandler], + tooltip:'滚动视图的事件回调函数', }) public scrollEvents: ComponentEventHandler[] = []; @@ -298,7 +312,9 @@ export class ScrollViewComponent extends ViewGroupComponent { * 如果这个属性被设置为 true,那么滚动行为会取消子节点上注册的触摸事件,默认被设置为 true。
* 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。 */ - @property + @property({ + tooltip:'滚动行为是否会取消子节点上注册的触摸事件', + }) public cancelInnerEvents = true; protected _autoScrolling = false; diff --git a/cocos/ui/components/slider-component.ts b/cocos/ui/components/slider-component.ts index 43785bf71e..64f51613f4 100644 --- a/cocos/ui/components/slider-component.ts +++ b/cocos/ui/components/slider-component.ts @@ -72,6 +72,7 @@ export class SliderComponent extends Component { */ @property({ type: SpriteComponent, + tooltip:'滑块按钮部件', }) get handle () { return this._handle; @@ -94,6 +95,7 @@ export class SliderComponent extends Component { */ @property({ type: Direction, + tooltip:'滑动方向', }) get direction () { return this._direction; @@ -115,6 +117,7 @@ export class SliderComponent extends Component { @property({ slide: true, range: [0, 1, 0.01], + tooltip:'当前进度值,该数值的区间是 0 - 1 之间。', }) get progress () { return this._progress; @@ -137,6 +140,7 @@ export class SliderComponent extends Component { */ @property({ type: EventHandler, + tooltip:'滑动器组件事件回调函数', }) public slideEvents: EventHandler[] = []; @property diff --git a/cocos/ui/components/sprite-component.ts b/cocos/ui/components/sprite-component.ts index b886f75a01..2ee30c9ef6 100644 --- a/cocos/ui/components/sprite-component.ts +++ b/cocos/ui/components/sprite-component.ts @@ -35,7 +35,7 @@ import { Vec2 } from '../../core/math'; import { ccenum } from '../../core/value-types/enum'; import { clamp } from '../../core/math/utils'; import { UI } from '../../core/renderer/ui/ui'; -import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; +import { UIRenderComponent, InstanceMaterialType } from '../../core/components/ui-base/ui-render-component'; /** * @zh @@ -153,6 +153,7 @@ export class SpriteComponent extends UIRenderComponent { @property({ type: SpriteAtlas, displayOrder: 4, + tooltip:'图片资源所属的 Atlas 图集资源', }) get spriteAtlas () { return this._atlas; @@ -164,7 +165,7 @@ export class SpriteComponent extends UIRenderComponent { } this._atlas = value; - this.spriteFrame = null; +// this.spriteFrame = null; } /** @@ -174,6 +175,7 @@ export class SpriteComponent extends UIRenderComponent { @property({ type: SpriteFrame, displayOrder: 5, + tooltip:'渲染 Sprite 使用的 SpriteFrame 图片资源', }) get spriteFrame () { return this._spriteFrame; @@ -207,6 +209,9 @@ export class SpriteComponent extends UIRenderComponent { @property({ type: SpriteType, displayOrder: 6, + tooltip:'渲染模式:\n- 普通(Simple):修改尺寸会整体拉伸图像,适用于序列帧动画和普通图像 \n' + + '- 九宫格(Sliced):修改尺寸时四个角的区域不会拉伸,适用于 UI 按钮和面板背景 \n' + + '- 填充(Filled):设置一定的填充起始位置和方向,能够以一定比率剪裁显示图片', }) get type () { return this._type; @@ -229,6 +234,7 @@ export class SpriteComponent extends UIRenderComponent { */ @property({ type: FillType, + tooltip:'填充方向,可以选择横向(Horizontal),纵向(Vertical)和扇形(Radial)三种方向', }) get fillType () { return this._fillType; @@ -258,7 +264,9 @@ export class SpriteComponent extends UIRenderComponent { * sprite.fillCenter = cc.v2(0, 0); * ``` */ - @property + @property({ + tooltip:'扇形填充时,指定扇形的中心点,取值范围 0 ~ 1', + }) get fillCenter () { return this._fillCenter; } @@ -281,7 +289,8 @@ export class SpriteComponent extends UIRenderComponent { * ``` */ @property({ - range: [0, 1, 0.1] + range: [0, 1, 0.1], + tooltip:'填充起始位置,输入一个 0 ~ 1 之间的小数表示起始位置的百分比', }) get fillStart () { return this._fillStart; @@ -306,7 +315,8 @@ export class SpriteComponent extends UIRenderComponent { * ``` */ @property({ - range: [0, 1, 0.1] + range: [0, 1, 0.1], + tooltip:'填充总量,取值范围 0 ~ 1 指定显示图像范围的百分比', }) get fillRange () { return this._fillRange; @@ -329,6 +339,7 @@ export class SpriteComponent extends UIRenderComponent { */ @property({ displayOrder: 8, + tooltip:'节点约束框内是否包括透明像素区域,勾选此项会去除节点约束框内的透明区域', }) get trim () { return this._isTrimmedMode; @@ -346,6 +357,23 @@ export class SpriteComponent extends UIRenderComponent { } } + @property + get grayscale () { + return this._useGrayscale; + } + set grayscale (value) { + if (this._useGrayscale === value) { + return; + } + this._useGrayscale = value; + if (value === true) { + this._instanceMaterialType = InstanceMaterialType.GRAYSCALE; } + else { + this._instanceMaterialType = InstanceMaterialType.ADDCOLORANDTEXTURE; + } + this._instanceMaterial(); + } + /** * @zh 精灵尺寸调整模式。 * @@ -357,6 +385,7 @@ export class SpriteComponent extends UIRenderComponent { @property({ type: SizeMode, displayOrder: 7, + tooltip:'指定 Sprite 所在节点的尺寸,CUSTOM 表示自定义尺寸,TRIMMED 表示取原始图片剪裁透明像素后的尺寸,RAW 表示取原始图片未剪裁的尺寸', }) get sizeMode () { return this._sizeMode; @@ -391,12 +420,18 @@ export class SpriteComponent extends UIRenderComponent { private _fillRange = 0; @property private _isTrimmedMode = true; + @property + private _useGrayscale = false; // _state = 0; @property private _atlas: SpriteAtlas | null = null; // static State = State; public __preload () { + if (this._useGrayscale) { + this._instanceMaterialType = InstanceMaterialType.GRAYSCALE; + } + if (super.__preload) { super.__preload(); } @@ -570,7 +605,7 @@ export class SpriteComponent extends UIRenderComponent { // this.markForRender(true); } } - +/* private _applyAtlas (spriteFrame: SpriteFrame | null) { if (!CC_EDITOR) { return; @@ -589,7 +624,7 @@ export class SpriteComponent extends UIRenderComponent { } } } - +*/ private _onTextureLoaded () { if (!this.isValid) { return; @@ -639,11 +674,12 @@ export class SpriteComponent extends UIRenderComponent { } } } - +/* if (CC_EDITOR) { // Set atlas this._applyAtlas(spriteFrame); } +*/ } /** @@ -655,6 +691,21 @@ export class SpriteComponent extends UIRenderComponent { this._renderDataFlag = true; } } + + /** + * @zh + * 精灵图集内的精灵替换 + * + * @returns + */ + public changeSpriteFrameFromAtlas (name: string) { + if(!this._atlas) { + console.warn('SpriteAtlas is null.'); + return; + } + const sprite = this._atlas.getSpriteFrame(name); + this.spriteFrame = sprite; + } } cc.SpriteComponent = SpriteComponent; diff --git a/cocos/ui/components/toggle-component.ts b/cocos/ui/components/toggle-component.ts index 4ef1657a9f..ed964d570c 100644 --- a/cocos/ui/components/toggle-component.ts +++ b/cocos/ui/components/toggle-component.ts @@ -42,14 +42,15 @@ import { ToggleContainerComponent } from './toggle-container-component'; @ccclass('cc.ToggleComponent') @executionOrder(110) @menu('UI/Toggle') -@executeInEditMode export class ToggleComponent extends ButtonComponent { /** * @zh * 如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。 */ - @property + @property({ + tooltip:'如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。', + }) get isChecked () { return this._isChecked; } @@ -69,6 +70,7 @@ export class ToggleComponent extends ButtonComponent { */ @property({ type: ToggleContainerComponent, + tooltip:'Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox,否则,Toggle 是一个 RadioButton。' }) get toggleGroup () { return this._toggleGroup; @@ -94,6 +96,7 @@ export class ToggleComponent extends ButtonComponent { */ @property({ type: SpriteComponent, + tooltip:'Toggle 处于选中状态时显示的精灵图片', }) get checkMark () { return this._checkMark; @@ -127,6 +130,7 @@ export class ToggleComponent extends ButtonComponent { */ @property({ type: [ComponentEventHandler], + tooltip:'列表类型,默认为空,用户添加的每一个事件由节点引用,组件名称和一个响应函数组成', }) public checkEvents: ComponentEventHandler[] = []; @property @@ -224,19 +228,6 @@ export class ToggleComponent extends ButtonComponent { } } - // _updateDisabledState() { - // this._super(); - - // if (this._checkMark) { - // this._checkMark.setState(0); - // } - // if (this.enableAutoGrayEffect) { - // if (this._checkMark && !this.interactable) { - // this._checkMark.setState(1); - // } - // } - // } - private _registerToggleEvent () { this.node.on('click', this.toggle, this); } diff --git a/cocos/ui/components/toggle-container-component.ts b/cocos/ui/components/toggle-container-component.ts index 349e7c1cc1..99ab52c538 100644 --- a/cocos/ui/components/toggle-container-component.ts +++ b/cocos/ui/components/toggle-container-component.ts @@ -46,6 +46,7 @@ import { ToggleComponent} from './toggle-component'; export class ToggleContainerComponent extends Component { @property({ type: [ComponentEventHandler], + tooltip:'选中事件。列表类型,默认为空,用户添加的每一个事件由节点引用,组件名称和一个响应函数组成。', }) public checkEvents: ComponentEventHandler[] = []; @property @@ -56,7 +57,9 @@ export class ToggleContainerComponent extends Component { * @zh * 如果这个设置为 true,那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。 */ - @property + @property({ + tooltip:'如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。', + }) get allowSwitchOff () { return this._allowSwitchOff; } diff --git a/cocos/ui/components/ui-model-component.ts b/cocos/ui/components/ui-model-component.ts index 77fb9f59aa..4774439a44 100644 --- a/cocos/ui/components/ui-model-component.ts +++ b/cocos/ui/components/ui-model-component.ts @@ -35,6 +35,7 @@ import { ccclass, executionOrder, menu } from '../../core/data/class-decorator'; import { director } from '../../core/director'; import { RenderPriority } from '../../core/pipeline/define'; import { UI } from '../../core/renderer/ui/ui'; +import { Model } from '../../core/renderer'; /** * @zh @@ -46,6 +47,8 @@ import { UI } from '../../core/renderer/ui/ui'; @menu('UI/Model') export class UIModelComponent extends UIComponent { + private _models: Model[] | null = null; + public get modelComponent () { return this._modelComponent; } @@ -60,7 +63,8 @@ export class UIModelComponent extends UIComponent { } this._modelComponent._sceneGetter = director.root!.ui.getRenderSceneGetter(); - this._modelComponent.recreateModel(); + this._modelComponent._changeSceneInModel(); + this._models = this._modelComponent._collectModels(); } public onDestroy () { @@ -71,13 +75,16 @@ export class UIModelComponent extends UIComponent { this._modelComponent._sceneGetter = null; if (cc.isValid(this.node, true)) { - this._modelComponent.recreateModel(); + this._modelComponent._changeSceneInModel(); } + this._models = null; } public updateAssembler (render: UI) { - if (this._modelComponent) { - render.commitModel.call(render, this, this._modelComponent._getModel(), this._modelComponent.material); + if (this._models) { + for(const m of this._models){ + render.commitModel.call(render, this, m, this._modelComponent!.material); + } return true; } @@ -88,6 +95,17 @@ export class UIModelComponent extends UIComponent { this._fitUIRenderQueue(); } + /** + * TODO: refactor using Pass.createPipelineState(null, overriddenPass) + * ``` + * const overriddenPass = new Pass(); // global scope + * // when creating PSO + * Pass.fillinPipelineInfo(overriddenPass, passes[j]); + * Pass.fillinPipelineInfo(overriddenPass, { priority: RenderPriority.MAX - 11, blendState: { targets: [ { blend: true } ] } }); + * const pso = passes[j].createPipelineState(null, overriddenPass); + * // ... + * ``` + */ private _fitUIRenderQueue () { if (!this._modelComponent) { return; diff --git a/cocos/ui/components/ui-static-batch-component.ts b/cocos/ui/components/ui-static-batch-component.ts new file mode 100644 index 0000000000..336199aa28 --- /dev/null +++ b/cocos/ui/components/ui-static-batch-component.ts @@ -0,0 +1,232 @@ +/* + Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** + * @category ui + */ + +import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; +import { UI } from '../../core/renderer/ui/ui'; +import { MeshBuffer } from '../../core/renderer/ui/mesh-buffer'; +import { ccclass, menu, executionOrder, property } from '../../core/data/class-decorator'; +import { UIDrawBatch } from '../../core/renderer/ui/ui-draw-batch'; +import { director, Color, GFXBlendFactor, Material } from '../../core'; +import { vfmt } from '../../core/renderer/ui/ui-vertex-format'; + + +/** + * @zh UI 静态合批组件。 + * 放置方式必须是放在在所有需要被静态合批的节点对象的根节点上,子节点放置对象必须是精灵和文本,其余对象不参与静态合批。 + * 用户必须通过手动方式启用收集静态合批数据,否则合批方式仍然采用动态合批(采集数据的流程相同)。此后渲染的内容是采用收集到的合批渲染数据,子节点的任何修改将不再有效。 + * 注意:子节点下不要放置 Mask,Graphics,以及 UI 模型或者粒子之类对象,否则会在启用完静态合批后跳过渲染。 + */ +@ccclass('cc.UIStaticBatchComponent') +@menu('UI/UIStaticBatchComponent') +@executionOrder(110) +export class UIStaticBatchComponent extends UIRenderComponent { + @property({ + visible: false, + override: true, + }) + get dstBlendFactor () { + return this._dstBlendFactor; + } + + set dstBlendFactor (value: GFXBlendFactor) { + if (this._dstBlendFactor === value) { + return; + } + + this._dstBlendFactor = value; + this._updateBlendFunc(); + } + + @property({ + visible: false, + override: true, + }) + get srcBlendFactor () { + return this._srcBlendFactor; + } + + set srcBlendFactor (value: GFXBlendFactor) { + if (this._srcBlendFactor === value) { + return; + } + + this._srcBlendFactor = value; + this._updateBlendFunc(); + } + + @property({ + visible: false, + override: true, + }) + get color (): Readonly { + return this._color; + } + + set color (value) { + if (this._color === value) { + return; + } + + this._color.set(value); + this._updateColor(); + this.markForUpdateRenderData(); + } + + @property({ + type: Material, + displayOrder: 3, + visible: false, + override: true, + }) + get sharedMaterial () { + return this._sharedMaterial; + } + + set sharedMaterial (value) { + if (this._sharedMaterial === value) { + return; + } + + this._sharedMaterial = value; + if (this._instanceMaterial) { + this._instanceMaterial(); + } + } + + /** + * @zh 开始采集数据。调用时存储 ia 数据。 + * 注意:尽量不要频繁调用此接口,因为会清空原先存储的 ia 数据重新采集,会有一定内存损耗。 + */ + @property({ + tooltip: CC_DEV ? '点击采集数据': '' + }) + get collect () { + return this._collect; + } + + set collect (value) { + const ui = this._getUI(); + if (this._collect === value || !ui){ + return; + } + + this.node._static = false; + this._collect = true; + this._init = false; + + if (!this._meshBuffer) { + const attr = vfmt; + const buffer = new MeshBuffer(ui); + buffer.initialize(attr, this._arrivalMaxBuffer); + this._meshBuffer = buffer; + } + + for (let i = 0; i < this._uiDrawBathcList.length; i++) { + const element = this._uiDrawBathcList[i]; + element.destroy(ui); + } + + this._uiDrawBathcList.length = 0; + } + + get drawBatchList (){ + return this._uiDrawBathcList; + } + + protected _init = false; + protected _meshBuffer: MeshBuffer | null = null; + protected _collect = false; + private _lastMeshBuffer: MeshBuffer | null = null; + private _uiDrawBathcList: UIDrawBatch[] = []; + + public onDestroy (){ + super.onDestroy(); + const ui = this._getUI(); + if (ui) { + for (let i = 0; i < this._uiDrawBathcList.length; i++) { + const element = this._uiDrawBathcList[i]; + element.destroy(ui); + } + } + + this._uiDrawBathcList.length = 0; + if(this._meshBuffer){ + this._meshBuffer.destroy(); + this._meshBuffer = null; + } + } + + + public updateAssembler (render: UI) { + if (this._collect) { + render.finishMergeBatches(); + this._lastMeshBuffer = render.currBufferBatch;; + render.currBufferBatch = this._meshBuffer; + render.currStaticRoot = this; + } + + if (this._init) { + render.finishMergeBatches(); + render.commitStaticBatch(this); + } + } + + public postUpdateAssembler (render: UI) { + if (this._collect) { + render.finishMergeBatches(); + render.currBufferBatch = this._lastMeshBuffer; + render.currStaticRoot = null; + this._collect = false; + this._init = true; + this.node._static = true; + + this._meshBuffer!.uploadData(); + } + } + + public requireDrawBatch (){ + const batch = new UIDrawBatch(); + batch.isStatic = true; + this._uiDrawBathcList.push(batch); + return batch; + } + + protected _getUI (){ + if(director.root && director.root.ui){ + return director.root.ui; + } + + cc.warn('The UI has not been initialized'); + return null; + } + + protected _arrivalMaxBuffer (){ + cc.warn('The current buffer beyond the limit, please reduce the amount'); + } +} diff --git a/cocos/ui/components/webview/webView-component.ts b/cocos/ui/components/webview/webView-component.ts index b89573503a..34fadee10e 100644 --- a/cocos/ui/components/webview/webView-component.ts +++ b/cocos/ui/components/webview/webView-component.ts @@ -77,7 +77,9 @@ export class WebviewComponent extends UIComponent { * @zh * 指定 WebView 加载的网址,它应该是一个 http 或者 https 开头的字符串。 */ - @property + @property({ + tooltip:'指定 WebView 加载的网址,它应该是一个 http 或者 https 开头的字符串', + }) get url () { return this._url; } @@ -100,6 +102,7 @@ export class WebviewComponent extends UIComponent { */ @property({ type: EventHandler, + tooltip:'WebView 的回调事件,当网页加载过程中,加载完成后或者加载出错时都会回调此函数', }) public webviewEvents: EventHandler[] = []; diff --git a/cocos/ui/components/widget-component.ts b/cocos/ui/components/widget-component.ts index 5ec9689a9c..c617e3862e 100644 --- a/cocos/ui/components/widget-component.ts +++ b/cocos/ui/components/widget-component.ts @@ -192,6 +192,7 @@ export class WidgetComponent extends Component { */ @property({ type: Node, + tooltip:'对齐目标', }) get target () { return this._target; @@ -219,7 +220,9 @@ export class WidgetComponent extends Component { * @zh * 是否对齐上边。 */ - @property + @property({ + tooltip:'是否对齐上边', + }) get isAlignTop () { return (this._alignFlags & AlignFlags.TOP) > 0; } @@ -232,7 +235,9 @@ export class WidgetComponent extends Component { * @zh * 是否对齐下边。 */ - @property + @property({ + tooltip:'是否对齐下边', + }) get isAlignBottom () { return (this._alignFlags & AlignFlags.BOT) > 0; } @@ -245,7 +250,9 @@ export class WidgetComponent extends Component { * @zh * 是否对齐左边。 */ - @property + @property({ + tooltip:'是否对齐左边', + }) get isAlignLeft () { return (this._alignFlags & AlignFlags.LEFT) > 0; } @@ -258,7 +265,9 @@ export class WidgetComponent extends Component { * @zh * 是否对齐右边。 */ - @property + @property({ + tooltip:'是否对齐右边', + }) get isAlignRight () { return (this._alignFlags & AlignFlags.RIGHT) > 0; } @@ -271,7 +280,9 @@ export class WidgetComponent extends Component { * @zh * 是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消。 */ - @property + @property({ + tooltip:'是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消', + }) get isAlignVerticalCenter () { return (this._alignFlags & AlignFlags.MID) > 0; } @@ -291,7 +302,9 @@ export class WidgetComponent extends Component { * @zh * 是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消。 */ - @property + @property({ + tooltip:'是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消', + }) get isAlignHorizontalCenter () { return (this._alignFlags & AlignFlags.CENTER) > 0; } @@ -334,7 +347,6 @@ export class WidgetComponent extends Component { * @zh * 本节点顶边和父节点顶边的距离,可填写负值,只有在 isAlignTop 开启时才有作用。 */ - @property get top () { return this._top; } @@ -343,11 +355,22 @@ export class WidgetComponent extends Component { this._recursiveDirty(); } + /** + * @EditorOnly Not for user + */ + @property + get editorTop () { + return this._isAbsTop ? this._top : (this._top * 100); + } + set editorTop (value) { + this._top = this._isAbsTop ? value : (value / 100); + this._recursiveDirty(); + } + /** * @zh * 本节点底边和父节点底边的距离,可填写负值,只有在 isAlignBottom 开启时才有作用。 */ - @property get bottom () { return this._bottom; } @@ -356,11 +379,22 @@ export class WidgetComponent extends Component { this._recursiveDirty(); } + /** + * @EditorOnly Not for user + */ + @property + get editorBottom () { + return this._isAbsBottom ? this._bottom : (this._bottom * 100); + } + set editorBottom (value) { + this._bottom = this._isAbsBottom ? value : (value / 100); + this._recursiveDirty(); + } + /** * @zh * 本节点左边和父节点左边的距离,可填写负值,只有在 isAlignLeft 开启时才有作用。 */ - @property get left () { return this._left; } @@ -369,11 +403,22 @@ export class WidgetComponent extends Component { this._recursiveDirty(); } + /** + * @EditorOnly Not for user + */ + @property + get editorLeft () { + return this._isAbsLeft ? this._left : (this._left * 100); + } + set editorLeft (value) { + this._left = this._isAbsLeft ? value : (value / 100); + this._recursiveDirty(); + } + /** * @zh * 本节点右边和父节点右边的距离,可填写负值,只有在 isAlignRight 开启时才有作用。 */ - @property get right () { return this._right; } @@ -382,11 +427,22 @@ export class WidgetComponent extends Component { this._recursiveDirty(); } + /** + * @EditorOnly Not for user + */ + @property + get editorRight () { + return this._isAbsRight ? this._right : (this._right * 100); + } + set editorRight (value) { + this._right = this._isAbsRight ? value : (value / 100); + this._recursiveDirty(); + } + /** * @zh * 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。 */ - @property get horizontalCenter () { return this._horizontalCenter; } @@ -395,11 +451,22 @@ export class WidgetComponent extends Component { this._recursiveDirty(); } + /** + * @EditorOnly Not for user + */ + @property + get editorHorizontalCenter () { + return this._isAbsHorizontalCenter ? this._horizontalCenter : (this._horizontalCenter * 100); + } + set editorHorizontalCenter (value) { + this._horizontalCenter = this._isAbsHorizontalCenter ? value : (value / 100); + this._recursiveDirty(); + } + /** * @zh * 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。 */ - @property get verticalCenter () { return this._verticalCenter; } @@ -408,9 +475,21 @@ export class WidgetComponent extends Component { this._recursiveDirty(); } + /** + * @EditorOnly Not for user + */ + @property + get editorVerticalCenter () { + return this._isAbsVerticalCenter ? this._verticalCenter : (this._verticalCenter * 100); + } + set editorVerticalCenter (value) { + this._verticalCenter = this._isAbsVerticalCenter ? value : (value / 100); + this._recursiveDirty(); + } + /** * @zh - * 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 + * 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的比例(0 到 1)作为边距。 */ @property get isAbsoluteTop () { @@ -427,7 +506,7 @@ export class WidgetComponent extends Component { /** * @zh - * 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 + * 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的比例(0 到 1)作为边距。 */ @property get isAbsoluteBottom () { @@ -444,7 +523,7 @@ export class WidgetComponent extends Component { /** * @zh - * 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 + * 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的比例(0 到 1)作为边距。 */ @property get isAbsoluteLeft () { @@ -461,7 +540,7 @@ export class WidgetComponent extends Component { /** * @zh - * 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 + * 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的比例(0 到 1)作为边距。 */ @property get isAbsoluteRight () { @@ -487,6 +566,7 @@ export class WidgetComponent extends Component { */ @property({ type: AlignMode, + tooltip:'指定 widget 的对齐方式,用于决定运行时 widget 应何时更新', }) get alignMode () { return this._alignMode; @@ -499,7 +579,7 @@ export class WidgetComponent extends Component { /** * @zh - * 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 + * 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为比例(0 到 1)。 */ @property get isAbsoluteHorizontalCenter () { @@ -517,7 +597,7 @@ export class WidgetComponent extends Component { /** * @zh - * 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 + * 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为比例(0 到 1)。 */ @property get isAbsoluteVerticalCenter () { @@ -676,27 +756,28 @@ export class WidgetComponent extends Component { const targetSize = getReadonlyNodeSize(target); const deltaInPercent = new Vec3(); if (targetSize.width !== 0 && targetSize.height !== 0) { - Vec3.set(deltaInPercent, delta.x / targetSize.width * 100, delta.y / targetSize.height * 100, deltaInPercent.z); + Vec3.set(deltaInPercent, delta.x / targetSize.width, delta.y / targetSize.height, deltaInPercent.z); } if (self.isAlignTop) { - self.top -= (self.isAbsoluteTop ? delta.y : deltaInPercent.y) * inverseScale.y; + self._top -= (self._isAbsTop ? delta.y : deltaInPercent.y) * inverseScale.y; } if (self.isAlignBottom) { - self.bottom += (self.isAbsoluteBottom ? delta.y : deltaInPercent.y) * inverseScale.y; + self._bottom += (self._isAbsBottom ? delta.y : deltaInPercent.y) * inverseScale.y; } if (self.isAlignLeft) { - self.left += (self.isAbsoluteLeft ? delta.x : deltaInPercent.x) * inverseScale.x; + self._left += (self._isAbsLeft ? delta.x : deltaInPercent.x) * inverseScale.x; } if (self.isAlignRight) { - self.right -= (self.isAbsoluteRight ? delta.x : deltaInPercent.x) * inverseScale.x; + self._right -= (self._isAbsRight ? delta.x : deltaInPercent.x) * inverseScale.x; } if (self.isAlignHorizontalCenter) { - self.horizontalCenter += (self.isAbsoluteHorizontalCenter ? delta.x : deltaInPercent.x) * inverseScale.x; + self._horizontalCenter += (self._isAbsHorizontalCenter ? delta.x : deltaInPercent.x) * inverseScale.x; } if (self.isAlignVerticalCenter) { - self.verticalCenter += (self.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y) * inverseScale.y; + self._verticalCenter += (self._isAbsVerticalCenter ? delta.y : deltaInPercent.y) * inverseScale.y; } + this._recursiveDirty(); } public _adjustWidgetToAllowResizingInEditor () { @@ -728,23 +809,24 @@ export class WidgetComponent extends Component { const targetSize = getReadonlyNodeSize(target); const deltaInPercent = new Vec3(); if (targetSize.width !== 0 && targetSize.height !== 0) { - Vec3.set(deltaInPercent, delta.x / targetSize.width * 100, delta.y / targetSize.height * 100, deltaInPercent.z); + Vec3.set(deltaInPercent, delta.x / targetSize.width , delta.y / targetSize.height, deltaInPercent.z); } const anchor = self.node.getAnchorPoint(); if (self.isAlignTop) { - self.top -= (self.isAbsoluteTop ? delta.y : deltaInPercent.y) * (1 - anchor.y) * inverseScale.y; + self._top -= (self._isAbsTop ? delta.y : deltaInPercent.y) * (1 - anchor.y) * inverseScale.y; } if (self.isAlignBottom) { - self.bottom -= (self.isAbsoluteBottom ? delta.y : deltaInPercent.y) * anchor.y * inverseScale.y; + self._bottom -= (self._isAbsBottom ? delta.y : deltaInPercent.y) * anchor.y * inverseScale.y; } if (self.isAlignLeft) { - self.left -= (self.isAbsoluteLeft ? delta.x : deltaInPercent.x) * anchor.x * inverseScale.x; + self._left -= (self._isAbsLeft ? delta.x : deltaInPercent.x) * anchor.x * inverseScale.x; } if (self.isAlignRight) { - self.right -= (self.isAbsoluteRight ? delta.x : deltaInPercent.x) * (1 - anchor.x) * inverseScale.x; + self._right -= (self._isAbsRight ? delta.x : deltaInPercent.x) * (1 - anchor.x) * inverseScale.x; } + this._recursiveDirty(); } public _adjustWidgetToAnchorChanged () { @@ -785,17 +867,17 @@ export class WidgetComponent extends Component { const size = this.node.parent!.getContentSize(); if (this.isAlignLeft && flag === AlignFlags.LEFT) { - this._left = isAbs ? this._left / 100 * size.width : this._left * 100 / size.width; + this._left = isAbs ? this._left * size.width : this._left / size.width; } else if (this.isAlignRight && flag === AlignFlags.RIGHT) { - this._right = isAbs ? this._right / 100 * size.width : this._right * 100 / size.width; + this._right = isAbs ? this._right * size.width : this._right / size.width; } else if (this.isAlignHorizontalCenter && flag === AlignFlags.CENTER) { - this._horizontalCenter = isAbs ? this._horizontalCenter / 100 * size.width : this._horizontalCenter * 100 / size.width; + this._horizontalCenter = isAbs ? this._horizontalCenter * size.width : this._horizontalCenter / size.width; } else if (this.isAlignTop && flag === AlignFlags.TOP) { - this._top = isAbs ? this._top / 100 * size.height : this._top * 100 / size.height; + this._top = isAbs ? this._top * size.height : this._top / size.height; } else if (this.isAlignBottom && flag === AlignFlags.BOT) { - this._bottom = isAbs ? this._bottom / 100 * size.height : this._bottom * 100 / size.height; + this._bottom = isAbs ? this._bottom * size.height : this._bottom / size.height; } else if (this.isAbsoluteVerticalCenter && flag === AlignFlags.MID) { - this._verticalCenter = isAbs ? this._verticalCenter / 100 * size.height : this._verticalCenter * 100 / size.height; + this._verticalCenter = isAbs ? this._verticalCenter / size.height : this._verticalCenter / size.height; } this._recursiveDirty(); diff --git a/cocos/ui/components/widget-manager.ts b/cocos/ui/components/widget-manager.ts index 5562c41445..2e491c10c7 100644 --- a/cocos/ui/components/widget-manager.ts +++ b/cocos/ui/components/widget-manager.ts @@ -90,8 +90,8 @@ function align (node: INode, widget: WidgetComponent) { } // adjust borders according to offsets - localLeft += widget.isAbsoluteLeft ? widget.left : widget.left / 100 * targetWidth; - localRight -= widget.isAbsoluteRight ? widget.right : widget.right / 100 * targetWidth; + localLeft += widget.isAbsoluteLeft ? widget.left : widget.left * targetWidth; + localRight -= widget.isAbsoluteRight ? widget.right : widget.right * targetWidth; if (hasTarget) { localLeft += inverseTranslate.x; @@ -117,7 +117,7 @@ function align (node: INode, widget: WidgetComponent) { width = node.width * scaleX; if (widget.isAlignHorizontalCenter) { let localHorizontalCenter = widget.isAbsoluteHorizontalCenter ? - widget.horizontalCenter : widget.horizontalCenter / 100 * targetWidth; + widget.horizontalCenter : widget.horizontalCenter * targetWidth; let targetCenter = (0.5 - targetAnchor.x) * targetSize.width; if (hasTarget) { localHorizontalCenter *= inverseScale.x; @@ -149,8 +149,8 @@ function align (node: INode, widget: WidgetComponent) { } // adjust borders according to offsets - localBottom += widget.isAbsoluteBottom ? widget.bottom : widget.bottom / 100 * targetHeight; - localTop -= widget.isAbsoluteTop ? widget.top : widget.top / 100 * targetHeight; + localBottom += widget.isAbsoluteBottom ? widget.bottom : widget.bottom * targetHeight; + localTop -= widget.isAbsoluteTop ? widget.top : widget.top * targetHeight; if (hasTarget) { // transform @@ -177,7 +177,7 @@ function align (node: INode, widget: WidgetComponent) { height = node.height * scaleY; if (widget.isAlignVerticalCenter) { let localVerticalCenter = widget.isAbsoluteVerticalCenter ? - widget.verticalCenter : widget.verticalCenter / 100 * targetHeight; + widget.verticalCenter : widget.verticalCenter * targetHeight; let targetMiddle = (0.5 - targetAnchor.y) * targetSize.height; if (hasTarget) { localVerticalCenter *= inverseScale.y; @@ -199,7 +199,8 @@ function align (node: INode, widget: WidgetComponent) { Vec3.set(widget._lastPos, x, y, _tempPos.z); } -function visitNode (node: Node) { +// TODO: type is hack, Change to the type actually used (Node or BaseNode) when BaseNode complete +function visitNode (node: any) { const widget = node.getComponent(WidgetComponent); if (widget) { // @ts-ignore @@ -211,7 +212,11 @@ function visitNode (node: Node) { if ((!CC_EDITOR || widgetManager.animationState!.animatedSinceLastFrame) && widget.alignMode !== AlignMode.ALWAYS) { widget.enabled = false; } else { - activeWidgets.push(widget); + if (cc.isValid(node, true)) { + activeWidgets.push(widget); + } else { + return; + } } } const children = node.children; diff --git a/predefine.ts b/predefine.ts index 0ccb2808bd..4444585685 100644 --- a/predefine.ts +++ b/predefine.ts @@ -213,7 +213,7 @@ if (CC_DEV) { * If you post a bug to forum, please attach this flag. * @property {String} ENGINE_VERSION */ -const engineVersion = '1.0.0'; +const engineVersion = '1.0.1'; _global['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; export default cc;