diff --git a/@types/globals.d.ts b/@types/globals.d.ts index 8fd63efef3..f20413f610 100644 --- a/@types/globals.d.ts +++ b/@types/globals.d.ts @@ -44,6 +44,8 @@ declare const cc : { [x: string]: any; }; +declare type CompareFunction = (a: T, b: T) => number; + declare type RecursivePartial = { [P in keyof T]?: T[P] extends Array ? Array> : diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index 88d02b2cfb..f3e58736d2 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -10,12 +10,9 @@ export interface IPropertyInfo { type: number; // auto-extracted if not specified value?: number[] | string; displayName?: string; - sampler?: IGFXSamplerInfo; + sampler?: number[]; } -export interface IPassInfo { - program: string; - // effect-writer part - switch?: string; +export interface IPassStates { priority?: number; primitive?: GFXPrimitiveMode; stage?: RenderPassStage; @@ -23,6 +20,10 @@ export interface IPassInfo { depthStencilState?: GFXDepthStencilState; blendState?: GFXBlendState; dynamics?: GFXDynamicState[]; +} +export interface IPassInfo extends IPassStates { + program: string; // auto-generated + switch?: string; properties?: Record; } export interface ITechniqueInfo { @@ -66,6 +67,7 @@ export interface IBuiltinInfo { } export interface IShaderInfo { name: string; + hash: number; glsl3: { vert: string, frag: string }; glsl1: { vert: string, frag: string }; builtins: { globals: IBuiltinInfo, locals: IBuiltinInfo }; diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index df04e08d80..718caf9e55 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -37,6 +37,7 @@ import { EffectAsset } from './effect-asset'; export interface IMaterialInfo { technique?: number; defines?: IDefineMap | IDefineMap[]; + states?: PassOverrides | PassOverrides[]; effectAsset?: EffectAsset | null; effectName?: string; } @@ -65,6 +66,8 @@ export class Material extends Asset { @property protected _defines: IDefineMap[] = []; @property + protected _states: PassOverrides[] = []; + @property protected _props: Array> = []; protected _passes: Pass[] = []; @@ -95,27 +98,20 @@ export class Material extends Asset { if (info.technique) { this._techIdx = info.technique; } if (info.effectAsset) { this._effectAsset = info.effectAsset; } else if (info.effectName) { this._effectAsset = EffectAsset.get(info.effectName); } - if (info.defines) { - const cur = this._defines; - let patch = info.defines; - if (!Array.isArray(patch) && this._effectAsset) { // fill all the passes if not specified - const len = Effect.getPassesInfo(this._effectAsset, this._techIdx).length; - patch = Array(len).fill(info.defines); - } - for (let i = 0; i < patch.length; i++) { - Object.assign(cur[i] || (cur[i] = {}), patch[i]); - } - } + if (info.defines) { this._prepareInfo(info.defines, this._defines); } + if (info.states) { this._prepareInfo(info.states, this._states); } this._update(); } public destroy () { + if (!this._effectAsset) { return; } if (this._passes) { for (const pass of this._passes) { pass.destroy(); } this._passes.length = 0; } + this._effectAsset = null; } /** @@ -177,7 +173,9 @@ export class Material extends Asset { Object.assign(this._props[i], mat._props[i]); } Object.assign(this._defines, mat._defines); - this._update(mat._effectAsset); + Object.assign(this._states, mat._states); + this._effectAsset = mat._effectAsset; + this._update(); } public overridePipelineStates (overrides: PassOverrides, passIdx?: number) { @@ -197,14 +195,24 @@ export class Material extends Asset { this._update(); } - protected _update (asset: EffectAsset | null = this._effectAsset, keepProps: boolean = true) { - // get effect asset - this._effectAsset = asset; - asset = asset || builtinResMgr.get('default-material').effectAsset!; + protected _prepareInfo (patch: object | object[], cur: object[]) { + if (!Array.isArray(patch)) { // fill all the passes if not specified + const len = this._effectAsset ? Effect.getPassesInfo(this._effectAsset, this._techIdx).length : 1; + patch = Array(len).fill(patch); + } + for (let i = 0; i < (patch as object[]).length; i++) { + Object.assign(cur[i] || (cur[i] = {}), patch[i]); + } + } + + protected _update (keepProps: boolean = true) { + const asset = this._effectAsset; + if (!asset) { this._passes = builtinResMgr.get('default-material')._passes.slice(); return; } // create passes this._passes = Effect.parseEffect(asset, { techIdx: this._techIdx, defines: this._defines, + states: this._states, }); // handle property values this._props.length = this._passes.length; diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 3da5baceeb..09baa3c29d 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,5 +1,30 @@ // absolute essential effects export default [ + { + "name": "builtin-base", + "techniques": [ + {"passes":[{"depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "program":"builtin-base|base-vs:vert|base-fs:frag", "priority":244}]} + ], + "shaders": [ + { + "name": "builtin-base|base-vs:vert|base-fs:frag", + "hash": 3414276249, + "glsl3": { + "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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;\nin vec4 a_color;\nout vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * pos;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + "frag": `\nprecision mediump float;\nin vec4 color;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= color;\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + }, + "glsl1": { + "vert": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * pos;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + "frag": `\nprecision mediump float;\nvarying vec4 color;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n` + }, + "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, + "defines": [], + "blocks": [], + "samplers": [], + "dependencies": {} + } + ] + }, { "name": "builtin-particle", "techniques": [ @@ -8,13 +33,14 @@ export default [ "shaders": [ { "name": "builtin-particle|particle-vs-legacy:lpvs_main|tinted-fs:add", + "hash": 1697722855, "glsl3": { "vert": `\nprecision mediump float;\nuniform Constants {\n vec4 mainTiling_Offset;\n vec4 frameTile_velLenScale;\n};\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nout vec2 uv;\nout vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\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 \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\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}\nin vec3 a_position; \nin vec3 a_texCoord; \nin vec2 a_texCoord1; \nin vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nin vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n`, - "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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};\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\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 PostProcess(col, cc_exposure.w, cc_exposure.z);\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 PostProcess(col, cc_exposure.w, cc_exposure.z);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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};\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * 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 PostProcess(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 PostProcess(col);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\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 \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\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}\nattribute vec3 a_position; \nattribute vec3 a_texCoord; \nattribute vec2 a_texCoord1; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , frameTile_velLenScale.z\n , frameTile_velLenScale.w\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\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 PostProcess(col, cc_exposure.w, cc_exposure.z);\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 PostProcess(col, cc_exposure.w, cc_exposure.z);\n}\nvoid main() { gl_FragColor = add(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * 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 PostProcess(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 PostProcess(col);\n}\nvoid main() { gl_FragColor = add(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal"], "samplers":[]}}, "defines": [ @@ -49,13 +75,14 @@ export default [ "shaders": [ { "name": "builtin-skybox|sky-vs:vert|sky-fs:frag", + "hash": 1728334606, "glsl3": { "vert": `\nprecision mediump float;\nin vec3 a_position;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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};\nout vec3 viewDir;\nvec4 vert () {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n viewDir = a_position;\n vec4 pos = clipPos;\n pos.z = clipPos.w * 0.99999;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nin vec3 viewDir;\nuniform samplerCube cubeMap;\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}\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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};\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(texture(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = texture(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nin vec3 viewDir;\nuniform samplerCube cubeMap;\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 \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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};\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(texture(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = texture(cubeMap, viewDir);\n#endif\n return PostProcess(o);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nattribute vec3 a_position;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvarying vec3 viewDir;\nvec4 vert () {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n viewDir = a_position;\n vec4 pos = clipPos;\n pos.z = clipPos.w * 0.99999;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nvarying vec3 viewDir;\nuniform samplerCube cubeMap;\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}\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = textureCube(cubeMap, viewDir);\n#endif\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nvarying vec3 viewDir;\nuniform samplerCube cubeMap;\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 \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\n return color;\n}\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = LinearToSRGB(c / (1.0 + c));\n vec4 o = vec4(c, 1.0);\n#else\n vec4 o = textureCube(cubeMap, viewDir);\n#endif\n return PostProcess(o);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, "defines": [ @@ -78,13 +105,14 @@ export default [ "shaders": [ { "name": "builtin-sprite|sprite-vs:vert|sprite-fs:frag", + "hash": 748330719, "glsl3": { "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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;\nin vec2 a_texCoord;\nin vec4 a_color;\nout vec2 uv0;\nout vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * pos;\n uv0 = a_texCoord;\n color = a_color;\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 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};\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nin vec2 uv0;\nin vec4 color;\nuniform sampler2D mainTexture;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture(mainTexture, uv0);\n o *= color;\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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};\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\n return color;\n}\nin vec2 uv0;\nin vec4 color;\nuniform sampler2D mainTexture;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture(mainTexture, uv0);\n o *= color;\n return PostProcess(o);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec2 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nvarying vec2 uv0;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture2D(mainTexture, uv0);\n o *= color;\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\n return color;\n}\nvarying vec2 uv0;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture2D(mainTexture, uv0);\n o *= color;\n return PostProcess(o);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":[], "samplers":[]}}, "defines": [ @@ -101,18 +129,19 @@ export default [ { "name": "builtin-standard", "techniques": [ - {"name":"opaque", "passes":[{"program":"builtin-standard|standard-vs:vert|standard-fs:frag", "properties":{"tilingOffset":{"type":16, "value":[1, 1, 0, 0]}, "albedo":{"type":17, "value":[1, 1, 1, 1]}, "albedoScale":{"type":16, "value":[1, 1, 1, 0]}, "pbrParams":{"type":16, "value":[1, 0.2, 0.6, 1]}, "pbrScale":{"type":16, "value":[1, 1, 1, 1]}, "emissive":{"type":17, "value":[1, 1, 1, 1]}, "emissiveScale":{"type":16, "value":[1, 1, 1, 1]}, "albedoMap":{"type":29, "value":"grey"}, "normalMap":{"type":29, "value":"normal"}, "pbrMap":{"type":29, "value":"grey"}, "emissiveMap":{"type":29, "value":"grey"}, "envMap":{"type":32, "value":"default-cube"}}}, {"depthStencilState":{"depthTest":true, "depthWrite":false}, "program":"builtin-standard|planar-shadow-vs:vert|planar-shadow-fs:frag", "switch":"USE_PLANAR_SHADOW"}]} + {"name":"opaque", "passes":[{"program":"builtin-standard|standard-vs:vert|standard-fs:frag", "properties":{"tilingOffset":{"type":16, "value":[1, 1, 0, 0]}, "albedo":{"type":17, "value":[1, 1, 1, 1]}, "albedoScale":{"type":16, "value":[1, 1, 1, 0]}, "pbrParams":{"type":16, "value":[0.2, 0.6, 1, 1]}, "pbrScale":{"type":16, "value":[1, 1, 1, 1]}, "emissive":{"type":17, "value":[1, 1, 1, 1]}, "emissiveScale":{"type":16, "value":[1, 1, 1, 1]}, "albedoMap":{"type":29, "value":"grey"}, "normalMap":{"type":29, "value":"normal"}, "pbrMap":{"type":29, "value":"grey"}, "emissiveMap":{"type":29, "value":"grey"}, "envMap":{"type":32, "value":"default-cube"}}}, {"depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "program":"builtin-standard|planar-shadow-vs:vert|planar-shadow-fs:frag", "switch":"USE_PLANAR_SHADOW"}]} ], "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", + "hash": 2134030718, "glsl3": { "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\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#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinning {\n mat4 cc_matJoint[128];\n vec4 cc_jointsTextureSize;\n};\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nin vec3 a_position;\nin vec3 a_normal;\nout vec3 v_worldPos;\nout vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n in vec2 a_texCoord;\n out vec2 v_uv;\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1.0);\n vec4 normal = vec4(a_normal, 0.0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n v_worldPos = (cc_matWorld * pos).xyz;\n v_worldNormal = (cc_matWorldIT * normal).xyz;\n #if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return cc_matViewProj * cc_matWorld * 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 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 MAX_LIGHTS 2\nuniform CCForwardLight {\n vec4 cc_sphereLitPos[2]; \n vec4 cc_sphereLitSizeRange[2]; \n vec4 cc_sphereLitColor[2]; \n vec4 cc_spotLitPosSize[2]; \n vec4 cc_spotLitDirRange[2]; \n vec4 cc_spotLitColor[2]; \n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt2(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\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_worldPos;\nin vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n in vec2 v_uv;\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_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n float metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = GetDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\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 finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = texture(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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 MAX_LIGHTS 2\nuniform CCForwardLight {\n vec4 cc_sphereLitPos[2]; \n vec4 cc_sphereLitSizeRange[2]; \n vec4 cc_sphereLitColor[2]; \n vec4 cc_spotLitPos[2]; \n vec4 cc_spotLitSizeRangeAngle[2]; \n vec4 cc_spotLitDir[2]; \n vec4 cc_spotLitColor[2]; \n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt2(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\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_worldPos;\nin vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n in vec2 v_uv;\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_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n float metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n \n vec3 SLU = cc_spotLitPos[i].xyz - v_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 finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\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 finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = texture(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\nuniform vec4 tilingOffset;\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform mat4 cc_matJoint[128];\nuniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nattribute vec3 a_position;\nattribute vec3 a_normal;\nvarying vec3 v_worldPos;\nvarying vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1.0);\n vec4 normal = vec4(a_normal, 0.0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n v_worldPos = (cc_matWorld * pos).xyz;\n v_worldNormal = (cc_matWorldIT * normal).xyz;\n #if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\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#define MAX_LIGHTS 2\nuniform vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform vec4 cc_spotLitPosSize[2];\nuniform vec4 cc_spotLitDirRange[2];\nuniform vec4 cc_spotLitColor[2];\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt2(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform vec4 tilingOffset;\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_worldPos;\nvarying vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n varying vec2 v_uv;\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_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture2D(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture2D(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n float metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 pDistSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , pDistSqr));\n float pInvSqrAttRadius = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n pInvSqrAttRadius *= pInvSqrAttRadius;\n float pAtt = GetDistAtt(pDistSqr, pInvSqrAttRadius);\n vec3 pSpec = specular * CalcSpecular(roughness, PNH, PH, N);\n finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * pAtt * (diffuseContrib + pSpec);\n vec3 SLU = cc_spotLitPosSize[i].xyz - v_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 cosConeAngle = max(dot(-cc_spotLitDirRange[i].xyz, SL), 0.01);\n float sInvSqrAttRadius = 1.0 / max(cc_spotLitDirRange[i].w, 0.01);\n float sDistSqr = dot(SLU, SLU);\n float sAtt = GetDistAtt(sDistSqr, sInvSqrAttRadius);\n sAtt *= cosConeAngle;\n vec3 sSpec = specular * CalcSpecular(roughness, SNH, SH, N);\n finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * sAtt * (diffuseContrib + sSpec);\n }\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 finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = textureCube(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\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#define MAX_LIGHTS 2\nuniform vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \n}\nfloat SmoothDistAtt2(float distSqr, float invSqrAttRadius)\n{\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{\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{\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{\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{\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{\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox(vec3 specular, float roughness, float NoV)\n{\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}\nuniform vec4 tilingOffset;\nuniform vec4 albedo;\nuniform vec4 albedoScale;\nuniform vec4 pbrParams;\nuniform vec4 pbrScale;\nuniform vec4 emissive;\nuniform vec4 emissiveScale;\nvarying vec3 v_worldPos;\nvarying vec3 v_worldNormal;\n#if USE_ALBEDO_MAP || USE_NORMAL_MAP || USE_PBR_MAP || USE_EMISSIVE_MAP\n varying vec2 v_uv;\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_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#ifdef USE_IBL\n uniform samplerCube envMap;\n#endif\n#if USE_NORMAL_MAP\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( v_uv.st );\n vec2 st1 = dFdy( v_uv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normalMap, v_uv).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nvec4 frag () {\n #if USE_ALBEDO_MAP\n vec4 baseColor = texture2D(albedoMap, v_uv);\n #else\n vec4 baseColor = albedo;\n #endif\n baseColor.rgb *= albedoScale.rgb;\n baseColor.rgb = SRGBToLinear(baseColor.rgb);\n #if USE_ALPHA_TEST\n if(baseColor.a < albedoScale.a)\n discard;\n #endif\n vec3 N = normalize(v_worldNormal);\n #if USE_NORMAL_MAP\n N = getNormal(v_worldPos, N);\n #endif\n #if USE_PBR_MAP\n vec4 pbr = texture2D(pbrMap, v_uv);\n #else\n vec4 pbr = pbrParams;\n #endif\n pbr *= pbrScale;\n float roughness = clamp(pbr.ROUGHNESS_CHANNEL, 0.04, 1.0);\n float metallic = clamp(pbr.METALLIC_CHANNEL, 0.0, 1.0);\n vec3 diffuse = baseColor.rgb * 0.96 * (1.0 - metallic);\n vec3 specular = mix(vec3(0.04), baseColor.rgb, metallic);\n vec3 V = normalize(cc_cameraPos.xyz - v_worldPos);\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, roughness, NV);\n vec3 specularContrib = specular * CalcSpecular(roughness, NH, H, N);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n for (int i = 0; i < 2; i++) {\n \n vec3 PLU = cc_sphereLitPos[i].xyz - v_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 finalColor += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n \n vec3 SLU = cc_spotLitPos[i].xyz - v_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 finalColor += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\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 finalColor += (ambDiff.rgb * diffuse);\n#if USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 env = textureCube(envMap, R);\n env.rgb = SRGBToLinear(env.rgb) * cc_ambientSky.w;\n finalColor += (env.rgb * specular);\n#endif\n#if CC_USE_HDR\n finalColor *= (1.0/1024.0);;\n#else\n finalColor *= cc_exposure.x;\n finalColor = LinearToSRGB(finalColor);\n#endif\n return vec4(finalColor, baseColor.a);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal", "CCSkinning", "CCForwardLight"], "samplers":["cc_jointsTexture"]}}, "defines": [ @@ -123,8 +152,8 @@ export default [ {"name":"USE_PBR_MAP", "type":"boolean", "defines":[]}, {"name":"USE_EMISSIVE_MAP", "type":"boolean", "defines":[]}, {"name":"USE_IBL", "type":"boolean", "defines":[]}, - {"name":"ROUGHNESS_CHANNEL", "type":"string", "options":["g", "b", "r", "a"]}, - {"name":"METALLIC_CHANNEL", "type":"string", "options":["b", "r", "g", "a"]}, + {"name":"ROUGHNESS_CHANNEL", "type":"string", "options":["r", "g", "b", "a"]}, + {"name":"METALLIC_CHANNEL", "type":"string", "options":["g", "r", "b", "a"]}, {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]}, {"name":"CC_USE_HDR", "type":"boolean", "defines":[]} ], @@ -150,16 +179,19 @@ export default [ }, { "name": "builtin-standard|planar-shadow-vs:vert|planar-shadow-fs:frag", + "hash": 3947426249, "glsl3": { - "vert": `\nprecision highp float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nuniform CCShadow {\n mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nin vec3 a_position;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n return cc_matViewProj * cc_matLightPlaneProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform CCShadow {\n mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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};\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nvec4 frag () {\n return PostProcess(cc_shadowColor, cc_exposure.w, cc_exposure.z);\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 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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nuniform CCShadow {\n mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinning {\n mat4 cc_matJoint[128];\n vec4 cc_jointsTextureSize;\n};\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nin vec3 a_position;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n return cc_matViewProj * cc_matLightPlaneProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + "frag": `\nprecision highp float;\nuniform CCShadow {\n mat4 cc_matLightPlaneProj;\n vec4 cc_shadowColor;\n};\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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};\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\n return color;\n}\nvec4 frag () {\n return PostProcess(cc_shadowColor);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { - "vert": `\nprecision highp float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\nuniform mat4 cc_matLightPlaneProj;\nuniform vec4 cc_shadowColor;\nattribute vec3 a_position;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n return cc_matViewProj * cc_matLightPlaneProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision highp float;\nuniform mat4 cc_matLightPlaneProj;\nuniform vec4 cc_shadowColor;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\nvec4 frag () {\n return PostProcess(cc_shadowColor, cc_exposure.w, cc_exposure.z);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "vert": `\nprecision highp float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\nuniform mat4 cc_matLightPlaneProj;\nuniform vec4 cc_shadowColor;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform mat4 cc_matJoint[128];\nuniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nattribute vec3 a_position;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n return cc_matViewProj * cc_matLightPlaneProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + "frag": `\nprecision highp float;\nuniform mat4 cc_matLightPlaneProj;\nuniform vec4 cc_shadowColor;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\n return color;\n}\nvec4 frag () {\n return PostProcess(cc_shadowColor);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, - "builtins": {"globals":{"blocks":["CCGlobal", "CCShadow"], "samplers":[]}, "locals":{"blocks":["CCLocal"], "samplers":[]}}, + "builtins": {"globals":{"blocks":["CCGlobal", "CCShadow"], "samplers":[]}, "locals":{"blocks":["CCLocal", "CCSkinning"], "samplers":["cc_jointsTexture"]}}, "defines": [ + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, {"name":"CC_USE_HDR", "type":"boolean", "defines":[]} ], "blocks": [], @@ -171,11 +203,12 @@ export default [ { "name": "builtin-tonemap", "techniques": [ - {"name":"tonemap", "passes":[{"depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-tonemap|tonemap-vs:vert|tonemap-fs:frag", "properties":{"u_texSampler":{"type":29}}}]} + {"name":"tonemap", "passes":[{"depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-tonemap|tonemap-vs:vert|tonemap-fs:frag", "properties":{"u_texSampler":{"sampler":[2, 2, null, 2, 2], "type":29}}}]} ], "shaders": [ { "name": "builtin-tonemap|tonemap-vs:vert|tonemap-fs:frag", + "hash": 181338825, "glsl3": { "vert": `\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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;\nvec4 vert () {\n vec4 pos = vec4(a_position, 0, 1);\n v_uv = a_texCoord * cc_screenScale.xy;\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 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 PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define FP_MAX = 65504.0;\n#define FP_SCALE (1.0/1024.0);\n#define FP_SCALE_INV 1024.0;\nfloat ComputeEV100(float aperture, float shutterTime, float iso, float ec) {\n return log2((aperture * aperture) / shutterTime * 100.0 / iso) - ec;\n}\nfloat ComputeExposure(float ev100) {\n return 0.833333 / pow(2.0, ev100);\n}\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n \n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n \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;\nuniform sampler2D u_texSampler;\nvec4 frag () {\n vec4 o = texture(u_texSampler, v_uv);\n#if CC_USE_HDR\n o.rgb *= cc_exposure.x * 1024.0;;\n o.rgb = ACESToneMap(o.rgb);\n o.rgb = LinearToSRGB(o.rgb);\n#endif\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` @@ -204,13 +237,14 @@ export default [ "shaders": [ { "name": "builtin-unlit|unlit-vs:vert|unlit-fs:frag", + "hash": 2274567937, "glsl3": { "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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 mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\nuniform CCSkinning {\n mat4 cc_matJoint[128];\n vec4 cc_jointsTextureSize;\n};\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nin vec3 a_position;\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 uv0;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * tilingOffset.xy + tilingOffset.zw;\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 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};\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform Constant {\n vec4 color;\n };\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \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};\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\n return color;\n}\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform Constant {\n vec4 color;\n };\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` }, "glsl1": { "vert": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform mat4 cc_matWorld;\nuniform mat4 cc_matWorldIT;\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform mat4 cc_matJoint[128];\nuniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nattribute vec3 a_position;\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 uv0;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, - "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color, float scale, float isHDR)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * scale, vec3(isHDR));\n#endif\n return color;\n}\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o, cc_exposure.w, cc_exposure.z);\n}\nvoid main() { gl_FragColor = frag(); }\n` + "frag": `\nprecision mediump float;\nuniform vec4 cc_time;\nuniform vec4 cc_screenSize;\nuniform vec4 cc_screenScale;\nuniform mat4 cc_matView;\nuniform mat4 cc_matViewInv;\nuniform mat4 cc_matProj;\nuniform mat4 cc_matProjInv;\nuniform mat4 cc_matViewProj;\nuniform mat4 cc_matViewProjInv;\nuniform vec4 cc_cameraPos;\nuniform vec4 cc_exposure;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_mainLitColor;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nvec4 PostProcess(vec4 color)\n{\n#if CC_USE_HDR\n color.rgb = mix(color.rgb, pow(color.rgb, vec3(2.2)) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\n return color;\n}\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return PostProcess(o);\n}\nvoid main() { gl_FragColor = frag(); }\n` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal", "CCSkinning"], "samplers":["cc_jointsTexture"]}}, "defines": [ diff --git a/cocos/3d/builtin/init.ts b/cocos/3d/builtin/init.ts index a7fd743047..59bc2d6131 100644 --- a/cocos/3d/builtin/init.ts +++ b/cocos/3d/builtin/init.ts @@ -4,7 +4,6 @@ import { ImageAsset } from '../../assets/image-asset'; import { Texture2D } from '../../assets/texture-2d'; import { Rect } from '../../core/value-types'; import { GFXDevice } from '../../gfx/device'; -import { EffectAsset } from '../assets/effect-asset'; import { TextureCube } from '../assets/texture-cube'; import effects from './effects'; @@ -122,10 +121,18 @@ class BuiltinResMgr { // builtin effects effects.forEach((e: any) => { - const effect = Object.assign(new EffectAsset(), e); + const effect = Object.assign(new cc.EffectAsset(), e); effect.onLoaded(); }); + // tonemap material + const smaaMtl = new cc.Material(); + smaaMtl._uuid = 'smaa-material'; + smaaMtl.initialize({ + effectName: 'builtin-smaa', + }); + resources[smaaMtl._uuid] = smaaMtl; + // tonemap material const tonemapMtl = new cc.Material(); tonemapMtl._uuid = 'tonemap-material'; @@ -146,8 +153,10 @@ class BuiltinResMgr { const defaultMtl = new cc.Material(); defaultMtl._uuid = 'default-material'; defaultMtl.initialize({ - effectName: 'builtin-standard', + effectName: 'builtin-unlit', + defines: { USE_COLOR: true }, }); + defaultMtl.setProperty('color', cc.color('#ff00ff')); resources[defaultMtl._uuid] = defaultMtl; // sprite material diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts index 198f3dbbef..206f84aaee 100644 --- a/cocos/3d/framework/physics/rigid-body-component.ts +++ b/cocos/3d/framework/physics/rigid-body-component.ts @@ -64,6 +64,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { this.angularDamping = this._angularDamping; this.material = this._material; this.useGravity = this._useGravity; + this.velocity = this._velocity; } // if (this.sharedBody) { // this.sharedBody.body.wakeUp(); diff --git a/cocos/3d/geom-utils/box.js b/cocos/3d/geom-utils/box.js deleted file mode 100644 index 4028c82061..0000000000 --- a/cocos/3d/geom-utils/box.js +++ /dev/null @@ -1,165 +0,0 @@ -import { vec3, mat3 } from '../../core/vmath'; - -let _v3_tmp = vec3.create(); -let _v3_tmp2 = vec3.create(); - -/** - * @access public - */ -class box { - constructor(px, py, pz, w, h, l, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) { - this.center = vec3.create(px, py, pz); - this.halfExtents = vec3.create(w, h, l); - this.orientation = mat3.create(ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3); - } - - /** - * create a new box - * - * @return {plane} - */ - static create() { - return new box(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1); - } - - /** - * create a new box - * - * @param {Number} px X coordinates for box's original point - * @param {Number} py Y coordinates for box's original point - * @param {Number} pz Z coordinates for box's original point - * @param {Number} w the half of box width - * @param {Number} h the half of box height - * @param {Number} l the half of box length - * @param {Number} ox_1 the orientation vector coordinates - * @param {Number} ox_2 the orientation vector coordinates - * @param {Number} ox_3 the orientation vector coordinates - * @param {Number} oy_1 the orientation vector coordinates - * @param {Number} oy_2 the orientation vector coordinates - * @param {Number} oy_3 the orientation vector coordinates - * @param {Number} oz_1 the orientation vector coordinates - * @param {Number} oz_2 the orientation vector coordinates - * @param {Number} oz_3 the orientation vector coordinates - * @return {box} - */ - static new(px, py, pz, w, h, l, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) { - return new box(px, py, pz, w, h, l, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3); - } - - /** - * create a new axis-aligned box from two corner points - * - * @param {vec3} minPos lower corner position of the box - * @param {vec3} maxPos upper corner position of the box - * @return {box} - */ - static fromPoints(minPos, maxPos) { - vec3.scale(_v3_tmp, vec3.add(_v3_tmp, minPos, maxPos), 0.5); - vec3.scale(_v3_tmp2, vec3.sub(_v3_tmp2, maxPos, minPos), 0.5); - return new box(_v3_tmp.x, _v3_tmp.y, _v3_tmp.z, - _v3_tmp2.x, _v3_tmp2.y, _v3_tmp2.z, - 1, 0, 0, 0, 1, 0, 0, 0, 1); - } - - /** - * clone a new box - * - * @param {box} a the source box - * @return {box} - */ - static clone(a) { - return new box(a.center.x, a.center.y, a.center.z, - a.halfExtents.x, a.halfExtents.y, a.halfExtents.z, - a.orientation.m00, a.orientation.m01, a.orientation.m02, - a.orientation.m03, a.orientation.m04, a.orientation.m05, - a.orientation.m06, a.orientation.m07, a.orientation.m08); - } - - /** - * copy the values from one box to another - * - * @param {box} out the receiving box - * @param {box} a the source box - * @return {box} - */ - static copy(out, a) { - out.center = a.center; - out.halfExtents = a.halfExtents; - out.orientation = a.orientation; - - return out; - } - - /** - * Set the components of a box to the given values - * - * @param {box} out the receiving box - * @param {Number} px X coordinates for box's original point - * @param {Number} py Y coordinates for box's original point - * @param {Number} pz Z coordinates for box's original point - * @param {Number} w the half of box width - * @param {Number} h the half of box height - * @param {Number} l the half of box length - * @param {Number} ox_1 the orientation vector coordinates - * @param {Number} ox_2 the orientation vector coordinates - * @param {Number} ox_3 the orientation vector coordinates - * @param {Number} oy_1 the orientation vector coordinates - * @param {Number} oy_2 the orientation vector coordinates - * @param {Number} oy_3 the orientation vector coordinates - * @param {Number} oz_1 the orientation vector coordinates - * @param {Number} oz_2 the orientation vector coordinates - * @param {Number} oz_3 the orientation vector coordinates - * @returns {box} out - * @function - */ - static set(out, px, py, pz, w, h, l, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) { - vec3.set(out.center, px, py, pz); - vec3.set(out.halfExtents, w, h, l); - mat3.set(out.orientation, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3); - return out; - } - - /** - * Get the bounding points of this shape - * @param {vec3} minPos - * @param {vec3} maxPos - */ - getBoundary(minPos, maxPos) { - vec3.sub(minPos, this.center, this.halfExtents); - vec3.add(maxPos, this.center, this.halfExtents); - } - - /** - * Translate this shape and apply the effect to a target shape - * @param {vec3} pos the translation factor - * @param {box?} out the target shape - */ - translate(pos, out) { - if (!out) out = this; - vec3.add(out.center, this.center, pos); - } - - /** - * Rotate this shape and apply the effect to a target shape - * @param {quat} rot the rotation factor - * @param {box?} out the target shape - */ - rotate(rot, out) { - if (!out) out = this; - // parent box doesn't contain rotations for now - mat3.fromQuat(out.orientation, rot); - } - - /** - * Scale this shape and apply the effect to a target shape - * @param {vec3} scale the scaling factor - * @param {box?} out the target shape - */ - scale(scale, out) { - if (!out) out = this; - vec3.mul(out.halfExtents, this.halfExtents, scale); - } -} - - -export default box; diff --git a/cocos/3d/geom-utils/box.ts b/cocos/3d/geom-utils/box.ts new file mode 100644 index 0000000000..6e8ee04033 --- /dev/null +++ b/cocos/3d/geom-utils/box.ts @@ -0,0 +1,149 @@ +import { mat3, quat, vec3 } from '../../core/vmath'; + +const _v3_tmp = vec3.create(); +const _v3_tmp2 = vec3.create(); + +export default class box { + + /** + * create a new box + */ + public static create () { + return new box(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1); + } + + /** + * create a new axis-aligned box from two corner points + * + * @param minPos lower corner position of the box + * @param maxPos upper corner position of the box + * @return + */ + public static fromPoints (minPos: vec3, maxPos: vec3) { + vec3.scale(_v3_tmp, vec3.add(_v3_tmp, minPos, maxPos), 0.5); + vec3.scale(_v3_tmp2, vec3.sub(_v3_tmp2, maxPos, minPos), 0.5); + return new box(_v3_tmp.x, _v3_tmp.y, _v3_tmp.z, + _v3_tmp2.x, _v3_tmp2.y, _v3_tmp2.z, + 1, 0, 0, 0, 1, 0, 0, 0, 1); + } + + /** + * clone a new box + * + * @param a the source box + * @return + */ + public static clone (a: box) { + return new box(a.center.x, a.center.y, a.center.z, + a.halfExtents.x, a.halfExtents.y, a.halfExtents.z, + a.orientation.m00, a.orientation.m01, a.orientation.m02, + a.orientation.m03, a.orientation.m04, a.orientation.m05, + a.orientation.m06, a.orientation.m07, a.orientation.m08); + } + + /** + * copy the values from one box to another + * + * @param out the receiving box + * @param a the source box + * @return + */ + public static copy (out: box, a: box) { + out.center = a.center; + out.halfExtents = a.halfExtents; + out.orientation = a.orientation; + + return out; + } + + /** + * Set the components of a box to the given values + * + * @param {box} out the receiving box + * @param px X coordinates for box's original point + * @param py Y coordinates for box's original point + * @param pz Z coordinates for box's original point + * @param w the half of box width + * @param h the half of box height + * @param l the half of box length + * @param ox_1 the orientation vector coordinates + * @param ox_2 the orientation vector coordinates + * @param ox_3 the orientation vector coordinates + * @param oy_1 the orientation vector coordinates + * @param oy_2 the orientation vector coordinates + * @param oy_3 the orientation vector coordinates + * @param oz_1 the orientation vector coordinates + * @param oz_2 the orientation vector coordinates + * @param oz_3 the orientation vector coordinates + * @returns out + * @function + */ + public static set ( + out: box, + px: number, py: number, pz: number, + w: number, h: number, l: number, + ox_1: number, ox_2: number, ox_3: number, + oy_1: number, oy_2: number, oy_3: number, + oz_1: number, oz_2: number, oz_3: number) { + vec3.set(out.center, px, py, pz); + vec3.set(out.halfExtents, w, h, l); + mat3.set(out.orientation, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3); + return out; + } + + public center: vec3; + public halfExtents: vec3; + public orientation: mat3; + + constructor ( + px: number, py: number, pz: number, + w: number, h: number, l: number, + ox_1: number, ox_2: number, ox_3: number, + oy_1: number, oy_2: number, oy_3: number, + oz_1: number, oz_2: number, oz_3: number) { + this.center = vec3.create(px, py, pz); + this.halfExtents = vec3.create(w, h, l); + this.orientation = mat3.create(ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3); + } + + /** + * Get the bounding points of this shape + * @param minPos + * @param maxPos + */ + public getBoundary (minPos: vec3, maxPos: vec3) { + vec3.sub(minPos, this.center, this.halfExtents); + vec3.add(maxPos, this.center, this.halfExtents); + } + + /** + * Translate this shape and apply the effect to a target shape + * @param pos the translation factor + * @param out the target shape + */ + public translate (pos: vec3, out?: box) { + if (!out) { out = this; } + vec3.add(out.center, this.center, pos); + } + + /** + * Rotate this shape and apply the effect to a target shape + * @param rot the rotation factor + * @param out the target shape + */ + public rotate (rot: quat, out?: box) { + if (!out) { out = this; } + // parent box doesn't contain rotations for now + mat3.fromQuat(out.orientation, rot); + } + + /** + * Scale this shape and apply the effect to a target shape + * @param scale the scaling factor + * @param out the target shape + */ + public scale (scale: vec3, out?: box) { + if (!out) { out = this; } + vec3.mul(out.halfExtents, this.halfExtents, scale); + } +} diff --git a/cocos/3d/geom-utils/line.js b/cocos/3d/geom-utils/line.js deleted file mode 100644 index 64bafa743e..0000000000 --- a/cocos/3d/geom-utils/line.js +++ /dev/null @@ -1,106 +0,0 @@ -import enums from './enums'; -import { vec3 } from '../../core/vmath'; - -export default class line { - constructor(sx = 0, sy = 0, sz = 0, ex = 0, ey = 0, ez = -1) { - this._type = enums.SHAPE_LINE; - this.s = vec3.create(sx, sy, sz); - this.e = vec3.create(ex, ey, ez); - } - - /** - * create a new line - * - * @param {number} sx start X component - * @param {number} sy start Y component - * @param {number} sz start Z component - * @param {number} ex end X component - * @param {number} ey end Y component - * @param {number} ez end Z component - * @return {line} - */ - static create(sx, sy, sz, ex, ey, ez) { - return new line(sx, sy, sz, ex, ey, ez); - } - - /** - * Creates a new line initialized with values from an existing line - * - * @param {line} a line to clone - * @return {line} a new line - */ - static clone(a) { - return new line( - a.s.x, a.s.y, a.s.z, - a.e.x, a.e.y, a.e.z - ); - } - - /** - * Copy the values from one line to another - * - * @param {line} out the receiving line - * @param {line} a the source line - * @return {line} out - */ - static copy(out, a) { - vec3.copy(out.s, a.s); - vec3.copy(out.e, a.e); - - return out; - } - - /** - * create a line from two points - * - * @param {line} out the receiving line - * @param {vec3} start line start - * @param {vec3} end target position - * @return {line} out - */ - static fromPoints(out, start, end) { - vec3.copy(out.s, start); - vec3.copy(out.e, end); - return out; - } - - /** - * Set the components of a vec3 to the given values - * - * @param {vec3} out the receiving vector - * @param {number} sx start X component - * @param {number} sy start Y component - * @param {number} sz start Z component - * @param {number} ex end X component - * @param {number} ey end Y component - * @param {number} ez end Z component - * @return {vec3} out - */ - static set(out, sx, sy, sz, ex, ey, ez) { - out.s.x = sx; - out.s.y = sy; - out.s.z = sz; - out.e.x = ex; - out.e.y = ey; - out.e.z = ez; - - return out; - } - - /** - * create line from 2 points - * - * @param {line} line - * @return {number} - */ - static magnitude(line) { - return vec3.distance(line.s, line.e); - } - - /** - *Alias of {@link line.magnitude}. - */ - static mag(line) { - return line.magnitude(line); - } -} diff --git a/cocos/3d/geom-utils/line.ts b/cocos/3d/geom-utils/line.ts new file mode 100644 index 0000000000..510b7bb390 --- /dev/null +++ b/cocos/3d/geom-utils/line.ts @@ -0,0 +1,112 @@ +import { vec3 } from '../../core/vmath'; +import enums from './enums'; + +export default class line { + + /** + * create a new line + * + * @param sx start X component + * @param sy start Y component + * @param sz start Z component + * @param ex end X component + * @param ey end Y component + * @param ez end Z component + * @return + */ + public static create (sx: number, sy: number, sz: number, ex: number, ey: number, ez: number) { + return new line(sx, sy, sz, ex, ey, ez); + } + + /** + * Creates a new line initialized with values from an existing line + * + * @param a line to clone + * @return a new line + */ + public static clone (a: line) { + return new line( + a.s.x, a.s.y, a.s.z, + a.e.x, a.e.y, a.e.z, + ); + } + + /** + * Copy the values from one line to another + * + * @param out the receiving line + * @param a the source line + * @return out + */ + public static copy (out: line, a: line) { + vec3.copy(out.s, a.s); + vec3.copy(out.e, a.e); + + return out; + } + + /** + * create a line from two points + * + * @param out the receiving line + * @param start line start + * @param end target position + * @return out + */ + public static fromPoints (out: line, start: vec3, end: vec3) { + vec3.copy(out.s, start); + vec3.copy(out.e, end); + return out; + } + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param sx start X component + * @param sy start Y component + * @param sz start Z component + * @param ex end X component + * @param ey end Y component + * @param ez end Z component + * @return out + */ + public static set (out: line, sx: number, sy: number, sz: number, ex: number, ey: number, ez: number) { + out.s.x = sx; + out.s.y = sy; + out.s.z = sz; + out.e.x = ex; + out.e.y = ey; + out.e.z = ez; + + return out; + } + + /** + * create line from 2 points + * + * @param a + * @return + */ + public static magnitude (a: line) { + return vec3.distance(a.s, a.e); + } + + /** + * Alias of {@link line.magnitude}. + */ + public static mag (a: line) { + return line.magnitude(a); + } + + public s: vec3; + public e: vec3; + + private _type: number; + + constructor (sx = 0, sy = 0, sz = 0, ex = 0, ey = 0, ez = -1) { + this._type = enums.SHAPE_LINE; + this.s = vec3.create(sx, sy, sz); + this.e = vec3.create(ex, ey, ez); + } +} diff --git a/cocos/3d/geom-utils/octree.js b/cocos/3d/geom-utils/octree.js deleted file mode 100644 index 597459837f..0000000000 --- a/cocos/3d/geom-utils/octree.js +++ /dev/null @@ -1,228 +0,0 @@ -import aabb from './aabb'; -import intersect from './intersect'; -import { vec3 } from '../../core/vmath'; -import { FixedArray } from '../memop'; - -let mul = function(out, v, x, y, z) { - return vec3.set(out, v.x * x, v.y * y, v.z * z); -}; - -class OctreeBlock { - constructor(minPos, maxPos, capacity, depth, maxDepth, getBoundingShape) { - this.minPos = minPos; - this.maxPos = maxPos; - this.boundingBox = aabb.fromPoints(aabb.create(), minPos, maxPos); - this.capacity = capacity; - this.depth = depth; - this.maxDepth = maxDepth; - this._getBoundingShape = getBoundingShape; - this.blocks = null; - this.entries = new FixedArray(this.capacity); - } - - addEntry(entry) { - if (this.blocks) { - for (let i = 0; i < this.blocks.length; i++) { - this.blocks[i].addEntry(entry); - } - } else { - let shape = this._getBoundingShape(entry); - if (!intersect.resolve(this.boundingBox, shape)) return; - this.entries.push(entry); - if (this.entries.length >= this.capacity && this.depth < this.maxDepth) { - this.blocks = Octree.createBlocks(this.minPos, this.maxPos, this.entries, - this.capacity, this.depth, this.maxDepth, this._getBoundingShape); - this.entries = null; - } - } - } - - removeEntry(entry) { - if (this.blocks) { - for (let i = 0; i < this.blocks.length; i++) { - this.blocks[i].removeEntry(entry); - } - } else { - this.entries.fastRemove(this.entries.indexOf(entry)); - } - } - - select(out, shape) { - if (!intersect.resolve(this.boundingBox, shape)) return; - if (this.blocks) { - for (let i = 0; i < this.blocks.length; i++) { - this.blocks[i].select(out, shape); - } - } else { - for (let i = 0; i < this.entries.length; i++) { - out.add(this.entries.data[i]); - } - } - } - - frustumSelect(out, frustum) { - if (!intersect.box_frustum(this.boundingBox, frustum)) return; - if (this.blocks) { - for (let i = 0; i < this.blocks.length; i++) { - this.blocks[i].frustumSelect(out, frustum); - } - } else { - for (let i = 0; i < this.entries.length; i++) { - out.add(this.entries.data[i]); - } - } - } -} - -/** - * An octree acceleration data structure - * @example - * let octree = new Octree(); - * octree.build(models, model => { - * return model._boundingShape; - * }); - * octree.select(enums.SHAPE_FRUSTUM, view._frustum); - */ -export default class Octree { - /** - * Create a octree structure - * @param {number} blockCapacity - maximum capacity for each block node - before it's been subdivided, might be exceeded if `maxDepth` is reached - * @param {number} maxDepth - maximum depth of this tree - */ - constructor(blockCapacity = 32, maxDepth = 5) { - this.blockCapacity = blockCapacity; - this.maxDepth = maxDepth; - this.blocks = []; - this.dynamics = []; - this._selection = new Set(); - this._getBoundingShape = () => { return this._getBoundingShape; }; - } - - /** - * Build this octree from given entries. - * Root Boundary is the bounding box of all the entries. - * @param {Array} entries - a collection of entries to be queried later - * @param {function(entry: Object): Object} getBoundingShape - * - a function takes an entry and returns its primitive info - */ - build(entries, getBoundingShape) { - // calc world min & max - let worldMin = vec3.create(Infinity, Infinity, Infinity); - let worldMax = vec3.create(-Infinity, -Infinity, -Infinity); - let minPos = vec3.create(); - let maxPos = vec3.create(); - let staticEntries = []; this.dynamics = []; - for (let i = 0; i < entries.length; i++) { - let entry = (entries.data || entries)[i]; - let shape = getBoundingShape(entry); - if (!shape) { - this.dynamics.push(entry); - } else { - shape.getBoundary(minPos, maxPos); - vec3.min(worldMin, worldMin, minPos); - vec3.max(worldMax, worldMax, maxPos); - staticEntries.push(entry); - } - } - this.blocks = Octree.createBlocks(worldMin, worldMax, staticEntries, - this.blockCapacity, 0, this.maxDepth, getBoundingShape); - this._getBoundingShape = getBoundingShape; - } - - /** - * Add an entry to this tree. Should be called after `build`. - * @param {Object} entry - the new entry - */ - addEntry(entry) { - if (!this._getBoundingShape(entry).shape) { - this.dynamics.push(entry); - return; - } - for (let i = 0; i < this.blocks.length; i++) { - this.blocks[i].addEntry(entry); - } - } - - /** - * Remove an entry from this tree. Should be called after `build`. - * @param {Object} entry - the entry to be removed - */ - removeEntry(entry) { - if (!this._getBoundingShape(entry).shape) { - this.dynamics.splice(this.dynamics.indexOf(entry), 1); - return; - } - for (let i = 0; i < this.blocks.length; i++) { - this.blocks[i].removeEntry(entry); - } - } - - /** - * Select all the entries overlapping the given primitive - * @param {Object} shape - the selecting primitive - * @return {Set} the resulting set of entries - */ - select(shape) { - this._selection.clear(); - for (let i = 0; i < this.blocks.length; i++) { - this.blocks[i].select(this._selection, shape); - } - for (let i = 0; i < this.dynamics.length; i++) { - this._selection.add(this.dynamics[i]); - } - return this._selection; - } - - /** - * Specialized selection for frustums - * @param {Object} frustum - the selecting frustum - * @return {Set} the resulting set of entries - */ - frustumSelect(frustum) { - this._selection.clear(); - for (let i = 0; i < this.blocks.length; i++) { - this.blocks[i].frustumSelect(this._selection, frustum); - } - for (let i = 0; i < this.dynamics.length; i++) { - this._selection.add(this.dynamics[i]); - } - return this._selection; - } - - /** - * Create sub blocks and populate them with given entries - * @param {vec3} worldMin - min position of the parent bounding box - * @param {vec3} worldMax - max position of the parent bounding box - * @param {Array} entries - the entries to be inserted - * @param {number} blockCapacity - maximum capacity for each block node - before it's been subdivided, might be exceeded if `maxDepth` is reached - * @param {number} curDepth - depth before subdivided - * @param {number} maxDepth - maximum depth of this tree - * @param {function(entry: Object): Object} getBoundingShape - - a function takes an entry and returns its primitive info - * @return {OctreeBlock[]} the sub blocks - */ - static createBlocks(worldMin, worldMax, entries, blockCapacity, curDepth, maxDepth, getBoundingShape) { - let blocks = []; - let blockSize = vec3.create(); - vec3.scale(blockSize, vec3.sub(blockSize, worldMax, worldMin), 0.5); - for (let x = 0; x < 2; x++) { - for (let y = 0; y < 2; y++) { - for (let z = 0; z < 2; z++) { - let localMin = vec3.create(), localMax = vec3.create(); - vec3.add(localMin, worldMin, mul(localMin, blockSize, x, y, z)); - vec3.add(localMax, worldMin, mul(localMax, blockSize, x + 1, y + 1, z + 1)); - let block = new OctreeBlock(localMin, localMax, - blockCapacity, curDepth + 1, maxDepth, getBoundingShape); - for (let i = 0; i < entries.length; i++) { - let entry = (entries.data || entries)[i]; - block.addEntry(entry); - } - blocks.push(block); - } - } - } - return blocks; - } -} \ No newline at end of file diff --git a/cocos/3d/geom-utils/octree.ts b/cocos/3d/geom-utils/octree.ts new file mode 100644 index 0000000000..acf00c2cbc --- /dev/null +++ b/cocos/3d/geom-utils/octree.ts @@ -0,0 +1,248 @@ +import { vec3 } from '../../core/vmath'; +import { FixedArray } from '../memop'; +import aabb from './aabb'; +import intersect from './intersect'; + +const mul = (out, v, x, y, z) => { + return vec3.set(out, v.x * x, v.y * y, v.z * z); +}; + +class OctreeBlock { + public minPos: vec3; + public maxPos: vec3; + public boundingBox: aabb; + public capacity: number; + public depth: number; + public maxDepth: number; + public blocks: null | OctreeBlock[]; + public entries: FixedArray; + + private _getBoundingShape: Function; + + constructor (minPos, maxPos, capacity, depth, maxDepth, getBoundingShape) { + this.minPos = minPos; + this.maxPos = maxPos; + this.boundingBox = aabb.fromPoints(aabb.create(), minPos, maxPos); + this.capacity = capacity; + this.depth = depth; + this.maxDepth = maxDepth; + this._getBoundingShape = getBoundingShape; + this.blocks = null; + this.entries = new FixedArray(this.capacity); + } + + public addEntry (entry) { + if (this.blocks) { + for (const block of this.blocks) { + block.addEntry(entry); + } + } else { + const shape = this._getBoundingShape(entry); + if (!intersect.resolve(this.boundingBox, shape)) { return; } + this.entries.push(entry); + if (this.entries.length >= this.capacity && this.depth < this.maxDepth) { + this.blocks = Octree.createBlocks(this.minPos, this.maxPos, this.entries, + this.capacity, this.depth, this.maxDepth, this._getBoundingShape); + this.entries = null; + } + } + } + + public removeEntry (entry) { + if (this.blocks) { + for (const block of this.blocks) { + block.removeEntry(entry); + } + } else { + this.entries.fastRemove(this.entries.indexOf(entry)); + } + } + + public select (out, shape) { + if (!intersect.resolve(this.boundingBox, shape)) { return; } + if (this.blocks) { + for (const block of this.blocks) { + block.select(out, shape); + } + } else { + for (let i = 0; i < this.entries.length; i++) { + out.add(this.entries.data[i]); + } + } + } + + public frustumSelect (out, frustum) { + if (!intersect.box_frustum(this.boundingBox, frustum)) { return; } + if (this.blocks) { + for (const block of this.blocks) { + block.frustumSelect(out, frustum); + } + } else { + for (let i = 0; i < this.entries.length; i++) { + out.add(this.entries.data[i]); + } + } + } +} + +/** + * An octree acceleration data structure + * @example + * let octree = new Octree(); + * octree.build(models, model => { + * return model._boundingShape; + * }); + * octree.select(enums.SHAPE_FRUSTUM, view._frustum); + */ +export default class Octree { + + /** + * Create sub blocks and populate them with given entries + * @param {vec3} worldMin - min position of the parent bounding box + * @param {vec3} worldMax - max position of the parent bounding box + * @param {Array} entries - the entries to be inserted + * @param {number} blockCapacity - maximum capacity for each block node + * before it's been subdivided, might be exceeded if `maxDepth` is reached + * @param {number} curDepth - depth before subdivided + * @param {number} maxDepth - maximum depth of this tree + * @param {function(entry: Object): Object} getBoundingShape - a function takes an entry and returns its primitive info + * @return {OctreeBlock[]} the sub blocks + */ + public static createBlocks (worldMin, worldMax, entries, blockCapacity, curDepth, maxDepth, getBoundingShape) { + const blocks: OctreeBlock[] = []; + const blockSize = vec3.create(); + vec3.scale(blockSize, vec3.sub(blockSize, worldMax, worldMin), 0.5); + for (let x = 0; x < 2; x++) { + for (let y = 0; y < 2; y++) { + for (let z = 0; z < 2; z++) { + const localMin = vec3.create(); + const localMax = vec3.create(); + vec3.add(localMin, worldMin, mul(localMin, blockSize, x, y, z)); + vec3.add(localMax, worldMin, mul(localMax, blockSize, x + 1, y + 1, z + 1)); + const block = new OctreeBlock(localMin, localMax, + blockCapacity, curDepth + 1, maxDepth, getBoundingShape); + for (let i = 0; i < entries.length; i++) { + const entry = (entries.data || entries)[i]; + block.addEntry(entry); + } + blocks.push(block); + } + } + } + return blocks; + } + + public blockCapacity: number; + public maxDepth: number; + public blocks: OctreeBlock[]; + public dynamics: any[]; + + private _selection: Set; + private _getBoundingShape: Function; + + /** + * Create a octree structure + * @param {number} blockCapacity - maximum capacity for each block node + * before it's been subdivided, might be exceeded if `maxDepth` is reached + * @param {number} maxDepth - maximum depth of this tree + */ + constructor (blockCapacity = 32, maxDepth = 5) { + this.blockCapacity = blockCapacity; + this.maxDepth = maxDepth; + this.blocks = []; + this.dynamics = []; + this._selection = new Set(); + this._getBoundingShape = () => this._getBoundingShape; + } + + /** + * Build this octree from given entries. + * Root Boundary is the bounding box of all the entries. + * @param {Array} entries - a collection of entries to be queried later + * @param {function(entry: Object): Object} getBoundingShape + * - a function takes an entry and returns its primitive info + */ + public build (entries, getBoundingShape) { + // calc world min & max + const worldMin = vec3.create(Infinity, Infinity, Infinity); + const worldMax = vec3.create(-Infinity, -Infinity, -Infinity); + const minPos = vec3.create(); + const maxPos = vec3.create(); + const staticEntries: any[] = []; this.dynamics = []; + for (let i = 0; i < entries.length; i++) { + const entry = (entries.data || entries)[i]; + const shape = getBoundingShape(entry); + if (!shape) { + this.dynamics.push(entry); + } else { + shape.getBoundary(minPos, maxPos); + vec3.min(worldMin, worldMin, minPos); + vec3.max(worldMax, worldMax, maxPos); + staticEntries.push(entry); + } + } + this.blocks = Octree.createBlocks(worldMin, worldMax, staticEntries, + this.blockCapacity, 0, this.maxDepth, getBoundingShape); + this._getBoundingShape = getBoundingShape; + } + + /** + * Add an entry to this tree. Should be called after `build`. + * @param {Object} entry - the new entry + */ + public addEntry (entry) { + if (!this._getBoundingShape(entry).shape) { + this.dynamics.push(entry); + return; + } + for (const block of this.blocks) { + block.addEntry(entry); + } + } + + /** + * Remove an entry from this tree. Should be called after `build`. + * @param {Object} entry - the entry to be removed + */ + public removeEntry (entry) { + if (!this._getBoundingShape(entry).shape) { + this.dynamics.splice(this.dynamics.indexOf(entry), 1); + return; + } + for (const block of this.blocks) { + block.removeEntry(entry); + } + } + + /** + * Select all the entries overlapping the given primitive + * @param {Object} shape - the selecting primitive + * @return {Set} the resulting set of entries + */ + public select (shape) { + this._selection.clear(); + for (const block of this.blocks) { + block.select(this._selection, shape); + } + for (const dynamic of this.dynamics) { + this._selection.add(dynamic); + } + return this._selection; + } + + /** + * Specialized selection for frustums + * @param {Object} frustum - the selecting frustum + * @return {Set} the resulting set of entries + */ + public frustumSelect (frustum) { + this._selection.clear(); + for (const block of this.blocks) { + block.frustumSelect(this._selection, frustum); + } + for (const dynamic of this.dynamics) { + this._selection.add(dynamic); + } + return this._selection; + } +} diff --git a/cocos/3d/geom-utils/ray.js b/cocos/3d/geom-utils/ray.js deleted file mode 100644 index 8e65a37dca..0000000000 --- a/cocos/3d/geom-utils/ray.js +++ /dev/null @@ -1,89 +0,0 @@ -import enums from './enums'; -import { vec3 } from '../../core/vmath'; - -export default class ray { - constructor(ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = -1) { - this._type = enums.SHAPE_RAY; - this.o = vec3.create(ox, oy, oz); - this.d = vec3.create(dx, dy, dz); - } - - /** - * create a new ray - * - * @param {number} ox origin X component - * @param {number} oy origin Y component - * @param {number} oz origin Z component - * @param {number} dx dir X component - * @param {number} dy dir Y component - * @param {number} dz dir Z component - * @return {ray} - */ - static create(ox, oy, oz, dx, dy, dz) { - return new ray(ox, oy, oz, dx, dy, dz); - } - - /** - * Creates a new ray initialized with values from an existing ray - * - * @param {ray} a ray to clone - * @return {ray} a new ray - */ - static clone(a) { - return new ray( - a.o.x, a.o.y, a.o.z, - a.d.x, a.d.y, a.d.z - ); - } - - /** - * Copy the values from one ray to another - * - * @param {ray} out the receiving ray - * @param {ray} a the source ray - * @return {ray} out - */ - static copy(out, a) { - vec3.copy(out.o, a.o); - vec3.copy(out.d, a.d); - - return out; - } - - /** - * create a ray from two points - * - * @param {ray} out the receiving ray - * @param {vec3} origin ray origin - * @param {vec3} target target position - * @return {ray} out - */ - static fromPoints(out, origin, target) { - vec3.copy(out.o, origin); - vec3.normalize(out.d, vec3.sub(out.d, target, origin)); - return out; - } - - /** - * Set the components of a ray to the given values - * - * @param {ray} out the receiving ray - * @param {number} ox origin X component - * @param {number} oy origin Y component - * @param {number} oz origin Z component - * @param {number} dx dir X component - * @param {number} dy dir Y component - * @param {number} dz dir Z component - * @return {ray} out - */ - static set(out, ox, oy, oz, dx, dy, dz) { - out.o.x = ox; - out.o.y = oy; - out.o.z = oz; - out.d.x = dx; - out.d.y = dy; - out.d.z = dz; - - return out; - } -} diff --git a/cocos/3d/geom-utils/ray.ts b/cocos/3d/geom-utils/ray.ts new file mode 100644 index 0000000000..421bc40790 --- /dev/null +++ b/cocos/3d/geom-utils/ray.ts @@ -0,0 +1,94 @@ +import { vec3 } from '../../core/vmath'; +import enums from './enums'; + +export default class ray { + + /** + * create a new ray + * + * @param {number} ox origin X component + * @param {number} oy origin Y component + * @param {number} oz origin Z component + * @param {number} dx dir X component + * @param {number} dy dir Y component + * @param {number} dz dir Z component + * @return {ray} + */ + public static create (ox, oy, oz, dx, dy, dz) { + return new ray(ox, oy, oz, dx, dy, dz); + } + + /** + * Creates a new ray initialized with values from an existing ray + * + * @param {ray} a ray to clone + * @return {ray} a new ray + */ + public static clone (a) { + return new ray( + a.o.x, a.o.y, a.o.z, + a.d.x, a.d.y, a.d.z, + ); + } + + /** + * Copy the values from one ray to another + * + * @param {ray} out the receiving ray + * @param {ray} a the source ray + * @return {ray} out + */ + public static copy (out, a) { + vec3.copy(out.o, a.o); + vec3.copy(out.d, a.d); + + return out; + } + + /** + * create a ray from two points + * + * @param {ray} out the receiving ray + * @param {vec3} origin ray origin + * @param {vec3} target target position + * @return {ray} out + */ + public static fromPoints (out, origin, target) { + vec3.copy(out.o, origin); + vec3.normalize(out.d, vec3.sub(out.d, target, origin)); + return out; + } + + /** + * Set the components of a ray to the given values + * + * @param {ray} out the receiving ray + * @param {number} ox origin X component + * @param {number} oy origin Y component + * @param {number} oz origin Z component + * @param {number} dx dir X component + * @param {number} dy dir Y component + * @param {number} dz dir Z component + * @return {ray} out + */ + public static set (out, ox, oy, oz, dx, dy, dz) { + out.o.x = ox; + out.o.y = oy; + out.o.z = oz; + out.d.x = dx; + out.d.y = dy; + out.d.z = dz; + + return out; + } + public o: vec3; + public d: vec3; + + private _type: number; + + constructor (ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = -1) { + this._type = enums.SHAPE_RAY; + this.o = vec3.create(ox, oy, oz); + this.d = vec3.create(dx, dy, dz); + } +} diff --git a/cocos/3d/geom-utils/sphere.js b/cocos/3d/geom-utils/sphere.js deleted file mode 100644 index 5ebde87a50..0000000000 --- a/cocos/3d/geom-utils/sphere.js +++ /dev/null @@ -1,104 +0,0 @@ -import enums from './enums'; -import { vec3 } from '../../core/vmath'; - -let _v3_tmp = vec3.create(); -function maxComponent(v) { return Math.max(Math.max(v.x, v.y), v.z); } - -export default class sphere { - constructor(cx = 0, cy = 0, cz = 0, r = 1) { - this._type = enums.SHAPE_SPHERE; - this.c = vec3.create(cx, cy, cz); - this.r = r; - } - - /** - * create a new sphere - * - * @return {plane} - */ - static create(cx, cy, cz, r) { - return new sphere(cx, cy, cz, r); - } - - /** - * clone a new sphere - * - * @param {sphere} p the source sphere - * @return {sphere} - */ - static clone (p) { - return new sphere(p.c.x, p.c.y, p.c.z, p.r); - } - - /** - * copy the values from one sphere to another - * - * @param {sphere} out the receiving sphere - * @param {sphere} p the source sphere - * @return {sphere} - */ - static copy (out, p) { - vec3.copy(out, p.c); - out.r = p.r; - - return out; - } - - /** - * create a new bounding sphere from two corner points - * - * @param {sphere} out the receiving sphere - * @param {vec3} minPos lower corner of the original shape - * @param {vec3} maxPos upper corner of the original shape - * @return {sphere} - */ - static fromPoints(out, minPos, maxPos) { - vec3.scale(out.c, vec3.add(_v3_tmp, minPos, maxPos), 0.5); - out.r = vec3.mag(vec3.sub(_v3_tmp, maxPos, minPos)) * 0.5; - return out; - } - - /** - * Set the components of a sphere to the given values - * - * @param {sphere} out the receiving sphere - * @param {number} cx X component of c - * @param {number} cy Y component of c - * @param {number} cz Z component of c - * @param {number} r - * @return {sphere} out - * @function - */ - static set (out, cx, cy, cz, r) { - out.c.x = cx; - out.c.y = cy; - out.c.z = cz; - out.r = r; - - return out; - } - - /** - * Get the bounding points of this shape - * @param {vec3} minPos - * @param {vec3} maxPos - */ - getBoundary(minPos, maxPos) { - vec3.set(minPos, this.c.x - this.r, this.c.y - this.r, this.c.z - this.r); - vec3.set(maxPos, this.c.x + this.r, this.c.y + this.r, this.c.z + this.r); - } - - /** - * Transform this shape - * @param {mat4} m the transform matrix - * @param {vec3} pos the position part of the transform - * @param {quat} rot the rotation part of the transform - * @param {vec3} scale the scale part of the transform - * @param {sphere} [out] the target shape - */ - transform(m, pos, rot, scale, out) { - if (!out) out = this; - vec3.transformMat4(out.c, this.c, m); - out.r = this.r * maxComponent(scale); - } -} diff --git a/cocos/3d/geom-utils/sphere.ts b/cocos/3d/geom-utils/sphere.ts new file mode 100644 index 0000000000..929ae8a3be --- /dev/null +++ b/cocos/3d/geom-utils/sphere.ts @@ -0,0 +1,110 @@ +import { vec3 } from '../../core/vmath'; +import enums from './enums'; + +const _v3_tmp = vec3.create(); +function maxComponent (v) { return Math.max(Math.max(v.x, v.y), v.z); } + +export default class sphere { + + /** + * create a new sphere + * + * @return {plane} + */ + public static create (cx, cy, cz, r) { + return new sphere(cx, cy, cz, r); + } + + /** + * clone a new sphere + * + * @param {sphere} p the source sphere + * @return {sphere} + */ + public static clone (p) { + return new sphere(p.c.x, p.c.y, p.c.z, p.r); + } + + /** + * copy the values from one sphere to another + * + * @param {sphere} out the receiving sphere + * @param {sphere} p the source sphere + * @return {sphere} + */ + public static copy (out, p) { + vec3.copy(out, p.c); + out.r = p.r; + + return out; + } + + /** + * create a new bounding sphere from two corner points + * + * @param {sphere} out the receiving sphere + * @param {vec3} minPos lower corner of the original shape + * @param {vec3} maxPos upper corner of the original shape + * @return {sphere} + */ + public static fromPoints (out, minPos, maxPos) { + vec3.scale(out.c, vec3.add(_v3_tmp, minPos, maxPos), 0.5); + out.r = vec3.mag(vec3.sub(_v3_tmp, maxPos, minPos)) * 0.5; + return out; + } + + /** + * Set the components of a sphere to the given values + * + * @param {sphere} out the receiving sphere + * @param {number} cx X component of c + * @param {number} cy Y component of c + * @param {number} cz Z component of c + * @param {number} r + * @return {sphere} out + * @function + */ + public static set (out, cx, cy, cz, r) { + out.c.x = cx; + out.c.y = cy; + out.c.z = cz; + out.r = r; + + return out; + } + + public c: vec3; + public r: number; + + private _type: number; + + constructor (cx = 0, cy = 0, cz = 0, r = 1) { + this._type = enums.SHAPE_SPHERE; + this.c = vec3.create(cx, cy, cz); + this.r = r; + } + + /** + * Get the bounding points of this shape + * @param {vec3} minPos + * @param {vec3} maxPos + */ + public getBoundary (minPos, maxPos) { + vec3.set(minPos, this.c.x - this.r, this.c.y - this.r, this.c.z - this.r); + vec3.set(maxPos, this.c.x + this.r, this.c.y + this.r, this.c.z + this.r); + } + + /** + * Transform this shape + * @param {mat4} m the transform matrix + * @param {vec3} pos the position part of the transform + * @param {quat} rot the rotation part of the transform + * @param {vec3} scale the scale part of the transform + * @param {sphere} [out] the target shape + */ + public transform (m, pos, rot, scale, out) { + if (!out) { out = this; } + vec3.transformMat4(out.c, this.c, m); + out.r = this.r * maxComponent(scale); + } +} diff --git a/cocos/3d/geom-utils/triangle.js b/cocos/3d/geom-utils/triangle.js deleted file mode 100644 index 0a22a1a738..0000000000 --- a/cocos/3d/geom-utils/triangle.js +++ /dev/null @@ -1,106 +0,0 @@ -import enums from './enums'; -import { vec3 } from '../../core/vmath'; - -export default class triangle { - constructor(ax = 0, ay = 0, az = 0, bx = 1, by = 0, bz = 0, cx = 0, cy = 1, cz = 0) { - this._type = enums.SHAPE_TRIANGLE; - this.a = vec3.create(ax, ay, az); - this.b = vec3.create(bx, by, bz); - this.c = vec3.create(cx, cy, cz); - } - - /** - * create a new triangle - * - * @param {number} ax - * @param {number} ay - * @param {number} az - * @param {number} bx - * @param {number} by - * @param {number} bz - * @param {number} cx - * @param {number} cy - * @param {number} cz - * @return {triangle} - */ - static create(ax, ay, az, bx, by, bz, cx, cy, cz) { - return new triangle(ax, ay, az, bx, by, bz, cx, cy, cz); - } - - /** - * clone a new triangle - * - * @param {triangle} t the source plane - * @return {triangle} - */ - static clone (t) { - return new triangle( - t.a.x, t.a.y, t.a.z, - t.b.x, t.b.y, t.b.z, - t.c.x, t.c.y, t.c.z - ); - } - - /** - * copy the values from one triangle to another - * - * @param {triangle} out the receiving triangle - * @param {triangle} t the source triangle - * @return {triangle} - */ - static copy (out, t) { - vec3.copy(out.a, t.a); - vec3.copy(out.b, t.b); - vec3.copy(out.c, t.c); - - return out; - } - - /** - * Create a triangle from three points - * - * @param {triangle} out the receiving triangle - * @param {vec3} a - * @param {vec3} b - * @param {vec3} c - * @return {triangle} - */ - static fromPoints(out, a, b, c) { - vec3.copy(out.a, a); - vec3.copy(out.b, b); - vec3.copy(out.c, c); - return out; - } - - /** - * Set the components of a triangle to the given values - * - * @param {triangle} out the receiving plane - * @param {number} ax X component of a - * @param {number} ay Y component of a - * @param {number} az Z component of a - * @param {number} bx X component of b - * @param {number} by Y component of b - * @param {number} bz Z component of b - * @param {number} cx X component of c - * @param {number} cy Y component of c - * @param {number} cz Z component of c - * @return {plane} - * @function - */ - static set (out, ax, ay, az, bx, by, bz, cx, cy, cz) { - out.a.x = ax; - out.a.y = ay; - out.a.z = az; - - out.b.x = bx; - out.b.y = by; - out.b.z = bz; - - out.c.x = cx; - out.c.y = cy; - out.c.z = cz; - - return out; - } -} diff --git a/cocos/3d/geom-utils/triangle.ts b/cocos/3d/geom-utils/triangle.ts new file mode 100644 index 0000000000..f221ac30f6 --- /dev/null +++ b/cocos/3d/geom-utils/triangle.ts @@ -0,0 +1,113 @@ +import { vec3 } from '../../core/vmath'; +import enums from './enums'; + +export default class triangle { + + /** + * create a new triangle + * + * @param {number} ax + * @param {number} ay + * @param {number} az + * @param {number} bx + * @param {number} by + * @param {number} bz + * @param {number} cx + * @param {number} cy + * @param {number} cz + * @return {triangle} + */ + public static create (ax, ay, az, bx, by, bz, cx, cy, cz) { + return new triangle(ax, ay, az, bx, by, bz, cx, cy, cz); + } + + /** + * clone a new triangle + * + * @param {triangle} t the source plane + * @return {triangle} + */ + public static clone (t) { + return new triangle( + t.a.x, t.a.y, t.a.z, + t.b.x, t.b.y, t.b.z, + t.c.x, t.c.y, t.c.z, + ); + } + + /** + * copy the values from one triangle to another + * + * @param {triangle} out the receiving triangle + * @param {triangle} t the source triangle + * @return {triangle} + */ + public static copy (out, t) { + vec3.copy(out.a, t.a); + vec3.copy(out.b, t.b); + vec3.copy(out.c, t.c); + + return out; + } + + /** + * Create a triangle from three points + * + * @param {triangle} out the receiving triangle + * @param {vec3} a + * @param {vec3} b + * @param {vec3} c + * @return {triangle} + */ + public static fromPoints (out, a, b, c) { + vec3.copy(out.a, a); + vec3.copy(out.b, b); + vec3.copy(out.c, c); + return out; + } + + /** + * Set the components of a triangle to the given values + * + * @param {triangle} out the receiving plane + * @param {number} ax X component of a + * @param {number} ay Y component of a + * @param {number} az Z component of a + * @param {number} bx X component of b + * @param {number} by Y component of b + * @param {number} bz Z component of b + * @param {number} cx X component of c + * @param {number} cy Y component of c + * @param {number} cz Z component of c + * @return {plane} + * @function + */ + public static set (out, ax, ay, az, bx, by, bz, cx, cy, cz) { + out.a.x = ax; + out.a.y = ay; + out.a.z = az; + + out.b.x = bx; + out.b.y = by; + out.b.z = bz; + + out.c.x = cx; + out.c.y = cy; + out.c.z = cz; + + return out; + } + + public a: vec3; + public b: vec3; + public c: vec3; + + private _type: number; + + constructor (ax = 0, ay = 0, az = 0, bx = 1, by = 0, bz = 0, cx = 0, cy = 1, cz = 0) { + this._type = enums.SHAPE_TRIANGLE; + this.a = vec3.create(ax, ay, az); + this.b = vec3.create(bx, by, bz); + this.c = vec3.create(cx, cy, cz); + } +} diff --git a/cocos/3d/memop/circular-pool.js b/cocos/3d/memop/circular-pool.js deleted file mode 100644 index 3dfafd5628..0000000000 --- a/cocos/3d/memop/circular-pool.js +++ /dev/null @@ -1,17 +0,0 @@ -export default class CircularPool { - constructor(fn, size) { - this._cursor = 0; - this._data = new Array(size); - - for (let i = 0; i < size; ++i) { - this._data[i] = fn(); - } - } - - request() { - let item = this._data[this._cursor]; - this._cursor = (this._cursor + 1) % this._data.length; - - return item; - } -} \ No newline at end of file diff --git a/cocos/3d/memop/circular-pool.ts b/cocos/3d/memop/circular-pool.ts new file mode 100644 index 0000000000..a6c1f99909 --- /dev/null +++ b/cocos/3d/memop/circular-pool.ts @@ -0,0 +1,20 @@ +export default class CircularPool { + private _cursor: number; + private _data: T[]; + + constructor (fn: () => T, size: number) { + this._cursor = 0; + this._data = new Array(size); + + for (let i = 0; i < size; ++i) { + this._data[i] = fn(); + } + } + + public request () { + const item = this._data[this._cursor]; + this._cursor = (this._cursor + 1) % this._data.length; + + return item; + } +} diff --git a/cocos/3d/memop/fixed-array.js b/cocos/3d/memop/fixed-array.js deleted file mode 100644 index 5ba9134463..0000000000 --- a/cocos/3d/memop/fixed-array.js +++ /dev/null @@ -1,73 +0,0 @@ -import sort from './timsort'; - -export default class FixedArray { - constructor(size) { - this._count = 0; - this._data = new Array(size); - } - - _resize(size) { - if (size > this._data.length) { - for (let i = this._data.length; i < size; ++i) { - this._data[i] = undefined; - } - } - } - - get length() { - return this._count; - } - - get data() { - return this._data; - } - - reset() { - for (let i = 0; i < this._count; ++i) { - this._data[i] = undefined; - } - - this._count = 0; - } - - push(val) { - if (this._count >= this._data.length) { - this._resize(this._data.length * 2); - } - - this._data[this._count] = val; - ++this._count; - } - - pop() { - --this._count; - - if (this._count < 0) { - this._count = 0; - } - - let ret = this._data[this._count]; - this._data[this._count] = undefined; - - return ret; - } - - fastRemove(idx) { - if (idx >= this._count || idx < 0) { - return; - } - - let last = this._count - 1; - this._data[idx] = this._data[last]; - this._data[last] = undefined; - this._count -= 1; - } - - indexOf(val) { - return this._data.indexOf(val); - } - - sort(cmp) { - return sort(this._data, 0, this._count, cmp); - } -} \ No newline at end of file diff --git a/cocos/3d/memop/fixed-array.ts b/cocos/3d/memop/fixed-array.ts new file mode 100644 index 0000000000..5a3176c087 --- /dev/null +++ b/cocos/3d/memop/fixed-array.ts @@ -0,0 +1,76 @@ +import sort from './timsort'; + +export default class FixedArray { + private _count: number; + private _data: Array; + + constructor (size: number) { + this._count = 0; + this._data = new Array(size); + } + + public _resize (size: number) { + if (size > this._data.length) { + for (let i = this._data.length; i < size; ++i) { + this._data[i] = undefined; + } + } + } + + get length () { + return this._count; + } + + get data () { + return this._data; + } + + public reset () { + for (let i = 0; i < this._count; ++i) { + this._data[i] = undefined; + } + + this._count = 0; + } + + public push (val) { + if (this._count >= this._data.length) { + this._resize(this._data.length * 2); + } + + this._data[this._count] = val; + ++this._count; + } + + public pop () { + --this._count; + + if (this._count < 0) { + this._count = 0; + } + + const ret = this._data[this._count]; + this._data[this._count] = undefined; + + return ret; + } + + public fastRemove (idx) { + if (idx >= this._count || idx < 0) { + return; + } + + const last = this._count - 1; + this._data[idx] = this._data[last]; + this._data[last] = undefined; + this._count -= 1; + } + + public indexOf (val) { + return this._data.indexOf(val); + } + + public sort (cmp) { + return sort(this._data, 0, this._count, cmp); + } +} diff --git a/cocos/3d/memop/index.js b/cocos/3d/memop/index.ts similarity index 80% rename from cocos/3d/memop/index.js rename to cocos/3d/memop/index.ts index 092d7d82ad..1e99efc236 100644 --- a/cocos/3d/memop/index.js +++ b/cocos/3d/memop/index.ts @@ -3,4 +3,4 @@ export { default as FixedArray } from './fixed-array'; export { default as LinkedArray } from './linked-array'; export { default as Pool } from './pool'; export { default as RecyclePool } from './recycle-pool'; -export { default as TypedArrayPool } from './typed-array-pool'; \ No newline at end of file +export { default as TypedArrayPool } from './typed-array-pool'; diff --git a/cocos/3d/memop/linked-array.js b/cocos/3d/memop/linked-array.js deleted file mode 100644 index 2b217c2ab9..0000000000 --- a/cocos/3d/memop/linked-array.js +++ /dev/null @@ -1,82 +0,0 @@ -import Pool from './pool'; - -// NOTE: you must have `_prev` and `_next` field in the object returns by `fn` - -export default class LinkedArray { - constructor(fn, size) { - this._fn = fn; - this._count = 0; - this._head = null; - this._tail = null; - - this._pool = new Pool(fn, size); - } - - get head() { - return this._head; - } - - get tail() { - return this._tail; - } - - get length() { - return this._count; - } - - add() { - let node = this._pool.alloc(); - - if (!this._tail) { - this._head = node; - } else { - this._tail._next = node; - node._prev = this._tail; - } - this._tail = node; - this._count += 1; - - return node; - } - - remove(node) { - if (node._prev) { - node._prev._next = node._next; - } else { - this._head = node._next; - } - - if (node._next) { - node._next._prev = node._prev; - } else { - this._tail = node._prev; - } - - node._next = null; - node._prev = null; - this._pool.free(node); - this._count -= 1; - } - - forEach(fn, binder) { - let cursor = this._head; - if (!cursor) { - return; - } - - if (binder) { - fn = fn.bind(binder); - } - - let idx = 0; - let next = cursor; - - while (cursor) { - next = cursor._next; - fn(cursor, idx, this); - - cursor = next; - ++idx; - } - } -} \ No newline at end of file diff --git a/cocos/3d/memop/linked-array.ts b/cocos/3d/memop/linked-array.ts new file mode 100644 index 0000000000..e0f9044af9 --- /dev/null +++ b/cocos/3d/memop/linked-array.ts @@ -0,0 +1,95 @@ +import Pool from './pool'; + +// NOTE: you must have `_prev` and `_next` field in the object returns by `fn` + +interface INode { + _prev: INode; + _next: INode; +} + +type NodeAllocator = () => INode; + +export default class LinkedArray { + private _fn: NodeAllocator; + private _count: number; + private _head: INode | null; + private _tail: INode | null; + private _pool: Pool; + + constructor (fn: NodeAllocator, size: number) { + this._fn = fn; + this._count = 0; + this._head = null; + this._tail = null; + + this._pool = new Pool(fn, size); + } + + get head () { + return this._head; + } + + get tail () { + return this._tail; + } + + get length () { + return this._count; + } + + public add () { + const node = this._pool.alloc(); + + if (!this._tail) { + this._head = node; + } else { + this._tail._next = node; + node._prev = this._tail; + } + this._tail = node; + this._count += 1; + + return node; + } + + public remove (node) { + if (node._prev) { + node._prev._next = node._next; + } else { + this._head = node._next; + } + + if (node._next) { + node._next._prev = node._prev; + } else { + this._tail = node._prev; + } + + node._next = null; + node._prev = null; + this._pool.free(node); + this._count -= 1; + } + + public forEach (fn, binder) { + let cursor = this._head; + if (!cursor) { + return; + } + + if (binder) { + fn = fn.bind(binder); + } + + let idx = 0; + let next = cursor; + + while (cursor) { + next = cursor._next; + fn(cursor, idx, this); + + cursor = next; + ++idx; + } + } +} diff --git a/cocos/3d/memop/optimized-array.js b/cocos/3d/memop/optimized-array.js deleted file mode 100644 index 3f013e06b2..0000000000 --- a/cocos/3d/memop/optimized-array.js +++ /dev/null @@ -1,187 +0,0 @@ -export class OptimizedArray { - /** - * Initialize this array with specified capacity. - * @param {Number} [size] The size. - */ - constructor(size = 0) { - this._size = size; - this._data = new Array(size); - } - - /** - * Size of this array. - * @return {Number} - */ - get size() { - return this._size; - } - - /** - * The underlying Array of this array. - * @return {Array} - */ - get data() { - return this._data; - } - - /** - * Capacity of this array. - */ - get capacity() { - return this._data.length; - } - - /** - * Push a value to back of this array. - * @param {any} value - */ - push(value) { - if (this._size > this._data.length) - this._extends(this._data.length); - this._data[this._size] = value; - ++this._size; - } - - /** - * Remove the last element and return it, if exists. - */ - pop() { - if (this._size == 0) - return; - --this._size; - let ret = this._data[this._size]; - this._data[this._size] = undefined; - return ret; - } - - /** - * Remove all elements. - */ - clear() { - for (let i = 0; i < this._data.length; ++i) - this._data[i] = undefined; - this._size = 0; - } - - /** - * @ignore - * @param {Number} size - */ - _extends(size) { - let finalSize = this._data.length + size; - for (let i = this._data.length; i < finalSize; ++i) - this._data[i] = undefined; - } -} - -export class OptimizedValueArray { - /** - * Initialize this array with specified capacity. - * @param {any} ctor The constructor to create the value. - * @param {Number} [size] The size. - */ - constructor(ctor, dtor, size = 0) { - this._size = size; - this._data = new Array(); - this._ctor = ctor; - this._dtor = dtor; - this._extends(size); - } - - /** - * Size of this array. - * @return {Number} - */ - get size() { - return this._size; - } - - /** - * The underlying Array of this array. - * @return {Array} - */ - get data() { - return this._data; - } - - /** - * Capacity of this array. - */ - get capacity() { - return this._data.length; - } - - /** - * Push a value to back of this array. - */ - push() { - if (this._size >= this._data.length) - this._extends(this._data.length + 1); - let retval = this._data[this._size]; - ++this._size; - return retval; - } - - /** - * Remove the last element, if exists. - * Since that element is not erased, so we cannot return it. - */ - pop() { - if (this._size == 0) - return; - --this._size; - this._dtor(this._data[this._size]); - } - - /** - * Remove all elements. - */ - clear() { - this._size = 0; - for (let i = 0; i < this._data.length; ++i) - this._dtor(this._data[i]); - } - - splice(from, number) { - if (number == 0) - return; - - if (from >= this.size) - return; // throw - - number = Math.min(this.size - from, number); - - let originalSize = this._size; - this._size -= number; - - for (let i = 0, moveStart = from + number, moveNumber = originalSize - moveStart; i < moveNumber; ++i) { - let temp = this._data[from + i]; - this._data[from + i] = this._data[moveStart + i]; - this._data[moveStart + i] = temp; - } - for (let i = this._size; i != originalSize; ++i) - this._dtor(this._data[i]); - } - - forEach(fx) { - for (let i = 0; i < this.size; ++i) - fx(this.data[i], i, this); - } - - map(fx) { - let result = new Array(); - for (let i = 0; i < this.size; ++i) - result.push(fx(this.data[i], i, this)); - return result; - } - - /** - * @ignore - * @param {Number} size - */ - _extends(size) { - let finalSize = this._data.length + size; - for (let i = this._data.length; i < finalSize; ++i) - this._data[i] = this._ctor(); - } -} \ No newline at end of file diff --git a/cocos/3d/memop/optimized-array.ts b/cocos/3d/memop/optimized-array.ts new file mode 100644 index 0000000000..e15f74978e --- /dev/null +++ b/cocos/3d/memop/optimized-array.ts @@ -0,0 +1,212 @@ +export class OptimizedArray { + private _size: number; + private _data: Array; + + /** + * Initialize this array with specified capacity. + * @param {Number} [size] The size. + */ + constructor (size = 0) { + this._size = size; + this._data = new Array(size); + } + + /** + * Size of this array. + * @return {Number} + */ + get size () { + return this._size; + } + + /** + * The underlying Array of this array. + * @return {Array} + */ + get data () { + return this._data; + } + + /** + * Capacity of this array. + */ + get capacity () { + return this._data.length; + } + + /** + * Push a value to back of this array. + * @param {any} value + */ + public push (value) { + if (this._size > this._data.length) { + this._extends(this._data.length); + } + this._data[this._size] = value; + ++this._size; + } + + /** + * Remove the last element and return it, if exists. + */ + public pop () { + if (this._size === 0) { + return; + } + --this._size; + const ret = this._data[this._size]; + this._data[this._size] = undefined; + return ret; + } + + /** + * Remove all elements. + */ + public clear () { + for (let i = 0; i < this._data.length; ++i) { + this._data[i] = undefined; + } + this._size = 0; + } + + /** + * @ignore + * @param {Number} size + */ + public _extends (size) { + const finalSize = this._data.length + size; + for (let i = this._data.length; i < finalSize; ++i) { + this._data[i] = undefined; + } + } +} + +type Allocator = () => T; + +type Deallocator = (value: T) => void; + +export class OptimizedValueArray { + private _size: number; + private _data: T[]; + private _ctor; + private _dtor; + + /** + * Initialize this array with specified capacity. + * @param {any} ctor The constructor to create the value. + * @param {Number} [size] The size. + */ + constructor (ctor: Allocator, dtor: Deallocator, size = 0) { + this._size = size; + this._data = new Array(); + this._ctor = ctor; + this._dtor = dtor; + this._extends(size); + } + + /** + * Size of this array. + * @return {Number} + */ + get size () { + return this._size; + } + + /** + * The underlying Array of this array. + * @return {Array} + */ + get data () { + return this._data as T[]; + } + + /** + * Capacity of this array. + */ + get capacity () { + return this._data.length; + } + + /** + * Push a value to back of this array. + */ + public push () { + if (this._size >= this._data.length) { + this._extends(this._data.length + 1); + } + const retval = this._data[this._size]; + ++this._size; + return retval; + } + + /** + * Remove the last element, if exists. + * Since that element is not erased, so we cannot return it. + */ + public pop () { + if (this._size === 0) { + return; + } + --this._size; + this._dtor(this._data[this._size]); + } + + /** + * Remove all elements. + */ + public clear () { + this._size = 0; + for (const value of this._data) { + this._dtor(value); + } + } + + public splice (from, number) { + if (number === 0) { + return; + } + + if (from >= this.size) { + return; + } // throw + + number = Math.min(this.size - from, number); + + const originalSize = this._size; + this._size -= number; + + for (let i = 0, moveStart = from + number, moveNumber = originalSize - moveStart; i < moveNumber; ++i) { + const temp = this._data[from + i]; + this._data[from + i] = this._data[moveStart + i]; + this._data[moveStart + i] = temp; + } + for (let i = this._size; i !== originalSize; ++i) { + this._dtor(this._data[i]); + } + } + + public forEach (fx) { + for (let i = 0; i < this.size; ++i) { + fx(this.data[i], i, this); + } + } + + public map (fx) { + const result = new Array(); + for (let i = 0; i < this.size; ++i) { + result.push(fx(this.data[i], i, this)); + } + return result; + } + + /** + * @ignore + * @param {Number} size + */ + public _extends (size) { + const finalSize = this._data.length + size; + for (let i = this._data.length; i < finalSize; ++i) { + this._data[i] = this._ctor(); + } + } +} diff --git a/cocos/3d/memop/sort.js b/cocos/3d/memop/sort.js deleted file mode 100644 index 34e0e29512..0000000000 --- a/cocos/3d/memop/sort.js +++ /dev/null @@ -1,166 +0,0 @@ -// reference: https://github.com/v8/v8/blob/master/src/js/array.js - -function _compare(a, b) { - return a - b; -} - -function _sort(array, from, to, comparefn) { - - function _insertionSort(a, from, to) { - for (let i = from + 1; i < to; i++) { - let element = a[i]; - let j; - - for (j = i - 1; j >= from; j--) { - let tmp = a[j]; - let order = comparefn(tmp, element); - if (order > 0) { - a[j + 1] = tmp; - } else { - break; - } - } - a[j + 1] = element; - } - } - - // function _getThirdIndex(a, from, to) { - // let t_array = new Array(); - // // Use both 'from' and 'to' to determine the pivot candidates. - // let increment = 200 + ((to - from) & 15); - // let j = 0; - // from += 1; - // to -= 1; - // for (let i = from; i < to; i += increment) { - // t_array[j] = [i, a[i]]; - // j++; - // } - // t_array.sort(function (a, b) { - // return comparefn(a[1], b[1]); - // }); - // let third_index = t_array[t_array.length >> 1][0]; - // return third_index; - // } - - function _quickSort(a, from, to) { - let third_index = 0; - - while (true) { - // Insertion sort is faster for short arrays. - if (to - from <= 10) { - _insertionSort(a, from, to); - return; - } - // if (to - from > 1000) { - // third_index = _getThirdIndex(a, from, to); - // } else { - third_index = from + ((to - from) >> 1); - // } - // Find a pivot as the median of first, last and middle element. - let v0 = a[from]; - let v1 = a[to - 1]; - let v2 = a[third_index]; - let c01 = comparefn(v0, v1); - if (c01 > 0) { - // v1 < v0, so swap them. - let tmp = v0; - v0 = v1; - v1 = tmp; - } // v0 <= v1. - let c02 = comparefn(v0, v2); - if (c02 >= 0) { - // v2 <= v0 <= v1. - let tmp = v0; - v0 = v2; - v2 = v1; - v1 = tmp; - } else { - // v0 <= v1 && v0 < v2 - let c12 = comparefn(v1, v2); - if (c12 > 0) { - // v0 <= v2 < v1 - let tmp = v1; - v1 = v2; - v2 = tmp; - } - } - // v0 <= v1 <= v2 - a[from] = v0; - a[to - 1] = v2; - let pivot = v1; - let low_end = from + 1; // Upper bound of elements lower than pivot. - let high_start = to - 1; // Lower bound of elements greater than pivot. - a[third_index] = a[low_end]; - a[low_end] = pivot; - - // From low_end to i are elements equal to pivot. - // From i to high_start are elements that haven't been compared yet. - partition: for (let i = low_end + 1; i < high_start; i++) { - let element = a[i]; - let order = comparefn(element, pivot); - if (order < 0) { - a[i] = a[low_end]; - a[low_end] = element; - low_end++; - } else if (order > 0) { - do { - high_start--; - if (high_start == i) break partition; - let top_elem = a[high_start]; - order = comparefn(top_elem, pivot); - } while (order > 0); - a[i] = a[high_start]; - a[high_start] = element; - if (order < 0) { - element = a[i]; - a[i] = a[low_end]; - a[low_end] = element; - low_end++; - } - } - } - if (to - high_start < low_end - from) { - _quickSort(a, high_start, to); - to = low_end; - } else { - _quickSort(a, from, low_end); - from = high_start; - } - } - } - - if (to - from < 2) { - return array; - } - - _quickSort(array, from, to); - - return array; -} - - -/** - * Calls the _quickSort function with it's initial values. - * - * @public - * @param {array} array The input array which should be sorted - * @param {Number} from - * @param {Number} to - * @param {Function} cmp - * @returns {array} array Sorted array - */ -export default function (array, from, to, cmp) { - if (from === undefined) { - from = 0; - } - - if (to === undefined) { - to = array.length; - } - - if (cmp === undefined) { - cmp = _compare; - } - - return _sort(array, from, to, cmp); -} \ No newline at end of file diff --git a/cocos/3d/memop/sort.ts b/cocos/3d/memop/sort.ts new file mode 100644 index 0000000000..1b0693a227 --- /dev/null +++ b/cocos/3d/memop/sort.ts @@ -0,0 +1,166 @@ +// reference: https://github.com/v8/v8/blob/master/src/js/array.js + +// tslint:disable:no-shadowed-variable + +function _compare (a, b) { + return a - b; +} + +function _sort (array, from, to, comparefn) { + + function _insertionSort (a, from, to) { + for (let i = from + 1; i < to; i++) { + const element = a[i]; + let j; + + for (j = i - 1; j >= from; j--) { + const tmp = a[j]; + const order = comparefn(tmp, element); + if (order > 0) { + a[j + 1] = tmp; + } else { + break; + } + } + a[j + 1] = element; + } + } + + // function _getThirdIndex(a, from, to) { + // let t_array = new Array(); + // // Use both 'from' and 'to' to determine the pivot candidates. + // let increment = 200 + ((to - from) & 15); + // let j = 0; + // from += 1; + // to -= 1; + // for (let i = from; i < to; i += increment) { + // t_array[j] = [i, a[i]]; + // j++; + // } + // t_array.sort(function (a, b) { + // return comparefn(a[1], b[1]); + // }); + // let third_index = t_array[t_array.length >> 1][0]; + // return third_index; + // } + + function _quickSort (a, from, to) { + let third_index = 0; + + while (true) { + // Insertion sort is faster for short arrays. + if (to - from <= 10) { + _insertionSort(a, from, to); + return; + } + // if (to - from > 1000) { + // third_index = _getThirdIndex(a, from, to); + // } else { + third_index = from + ((to - from) >> 1); + // } + // Find a pivot as the median of first, last and middle element. + let v0 = a[from]; + let v1 = a[to - 1]; + let v2 = a[third_index]; + const c01 = comparefn(v0, v1); + if (c01 > 0) { + // v1 < v0, so swap them. + const tmp = v0; + v0 = v1; + v1 = tmp; + } // v0 <= v1. + const c02 = comparefn(v0, v2); + if (c02 >= 0) { + // v2 <= v0 <= v1. + const tmp = v0; + v0 = v2; + v2 = v1; + v1 = tmp; + } else { + // v0 <= v1 && v0 < v2 + const c12 = comparefn(v1, v2); + if (c12 > 0) { + // v0 <= v2 < v1 + const tmp = v1; + v1 = v2; + v2 = tmp; + } + } + // v0 <= v1 <= v2 + a[from] = v0; + a[to - 1] = v2; + const pivot = v1; + let low_end = from + 1; // Upper bound of elements lower than pivot. + let high_start = to - 1; // Lower bound of elements greater than pivot. + a[third_index] = a[low_end]; + a[low_end] = pivot; + + // From low_end to i are elements equal to pivot. + // From i to high_start are elements that haven't been compared yet. + partition: for (let i = low_end + 1; i < high_start; i++) { + let element = a[i]; + let order = comparefn(element, pivot); + if (order < 0) { + a[i] = a[low_end]; + a[low_end] = element; + low_end++; + } else if (order > 0) { + do { + high_start--; + if (high_start === i) { break partition; } + const top_elem = a[high_start]; + order = comparefn(top_elem, pivot); + } while (order > 0); + a[i] = a[high_start]; + a[high_start] = element; + if (order < 0) { + element = a[i]; + a[i] = a[low_end]; + a[low_end] = element; + low_end++; + } + } + } + if (to - high_start < low_end - from) { + _quickSort(a, high_start, to); + to = low_end; + } else { + _quickSort(a, from, low_end); + from = high_start; + } + } + } + + if (to - from < 2) { + return array; + } + + _quickSort(array, from, to); + + return array; +} + +/** + * Calls the _quickSort function with it's initial values. + * + * @param array The input array which should be sorted + * @param from + * @param to + * @param cmp + * @returns array Sorted array + */ +export default function (array: T[], from?: number, to?: number, cmp?: CompareFunction): T[] { + if (from === undefined) { + from = 0; + } + + if (to === undefined) { + to = array.length; + } + + if (cmp === undefined) { + cmp = _compare; + } + + return _sort(array, from, to, cmp); +} diff --git a/cocos/3d/memop/timsort.js b/cocos/3d/memop/timsort.js deleted file mode 100644 index 737a47af93..0000000000 --- a/cocos/3d/memop/timsort.js +++ /dev/null @@ -1,967 +0,0 @@ -// reference: https://github.com/mziccard/node-timsort - -/** - * Default minimum size of a run. - */ -const DEFAULT_MIN_MERGE = 32; - -/** - * Minimum ordered subsequece required to do galloping. - */ -const DEFAULT_MIN_GALLOPING = 7; - -/** - * Default tmp storage length. Can increase depending on the size of the - * smallest run to merge. - */ -const DEFAULT_TMP_STORAGE_LENGTH = 256; - -/** - * Pre-computed powers of 10 for efficient lexicographic comparison of - * small integers. - */ -const POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9] - -/** - * Estimate the logarithm base 10 of a small integer. - * - * @param {number} x - The integer to estimate the logarithm of. - * @return {number} - The estimated logarithm of the integer. - */ -function log10(x) { - if (x < 1e5) { - if (x < 1e2) { - return x < 1e1 ? 0 : 1; - } - - if (x < 1e4) { - return x < 1e3 ? 2 : 3; - } - - return 4; - } - - if (x < 1e7) { - return x < 1e6 ? 5 : 6; - } - - if (x < 1e9) { - return x < 1e8 ? 7 : 8; - } - - return 9; -} - -/** - * Default alphabetical comparison of items. - * - * @param {string|object|number} a - First element to compare. - * @param {string|object|number} b - Second element to compare. - * @return {number} - A positive number if a.toString() > b.toString(), a - * negative number if .toString() < b.toString(), 0 otherwise. - */ -function alphabeticalCompare(a, b) { - if (a === b) { - return 0; - } - - if (~~a === a && ~~b === b) { - if (a === 0 || b === 0) { - return a < b ? -1 : 1; - } - - if (a < 0 || b < 0) { - if (b >= 0) { - return -1; - } - - if (a >= 0) { - return 1; - } - - a = -a; - b = -b; - } - - const al = log10(a); - const bl = log10(b); - - let t = 0; - - if (al < bl) { - a *= POWERS_OF_TEN[bl - al - 1]; - b /= 10; - t = -1; - } else if (al > bl) { - b *= POWERS_OF_TEN[al - bl - 1]; - a /= 10; - t = 1; - } - - if (a === b) { - return t; - } - - return a < b ? -1 : 1; - } - - let aStr = String(a); - let bStr = String(b); - - if (aStr === bStr) { - return 0; - } - - return aStr < bStr ? -1 : 1; -} - -/** - * Compute minimum run length for TimSort - * - * @param {number} n - The size of the array to sort. - */ -function minRunLength(n) { - let r = 0; - - while (n >= DEFAULT_MIN_MERGE) { - r |= (n & 1); - n >>= 1; - } - - return n + r; -} - -/** - * Counts the length of a monotonically ascending or strictly monotonically - * descending sequence (run) starting at array[lo] in the range [lo, hi). If - * the run is descending it is made ascending. - * - * @param {array} array - The array to reverse. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * @param {function} compare - Item comparison function. - * @return {number} - The length of the run. - */ -function makeAscendingRun(array, lo, hi, compare) { - let runHi = lo + 1; - - if (runHi === hi) { - return 1; - } - - // Descending - if (compare(array[runHi++], array[lo]) < 0) { - while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) { - runHi++; - } - - reverseRun(array, lo, runHi); - // Ascending - } else { - while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) { - runHi++; - } - } - - return runHi - lo; -} - -/** - * Reverse an array in the range [lo, hi). - * - * @param {array} array - The array to reverse. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - */ -function reverseRun(array, lo, hi) { - hi--; - - while (lo < hi) { - let t = array[lo]; - array[lo++] = array[hi]; - array[hi--] = t; - } -} - -/** - * Perform the binary sort of the array in the range [lo, hi) where start is - * the first element possibly out of order. - * - * @param {array} array - The array to sort. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * @param {number} start - First element possibly out of order. - * @param {function} compare - Item comparison function. - */ -function binaryInsertionSort(array, lo, hi, start, compare) { - if (start === lo) { - start++; - } - - for (; start < hi; start++) { - let pivot = array[start]; - - // Ranges of the array where pivot belongs - let left = lo; - let right = start; - - /* - * pivot >= array[i] for i in [lo, left) - * pivot < array[i] for i in in [right, start) - */ - while (left < right) { - let mid = (left + right) >>> 1; - - if (compare(pivot, array[mid]) < 0) { - right = mid; - } else { - left = mid + 1; - } - } - - /* - * Move elements right to make room for the pivot. If there are elements - * equal to pivot, left points to the first slot after them: this is also - * a reason for which TimSort is stable - */ - let n = start - left; - // Switch is just an optimization for small arrays - switch (n) { - case 3: - array[left + 3] = array[left + 2]; - /* falls through */ - case 2: - array[left + 2] = array[left + 1]; - /* falls through */ - case 1: - array[left + 1] = array[left]; - break; - default: - while (n > 0) { - array[left + n] = array[left + n - 1]; - n--; - } - } - - array[left] = pivot; - } -} - -/** - * Find the position at which to insert a value in a sorted range. If the range - * contains elements equal to the value the leftmost element index is returned - * (for stability). - * - * @param {number} value - Value to insert. - * @param {array} array - The array in which to insert value. - * @param {number} start - First element in the range. - * @param {number} length - Length of the range. - * @param {number} hint - The index at which to begin the search. - * @param {function} compare - Item comparison function. - * @return {number} - The index where to insert value. - */ -function gallopLeft(value, array, start, length, hint, compare) { - let lastOffset = 0; - let maxOffset = 0; - let offset = 1; - - if (compare(value, array[start + hint]) > 0) { - maxOffset = length - hint; - - while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - lastOffset += hint; - offset += hint; - - // value <= array[start + hint] - } else { - maxOffset = hint + 1; - while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - let tmp = lastOffset; - lastOffset = hint - offset; - offset = hint - tmp; - } - - /* - * Now array[start+lastOffset] < value <= array[start+offset], so value - * belongs somewhere in the range (start + lastOffset, start + offset]. Do a - * binary search, with invariant array[start + lastOffset - 1] < value <= - * array[start + offset]. - */ - lastOffset++; - while (lastOffset < offset) { - let m = lastOffset + ((offset - lastOffset) >>> 1); - - if (compare(value, array[start + m]) > 0) { - lastOffset = m + 1; - - } else { - offset = m; - } - } - return offset; -} - -/** - * Find the position at which to insert a value in a sorted range. If the range - * contains elements equal to the value the rightmost element index is returned - * (for stability). - * - * @param {number} value - Value to insert. - * @param {array} array - The array in which to insert value. - * @param {number} start - First element in the range. - * @param {number} length - Length of the range. - * @param {number} hint - The index at which to begin the search. - * @param {function} compare - Item comparison function. - * @return {number} - The index where to insert value. - */ -function gallopRight(value, array, start, length, hint, compare) { - let lastOffset = 0; - let maxOffset = 0; - let offset = 1; - - if (compare(value, array[start + hint]) < 0) { - maxOffset = hint + 1; - - while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - let tmp = lastOffset; - lastOffset = hint - offset; - offset = hint - tmp; - - // value >= array[start + hint] - } else { - maxOffset = length - hint; - - while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) { - lastOffset = offset; - offset = (offset << 1) + 1; - - if (offset <= 0) { - offset = maxOffset; - } - } - - if (offset > maxOffset) { - offset = maxOffset; - } - - // Make offsets relative to start - lastOffset += hint; - offset += hint; - } - - /* - * Now array[start+lastOffset] < value <= array[start+offset], so value - * belongs somewhere in the range (start + lastOffset, start + offset]. Do a - * binary search, with invariant array[start + lastOffset - 1] < value <= - * array[start + offset]. - */ - lastOffset++; - - while (lastOffset < offset) { - let m = lastOffset + ((offset - lastOffset) >>> 1); - - if (compare(value, array[start + m]) < 0) { - offset = m; - - } else { - lastOffset = m + 1; - } - } - - return offset; -} - -class TimSort { - - constructor(array, compare) { - this.array = array; - this.compare = compare; - this.minGallop = DEFAULT_MIN_GALLOPING; - this.length = array.length; - - this.tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH; - if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) { - this.tmpStorageLength = this.length >>> 1; - } - - this.tmp = new Array(this.tmpStorageLength); - - this.stackLength = - (this.length < 120 ? 5 : - this.length < 1542 ? 10 : - this.length < 119151 ? 19 : 40); - - this.runStart = new Array(this.stackLength); - this.runLength = new Array(this.stackLength); - this.stackSize = 0; - } - - /** - * Push a new run on TimSort's stack. - * - * @param {number} runStart - Start index of the run in the original array. - * @param {number} runLength - Length of the run; - */ - pushRun(runStart, runLength) { - this.runStart[this.stackSize] = runStart; - this.runLength[this.stackSize] = runLength; - this.stackSize += 1; - } - - /** - * Merge runs on TimSort's stack so that the following holds for all i: - * 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1] - * 2) runLength[i - 2] > runLength[i - 1] - */ - mergeRuns() { - while (this.stackSize > 1) { - let n = this.stackSize - 2; - - if ((n >= 1 && - this.runLength[n - 1] <= this.runLength[n] + this.runLength[n + 1]) || - (n >= 2 && - this.runLength[n - 2] <= this.runLength[n] + this.runLength[n - 1])) { - - if (this.runLength[n - 1] < this.runLength[n + 1]) { - n--; - } - - } else if (this.runLength[n] > this.runLength[n + 1]) { - break; - } - this.mergeAt(n); - } - } - - /** - * Merge all runs on TimSort's stack until only one remains. - */ - forceMergeRuns() { - while (this.stackSize > 1) { - let n = this.stackSize - 2; - - if (n > 0 && this.runLength[n - 1] < this.runLength[n + 1]) { - n--; - } - - this.mergeAt(n); - } - } - - /** - * Merge the runs on the stack at positions i and i+1. Must be always be called - * with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack). - * - * @param {number} i - Index of the run to merge in TimSort's stack. - */ - mergeAt(i) { - let compare = this.compare; - let array = this.array; - - let start1 = this.runStart[i]; - let length1 = this.runLength[i]; - let start2 = this.runStart[i + 1]; - let length2 = this.runLength[i + 1]; - - this.runLength[i] = length1 + length2; - - if (i === this.stackSize - 3) { - this.runStart[i + 1] = this.runStart[i + 2]; - this.runLength[i + 1] = this.runLength[i + 2]; - } - - this.stackSize--; - - /* - * Find where the first element in the second run goes in run1. Previous - * elements in run1 are already in place - */ - let k = gallopRight(array[start2], array, start1, length1, 0, compare); - start1 += k; - length1 -= k; - - if (length1 === 0) { - return; - } - - /* - * Find where the last element in the first run goes in run2. Next elements - * in run2 are already in place - */ - length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare); - - if (length2 === 0) { - return; - } - - /* - * Merge remaining runs. A tmp array with length = min(length1, length2) is - * used - */ - if (length1 <= length2) { - this.mergeLow(start1, length1, start2, length2); - - } else { - this.mergeHigh(start1, length1, start2, length2); - } - } - - /** - * Merge two adjacent runs in a stable way. The runs must be such that the - * first element of run1 is bigger than the first element in run2 and the - * last element of run1 is greater than all the elements in run2. - * The method should be called when run1.length <= run2.length as it uses - * TimSort temporary array to store run1. Use mergeHigh if run1.length > - * run2.length. - * - * @param {number} start1 - First element in run1. - * @param {number} length1 - Length of run1. - * @param {number} start2 - First element in run2. - * @param {number} length2 - Length of run2. - */ - mergeLow(start1, length1, start2, length2) { - - let compare = this.compare; - let array = this.array; - let tmp = this.tmp; - let i = 0; - - for (i = 0; i < length1; i++) { - tmp[i] = array[start1 + i]; - } - - let cursor1 = 0; - let cursor2 = start2; - let dest = start1; - - array[dest++] = array[cursor2++]; - - if (--length2 === 0) { - for (i = 0; i < length1; i++) { - array[dest + i] = tmp[cursor1 + i]; - } - return; - } - - if (length1 === 1) { - for (i = 0; i < length2; i++) { - array[dest + i] = array[cursor2 + i]; - } - array[dest + length2] = tmp[cursor1]; - return; - } - - let minGallop = this.minGallop; - - while (true) { - let count1 = 0; - let count2 = 0; - let exit = false; - - do { - if (compare(array[cursor2], tmp[cursor1]) < 0) { - array[dest++] = array[cursor2++]; - count2++; - count1 = 0; - - if (--length2 === 0) { - exit = true; - break; - } - - } else { - array[dest++] = tmp[cursor1++]; - count1++; - count2 = 0; - if (--length1 === 1) { - exit = true; - break; - } - } - } while ((count1 | count2) < minGallop); - - if (exit) { - break; - } - - do { - count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare); - - if (count1 !== 0) { - for (i = 0; i < count1; i++) { - array[dest + i] = tmp[cursor1 + i]; - } - - dest += count1; - cursor1 += count1; - length1 -= count1; - if (length1 <= 1) { - exit = true; - break; - } - } - - array[dest++] = array[cursor2++]; - - if (--length2 === 0) { - exit = true; - break; - } - - count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare); - - if (count2 !== 0) { - for (i = 0; i < count2; i++) { - array[dest + i] = array[cursor2 + i]; - } - - dest += count2; - cursor2 += count2; - length2 -= count2; - - if (length2 === 0) { - exit = true; - break; - } - } - array[dest++] = tmp[cursor1++]; - - if (--length1 === 1) { - exit = true; - break; - } - - minGallop--; - - } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); - - if (exit) { - break; - } - - if (minGallop < 0) { - minGallop = 0; - } - - minGallop += 2; - } - - this.minGallop = minGallop; - - if (minGallop < 1) { - this.minGallop = 1; - } - - if (length1 === 1) { - for (i = 0; i < length2; i++) { - array[dest + i] = array[cursor2 + i]; - } - array[dest + length2] = tmp[cursor1]; - - } else if (length1 === 0) { - throw new Error('mergeLow preconditions were not respected'); - - } else { - for (i = 0; i < length1; i++) { - array[dest + i] = tmp[cursor1 + i]; - } - } - } - - /** - * Merge two adjacent runs in a stable way. The runs must be such that the - * first element of run1 is bigger than the first element in run2 and the - * last element of run1 is greater than all the elements in run2. - * The method should be called when run1.length > run2.length as it uses - * TimSort temporary array to store run2. Use mergeLow if run1.length <= - * run2.length. - * - * @param {number} start1 - First element in run1. - * @param {number} length1 - Length of run1. - * @param {number} start2 - First element in run2. - * @param {number} length2 - Length of run2. - */ - mergeHigh(start1, length1, start2, length2) { - let compare = this.compare; - let array = this.array; - let tmp = this.tmp; - let i = 0; - - for (i = 0; i < length2; i++) { - tmp[i] = array[start2 + i]; - } - - let cursor1 = start1 + length1 - 1; - let cursor2 = length2 - 1; - let dest = start2 + length2 - 1; - let customCursor = 0; - let customDest = 0; - - array[dest--] = array[cursor1--]; - - if (--length1 === 0) { - customCursor = dest - (length2 - 1); - - for (i = 0; i < length2; i++) { - array[customCursor + i] = tmp[i]; - } - - return; - } - - if (length2 === 1) { - dest -= length1; - cursor1 -= length1; - customDest = dest + 1; - customCursor = cursor1 + 1; - - for (i = length1 - 1; i >= 0; i--) { - array[customDest + i] = array[customCursor + i]; - } - - array[dest] = tmp[cursor2]; - return; - } - - let minGallop = this.minGallop; - - while (true) { - let count1 = 0; - let count2 = 0; - let exit = false; - - do { - if (compare(tmp[cursor2], array[cursor1]) < 0) { - array[dest--] = array[cursor1--]; - count1++; - count2 = 0; - if (--length1 === 0) { - exit = true; - break; - } - - } else { - array[dest--] = tmp[cursor2--]; - count2++; - count1 = 0; - if (--length2 === 1) { - exit = true; - break; - } - } - - } while ((count1 | count2) < minGallop); - - if (exit) { - break; - } - - do { - count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare); - - if (count1 !== 0) { - dest -= count1; - cursor1 -= count1; - length1 -= count1; - customDest = dest + 1; - customCursor = cursor1 + 1; - - for (i = count1 - 1; i >= 0; i--) { - array[customDest + i] = array[customCursor + i]; - } - - if (length1 === 0) { - exit = true; - break; - } - } - - array[dest--] = tmp[cursor2--]; - - if (--length2 === 1) { - exit = true; - break; - } - - count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare); - - if (count2 !== 0) { - dest -= count2; - cursor2 -= count2; - length2 -= count2; - customDest = dest + 1; - customCursor = cursor2 + 1; - - for (i = 0; i < count2; i++) { - array[customDest + i] = tmp[customCursor + i]; - } - - if (length2 <= 1) { - exit = true; - break; - } - } - - array[dest--] = array[cursor1--]; - - if (--length1 === 0) { - exit = true; - break; - } - - minGallop--; - - } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); - - if (exit) { - break; - } - - if (minGallop < 0) { - minGallop = 0; - } - - minGallop += 2; - } - - this.minGallop = minGallop; - - if (minGallop < 1) { - this.minGallop = 1; - } - - if (length2 === 1) { - dest -= length1; - cursor1 -= length1; - customDest = dest + 1; - customCursor = cursor1 + 1; - - for (i = length1 - 1; i >= 0; i--) { - array[customDest + i] = array[customCursor + i]; - } - - array[dest] = tmp[cursor2]; - - } else if (length2 === 0) { - throw new Error('mergeHigh preconditions were not respected'); - - } else { - customCursor = dest - (length2 - 1); - for (i = 0; i < length2; i++) { - array[customCursor + i] = tmp[i]; - } - } - } -} - -/** - * Sort an array in the range [lo, hi) using TimSort. - * - * @param {array} array - The array to sort. - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * @param {function=} compare - Item comparison function. Default is alphabetical. - */ -export default function (array, lo, hi, compare) { - if (!Array.isArray(array)) { - throw new TypeError('Can only sort arrays'); - } - - /* - * Handle the case where a comparison function is not provided. We do - * lexicographic sorting - */ - - if (lo === undefined) { - lo = 0; - } - - if (hi === undefined) { - hi = array.length; - } - - if (compare === undefined) { - compare = alphabeticalCompare; - } - - let remaining = hi - lo; - - // The array is already sorted - if (remaining < 2) { - return; - } - - let runLength = 0; - // On small arrays binary sort can be used directly - if (remaining < DEFAULT_MIN_MERGE) { - runLength = makeAscendingRun(array, lo, hi, compare); - binaryInsertionSort(array, lo, hi, lo + runLength, compare); - return; - } - - let ts = new TimSort(array, compare); - - let minRun = minRunLength(remaining); - - do { - runLength = makeAscendingRun(array, lo, hi, compare); - if (runLength < minRun) { - let force = remaining; - if (force > minRun) { - force = minRun; - } - - binaryInsertionSort(array, lo, lo + force, lo + runLength, compare); - runLength = force; - } - // Push new run and merge if necessary - ts.pushRun(lo, runLength); - ts.mergeRuns(); - - // Go find next run - remaining -= runLength; - lo += runLength; - - } while (remaining !== 0); - - // Force merging of remaining runs - ts.forceMergeRuns(); -} \ No newline at end of file diff --git a/cocos/3d/memop/timsort.ts b/cocos/3d/memop/timsort.ts new file mode 100644 index 0000000000..a6877f45c2 --- /dev/null +++ b/cocos/3d/memop/timsort.ts @@ -0,0 +1,977 @@ +// reference: https://github.com/mziccard/node-timsort + +/** + * Default minimum size of a run. + */ +const DEFAULT_MIN_MERGE = 32; + +/** + * Minimum ordered subsequece required to do galloping. + */ +const DEFAULT_MIN_GALLOPING = 7; + +/** + * Default tmp storage length. Can increase depending on the size of the + * smallest run to merge. + */ +const DEFAULT_TMP_STORAGE_LENGTH = 256; + +/** + * Pre-computed powers of 10 for efficient lexicographic comparison of + * small integers. + */ +const POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; + +/** + * Estimate the logarithm base 10 of a small integer. + * + * @param {number} x - The integer to estimate the logarithm of. + * @return {number} - The estimated logarithm of the integer. + */ +function log10 (x) { + if (x < 1e5) { + if (x < 1e2) { + return x < 1e1 ? 0 : 1; + } + + if (x < 1e4) { + return x < 1e3 ? 2 : 3; + } + + return 4; + } + + if (x < 1e7) { + return x < 1e6 ? 5 : 6; + } + + if (x < 1e9) { + return x < 1e8 ? 7 : 8; + } + + return 9; +} + +/** + * Default alphabetical comparison of items. + * + * @param {string|object|number} a - First element to compare. + * @param {string|object|number} b - Second element to compare. + * @return {number} - A positive number if a.toString() > b.toString(), a + * negative number if .toString() < b.toString(), 0 otherwise. + */ +function alphabeticalCompare (a, b) { + if (a === b) { + return 0; + } + + if (~~a === a && ~~b === b) { + if (a === 0 || b === 0) { + return a < b ? -1 : 1; + } + + if (a < 0 || b < 0) { + if (b >= 0) { + return -1; + } + + if (a >= 0) { + return 1; + } + + a = -a; + b = -b; + } + + const al = log10(a); + const bl = log10(b); + + let t = 0; + + if (al < bl) { + a *= POWERS_OF_TEN[bl - al - 1]; + b /= 10; + t = -1; + } else if (al > bl) { + b *= POWERS_OF_TEN[al - bl - 1]; + a /= 10; + t = 1; + } + + if (a === b) { + return t; + } + + return a < b ? -1 : 1; + } + + const aStr = String(a); + const bStr = String(b); + + if (aStr === bStr) { + return 0; + } + + return aStr < bStr ? -1 : 1; +} + +/** + * Compute minimum run length for TimSort + * + * @param {number} n - The size of the array to sort. + */ +function minRunLength (n) { + let r = 0; + + while (n >= DEFAULT_MIN_MERGE) { + r |= (n & 1); + n >>= 1; + } + + return n + r; +} + +/** + * Counts the length of a monotonically ascending or strictly monotonically + * descending sequence (run) starting at array[lo] in the range [lo, hi). If + * the run is descending it is made ascending. + * + * @param {array} array - The array to reverse. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * @param {function} compare - Item comparison function. + * @return {number} - The length of the run. + */ +function makeAscendingRun (array, lo, hi, compare) { + let runHi = lo + 1; + + if (runHi === hi) { + return 1; + } + + // Descending + if (compare(array[runHi++], array[lo]) < 0) { + while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) { + runHi++; + } + + reverseRun(array, lo, runHi); + // Ascending + } else { + while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) { + runHi++; + } + } + + return runHi - lo; +} + +/** + * Reverse an array in the range [lo, hi). + * + * @param {array} array - The array to reverse. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + */ +function reverseRun (array, lo, hi) { + hi--; + + while (lo < hi) { + const t = array[lo]; + array[lo++] = array[hi]; + array[hi--] = t; + } +} + +/** + * Perform the binary sort of the array in the range [lo, hi) where start is + * the first element possibly out of order. + * + * @param {array} array - The array to sort. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * @param {number} start - First element possibly out of order. + * @param {function} compare - Item comparison function. + */ +function binaryInsertionSort (array, lo, hi, start, compare) { + if (start === lo) { + start++; + } + + for (; start < hi; start++) { + const pivot = array[start]; + + // Ranges of the array where pivot belongs + let left = lo; + let right = start; + + /* + * pivot >= array[i] for i in [lo, left) + * pivot < array[i] for i in in [right, start) + */ + while (left < right) { + const mid = (left + right) >>> 1; + + if (compare(pivot, array[mid]) < 0) { + right = mid; + } else { + left = mid + 1; + } + } + + /* + * Move elements right to make room for the pivot. If there are elements + * equal to pivot, left points to the first slot after them: this is also + * a reason for which TimSort is stable + */ + let n = start - left; + // Switch is just an optimization for small arrays + switch (n) { + case 3: + array[left + 3] = array[left + 2]; + /* falls through */ + case 2: + array[left + 2] = array[left + 1]; + /* falls through */ + case 1: + array[left + 1] = array[left]; + break; + default: + while (n > 0) { + array[left + n] = array[left + n - 1]; + n--; + } + } + + array[left] = pivot; + } +} + +/** + * Find the position at which to insert a value in a sorted range. If the range + * contains elements equal to the value the leftmost element index is returned + * (for stability). + * + * @param {number} value - Value to insert. + * @param {array} array - The array in which to insert value. + * @param {number} start - First element in the range. + * @param {number} length - Length of the range. + * @param {number} hint - The index at which to begin the search. + * @param {function} compare - Item comparison function. + * @return {number} - The index where to insert value. + */ +function gallopLeft (value, array, start, length, hint, compare) { + let lastOffset = 0; + let maxOffset = 0; + let offset = 1; + + if (compare(value, array[start + hint]) > 0) { + maxOffset = length - hint; + + while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + lastOffset += hint; + offset += hint; + + // value <= array[start + hint] + } else { + maxOffset = hint + 1; + while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + const tmp = lastOffset; + lastOffset = hint - offset; + offset = hint - tmp; + } + + /* + * Now array[start+lastOffset] < value <= array[start+offset], so value + * belongs somewhere in the range (start + lastOffset, start + offset]. Do a + * binary search, with invariant array[start + lastOffset - 1] < value <= + * array[start + offset]. + */ + lastOffset++; + while (lastOffset < offset) { + const m = lastOffset + ((offset - lastOffset) >>> 1); + + if (compare(value, array[start + m]) > 0) { + lastOffset = m + 1; + + } else { + offset = m; + } + } + return offset; +} + +/** + * Find the position at which to insert a value in a sorted range. If the range + * contains elements equal to the value the rightmost element index is returned + * (for stability). + * + * @param {number} value - Value to insert. + * @param {array} array - The array in which to insert value. + * @param {number} start - First element in the range. + * @param {number} length - Length of the range. + * @param {number} hint - The index at which to begin the search. + * @param {function} compare - Item comparison function. + * @return {number} - The index where to insert value. + */ +function gallopRight (value, array, start, length, hint, compare) { + let lastOffset = 0; + let maxOffset = 0; + let offset = 1; + + if (compare(value, array[start + hint]) < 0) { + maxOffset = hint + 1; + + while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + const tmp = lastOffset; + lastOffset = hint - offset; + offset = hint - tmp; + + // value >= array[start + hint] + } else { + maxOffset = length - hint; + + while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) { + lastOffset = offset; + offset = (offset << 1) + 1; + + if (offset <= 0) { + offset = maxOffset; + } + } + + if (offset > maxOffset) { + offset = maxOffset; + } + + // Make offsets relative to start + lastOffset += hint; + offset += hint; + } + + /* + * Now array[start+lastOffset] < value <= array[start+offset], so value + * belongs somewhere in the range (start + lastOffset, start + offset]. Do a + * binary search, with invariant array[start + lastOffset - 1] < value <= + * array[start + offset]. + */ + lastOffset++; + + while (lastOffset < offset) { + const m = lastOffset + ((offset - lastOffset) >>> 1); + + if (compare(value, array[start + m]) < 0) { + offset = m; + + } else { + lastOffset = m + 1; + } + } + + return offset; +} + +class TimSort { + public array: T[]; + public compare: CompareFunction; + public minGallop: number; + public length: number; + public tmpStorageLength: number; + public tmp: T[]; + public stackLength: number; + public runStart: number[]; + public runLength: number[]; + public stackSize: number; + + constructor (array, compare) { + this.array = array; + this.compare = compare; + this.minGallop = DEFAULT_MIN_GALLOPING; + this.length = array.length; + + this.tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH; + if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) { + this.tmpStorageLength = this.length >>> 1; + } + + this.tmp = new Array(this.tmpStorageLength); + + this.stackLength = + (this.length < 120 ? 5 : + this.length < 1542 ? 10 : + this.length < 119151 ? 19 : 40); + + this.runStart = new Array(this.stackLength); + this.runLength = new Array(this.stackLength); + this.stackSize = 0; + } + + /** + * Push a new run on TimSort's stack. + * + * @param {number} runStart - Start index of the run in the original array. + * @param {number} runLength - Length of the run; + */ + public pushRun (runStart, runLength) { + this.runStart[this.stackSize] = runStart; + this.runLength[this.stackSize] = runLength; + this.stackSize += 1; + } + + /** + * Merge runs on TimSort's stack so that the following holds for all i: + * 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1] + * 2) runLength[i - 2] > runLength[i - 1] + */ + public mergeRuns () { + while (this.stackSize > 1) { + let n = this.stackSize - 2; + + if ((n >= 1 && + this.runLength[n - 1] <= this.runLength[n] + this.runLength[n + 1]) || + (n >= 2 && + this.runLength[n - 2] <= this.runLength[n] + this.runLength[n - 1])) { + + if (this.runLength[n - 1] < this.runLength[n + 1]) { + n--; + } + + } else if (this.runLength[n] > this.runLength[n + 1]) { + break; + } + this.mergeAt(n); + } + } + + /** + * Merge all runs on TimSort's stack until only one remains. + */ + public forceMergeRuns () { + while (this.stackSize > 1) { + let n = this.stackSize - 2; + + if (n > 0 && this.runLength[n - 1] < this.runLength[n + 1]) { + n--; + } + + this.mergeAt(n); + } + } + + /** + * Merge the runs on the stack at positions i and i+1. Must be always be called + * with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack). + * + * @param {number} i - Index of the run to merge in TimSort's stack. + */ + public mergeAt (i) { + const compare = this.compare; + const array = this.array; + + let start1 = this.runStart[i]; + let length1 = this.runLength[i]; + const start2 = this.runStart[i + 1]; + let length2 = this.runLength[i + 1]; + + this.runLength[i] = length1 + length2; + + if (i === this.stackSize - 3) { + this.runStart[i + 1] = this.runStart[i + 2]; + this.runLength[i + 1] = this.runLength[i + 2]; + } + + this.stackSize--; + + /* + * Find where the first element in the second run goes in run1. Previous + * elements in run1 are already in place + */ + const k = gallopRight(array[start2], array, start1, length1, 0, compare); + start1 += k; + length1 -= k; + + if (length1 === 0) { + return; + } + + /* + * Find where the last element in the first run goes in run2. Next elements + * in run2 are already in place + */ + length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare); + + if (length2 === 0) { + return; + } + + /* + * Merge remaining runs. A tmp array with length = min(length1, length2) is + * used + */ + if (length1 <= length2) { + this.mergeLow(start1, length1, start2, length2); + + } else { + this.mergeHigh(start1, length1, start2, length2); + } + } + + /** + * Merge two adjacent runs in a stable way. The runs must be such that the + * first element of run1 is bigger than the first element in run2 and the + * last element of run1 is greater than all the elements in run2. + * The method should be called when run1.length <= run2.length as it uses + * TimSort temporary array to store run1. Use mergeHigh if run1.length > + * run2.length. + * + * @param {number} start1 - First element in run1. + * @param {number} length1 - Length of run1. + * @param {number} start2 - First element in run2. + * @param {number} length2 - Length of run2. + */ + public mergeLow (start1, length1, start2, length2) { + + const compare = this.compare; + const array = this.array; + const tmp = this.tmp; + let i = 0; + + for (i = 0; i < length1; i++) { + tmp[i] = array[start1 + i]; + } + + let cursor1 = 0; + let cursor2 = start2; + let dest = start1; + + array[dest++] = array[cursor2++]; + + if (--length2 === 0) { + for (i = 0; i < length1; i++) { + array[dest + i] = tmp[cursor1 + i]; + } + return; + } + + if (length1 === 1) { + for (i = 0; i < length2; i++) { + array[dest + i] = array[cursor2 + i]; + } + array[dest + length2] = tmp[cursor1]; + return; + } + + let minGallop = this.minGallop; + + while (true) { + let count1 = 0; + let count2 = 0; + let exit = false; + + do { + if (compare(array[cursor2], tmp[cursor1]) < 0) { + array[dest++] = array[cursor2++]; + count2++; + count1 = 0; + + if (--length2 === 0) { + exit = true; + break; + } + + } else { + array[dest++] = tmp[cursor1++]; + count1++; + count2 = 0; + if (--length1 === 1) { + exit = true; + break; + } + } + } while ((count1 | count2) < minGallop); + + if (exit) { + break; + } + + do { + count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare); + + if (count1 !== 0) { + for (i = 0; i < count1; i++) { + array[dest + i] = tmp[cursor1 + i]; + } + + dest += count1; + cursor1 += count1; + length1 -= count1; + if (length1 <= 1) { + exit = true; + break; + } + } + + array[dest++] = array[cursor2++]; + + if (--length2 === 0) { + exit = true; + break; + } + + count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare); + + if (count2 !== 0) { + for (i = 0; i < count2; i++) { + array[dest + i] = array[cursor2 + i]; + } + + dest += count2; + cursor2 += count2; + length2 -= count2; + + if (length2 === 0) { + exit = true; + break; + } + } + array[dest++] = tmp[cursor1++]; + + if (--length1 === 1) { + exit = true; + break; + } + + minGallop--; + + } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); + + if (exit) { + break; + } + + if (minGallop < 0) { + minGallop = 0; + } + + minGallop += 2; + } + + this.minGallop = minGallop; + + if (minGallop < 1) { + this.minGallop = 1; + } + + if (length1 === 1) { + for (i = 0; i < length2; i++) { + array[dest + i] = array[cursor2 + i]; + } + array[dest + length2] = tmp[cursor1]; + + } else if (length1 === 0) { + throw new Error('mergeLow preconditions were not respected'); + + } else { + for (i = 0; i < length1; i++) { + array[dest + i] = tmp[cursor1 + i]; + } + } + } + + /** + * Merge two adjacent runs in a stable way. The runs must be such that the + * first element of run1 is bigger than the first element in run2 and the + * last element of run1 is greater than all the elements in run2. + * The method should be called when run1.length > run2.length as it uses + * TimSort temporary array to store run2. Use mergeLow if run1.length <= + * run2.length. + * + * @param {number} start1 - First element in run1. + * @param {number} length1 - Length of run1. + * @param {number} start2 - First element in run2. + * @param {number} length2 - Length of run2. + */ + public mergeHigh (start1, length1, start2, length2) { + const compare = this.compare; + const array = this.array; + const tmp = this.tmp; + let i = 0; + + for (i = 0; i < length2; i++) { + tmp[i] = array[start2 + i]; + } + + let cursor1 = start1 + length1 - 1; + let cursor2 = length2 - 1; + let dest = start2 + length2 - 1; + let customCursor = 0; + let customDest = 0; + + array[dest--] = array[cursor1--]; + + if (--length1 === 0) { + customCursor = dest - (length2 - 1); + + for (i = 0; i < length2; i++) { + array[customCursor + i] = tmp[i]; + } + + return; + } + + if (length2 === 1) { + dest -= length1; + cursor1 -= length1; + customDest = dest + 1; + customCursor = cursor1 + 1; + + for (i = length1 - 1; i >= 0; i--) { + array[customDest + i] = array[customCursor + i]; + } + + array[dest] = tmp[cursor2]; + return; + } + + let minGallop = this.minGallop; + + while (true) { + let count1 = 0; + let count2 = 0; + let exit = false; + + do { + if (compare(tmp[cursor2], array[cursor1]) < 0) { + array[dest--] = array[cursor1--]; + count1++; + count2 = 0; + if (--length1 === 0) { + exit = true; + break; + } + + } else { + array[dest--] = tmp[cursor2--]; + count2++; + count1 = 0; + if (--length2 === 1) { + exit = true; + break; + } + } + + } while ((count1 | count2) < minGallop); + + if (exit) { + break; + } + + do { + count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare); + + if (count1 !== 0) { + dest -= count1; + cursor1 -= count1; + length1 -= count1; + customDest = dest + 1; + customCursor = cursor1 + 1; + + for (i = count1 - 1; i >= 0; i--) { + array[customDest + i] = array[customCursor + i]; + } + + if (length1 === 0) { + exit = true; + break; + } + } + + array[dest--] = tmp[cursor2--]; + + if (--length2 === 1) { + exit = true; + break; + } + + count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare); + + if (count2 !== 0) { + dest -= count2; + cursor2 -= count2; + length2 -= count2; + customDest = dest + 1; + customCursor = cursor2 + 1; + + for (i = 0; i < count2; i++) { + array[customDest + i] = tmp[customCursor + i]; + } + + if (length2 <= 1) { + exit = true; + break; + } + } + + array[dest--] = array[cursor1--]; + + if (--length1 === 0) { + exit = true; + break; + } + + minGallop--; + + } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); + + if (exit) { + break; + } + + if (minGallop < 0) { + minGallop = 0; + } + + minGallop += 2; + } + + this.minGallop = minGallop; + + if (minGallop < 1) { + this.minGallop = 1; + } + + if (length2 === 1) { + dest -= length1; + cursor1 -= length1; + customDest = dest + 1; + customCursor = cursor1 + 1; + + for (i = length1 - 1; i >= 0; i--) { + array[customDest + i] = array[customCursor + i]; + } + + array[dest] = tmp[cursor2]; + + } else if (length2 === 0) { + throw new Error('mergeHigh preconditions were not respected'); + + } else { + customCursor = dest - (length2 - 1); + for (i = 0; i < length2; i++) { + array[customCursor + i] = tmp[i]; + } + } + } +} + +/** + * Sort an array in the range [lo, hi) using TimSort. + * + * @param {array} array - The array to sort. + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * @param {function=} compare - Item comparison function. Default is alphabetical. + */ +export default function (array, lo, hi, compare) { + if (!Array.isArray(array)) { + throw new TypeError('Can only sort arrays'); + } + + /* + * Handle the case where a comparison function is not provided. We do + * lexicographic sorting + */ + + if (lo === undefined) { + lo = 0; + } + + if (hi === undefined) { + hi = array.length; + } + + if (compare === undefined) { + compare = alphabeticalCompare; + } + + let remaining = hi - lo; + + // The array is already sorted + if (remaining < 2) { + return; + } + + let runLength = 0; + // On small arrays binary sort can be used directly + if (remaining < DEFAULT_MIN_MERGE) { + runLength = makeAscendingRun(array, lo, hi, compare); + binaryInsertionSort(array, lo, hi, lo + runLength, compare); + return; + } + + const ts = new TimSort(array, compare); + + const minRun = minRunLength(remaining); + + do { + runLength = makeAscendingRun(array, lo, hi, compare); + if (runLength < minRun) { + let force = remaining; + if (force > minRun) { + force = minRun; + } + + binaryInsertionSort(array, lo, lo + force, lo + runLength, compare); + runLength = force; + } + // Push new run and merge if necessary + ts.pushRun(lo, runLength); + ts.mergeRuns(); + + // Go find next run + remaining -= runLength; + lo += runLength; + + } while (remaining !== 0); + + // Force merging of remaining runs + ts.forceMergeRuns(); +} diff --git a/cocos/3d/memop/typed-array-pool.js b/cocos/3d/memop/typed-array-pool.js deleted file mode 100644 index 9711e8fdb4..0000000000 --- a/cocos/3d/memop/typed-array-pool.js +++ /dev/null @@ -1,129 +0,0 @@ -let _bufferPools = Array(8); -for (let i = 0; i < 8; ++i) { - _bufferPools[i] = []; -} - -function _nextPow16(v) { - for (let i = 16; i <= (1 << 28); i *= 16) { - if (v <= i) { - return i; - } - } - return 0; -} - -function _log2(v) { - let r, shift; - r = (v > 0xFFFF) << 4; v >>>= r; - shift = (v > 0xFF) << 3; v >>>= shift; r |= shift; - shift = (v > 0xF) << 2; v >>>= shift; r |= shift; - shift = (v > 0x3) << 1; v >>>= shift; r |= shift; - return r | (v >> 1); -} - -function _alloc(n) { - let sz = _nextPow16(n); - let bin = _bufferPools[_log2(sz) >> 2]; - if (bin.length > 0) { - return bin.pop(); - } - return new ArrayBuffer(sz); -} - -function _free(buf) { - _bufferPools[_log2(buf.byteLength) >> 2].push(buf); -} - -export default { - alloc_int8(n) { - let result = new Int8Array(_alloc(n), 0, n); - if (result.length !== n) { - return result.subarray(0, n); - } - - return result; - }, - - alloc_uint8(n) { - let result = new Uint8Array(_alloc(n), 0, n); - if (result.length !== n) { - return result.subarray(0, n); - } - - return result; - }, - - alloc_int16(n) { - let result = new Int16Array(_alloc(2 * n), 0, n); - if (result.length !== n) { - return result.subarray(0, n); - } - - return result; - }, - - alloc_uint16(n) { - let result = new Uint16Array(_alloc(2 * n), 0, n); - if (result.length !== n) { - return result.subarray(0, n); - } - - return result; - }, - - alloc_int32(n) { - let result = new Int32Array(_alloc(4 * n), 0, n); - if (result.length !== n) { - return result.subarray(0, n); - } - - return result; - }, - - alloc_uint32(n) { - let result = new Uint32Array(_alloc(4 * n), 0, n); - if (result.length !== n) { - return result.subarray(0, n); - } - - return result; - }, - - alloc_float32(n) { - let result = new Float32Array(_alloc(4 * n), 0, n); - if (result.length !== n) { - return result.subarray(0, n); - } - - return result; - }, - - alloc_float64(n) { - let result = new Float64Array(_alloc(8 * n), 0, n); - if (result.length !== n) { - return result.subarray(0, n); - } - - return result; - }, - - alloc_dataview(n) { - let result = new DataView(_alloc(n), 0, n); - if (result.length !== n) { - return result.subarray(0, n); - } - - return result; - }, - - free(array) { - _free(array.buffer); - }, - - reset() { - let _bufferPools = Array(8); - for (let i = 0; i < 8; ++i) { - _bufferPools[i] = []; - } - }, -}; \ No newline at end of file diff --git a/cocos/3d/memop/typed-array-pool.ts b/cocos/3d/memop/typed-array-pool.ts new file mode 100644 index 0000000000..11af4a3ac5 --- /dev/null +++ b/cocos/3d/memop/typed-array-pool.ts @@ -0,0 +1,128 @@ +let _bufferPools: ArrayBuffer[][] = Array(8); +for (let i = 0; i < 8; ++i) { + _bufferPools[i] = []; +} + +function _nextPow16 (v) { + for (let i = 16; i <= (1 << 28); i *= 16) { + if (v <= i) { + return i; + } + } + return 0; +} + +function _log2 (v: number) { + let r = ((v > 0xFFFF) as unknown as number) << 4; v >>>= r; + let shift = ((v > 0xFF) as unknown as number) << 3; v >>>= shift; r |= shift; + shift = ((v > 0xF) as unknown as number) << 2; v >>>= shift; r |= shift; + shift = ((v > 0x3) as unknown as number) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +function _alloc (n: number) { + const sz = _nextPow16(n); + const bin = _bufferPools[_log2(sz) >> 2]; + if (bin.length > 0) { + return bin.pop() as ArrayBuffer; + } + return new ArrayBuffer(sz); +} + +function _free (buf) { + _bufferPools[_log2(buf.byteLength) >> 2].push(buf); +} + +export default { + alloc_int8 (n) { + const result = new Int8Array(_alloc(n), 0, n); + if (result.length !== n) { + return result.subarray(0, n); + } + + return result; + }, + + alloc_uint8 (n) { + const result = new Uint8Array(_alloc(n), 0, n); + if (result.length !== n) { + return result.subarray(0, n); + } + + return result; + }, + + alloc_int16 (n) { + const result = new Int16Array(_alloc(2 * n), 0, n); + if (result.length !== n) { + return result.subarray(0, n); + } + + return result; + }, + + alloc_uint16 (n) { + const result = new Uint16Array(_alloc(2 * n), 0, n); + if (result.length !== n) { + return result.subarray(0, n); + } + + return result; + }, + + alloc_int32 (n) { + const result = new Int32Array(_alloc(4 * n), 0, n); + if (result.length !== n) { + return result.subarray(0, n); + } + + return result; + }, + + alloc_uint32 (n) { + const result = new Uint32Array(_alloc(4 * n), 0, n); + if (result.length !== n) { + return result.subarray(0, n); + } + + return result; + }, + + alloc_float32 (n) { + const result = new Float32Array(_alloc(4 * n), 0, n); + if (result.length !== n) { + return result.subarray(0, n); + } + + return result; + }, + + alloc_float64 (n) { + const result = new Float64Array(_alloc(8 * n), 0, n); + if (result.length !== n) { + return result.subarray(0, n); + } + + return result; + }, + + // alloc_dataview (n) { + // const result = new DataView(_alloc(n), 0, n); + // if (result.length !== n) { + // return result.subarray(0, n); + // } + + // return result; + // }, + + free (array) { + _free(array.buffer); + }, + + reset () { + _bufferPools = Array(8); + for (let i = 0; i < 8; ++i) { + _bufferPools[i] = []; + } + }, +}; diff --git a/cocos/3d/misc/async.js b/cocos/3d/misc/async.js deleted file mode 100644 index 9ec658d1ce..0000000000 --- a/cocos/3d/misc/async.js +++ /dev/null @@ -1,23 +0,0 @@ -function parallel(tasks, callback) { - let length = tasks.length; - if (length === 0) { - callback(null); - } - - let completed = 0; - - for (let i = 0; i < tasks.length; ++i) { - let task = tasks[i]; - task(err => { - if (err) { - callback(err); - } else if (++completed === length) { - callback(null); - } - }); - } -} - -export default { - parallel -}; \ No newline at end of file diff --git a/cocos/3d/misc/index.js b/cocos/3d/misc/index.js deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cocos/3d/misc/mappings.js b/cocos/3d/misc/mappings.js deleted file mode 100644 index dd4f12bab2..0000000000 --- a/cocos/3d/misc/mappings.js +++ /dev/null @@ -1,48 +0,0 @@ -import gfx from '../../renderer/gfx'; - -export const gfxFilters = { - 'linear': gfx.FILTER_LINEAR, - 'nearest': gfx.FILTER_NEAREST, -}; - -export const gfxWraps = { - 'repeat': gfx.WRAP_REPEAT, - 'clamp': gfx.WRAP_CLAMP, - 'mirror': gfx.WRAP_MIRROR, -}; - -export const gfxTextureFmts = { - // compress formats - 'rgb-dxt1': gfx.TEXTURE_FMT_RGB_DXT1, - 'rgba-dxt1': gfx.TEXTURE_FMT_RGBA_DXT1, - 'rgba-dxt3': gfx.TEXTURE_FMT_RGBA_DXT3, - 'rgba-dxt5': gfx.TEXTURE_FMT_RGBA_DXT5, - 'rgb-etc1': gfx.TEXTURE_FMT_RGB_ETC1, - 'rgb-pvrtc-2bppv1': gfx.TEXTURE_FMT_RGB_PVRTC_2BPPV1, - 'rgba-pvrtc-2bppv1': gfx.TEXTURE_FMT_RGBA_PVRTC_2BPPV1, - 'rgb-pvrtc-4bppv1': gfx.TEXTURE_FMT_RGB_PVRTC_4BPPV1, - 'rgba-pvrtc-4bppv1': gfx.TEXTURE_FMT_RGBA_PVRTC_4BPPV1, - - // normal formats - 'a8': gfx.TEXTURE_FMT_A8, - 'l8': gfx.TEXTURE_FMT_L8, - 'l8-a8': gfx.TEXTURE_FMT_L8_A8, - 'r5-g6-b5': gfx.TEXTURE_FMT_R5_G6_B5, - 'r5-g5-b5-a1': gfx.TEXTURE_FMT_R5_G5_B5_A1, - 'r4-g4-b4-a4': gfx.TEXTURE_FMT_R4_G4_B4_A4, - 'rgb8': gfx.TEXTURE_FMT_RGB8, - 'rgba8': gfx.TEXTURE_FMT_RGBA8, - 'rgb16f': gfx.TEXTURE_FMT_RGB16F, - 'rgba16f': gfx.TEXTURE_FMT_RGBA16F, - 'rgb32f': gfx.TEXTURE_FMT_RGB32F, - 'rgba32f': gfx.TEXTURE_FMT_RGBA32F, - 'r32f': gfx.TEXTURE_FMT_R32F, - '111110f': gfx.TEXTURE_FMT_111110F, - 'srgb': gfx.TEXTURE_FMT_SRGB, - 'srgba': gfx.TEXTURE_FMT_SRGBA, - - // depth formats - 'd16': gfx.TEXTURE_FMT_D16, - 'd32': gfx.TEXTURE_FMT_D32, - 'd24s8': gfx.TEXTURE_FMT_D24S8, -}; diff --git a/cocos/3d/misc/path.js b/cocos/3d/misc/path.js deleted file mode 100644 index 28232efb0e..0000000000 --- a/cocos/3d/misc/path.js +++ /dev/null @@ -1,26 +0,0 @@ -function _normalize (url) { - return url - .replace(/\\/g, '/') - .replace(/[\/]+/g, '/') - .replace(/\/\?/g, '?') - .replace(/\/\#/g, '#') - .replace(/\:\//g, '://'); -} - -export default { - /** - * @method normalize - * @param {string} url - */ - normalize(url) { - return _normalize(url); - }, - - /** - * @method join - */ - join() { - let joined = [].slice.call(arguments, 0).join('/'); - return _normalize(joined); - }, -}; \ No newline at end of file diff --git a/cocos/3d/misc/registry.js b/cocos/3d/misc/registry.js deleted file mode 100644 index 0fa98257c7..0000000000 --- a/cocos/3d/misc/registry.js +++ /dev/null @@ -1,52 +0,0 @@ -let _loaderInfos = []; -let _classInfos = []; -let _typeInfos = []; -let _systemInfos = []; - -export default { - registerLoader(id, def) { - _loaderInfos.push({ - id, def - }); - }, - - registerType(id, def) { - _typeInfos.push({ - id, def - }); - }, - - registerClass(id, def) { - _classInfos.push({ - id, def - }); - }, - - registerSystem(id, system, component, priority) { - _systemInfos.push({ - id, system, component, priority - }); - }, - - _init (app) { - for (let i = 0; i < _loaderInfos.length; ++i) { - let info = _loaderInfos[i]; - app._assetMng.registerLoader(info.id, info.def); - } - - for (let i = 0; i < _typeInfos.length; ++i) { - let info = _typeInfos[i]; - app.registerType(info.id, info.def); - } - - for (let i = 0; i < _classInfos.length; ++i) { - let info = _classInfos[i]; - app.registerClass(info.id, info.def); - } - - for (let i = 0; i < _systemInfos.length; ++i) { - let info = _systemInfos[i]; - app.registerSystem(info.id, info.system, info.component, info.priority); - } - } -}; \ No newline at end of file diff --git a/cocos/3d/misc/resl.js b/cocos/3d/misc/resl.js deleted file mode 100644 index d93962c900..0000000000 --- a/cocos/3d/misc/resl.js +++ /dev/null @@ -1,426 +0,0 @@ -/** - * (c) 2016 Mikola Lysenko. MIT License - * https://github.com/regl-project/resl - */ - -/* global XMLHttpRequest */ -const configParameters = [ - 'manifest', - 'onDone', - 'onProgress', - 'onError' -]; - -const manifestParameters = [ - 'type', - 'src', - 'stream', - 'credentials', - 'parser' -]; - -const parserParameters = [ - 'onData', - 'onDone' -]; - -const STATE_ERROR = -1; -const STATE_DATA = 0; -const STATE_COMPLETE = 1; - -function raise(message) { - throw new Error('resl: ' + message); -} - -function checkType(object, parameters, name) { - Object.keys(object).forEach(function (param) { - if (parameters.indexOf(param) < 0) { - raise('invalid parameter "' + param + '" in ' + name); - } - }); -} - -function Loader(name, cancel) { - this.state = STATE_DATA; - this.ready = false; - this.progress = 0; - this.name = name; - this.cancel = cancel; -} - -export default function resl(config) { - if (typeof config !== 'object' || !config) { - raise('invalid or missing configuration'); - } - - checkType(config, configParameters, 'config'); - - let manifest = config.manifest; - if (typeof manifest !== 'object' || !manifest) { - raise('missing manifest'); - } - - function getFunction(name) { - if (name in config) { - let func = config[name]; - if (typeof func !== 'function') { - raise('invalid callback "' + name + '"'); - } - return func; - } - return null; - } - - let onDone = getFunction('onDone'); - if (!onDone) { - raise('missing onDone() callback'); - } - - let onProgress = getFunction('onProgress'); - let onError = getFunction('onError'); - - let assets = {}; - - let state = STATE_DATA; - - function loadXHR(request) { - let name = request.name; - let stream = request.stream; - let binary = request.type === 'binary'; - let parser = request.parser; - - let xhr = new XMLHttpRequest(); - let asset = null; - - let loader = new Loader(name, cancel); - - if (stream) { - xhr.onreadystatechange = onReadyStateChange; - } else { - xhr.onreadystatechange = function () { - if (xhr.readyState === 4) { - onReadyStateChange(); - } - }; - } - - if (binary) { - xhr.responseType = 'arraybuffer'; - } - - function onReadyStateChange() { - if (xhr.readyState < 2 || - loader.state === STATE_COMPLETE || - loader.state === STATE_ERROR) { - return; - } - if (xhr.status !== 200) { - return abort('error loading resource "' + request.name + '"'); - } - if (xhr.readyState > 2 && loader.state === STATE_DATA) { - let response; - if (request.type === 'binary') { - response = xhr.response; - } else { - response = xhr.responseText; - } - if (parser.data) { - try { - asset = parser.data(response); - } catch (e) { - return abort(e); - } - } else { - asset = response; - } - } - if (xhr.readyState > 3 && loader.state === STATE_DATA) { - if (parser.done) { - try { - asset = parser.done(); - } catch (e) { - return abort(e); - } - } - loader.state = STATE_COMPLETE; - } - assets[name] = asset; - loader.progress = 0.75 * loader.progress + 0.25; - loader.ready = - (request.stream && !!asset) || - loader.state === STATE_COMPLETE; - notifyProgress(); - } - - function cancel() { - if (loader.state === STATE_COMPLETE || loader.state === STATE_ERROR) { - return; - } - xhr.onreadystatechange = null; - xhr.abort(); - loader.state = STATE_ERROR; - } - - // set up request - if (request.credentials) { - xhr.withCredentials = true; - } - xhr.open('GET', request.src, true); - xhr.send(); - - return loader; - } - - function loadElement(request, element) { - let name = request.name; - let parser = request.parser; - - let loader = new Loader(name, cancel); - let asset = element; - - function handleProgress() { - if (loader.state === STATE_DATA) { - if (parser.data) { - try { - asset = parser.data(element); - } catch (e) { - return abort(e); - } - } else { - asset = element; - } - } - } - - function onProgress(e) { - handleProgress(); - assets[name] = asset; - if (e.lengthComputable) { - loader.progress = Math.max(loader.progress, e.loaded / e.total); - } else { - loader.progress = 0.75 * loader.progress + 0.25; - } - notifyProgress(name); - } - - let completed = false; - function onComplete() { - if (completed) return; - completed = true; - handleProgress(); - if (loader.state === STATE_DATA) { - if (parser.done) { - try { - asset = parser.done(); - } catch (e) { - return abort(e); - } - } - loader.state = STATE_COMPLETE; - } - loader.progress = 1; - loader.ready = true; - assets[name] = asset; - removeListeners(); - notifyProgress('finish ' + name); - } - - function onError() { - abort('error loading asset "' + name + '"'); - } - - if (request.stream) { - element.addEventListener('progress', onProgress); - } - if (request.type === 'image') { - element.addEventListener('load', onComplete); - } else { - // 'canplay' event is not supported on iOS - element.addEventListener('loadedmetadata', onComplete); - // there is no event in ios wechat browser - setTimeout(onComplete, 5000); - // TODO: could do platform-specific switching here - } - element.addEventListener('error', onError); - - function removeListeners() { - if (request.stream) { - element.removeEventListener('progress', onProgress); - } - if (request.type === 'image') { - element.removeEventListener('load', onComplete); - } else { - element.removeEventListener('loadedmetadata', onComplete); - } - element.removeEventListener('error', onError); - } - - function cancel() { - if (loader.state === STATE_COMPLETE || loader.state === STATE_ERROR) { - return; - } - - loader.state = STATE_ERROR; - removeListeners(); - element.src = ''; - } - - // set up request - if (request.credentials) { - element.crossOrigin = 'use-credentials'; - } else { - element.crossOrigin = 'anonymous'; - } - element.src = request.src; - - return loader; - } - - let loaders = { - text: loadXHR, - binary: function (request) { - // TODO use fetch API for streaming if supported - return loadXHR(request); - }, - image: function (request) { - return loadElement(request, document.createElement('img')); - }, - video: function (request) { - return loadElement(request, document.createElement('video')); - }, - audio: function (request) { - return loadElement(request, document.createElement('audio')); - } - }; - - // First we parse all objects in order to verify that all type information - // is correct - let pending = Object.keys(manifest).map(function (name) { - let request = manifest[name]; - if (typeof request === 'string') { - request = { - src: request - }; - } else if (typeof request !== 'object' || !request) { - raise('invalid asset definition "' + name + '"'); - } - - checkType(request, manifestParameters, 'asset "' + name + '"'); - - function getParameter(prop, accepted, init) { - let value = init; - if (prop in request) { - value = request[prop]; - } - if (accepted.indexOf(value) < 0) { - raise('invalid ' + prop + ' "' + value + '" for asset "' + name + '", possible values: ' + accepted); - } - return value; - } - - function getString(prop, required, init) { - let value = init; - if (prop in request) { - value = request[prop]; - } else if (required) { - raise('missing ' + prop + ' for asset "' + name + '"'); - } - if (typeof value !== 'string') { - raise('invalid ' + prop + ' for asset "' + name + '", must be a string'); - } - return value; - } - - function getParseFunc(name, dflt) { - if (name in request.parser) { - let result = request.parser[name]; - if (typeof result !== 'function') { - raise('invalid parser callback ' + name + ' for asset "' + name + '"'); - } - return result; - } else { - return dflt; - } - } - - let parser = {}; - if ('parser' in request) { - if (typeof request.parser === 'function') { - parser = { - data: request.parser - }; - } else if (typeof request.parser === 'object' && request.parser) { - checkType(request.parser, parserParameters, 'parser for asset "' + name + '"'); - if (!('onData' in request.parser)) { - raise('missing onData callback for parser in asset "' + name + '"'); - } - parser = { - data: getParseFunc('onData'), - done: getParseFunc('onDone') - }; - } else { - raise('invalid parser for asset "' + name + '"'); - } - } - - return { - name: name, - type: getParameter('type', Object.keys(loaders), 'text'), - stream: !!request.stream, - credentials: !!request.credentials, - src: getString('src', true, ''), - parser: parser - }; - }).map(function (request) { - return (loaders[request.type])(request); - }); - - function abort(message) { - if (state === STATE_ERROR || state === STATE_COMPLETE) { - return; - } - state = STATE_ERROR; - pending.forEach(function (loader) { - loader.cancel(); - }); - if (onError) { - if (typeof message === 'string') { - onError(new Error('resl: ' + message)); - } else { - onError(message); - } - } else { - console.error('resl error:', message); - } - } - - function notifyProgress(message) { - if (state === STATE_ERROR || state === STATE_COMPLETE) { - return; - } - - let progress = 0; - let numReady = 0; - pending.forEach(function (loader) { - if (loader.ready) { - numReady += 1; - } - progress += loader.progress; - }); - - if (numReady === pending.length) { - state = STATE_COMPLETE; - onDone(assets); - } else { - if (onProgress) { - onProgress(progress / pending.length, message); - } - } - } - - if (pending.length === 0) { - setTimeout(function () { - notifyProgress('done'); - }, 1); - } -} \ No newline at end of file diff --git a/cocos/3d/physics/ammo/debugger.ts b/cocos/3d/physics/ammo/debugger.ts index 4277b40f6c..d2f026610b 100644 --- a/cocos/3d/physics/ammo/debugger.ts +++ b/cocos/3d/physics/ammo/debugger.ts @@ -62,14 +62,14 @@ export class Debugger implements Ammo.btIDebugDraw { defines: { USE_COLOR: true, }, + states: { + primitive: cc.GFXPrimitiveMode.LINE_LIST, + // depthStencilState: { + // depthFunc: GFXComparisonFunc.LESS_EQUAL, + // }, + } }); material.setProperty('color', new Color(0, 255, 0, 255)); - material.overridePipelineStates({ - primitive: cc.GFXPrimitiveMode.LINE_LIST, - // depthStencilState: { - // depthFunc: GFXComparisonFunc.LESS_EQUAL, - // }, - }); this._modelComponent.sharedMaterials = [ material ]; } } diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts index 67999365b0..fd4469ae07 100644 --- a/cocos/3d/ui/components/label-component.ts +++ b/cocos/3d/ui/components/label-component.ts @@ -31,6 +31,8 @@ import { ImageAsset } from '../../../assets/image-asset'; import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { ccenum } from '../../../core/value-types/enum'; import { UI } from '../../../renderer/ui/ui'; +import { Material } from '../../assets'; +import { RenderableComponent } from '../../framework/renderable-component'; import { FontAtlas } from '../assembler/label/bmfontUtils'; import { ISharedLabelData } from '../assembler/label/ttfUtils'; import { UIRenderComponent } from './ui-render-component'; @@ -618,6 +620,22 @@ export class LabelComponent extends UIRenderComponent { return result; } + protected _instanceMaterial () { + if (this._sharedMaterial) { + this._updateMaterial( + Material.getInstantiatedMaterial(this._sharedMaterial, + new RenderableComponent(), + CC_EDITOR ? true : false, + )); + } else { + this._updateMaterial( + Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), + new RenderableComponent(), + CC_EDITOR ? true : false, + )); + } + } + private _checkStringEmpty () { this._renderPermit = !!this.string; } diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/3d/ui/components/mask-component.ts index 44feb29ce4..f444a963c8 100644 --- a/cocos/3d/ui/components/mask-component.ts +++ b/cocos/3d/ui/components/mask-component.ts @@ -270,6 +270,22 @@ export class MaskComponent extends UIRenderComponent { return this._maskMaterial !== null && this._clearMaskMaterial !== null && this._renderPermit; } + protected _instanceMaterial () { + if (this._sharedMaterial) { + this._updateMaterial( + Material.getInstantiatedMaterial(this._sharedMaterial, + new RenderableComponent(), + CC_EDITOR ? true : false, + )); + } else { + this._updateMaterial( + Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-base'), + new RenderableComponent(), + CC_EDITOR ? true : false, + )); + } + } + // _resizeNodeToTargetNode: CC_EDITOR && function () { // if (this.spriteFrame) { // const rect = this.spriteFrame.getRect(); diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 4cdfe10c52..767e7cbcff 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -32,6 +32,8 @@ import { clampf } from '../../../core/utils/misc'; import { Vec2 } from '../../../core/value-types'; import { ccenum } from '../../../core/value-types/enum'; import { UI } from '../../../renderer/ui/ui'; +import { Material } from '../../assets'; +import { RenderableComponent } from '../../framework/renderable-component'; import { UIRenderComponent } from './ui-render-component'; /** @@ -353,7 +355,9 @@ export class SpriteComponent extends UIRenderComponent { * @example * sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM; */ - @property() + @property({ + type: SizeMode, + }) get sizeMode () { return this._sizeMode; } @@ -514,6 +518,22 @@ export class SpriteComponent extends UIRenderComponent { return canRender; } + protected _instanceMaterial () { + if (this._sharedMaterial) { + this._updateMaterial( + Material.getInstantiatedMaterial(this._sharedMaterial, + new RenderableComponent(), + CC_EDITOR ? true : false, + )); + } else { + this._updateMaterial( + Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), + new RenderableComponent(), + CC_EDITOR ? true : false, + )); + } + } + private _flushAssembler () { const assembler = SpriteComponent.Assembler!.getAssembler(this); diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts index 467b05eb03..fb66a64131 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -38,7 +38,6 @@ import { GFXBlendFactor } from '../../../gfx/define'; import { RenderData } from '../../../renderer/ui/renderData'; import { UI } from '../../../renderer/ui/ui'; import { Material } from '../../assets/material'; -import { RenderableComponent } from '../../framework/renderable-component'; import { IAssembler, IAssemblerManager } from '../assembler/assembler'; import { CanvasComponent } from './canvas-component'; import { UITransformComponent } from './ui-transfrom-component'; @@ -120,6 +119,10 @@ export class UIRenderComponent extends Component { } set priority (value) { + if (this._priority === value) { + return; + } + this._priority = value; } @@ -160,7 +163,9 @@ export class UIRenderComponent extends Component { } this._sharedMaterial = value; - this._instanceMaterial(); + if (this._instanceMaterial) { + this._instanceMaterial(); + } } get material () { @@ -226,7 +231,9 @@ export class UIRenderComponent extends Component { } public __preload (){ - this._instanceMaterial(); + if (this._instanceMaterial) { + this._instanceMaterial(); + } } public onEnable () { @@ -271,6 +278,10 @@ export class UIRenderComponent extends Component { // } // this._allocedDatas.length = 0; this.destroyRenderData(); + if (this._material){ + this._material.destroy(); + } + this._updateMaterial(null); this._renderData = null; } @@ -381,11 +392,7 @@ export class UIRenderComponent extends Component { } } - private _instanceMaterial (){ - if (this._sharedMaterial) { - this._updateMaterial(Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false)); - } - } + protected _instanceMaterial? (): void; } cc.UIRenderComponent = UIRenderComponent; diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index a058eb61d1..9b01c98083 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -32,6 +32,7 @@ import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat, import { GFXDevice } from '../gfx/device'; import { GFXTexture, IGFXTextureInfo } from '../gfx/texture'; import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view'; +import { SamplerInfoIndex } from '../renderer/core/sampler-lib'; import { Asset } from './asset'; import { ImageAsset } from './image-asset'; @@ -313,10 +314,10 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param wrapR */ public setWrapMode (wrapS: WrapMode, wrapT: WrapMode, wrapR?: WrapMode) { - if (wrapS !== this._wrapS) { this._wrapS = wrapS; this._samplerInfo[3] = wrapS; } - if (wrapT !== this._wrapT) { this._wrapT = wrapT; this._samplerInfo[4] = wrapT; } + if (wrapS !== this._wrapS) { this._wrapS = wrapS; this._samplerInfo[SamplerInfoIndex.addressU] = wrapS; } + if (wrapT !== this._wrapT) { this._wrapT = wrapT; this._samplerInfo[SamplerInfoIndex.addressV] = wrapT; } if (wrapR === undefined) { return; } - if (wrapR !== this._wrapR) { this._wrapR = wrapR; this._samplerInfo[5] = wrapR; } + if (wrapR !== this._wrapR) { this._wrapR = wrapR; this._samplerInfo[SamplerInfoIndex.addressW] = wrapR; } } /** @@ -326,8 +327,8 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param magFilter */ public setFilters (minFilter: Filter, magFilter: Filter) { - if (minFilter !== this._minFilter) { this._minFilter = minFilter; this._samplerInfo[0] = minFilter; } - if (magFilter !== this._magFilter) { this._magFilter = magFilter; this._samplerInfo[1] = magFilter; } + if (minFilter !== this._minFilter) { this._minFilter = minFilter; this._samplerInfo[SamplerInfoIndex.minFilter] = minFilter; } + if (magFilter !== this._magFilter) { this._magFilter = magFilter; this._samplerInfo[SamplerInfoIndex.magFilter] = magFilter; } } /** @@ -336,7 +337,7 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param mipFilter */ public setMipFilter (mipFilter: Filter) { - if (mipFilter !== this._mipFilter) { this._mipFilter = mipFilter; this._samplerInfo[2] = mipFilter; } + if (mipFilter !== this._mipFilter) { this._mipFilter = mipFilter; this._samplerInfo[SamplerInfoIndex.mipFilter] = mipFilter; } } /** @@ -365,7 +366,7 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param anisotropy */ public setAnisotropy (anisotropy: number) { - if (anisotropy !== this._anisotropy) { this._anisotropy = anisotropy; this._samplerInfo[6] = anisotropy; } + if (anisotropy !== this._anisotropy) { this._anisotropy = anisotropy; this._samplerInfo[SamplerInfoIndex.maxAnisotropy] = anisotropy; } } /** diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index d9a98d9bb8..d6c7242819 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -138,6 +138,19 @@ export abstract class GFXInputAssembler extends GFXObject { drawInfo.firstInstance = this._firstInstance; } + /** + * update VB data on the fly. + * @param vbuffer - an ArrayBuffer containing the full VB + * @param attr - name of the attribute to update (default names are specified in GFXAttributeName) + * @param data - the new VB attribute data to be uploaded + * @example + * // get VB array buffer from mesh, better to cache this somewhere convenient + * const vbInfo = mesh.struct.vertexBundles[0].data; + * const vbuffer = mesh.data.buffer.slice(vbInfo.offset, vbInfo.offset + vbInfo.length); + * const submodel = someModelComponent.model.getSubModel(0); + * // say the new positions is stored in 'data' as a plain array + * submodel.inputAssembler.updateVertexBuffer(vbuffer, cc.GFXAttributeName.ATTR_POSITION, data); + */ public updateVertexAttr (vbuffer: GFXBufferSource, attr: string, data: number[]) { let offset = 0; let count = 0; @@ -166,6 +179,19 @@ export abstract class GFXInputAssembler extends GFXObject { vb.update(vbuffer); } + /** + * update IB data on the fly. + * need to call submodel.updateCommandBuffer after this if index count changed + * @param ibuffer - an ArrayBuffer containing the full IB + * @param data - the new IB data to be uploaded + * @example + * // get IB array buffer from mesh, better to cache this somewhere convenient + * const ibInfo = mesh.struct.primitives[0].indices.range; + * submesh.ibuffer = mesh.data.buffer.slice(ibInfo.offset, ibInfo.offset + ibInfo.length); + * const submodel = someModelComponent.model.getSubModel(0); + * submodel.inputAssembler.updateIndexBuffer(ibuffer, [0, 1, 2]); + * submodel.updateCommandBuffer(); // index count changed + */ public updateIndexBuffer (ibuffer: GFXBufferSource, data: number[]) { const count = this._indexCount; const ib = this._indexBuffer; diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index acde4cbf78..846375da77 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -312,10 +312,13 @@ export class WebGLGFXDevice extends GFXDevice { // console.info('MAX_VERTEX_ATTRIBS: ' + this._maxVertexAttributes); console.info('MAX_VERTEX_UNIFORM_VECTORS: ' + this._maxVertexUniformVectors); console.info('MAX_FRAGMENT_UNIFORM_VECTORS: ' + this._maxFragmentUniformVectors); - console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits); + // console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits); // console.info('MAX_VERTEX_TEXTURE_IMAGE_UNITS: ' + this._maxVertexTextureUnits); console.info('DEPTH_BITS: ' + this._depthBits); console.info('STENCIL_BITS: ' + this._stencilBits); + if (this._EXT_texture_filter_anisotropic) { + console.info('MAX_TEXTURE_MAX_ANISOTROPY_EXT: ' + this._EXT_texture_filter_anisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } console.info('USE_VAO: ' + this._useVAO); // init states diff --git a/cocos/gfx/webgl2/webgl2-commands.ts b/cocos/gfx/webgl2/webgl2-commands.ts index 35d02f2f08..3b54c6f4db 100644 --- a/cocos/gfx/webgl2/webgl2-commands.ts +++ b/cocos/gfx/webgl2/webgl2-commands.ts @@ -1516,8 +1516,6 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W let gpuShader: WebGL2GPUShader | null = null; let gpuInputAssembler: IWebGL2GPUInputAssembler | null = null; let glPrimitive = WebGL2RenderingContext.TRIANGLES; - let glWrapS; - let glWrapT; for (let i = 0; i < cmdPackage.cmds.length; ++i) { const cmd = cmdPackage.cmds.array[i]; @@ -2015,15 +2013,6 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W } } - const gpuSampler = gpuBinding.gpuSampler; - if (gpuTexture.isPowerOf2) { - glWrapS = gpuSampler.glWrapS; - glWrapT = gpuSampler.glWrapT; - } else { - glWrapS = WebGLRenderingContext.CLAMP_TO_EDGE; - glWrapT = WebGLRenderingContext.CLAMP_TO_EDGE; - } - if (cache.glSamplerUnits[texUnit] !== gpuBinding.gpuSampler.glSampler) { gl.bindSampler(texUnit, gpuBinding.gpuSampler.glSampler); cache.glSamplerUnits[texUnit] = gpuBinding.gpuSampler.glSampler; diff --git a/cocos/gfx/webgl2/webgl2-device.ts b/cocos/gfx/webgl2/webgl2-device.ts index 98f483c46a..12f586f030 100644 --- a/cocos/gfx/webgl2/webgl2-device.ts +++ b/cocos/gfx/webgl2/webgl2-device.ts @@ -3,7 +3,7 @@ import { GFXBindingLayout, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXBuffer, IGFXBufferInfo } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; -import { GFXBufferTextureCopy, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXQueueType } from '../define'; +import { GFXBufferTextureCopy, GFXFormat, GFXFormatSize, GFXQueueType } from '../define'; import { GFXAPI, GFXDevice, GFXFeature, IGFXDeviceInfo } from '../device'; import { GFXFramebuffer, IGFXFramebufferInfo } from '../framebuffer'; import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler'; @@ -20,7 +20,7 @@ import { WebGL2GFXBindingLayout } from './webgl2-binding-layout'; import { WebGL2GFXBuffer } from './webgl2-buffer'; import { WebGL2GFXCommandAllocator } from './webgl2-command-allocator'; import { WebGL2GFXCommandBuffer } from './webgl2-command-buffer'; -import { WebGL2CmdFuncCopyTexImagesToTexture, WebGL2CmdFuncCopyBuffersToTexture } from './webgl2-commands'; +import { WebGL2CmdFuncCopyBuffersToTexture, WebGL2CmdFuncCopyTexImagesToTexture } from './webgl2-commands'; import { WebGL2GFXFramebuffer } from './webgl2-framebuffer'; import { WebGL2GFXInputAssembler } from './webgl2-input-assembler'; import { WebGL2GFXPipelineLayout } from './webgl2-pipeline-layout'; @@ -229,7 +229,7 @@ export class WebGL2GFXDevice extends GFXDevice { // console.info('MAX_VERTEX_ATTRIBS: ' + this._maxVertexAttributes); console.info('MAX_VERTEX_UNIFORM_VECTORS: ' + this._maxVertexUniformVectors); console.info('MAX_FRAGMENT_UNIFORM_VECTORS: ' + this._maxFragmentUniformVectors); - console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits); + // console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits); // console.info('MAX_VERTEX_TEXTURE_IMAGE_UNITS: ' + this._maxVertexTextureUnits); console.info('MAX_UNIFORM_BUFFER_BINDINGS: ' + this._maxUniformBufferBindings); // console.info('MAX_UNIFORM_BLOCK_SIZE: ' + this._maxUniformBlockSize); @@ -237,6 +237,9 @@ export class WebGL2GFXDevice extends GFXDevice { console.info('DEPTH_BITS: ' + this._depthBits); console.info('STENCIL_BITS: ' + this._stencilBits); // console.info('UNIFORM_BUFFER_OFFSET_ALIGNMENT: ' + uboOffsetAlignment); + if (this._EXT_texture_filter_anisotropic) { + console.info('MAX_TEXTURE_MAX_ANISOTROPY_EXT: ' + this._EXT_texture_filter_anisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } console.info('USE_VAO: ' + this._useVAO); // init states diff --git a/cocos/load-pipeline/uuid-loader.js b/cocos/load-pipeline/uuid-loader.js index bca06ad566..24fffae194 100644 --- a/cocos/load-pipeline/uuid-loader.js +++ b/cocos/load-pipeline/uuid-loader.js @@ -290,7 +290,13 @@ export function loadUuid (item, callback) { cc.deserialize.Details.pool.put(tdInfo); var wrappedCallback = function(err, asset) { - if (!err && asset.onLoaded) asset.onLoaded(); + if (!err && asset.onLoaded) { + try { + asset.onLoaded(); + } catch(error) { + err = error; + } + } callback(err, asset); }; diff --git a/cocos/pipeline/define.ts b/cocos/pipeline/define.ts index 4be6b88ce7..dd471db082 100644 --- a/cocos/pipeline/define.ts +++ b/cocos/pipeline/define.ts @@ -1,9 +1,12 @@ import { GFXBuffer } from '../gfx/buffer'; -import { GFXBindingType, GFXType, IGFXColor } from '../gfx/define'; +import { GFXBindingType, GFXType } from '../gfx/define'; import { GFXSampler } from '../gfx/sampler'; import { GFXUniformBlock, GFXUniformSampler } from '../gfx/shader'; import { GFXTextureView } from '../gfx/texture-view'; -import { Vec3 } from '../core/value-types'; + +export const PIPELINE_FLOW_FORWARD: string = 'ForwardFlow'; +export const PIPELINE_FLOW_SMAA: string = 'SMAAFlow'; +export const PIPELINE_FLOW_TONEMAP: string = 'ToneMapFlow'; export enum RenderPassStage { DEFAULT = 100, @@ -33,7 +36,8 @@ export class UBOGlobal { public static TIME_OFFSET: number = 0; public static SCREEN_SIZE_OFFSET: number = UBOGlobal.TIME_OFFSET + 4; public static SCREEN_SCALE_OFFSET: number = UBOGlobal.SCREEN_SIZE_OFFSET + 4; - public static MAT_VIEW_OFFSET: number = UBOGlobal.SCREEN_SCALE_OFFSET + 4; + public static NATIVE_SIZE_OFFSET: number = UBOGlobal.SCREEN_SCALE_OFFSET + 4; + public static MAT_VIEW_OFFSET: number = UBOGlobal.NATIVE_SIZE_OFFSET + 4; public static MAT_VIEW_INV_OFFSET: number = UBOGlobal.MAT_VIEW_OFFSET + 16; public static MAT_PROJ_OFFSET: number = UBOGlobal.MAT_VIEW_INV_OFFSET + 16; public static MAT_PROJ_INV_OFFSET: number = UBOGlobal.MAT_PROJ_OFFSET + 16; @@ -53,6 +57,7 @@ export class UBOGlobal { { name: 'cc_time', type: GFXType.FLOAT4, count: 1 }, { name: 'cc_screenSize', type: GFXType.FLOAT4, count: 1 }, { name: 'cc_screenScale', type: GFXType.FLOAT4, count: 1 }, + { name: 'cc_nativeSize', type: GFXType.FLOAT4, count: 1 }, { name: 'cc_matView', type: GFXType.MAT4, count: 1 }, { name: 'cc_matViewInv', type: GFXType.MAT4, count: 1 }, { name: 'cc_matProj', type: GFXType.MAT4, count: 1 }, @@ -114,9 +119,10 @@ export class UBOForwardLight { public static SPHERE_LIGHT_POS_OFFSET: number = 0; public static SPHERE_LIGHT_SIZE_RANGE_OFFSET: number = UBOForwardLight.SPHERE_LIGHT_POS_OFFSET + UBOForwardLight.MAX_SPHERE_LIGHTS * 4; public static SPHERE_LIGHT_COLOR_OFFSET: number = UBOForwardLight.SPHERE_LIGHT_SIZE_RANGE_OFFSET + UBOForwardLight.MAX_SPHERE_LIGHTS * 4; - public static SPOT_LIGHT_POS_SIZE_OFFSET: number = UBOForwardLight.SPHERE_LIGHT_COLOR_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4; - public static SPOT_LIGHT_DIR_RANGE_OFFSET: number = UBOForwardLight.SPOT_LIGHT_POS_SIZE_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4; - public static SPOT_LIGHT_COLOR_OFFSET: number = UBOForwardLight.SPOT_LIGHT_DIR_RANGE_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4; + public static SPOT_LIGHT_POS_OFFSET: number = UBOForwardLight.SPHERE_LIGHT_COLOR_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4; + public static SPOT_LIGHT_SIZE_RANGE_ANGLE_OFFSET: number = UBOForwardLight.SPOT_LIGHT_POS_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4; + public static SPOT_LIGHT_DIR_OFFSET: number = UBOForwardLight.SPOT_LIGHT_SIZE_RANGE_ANGLE_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4; + public static SPOT_LIGHT_COLOR_OFFSET: number = UBOForwardLight.SPOT_LIGHT_DIR_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4; public static COUNT: number = UBOForwardLight.SPOT_LIGHT_COLOR_OFFSET + UBOForwardLight.MAX_SPOT_LIGHTS * 4; public static SIZE: number = UBOForwardLight.COUNT * 4; @@ -125,8 +131,9 @@ export class UBOForwardLight { { name: 'cc_sphereLitPos', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPHERE_LIGHTS }, { name: 'cc_sphereLitSizeRange', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPHERE_LIGHTS }, { name: 'cc_sphereLitColor', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPHERE_LIGHTS }, - { name: 'cc_spotLitPosSize', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS }, - { name: 'cc_spotLitDirRange', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS }, + { name: 'cc_spotLitPos', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS }, + { name: 'cc_spotLitSizeRangeAngle', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS }, + { name: 'cc_spotLitDir', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS }, { name: 'cc_spotLitColor', type: GFXType.FLOAT4, count: UBOForwardLight.MAX_SPOT_LIGHTS }, ], }; @@ -175,36 +182,3 @@ export interface IInternalBindingInst extends IInternalBindingDesc { sampler?: GFXSampler; textureView?: GFXTextureView; } - -export function SRGBToLinear (gamma: IGFXColor): IGFXColor { - const r = Math.pow(gamma.r, 2.2); - const g = Math.pow(gamma.g, 2.2); - const b = Math.pow(gamma.b, 2.2); - return { r, g, b, a: 1.0 }; -} - -export function LinearToSRGB (linear: IGFXColor): IGFXColor { - const r = Math.pow(linear.r, 0.454545); - const g = Math.pow(linear.g, 0.454545); - const b = Math.pow(linear.b, 0.454545); - return { r, g, b, a: 1.0 }; -} - -// Color temperature (in Kelvin) to RGB script. -// Valid from 1000 to 40000 K (and additionally 0 for pure full white) -export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) { - const temp = kelvin / 100.0; - if (temp <= 66.0) { - rgb.x = 1.0; - rgb.y = 0.390081579 * Math.log(temp) - 0.631841444; - if (temp <= 19.0) { - rgb.z = 0.0; - } else { - rgb.z = 0.543206789 * Math.log(temp - 10.0) - 1.19625409; - } - } else { - rgb.x = 1.29293619 * Math.pow(temp - 60.0, -0.1332047592); - rgb.y = 11.3259693 * Math.pow(temp - 60.0, -0.0755148492); - rgb.z = 1.0; - } -} diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 0be70052c9..28a3695692 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -25,8 +25,6 @@ export class ForwardFlow extends RenderFlow { this.createStage(ForwardStage, { name: 'ForwardStage', priority: ForwardStagePriority.FORWARD, - framebuffer: this._pipeline.shadingFBO, - // framebuffer, }); return true; diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index 1078ebf430..09760ea6a7 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -5,18 +5,18 @@ import { v3 } from '../../core/value-types/vec3'; import { vec3 } from '../../core/vmath'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBindingType, GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; -import { GFXFeature } from '../../gfx/device'; import { GFXRenderPass } from '../../gfx/render-pass'; import { Light, Model } from '../../renderer'; import { DirectionalLight } from '../../renderer/scene/directional-light'; import { LightType } from '../../renderer/scene/light'; import { SphereLight } from '../../renderer/scene/sphere-light'; import { SpotLight } from '../../renderer/scene/spot-light'; -import { RenderPassStage, UBOForwardLight } from '../define'; +import { PIPELINE_FLOW_FORWARD, PIPELINE_FLOW_TONEMAP, RenderPassStage, UBOForwardLight, PIPELINE_FLOW_SMAA } from '../define'; import { ToneMapFlow } from '../ppfx/tonemap-flow'; import { IRenderPipelineInfo, RenderPipeline } from '../render-pipeline'; import { RenderView } from '../render-view'; import { ForwardFlow } from './forward-flow'; +import { SMAAEdgeFlow } from '../ppfx/smaa-flow'; export enum ForwardFlowPriority { FORWARD = 0, @@ -49,24 +49,26 @@ export class ForwardPipeline extends RenderPipeline { public initialize (info: IRenderPipelineInfo): boolean { - if (this._device.hasFeature(GFXFeature.FORMAT_R11G11B10F) || - this._device.hasFeature(GFXFeature.TEXTURE_HALF_FLOAT) || - this._device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { - this._isHDRSupported = true; - } - - // this._isHDRSupported = false; - - if (!this.createShadingTarget(info)) { + if (!this._initialize(info)) { return false; } - if (!this.createQuadInputAssembler()) { - return false; - } + if (!this._globalBindings.get(UBOForwardLight.BLOCK.name)) { + const lightsUBO = this._root.device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: UBOForwardLight.SIZE, + }); - if (!this.createUBOs()) { - return false; + if (!lightsUBO) { + return false; + } + + this._globalBindings.set(UBOForwardLight.BLOCK.name, { + type: GFXBindingType.UNIFORM_BUFFER, + blockInfo: UBOForwardLight.BLOCK, + buffer: lightsUBO, + }); } const mainWindow = this._root.mainWindow; @@ -87,12 +89,19 @@ export class ForwardPipeline extends RenderPipeline { // create flows this.createFlow(ForwardFlow, { - name: 'ForwardFlow', + name: PIPELINE_FLOW_FORWARD, priority: ForwardFlowPriority.FORWARD, }); + /* + this.createFlow(SMAAEdgeFlow, { + name: PIPELINE_FLOW_SMAA, + priority: 0, + }); + */ + this.createFlow(ToneMapFlow, { - name: 'ToneMapFlow', + name: PIPELINE_FLOW_TONEMAP, priority: 0, }); @@ -100,45 +109,13 @@ export class ForwardPipeline extends RenderPipeline { } public destroy () { - this.destroyFlows(); - this.clearRenderPasses(); - this.destroyUBOs(); - this.destroyQuadInputAssembler(); - this.destroyShadingTarget(); - } - - protected createUBOs (): boolean { - super.createUBOs(); - - if (!this._globalBindings.get(UBOForwardLight.BLOCK.name)) { - const lightsUBO = this._root.device.createBuffer({ - usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, - memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: UBOForwardLight.SIZE, - }); - - if (!lightsUBO) { - return false; - } - - this._globalBindings.set(UBOForwardLight.BLOCK.name, { - type: GFXBindingType.UNIFORM_BUFFER, - blockInfo: UBOForwardLight.BLOCK, - buffer: lightsUBO, - }); - } - - return true; - } - - protected destroyUBOs () { - super.destroyUBOs(); - const lightsUBO = this._globalBindings.get(UBOForwardLight.BLOCK.name); if (lightsUBO) { lightsUBO.buffer!.destroy(); this._globalBindings.delete(UBOForwardLight.BLOCK.name); } + + this._destroy(); } protected updateUBOs (view: RenderView) { @@ -166,11 +143,13 @@ export class ForwardPipeline extends RenderPipeline { if (sphereNum >= UBOForwardLight.MAX_SPHERE_LIGHTS) { continue; } - vec3.array(_vec4Array, (light as SphereLight).position); + + const sphereLit = light as SphereLight; + vec3.array(_vec4Array, sphereLit.position); this._uboLights.view.set(_vec4Array, UBOForwardLight.SPHERE_LIGHT_POS_OFFSET + sphereNum * 4); - _vec4Array[0] = (light as SphereLight).size; - _vec4Array[1] = (light as SphereLight).range; + _vec4Array[0] = sphereLit.size; + _vec4Array[1] = sphereLit.range; _vec4Array[2] = 0.0; this._uboLights.view.set(_vec4Array, UBOForwardLight.SPHERE_LIGHT_SIZE_RANGE_OFFSET + sphereNum * 4); @@ -181,7 +160,7 @@ export class ForwardPipeline extends RenderPipeline { _vec4Array[1] *= tempRGB.y; _vec4Array[2] *= tempRGB.z; } - _vec4Array[3] = (light as SphereLight).luminance * 10000.0; + _vec4Array[3] = sphereLit.luminance * 10000.0; this._uboLights.view.set(_vec4Array, UBOForwardLight.SPHERE_LIGHT_COLOR_OFFSET + sphereNum * 4); sphereNum++; break; @@ -189,13 +168,20 @@ export class ForwardPipeline extends RenderPipeline { if (spotNum >= UBOForwardLight.MAX_SPOT_LIGHTS) { continue; } - vec3.array(_vec4Array, (light as SpotLight).position); - _vec4Array[3] = (light as SpotLight).size; - this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_POS_SIZE_OFFSET + spotNum * 4); - vec3.array(_vec4Array, (light as SpotLight).direction); - _vec4Array[3] = (light as SpotLight).range; - this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_DIR_RANGE_OFFSET + spotNum * 4); + const spotLit = light as SpotLight; + + vec3.array(_vec4Array, spotLit.position); + _vec4Array[3] = spotLit.size; + this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_POS_OFFSET + spotNum * 4); + + _vec4Array[0] = spotLit.size; + _vec4Array[1] = spotLit.range; + _vec4Array[2] = spotLit.spotAngle; + this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_SIZE_RANGE_ANGLE_OFFSET + spotNum * 4); + + vec3.array(_vec4Array, spotLit.direction); + this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_DIR_OFFSET + spotNum * 4); vec3.array(_vec4Array, light.color); if (light.useColorTemperature) { @@ -204,7 +190,7 @@ export class ForwardPipeline extends RenderPipeline { _vec4Array[1] *= tempRGB.y; _vec4Array[2] *= tempRGB.z; } - _vec4Array[3] = (light as SpotLight).luminance * 10000.0; + _vec4Array[3] = spotLit.luminance * 10000.0; this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_COLOR_OFFSET + spotNum * 4); spotNum++; break; diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index 051e90b9f9..657153937c 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -1,6 +1,6 @@ import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXCommandBufferType, IGFXColor, GFXClearFlag } from '../../gfx/define'; -import { SRGBToLinear } from '../define'; +import { GFXClearFlag, GFXCommandBufferType, IGFXColor } from '../../gfx/define'; +import { SRGBToLinear } from '../pipeline-funcs'; import { RenderFlow } from '../render-flow'; import { IRenderStageInfo, RenderStage } from '../render-stage'; import { RenderView } from '../render-view'; @@ -21,7 +21,6 @@ export class ForwardStage extends RenderStage { } this._priority = info.priority; - this._framebuffer = info.framebuffer; this._cmdBuff = this._device.createCommandBuffer({ allocator: this._device.commandAllocator, @@ -65,6 +64,8 @@ export class ForwardStage extends RenderStage { colors.length = 1; } + this._framebuffer = this._pipeline.curShadingFBO; + cmdBuff.begin(); cmdBuff.beginRenderPass(this._framebuffer!, this._renderArea, camera.clearFlag, colors, camera.clearDepth, camera.clearStencil); diff --git a/cocos/pipeline/pipeline-funcs.ts b/cocos/pipeline/pipeline-funcs.ts new file mode 100644 index 0000000000..e13f1896b0 --- /dev/null +++ b/cocos/pipeline/pipeline-funcs.ts @@ -0,0 +1,15 @@ +import { IGFXColor } from '../gfx/define'; + +export function SRGBToLinear (gamma: IGFXColor): IGFXColor { + const r = Math.pow(gamma.r, 2.2); + const g = Math.pow(gamma.g, 2.2); + const b = Math.pow(gamma.b, 2.2); + return { r, g, b, a: 1.0 }; +} + +export function LinearToSRGB (linear: IGFXColor): IGFXColor { + const r = Math.pow(linear.r, 0.454545); + const g = Math.pow(linear.g, 0.454545); + const b = Math.pow(linear.b, 0.454545); + return { r, g, b, a: 1.0 }; +} diff --git a/cocos/pipeline/ppfx/smaa-blend-stage.ts b/cocos/pipeline/ppfx/smaa-blend-stage.ts new file mode 100644 index 0000000000..a16e004a2d --- /dev/null +++ b/cocos/pipeline/ppfx/smaa-blend-stage.ts @@ -0,0 +1,136 @@ +import { ImageAsset } from '../../assets/image-asset'; +import { Texture2D } from '../../assets/texture-2d'; +import { GFXBindingLayout } from '../../gfx/binding-layout'; +import { GFXClearFlag, GFXCommandBufferType } from '../../gfx/define'; +import { UBOGlobal } from '../define'; +import { RenderFlow } from '../render-flow'; +import { IRenderStageInfo, RenderStage } from '../render-stage'; +import { RenderView } from '../render-view'; + +export class SMAABlendStage extends RenderStage { + + private _areaTexImage = new Image(); + private _searchTexImage = new Image(); + private _areaTexAsset: Texture2D = new Texture2D(); + private _searchTexAsset: Texture2D = new Texture2D(); + private _hEdgeTexSampler: number = 0; + private _hAreaTexSampler: number = 0; + private _hSearchTexSampler: number = 0; + private _isAreaImageLoaded: boolean = false; + private _isSearchImageLoaded: boolean = false; + private _isLoaded: boolean = false; + + private _bindingLayout: GFXBindingLayout | null = null; + + constructor (flow: RenderFlow) { + super(flow); + } + + public initialize (info: IRenderStageInfo): boolean { + + if (info.name !== undefined) { + this._name = info.name; + } + + this._priority = info.priority; + + if (info.framebuffer !== undefined) { + this._framebuffer = info.framebuffer ; + } + + this._cmdBuff = this._device.createCommandBuffer({ + allocator: this._device.commandAllocator, + type: GFXCommandBufferType.PRIMARY, + }); + + this._pass = this._flow.material.passes[1]; + this._hEdgeTexSampler = this._pass.getBinding('u_edgeTexSampler'); + this._hAreaTexSampler = this._pass.getBinding('u_areaTexSampler'); + this._hSearchTexSampler = this._pass.getBinding('u_searchTexSampler'); + + const globalUBO = this._pipeline.globalBindings.get(UBOGlobal.BLOCK.name); + + this._pso = this._pass.createPipelineState(); + this._bindingLayout = this._pso!.pipelineLayout.layouts[0]; + + this._pass.bindBuffer(UBOGlobal.BLOCK.binding, globalUBO!.buffer!); + this._pass.bindTextureView(this._hEdgeTexSampler, this._pipeline.smaaEdgeTexView); + this._pass.update(); + this._bindingLayout.update(); + + // load textures + this._areaTexImage.src = this.getAreaTexEncode(); + this._areaTexImage.onload = () => { + this._isAreaImageLoaded = true; + this.bindTextures(); + }; + + this._searchTexImage.src = this.getSearchTexEncode(); + this._searchTexImage.onload = () => { + this._isSearchImageLoaded = true; + this.bindTextures(); + }; + + return true; + } + + public destroy () { + + this._areaTexAsset.destroy(); + this._searchTexAsset.destroy(); + + if (this._cmdBuff) { + this._cmdBuff.destroy(); + this._cmdBuff = null; + } + } + + public resize (width: number, height: number) { + } + + public render (view: RenderView) { + if (this._isLoaded) { + const camera = view.camera!; + + if (this._cmdBuff) { + + this._renderArea.width = camera.width; + this._renderArea.height = camera.height; + + this._cmdBuff.begin(); + this._cmdBuff.beginRenderPass(this._framebuffer!, this._renderArea, + GFXClearFlag.ALL, [{ r: 0.0, g: 0.0, b: 0.0, a: 1.0 }], 1.0, 0); + this._cmdBuff.bindPipelineState(this._pso!); + this._cmdBuff.bindBindingLayout(this._bindingLayout!); + this._cmdBuff.bindInputAssembler(this._pipeline.quadIA); + this._cmdBuff.draw(this._pipeline.quadIA); + this._cmdBuff.endRenderPass(); + this._cmdBuff.end(); + } + + this._device.queue.submit([this._cmdBuff!]); + } + } + + private bindTextures () { + if (this._isAreaImageLoaded && this._isSearchImageLoaded) { + this._areaTexAsset.image = new ImageAsset(this._areaTexImage); + this._searchTexAsset.image = new ImageAsset(this._searchTexImage); + this._pass!.bindTextureView(this._hAreaTexSampler, this._areaTexAsset.getGFXTextureView()!); + this._pass!.bindTextureView(this._hSearchTexSampler, this._searchTexAsset.getGFXTextureView()!); + this._pass!.update(); + this._bindingLayout!.update(); + this._isLoaded = true; + } + } + + private getAreaTexEncode (): string { + // tslint:disable-next-line: max-line-length + return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAIwCAIAAACOVPcQAACBeklEQVR42u39W4xlWXrnh/3WWvuciIzMrKxrV8/0rWbY0+SQFKcb4owIkSIFCjY9AC1BT/LYBozRi+EX+cV+8IMsYAaCwRcBwjzMiw2jAWtgwC8WR5Q8mDFHZLNHTarZGrLJJllt1W2qKrsumZWZcTvn7L3W54e1vrXX3vuciLPPORFR1XE2EomorB0nVuz//r71re/y/1eMvb4Cb3N11xV/PP/2v4UBAwJG/7H8urx6/25/Gf8O5hypMQ0EEEQwAqLfoN/Z+97f/SW+/NvcgQk4sGBJK6H7N4PFVL+K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HUp5toHGsVfn4NX4RnMCe+AxTpwmApTYxqMxwfCeJGjpXzRF61nbcHhUBPqWze9svwcHJ+S6NPscKrEjug78Dx8Lj3T8D4YxGIdxmJcwhi34fzZUr7olevZCw5vkOhoClq5zBPZAnygD/Tl9EzDh6kl3VhsHYcDEb+hCtJSvuiV69kLDm+WycrOTArHmB5/VYyP6jOVjwgGawk2zQOaTcc1L+aLXrKeveDwZqlKrw8U9Y1p66uK8dEzdYwBeUQAY7DbyYNezBfdWQ97weEtAKYQg2xJIkuveAT3dYeLGH+ShrWNwZgN0b2YL7qznr3g8JYAo5bQBziPjx7BPZ0d9RCQp4UZbnFdzBddor4XHN4KYMrB2qHFRIzzcLAHQZ5the5ovui94PCWAPefaYnxIdzRwdHCbuR4B+tbiy96Lzi8E4D7z7S0mEPd+eqO3cT53Z0Y8SV80XvB4Z0ADJi/f7X113f+7p7/+UYBvur6657/+YYBvur6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+VMA8FXWX/f8z58OgK+y/rrnf75RgLna+uue//lTA/CV1V/3/M837aKvvv6653++UQvmauuve/7nTwfAV1N/3fM/fzr24Cuuv+75nz8FFnxl9dc9//MOr/8/glixwRuUfM4AAAAASUVORK5CYII='; + } + + private getSearchTexEncode (): string { + // tslint:disable-next-line: max-line-length + return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAAhCAAAAABIXyLAAAAAOElEQVRIx2NgGAWjYBSMglEwEICREYRgFBZBqDCSLA2MGPUIVQETE9iNUAqLR5gIeoQKRgwXjwAAGn4AtaFeYLEAAAAASUVORK5CYII='; + } +} diff --git a/cocos/pipeline/ppfx/smaa-edge-stage.ts b/cocos/pipeline/ppfx/smaa-edge-stage.ts new file mode 100644 index 0000000000..9bf63cfb5b --- /dev/null +++ b/cocos/pipeline/ppfx/smaa-edge-stage.ts @@ -0,0 +1,82 @@ +import { GFXBindingLayout } from '../../gfx/binding-layout'; +import { GFXClearFlag, GFXCommandBufferType } from '../../gfx/define'; +import { UBOGlobal } from '../define'; +import { RenderFlow } from '../render-flow'; +import { IRenderStageInfo, RenderStage } from '../render-stage'; +import { RenderView } from '../render-view'; + +export class SMAAEdgeStage extends RenderStage { + + private _hTexSampler: number = 0; + private _bindingLayout: GFXBindingLayout | null = null; + + constructor (flow: RenderFlow) { + super(flow); + } + + public initialize (info: IRenderStageInfo): boolean { + + if (info.name !== undefined) { + this._name = info.name; + } + + this._priority = info.priority; + + if (info.framebuffer !== undefined) { + this._framebuffer = info.framebuffer ; + } + + this._cmdBuff = this._device.createCommandBuffer({ + allocator: this._device.commandAllocator, + type: GFXCommandBufferType.PRIMARY, + }); + + this._pass = this._flow.material.passes[0]; + this._hTexSampler = this._pass.getBinding('u_texSampler'); + + const globalUBO = this._pipeline.globalBindings.get(UBOGlobal.BLOCK.name); + + this._pso = this._pass.createPipelineState(); + this._bindingLayout = this._pso!.pipelineLayout.layouts[0]; + + this._pass.bindBuffer(UBOGlobal.BLOCK.binding, globalUBO!.buffer!); + this._pass.bindTextureView(this._hTexSampler, this._pipeline.curShadingTexView); + this._pass.update(); + this._bindingLayout.update(); + + return true; + } + + public destroy () { + if (this._cmdBuff) { + this._cmdBuff.destroy(); + this._cmdBuff = null; + } + } + + public resize (width: number, height: number) { + } + + public render (view: RenderView) { + + const camera = view.camera!; + + if (this._cmdBuff) { + + this._renderArea.width = camera.width; + this._renderArea.height = camera.height; + + this._cmdBuff.begin(); + this._cmdBuff.beginRenderPass(this._framebuffer!, this._renderArea, + GFXClearFlag.ALL, [{ r: 0.0, g: 0.0, b: 0.0, a: 1.0 }], 1.0, 0); + this._cmdBuff.bindPipelineState(this._pso!); + this._cmdBuff.bindBindingLayout(this._bindingLayout!); + this._cmdBuff.bindInputAssembler(this._pipeline.quadIA); + this._cmdBuff.draw(this._pipeline.quadIA); + this._cmdBuff.endRenderPass(); + this._cmdBuff.end(); + } + + this._device.queue.submit([this._cmdBuff!]); + } +} diff --git a/cocos/pipeline/ppfx/smaa-flow.ts b/cocos/pipeline/ppfx/smaa-flow.ts new file mode 100644 index 0000000000..bfe15d5436 --- /dev/null +++ b/cocos/pipeline/ppfx/smaa-flow.ts @@ -0,0 +1,45 @@ +import { IRenderFlowInfo, RenderFlow } from '../render-flow'; +import { RenderPipeline } from '../render-pipeline'; +import { SMAAEdgeStage } from './smaa-edge-stage'; +import { SMAABlendStage } from './smaa-blend-stage'; + +export class SMAAEdgeFlow extends RenderFlow { + + constructor (pipeline: RenderPipeline) { + super(pipeline); + } + + public initialize (info: IRenderFlowInfo): boolean { + + if (info.name !== undefined) { + this._name = info.name; + } + + this._priority = info.priority; + + const material = new cc.Material(); + material.initialize({ + effectName: 'builtin-smaa', + }); + + this._material = material; + + this.createStage(SMAAEdgeStage, { + name: 'SMAAEdgeStage', + priority: 0, + framebuffer: this._pipeline.smaaEdgeFBO, + }); + + this.createStage(SMAABlendStage, { + name: 'SMAABlendStage', + priority: 0, + framebuffer: this._pipeline.smaaBlendFBO, + }); + + return true; + } + + public destroy (): void { + this.destroyStages(); + } +} diff --git a/cocos/pipeline/ppfx/tonemap-stage.ts b/cocos/pipeline/ppfx/tonemap-stage.ts index fe220d514c..41b676b61c 100644 --- a/cocos/pipeline/ppfx/tonemap-stage.ts +++ b/cocos/pipeline/ppfx/tonemap-stage.ts @@ -1,15 +1,17 @@ +import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXCommandBufferType, IGFXColor, GFXClearFlag } from '../../gfx/define'; +import { GFXClearFlag, GFXCommandBufferType, IGFXColor } from '../../gfx/define'; import { UBOGlobal } from '../define'; import { RenderFlow } from '../render-flow'; import { IRenderStageInfo, RenderStage } from '../render-stage'; import { RenderView } from '../render-view'; -const colors: IGFXColor[] = []; -const bufs: GFXCommandBuffer[] = []; - export class ToneMapStage extends RenderStage { + private _hTexSampler: number = 0; + private _hBlendTexSampler: number = 0; + private _bindingLayout: GFXBindingLayout | null = null; + constructor (flow: RenderFlow) { super(flow); } @@ -21,7 +23,10 @@ export class ToneMapStage extends RenderStage { } this._priority = info.priority; - this._framebuffer = info.framebuffer; + + if (info.framebuffer !== undefined) { + this._framebuffer = info.framebuffer ; + } this._cmdBuff = this._device.createCommandBuffer({ allocator: this._device.commandAllocator, @@ -29,15 +34,19 @@ export class ToneMapStage extends RenderStage { }); this._pass = this._flow.material.passes[0]; - const binding = this._pass.getBinding('u_texSampler'); + this._hTexSampler = this._pass.getBinding('u_texSampler'); + this._hBlendTexSampler = this._pass.getBinding('u_blendTexSampler'); const globalUBO = this._pipeline.globalBindings.get(UBOGlobal.BLOCK.name); - this._pass.bindBuffer(UBOGlobal.BLOCK.binding, globalUBO!.buffer!); - this._pass.bindTextureView(binding, this._pipeline.shadingTexView); - this._pass.update(); this._pso = this._pass.createPipelineState(); - this._pso!.pipelineLayout.layouts[0].update(); + this._bindingLayout = this._pso!.pipelineLayout.layouts[0]; + + this._pass.bindBuffer(UBOGlobal.BLOCK.binding, globalUBO!.buffer!); + this._pass.bindTextureView(this._hTexSampler, this._pipeline.curShadingTexView); + // this._pass.bindTextureView(this._hBlendTexSampler, this._pipeline.smaaBlendTexView); + this._pass.update(); + this._bindingLayout.update(); return true; } @@ -60,7 +69,7 @@ export class ToneMapStage extends RenderStage { this._renderArea.width = camera.width; this._renderArea.height = camera.height; - const framebuffer = !view.isOffscreen? view.window!.framebuffer : view.framebuffer; + const framebuffer = !view.isOffscreen ? view.window!.framebuffer : view.framebuffer; this._cmdBuff.begin(); this._cmdBuff.beginRenderPass(framebuffer, this._renderArea, @@ -74,5 +83,7 @@ export class ToneMapStage extends RenderStage { } this._device.queue.submit([this._cmdBuff!]); + + // this._pipeline.swapFBOs(); } } diff --git a/cocos/pipeline/render-flow.ts b/cocos/pipeline/render-flow.ts index ffdfd8d168..1a4fbfae7d 100644 --- a/cocos/pipeline/render-flow.ts +++ b/cocos/pipeline/render-flow.ts @@ -19,10 +19,18 @@ export abstract class RenderFlow { return this._pipeline; } + public get name (): string { + return this._name; + } + public get priority (): number { return this._priority; } + public get stages (): RenderStage[] { + return this._stages!; + } + public get material (): Material { return this._material!; } diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 740b4c6dae..24325f8b7a 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -64,18 +64,42 @@ export abstract class RenderPipeline { return this._isHDR; } - public get shadingTexView (): GFXTextureView { - return this._shadingTexView!; - } - - public get shadingFBO (): GFXFramebuffer { - return this._shadingFBO!; - } - public get depthStencilTexView (): GFXTextureView { return this._depthStencilTexView!; } + public get curShadingTexView (): GFXTextureView { + return this._shadingTexViews[this._curIdx]; + } + + public get prevShadingTexView (): GFXTextureView { + return this._shadingTexViews[this._prevIdx]; + } + + public get curShadingFBO (): GFXFramebuffer { + return this._shadingFBOs[this._curIdx]; + } + + public get prevShadingFBO (): GFXFramebuffer { + return this._shadingFBOs[this._prevIdx]; + } + + public get smaaEdgeTexView (): GFXTextureView { + return this._smaaEdgeTexView!; + } + + public get smaaEdgeFBO (): GFXFramebuffer { + return this._smaaEdgeFBO!; + } + + public get smaaBlendTexView (): GFXTextureView { + return this._smaaBlendTexView!; + } + + public get smaaBlendFBO (): GFXFramebuffer { + return this._smaaBlendFBO!; + } + public get quadIA (): GFXInputAssembler { return this._quadIA!; } @@ -108,11 +132,24 @@ export abstract class RenderPipeline { protected _isHDRSupported: boolean = false; protected _isHDR: boolean = false; protected _shadingPass: GFXRenderPass | null = null; - protected _shadingTex: GFXTexture | null = null; - protected _shadingTexView: GFXTextureView | null = null; + protected _fboCount: number = 1; + protected _shadingTextures: GFXTexture[] = []; + protected _shadingTexViews: GFXTextureView[] = []; protected _depthStencilTex: GFXTexture | null = null; protected _depthStencilTexView: GFXTextureView | null = null; - protected _shadingFBO: GFXFramebuffer | null = null; + protected _shadingFBOs: GFXFramebuffer[] = []; + protected _shadingTexWidth: number = 0.0; + protected _shadingTexHeight: number = 0.0; + protected _curIdx: number = 0; + protected _prevIdx: number = 1; + protected _useSMAA: boolean = false; + protected _smaaPass: GFXRenderPass | null = null; + protected _smaaEdgeFBO: GFXFramebuffer | null = null; + protected _smaaEdgeTex: GFXTexture | null = null; + protected _smaaEdgeTexView: GFXTextureView | null = null; + protected _smaaBlendFBO: GFXFramebuffer | null = null; + protected _smaaBlendTex: GFXTexture | null = null; + protected _smaaBlendTexView: GFXTextureView | null = null; protected _quadVB: GFXBuffer | null = null; protected _quadIB: GFXBuffer | null = null; protected _quadIA: GFXInputAssembler | null = null; @@ -152,6 +189,12 @@ export abstract class RenderPipeline { } } + public swapFBOs () { + const temp = this._curIdx; + this._curIdx = this._prevIdx; + this._prevIdx = temp; + } + public addRenderPass (stage: number, renderPass: GFXRenderPass) { if (renderPass) { this._renderPasses.set(stage, renderPass); @@ -199,7 +242,31 @@ export abstract class RenderPipeline { this._flows = []; } - protected createShadingTarget (info: IRenderPipelineInfo): boolean { + public getFlow (name: string): RenderFlow | null { + for (const flow of this._flows) { + if (flow.name === name) { + return flow; + } + } + + return null; + } + + protected _initialize (info: IRenderPipelineInfo): boolean { + + if (this._device.hasFeature(GFXFeature.FORMAT_R11G11B10F) || + this._device.hasFeature(GFXFeature.TEXTURE_HALF_FLOAT) || + this._device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { + this._isHDRSupported = true; + } + + // this._isHDRSupported = false; + + this._fboCount = 1; + this._shadingTextures = new Array(this._fboCount); + this._shadingTexViews = new Array(this._fboCount); + this._shadingFBOs = new Array(this._fboCount); + let colorFmt: GFXFormat; let depthStencilFmt: GFXFormat; @@ -233,37 +300,22 @@ export abstract class RenderPipeline { // colorFmt = GFXFormat.RGBA16F; + const scale = 1.0; + const texWidth = Math.min(this._device.width * scale, 2048); + const texHeight = Math.min(this._device.height * scale, 2048); + let screenScale = Math.min(texWidth / this._device.width, texHeight / this._device.height); + screenScale = Math.min(scale, screenScale); + + // this._shadingTexWidth = Math.floor(this._device.width * screenScale); + // this._shadingTexHeight = Math.floor(this._device.height * screenScale); + this._shadingTexWidth = this._device.nativeWidth; + this._shadingTexHeight = this._device.nativeHeight; + console.info('CC_USE_HDR: ' + this._isHDR); - console.info('Shading Color Format: ' + GFXFormatInfos[colorFmt].name); - console.info('Shading Depth Format: ' + GFXFormatInfos[depthStencilFmt].name); - - this._shadingTex = this._device.createTexture({ - type: GFXTextureType.TEX2D, - usage: GFXTextureUsageBit.COLOR_ATTACHMENT | GFXTextureUsageBit.SAMPLED, - format: colorFmt, - width: this._device.nativeWidth, - height: this._device.nativeHeight, - }); - - this._shadingTexView = this._device.createTextureView({ - texture : this._shadingTex, - type : GFXTextureViewType.TV2D, - format : colorFmt, - }); - - this._depthStencilTex = this._device.createTexture({ - type : GFXTextureType.TEX2D, - usage : GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT | GFXTextureUsageBit.SAMPLED, - format : depthStencilFmt, - width : this._device.nativeWidth, - height : this._device.nativeHeight, - }); - - this._depthStencilTexView = this._device.createTextureView({ - texture : this._depthStencilTex, - type : GFXTextureViewType.TV2D, - format : depthStencilFmt, - }); + console.info('SHADING_SIZE: ' + this._shadingTexWidth + ' x ' + this._shadingTexHeight); + console.info('SCREEN_SCALE: ' + screenScale); + console.info('SHADING_COLOR_FORMAT: ' + GFXFormatInfos[colorFmt].name); + console.info('SHADING_DEPTH_FORMAT: ' + GFXFormatInfos[depthStencilFmt].name); this._shadingPass = this._device.createRenderPass({ colorAttachments: [{ @@ -286,26 +338,160 @@ export abstract class RenderPipeline { }, }); - this._shadingFBO = this._device.createFramebuffer({ - renderPass: this._shadingPass, - colorViews: [ this._shadingTexView ], - depthStencilView: this._depthStencilTexView!, + this._depthStencilTex = this._device.createTexture({ + type : GFXTextureType.TEX2D, + usage : GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT | GFXTextureUsageBit.SAMPLED, + format : depthStencilFmt, + width : this._shadingTexWidth, + height : this._shadingTexHeight, }); + this._depthStencilTexView = this._device.createTextureView({ + texture : this._depthStencilTex, + type : GFXTextureViewType.TV2D, + format : depthStencilFmt, + }); + + for (let i = 0; i < this._fboCount; ++i) { + this._shadingTextures[i] = this._device.createTexture({ + type: GFXTextureType.TEX2D, + usage: GFXTextureUsageBit.COLOR_ATTACHMENT | GFXTextureUsageBit.SAMPLED, + format: colorFmt, + width: this._shadingTexWidth, + height: this._shadingTexHeight, + }); + + this._shadingTexViews[i] = this._device.createTextureView({ + texture : this._shadingTextures[i], + type : GFXTextureViewType.TV2D, + format : colorFmt, + }); + + this._shadingFBOs[i] = this._device.createFramebuffer({ + renderPass: this._shadingPass, + colorViews: [ this._shadingTexViews[i] ], + depthStencilView: this._depthStencilTexView!, + }); + } + + // create smaa framebuffer + const smaaColorFmt = GFXFormat.RGBA8; + + this._smaaPass = this._device.createRenderPass({ + colorAttachments: [{ + format: smaaColorFmt, + loadOp: GFXLoadOp.CLEAR, + storeOp: GFXStoreOp.STORE, + sampleCount: 1, + beginLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL, + endLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL, + }], + }); + + this._smaaEdgeTex = this._device.createTexture({ + type: GFXTextureType.TEX2D, + usage: GFXTextureUsageBit.COLOR_ATTACHMENT | GFXTextureUsageBit.SAMPLED, + format: smaaColorFmt, + width: this._shadingTexWidth, + height: this._shadingTexHeight, + }); + + this._smaaEdgeTexView = this._device.createTextureView({ + texture : this._smaaEdgeTex, + type : GFXTextureViewType.TV2D, + format : smaaColorFmt, + }); + + this._smaaEdgeFBO = this._device.createFramebuffer({ + renderPass: this._smaaPass, + colorViews: [ this._smaaEdgeTexView ], + }); + + this._smaaBlendTex = this._device.createTexture({ + type: GFXTextureType.TEX2D, + usage: GFXTextureUsageBit.COLOR_ATTACHMENT | GFXTextureUsageBit.SAMPLED, + format: smaaColorFmt, + width: this._shadingTexWidth, + height: this._shadingTexHeight, + }); + + this._smaaBlendTexView = this._device.createTextureView({ + texture : this._smaaBlendTex, + type : GFXTextureViewType.TV2D, + format : smaaColorFmt, + }); + + this._smaaBlendFBO = this._device.createFramebuffer({ + renderPass: this._smaaPass, + colorViews: [ this._smaaBlendTexView ], + }); + + if (!this.createQuadInputAssembler()) { + return false; + } + + if (!this.createUBOs()) { + return false; + } + return true; } - protected destroyShadingTarget () { - if (this._shadingTexView) { - this._shadingTexView.destroy(); - this._shadingTexView = null; + protected _destroy () { + + this.destroyFlows(); + this.clearRenderPasses(); + this.destroyQuadInputAssembler(); + this.destroyUBOs(); + + if (this._smaaEdgeTexView) { + this._smaaEdgeTexView.destroy(); + this._smaaEdgeTexView = null; } - if (this._shadingTex) { - this._shadingTex.destroy(); - this._shadingTex = null; + if (this._smaaEdgeTex) { + this._smaaEdgeTex.destroy(); + this._smaaEdgeTex = null; } + if (this._smaaEdgeFBO) { + this._smaaEdgeFBO.destroy(); + this._smaaEdgeFBO = null; + } + + if (this._smaaBlendTexView) { + this._smaaBlendTexView.destroy(); + this._smaaBlendTexView = null; + } + + if (this._smaaBlendTex) { + this._smaaBlendTex.destroy(); + this._smaaBlendTex = null; + } + + if (this._smaaBlendFBO) { + this._smaaBlendFBO.destroy(); + this._smaaBlendFBO = null; + } + + for (let i = 0; i < this._shadingTexViews.length; ++i) { + if (this._shadingTexViews[i]) { + this._shadingTexViews[i].destroy(); + } + + if (this._shadingTextures[i]) { + this._shadingTextures[i].destroy(); + } + + if (this._shadingFBOs[i]) { + this._shadingFBOs[i].destroy(); + } + } + + this._shadingTexViews.splice(0); + this._shadingTextures.splice(0); + this._shadingFBOs.splice(0); + if (this._depthStencilTexView) { this._depthStencilTexView.destroy(); this._depthStencilTexView = null; @@ -316,11 +502,6 @@ export abstract class RenderPipeline { this._depthStencilTex = null; } - if (this._shadingFBO) { - this._shadingFBO.destroy(); - this._shadingFBO = null; - } - if (this._shadingPass) { this._shadingPass.destroy(); this._shadingPass = null; @@ -490,8 +671,8 @@ export abstract class RenderPipeline { this._defaultUboGlobal!.view.set(_vec4Array, UBOGlobal.SCREEN_SIZE_OFFSET); if (!view.isOffscreen) { - _vec4Array[0] = camera.width / device.nativeWidth; - _vec4Array[1] = camera.height / device.nativeHeight; + _vec4Array[0] = camera.width / this._shadingTexWidth; + _vec4Array[1] = camera.height / this._shadingTexHeight; } else { _vec4Array[0] = 1.0; _vec4Array[1] = 1.0; @@ -500,6 +681,12 @@ export abstract class RenderPipeline { _vec4Array[3] = 1.0 / _vec4Array[1]; this._defaultUboGlobal!.view.set(_vec4Array, UBOGlobal.SCREEN_SCALE_OFFSET); + _vec4Array[0] = this._shadingTexWidth; + _vec4Array[1] = this._shadingTexHeight; + _vec4Array[2] = 1.0 / _vec4Array[0]; + _vec4Array[3] = 1.0 / _vec4Array[1]; + this._defaultUboGlobal!.view.set(_vec4Array, UBOGlobal.NATIVE_SIZE_OFFSET); + mat4.array(_mat4Array, camera.matView); this._defaultUboGlobal!.view.set(_mat4Array, UBOGlobal.MAT_VIEW_OFFSET); @@ -558,7 +745,7 @@ export abstract class RenderPipeline { this._globalBindings.get(UBOGlobal.BLOCK.name)!.buffer!.update(this._defaultUboGlobal!.view.buffer); const planarShadow = scene.planarShadow; - planarShadow.update(scene.mainLight); + planarShadow.updateDirLight(scene.mainLight); this._globalBindings.get(UBOShadow.BLOCK.name)!.buffer!.update(planarShadow.data); } diff --git a/cocos/pipeline/render-stage.ts b/cocos/pipeline/render-stage.ts index 5130dbf33c..e315e0c873 100644 --- a/cocos/pipeline/render-stage.ts +++ b/cocos/pipeline/render-stage.ts @@ -2,17 +2,16 @@ import { GFXCommandBuffer } from '../gfx/command-buffer'; import { IGFXColor, IGFXRect } from '../gfx/define'; import { GFXDevice } from '../gfx/device'; import { GFXFramebuffer } from '../gfx/framebuffer'; -import { Camera } from '../renderer/scene/camera'; +import { GFXPipelineState } from '../gfx/pipeline-state'; +import { Pass } from '../renderer'; import { RenderFlow } from './render-flow'; import { RenderPipeline } from './render-pipeline'; import { RenderView } from './render-view'; -import { GFXPipelineState } from '../gfx/pipeline-state'; -import { Pass } from '../renderer'; export interface IRenderStageInfo { name?: string; priority: number; - framebuffer: GFXFramebuffer; + framebuffer?: GFXFramebuffer; } export abstract class RenderStage { diff --git a/cocos/pipeline/ui/ui-pipeline.ts b/cocos/pipeline/ui/ui-pipeline.ts index 894d735315..95c7a24b6e 100644 --- a/cocos/pipeline/ui/ui-pipeline.ts +++ b/cocos/pipeline/ui/ui-pipeline.ts @@ -30,10 +30,7 @@ export class UIPipeline extends RenderPipeline { } public destroy () { - this.destroyFlows(); - this.clearRenderPasses(); - this.destroyUBOs(); - this.destroyQuadInputAssembler(); + this._destroy(); } protected updateUBOs (view: RenderView) { diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 6e5f212de4..208fdb3a2b 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -1,11 +1,12 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { EffectAsset } from '../../3d/assets/effect-asset'; -import { IDefineMap, IPassInfoFull, Pass } from './pass'; +import { IDefineMap, IPassInfoFull, Pass, PassOverrides } from './pass'; export interface IEffectInfo { - techIdx?: number; - defines?: IDefineMap[]; + techIdx: number; + defines: IDefineMap[]; + states: PassOverrides[]; } export class Effect { @@ -13,16 +14,17 @@ export class Effect { return effect.techniques[techIdx].passes; } - public static parseEffect (effect: EffectAsset, info?: IEffectInfo) { + public static parseEffect (effect: EffectAsset, info: IEffectInfo) { // techniques - const { techIdx, defines } = info || {} as IEffectInfo; + const { techIdx, defines, states } = info; const tech = effect.techniques[techIdx || 0]; const passNum = tech.passes.length; const passes: Pass[] = []; for (let k = 0; k < passNum; ++k) { const passInfo = tech.passes[k] as IPassInfoFull; - const defs = passInfo.curDefs = defines && defines[k] || {}; + const defs = passInfo.curDefs = defines.length > k ? defines[k] : {}; if (passInfo.switch && !defs[passInfo.switch]) { continue; } + passInfo.states = states.length > k ? states[k] : {}; passInfo.idxInTech = k; const pass = new Pass(cc.game._gfxDevice); pass.initialize(passInfo); diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index a4b4b406a7..b0f9364066 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -1,6 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { IPassInfo, IShaderInfo } from '../../3d/assets/effect-asset'; +import { IPassInfo, IPassStates, IShaderInfo } from '../../3d/assets/effect-asset'; import { builtinResMgr } from '../../3d/builtin'; import { TextureBase } from '../../assets/texture-base'; import { color4, mat2, mat3, mat4, vec2, vec3, vec4 } from '../../core/vmath'; @@ -26,9 +26,9 @@ export interface IPassInfoFull extends IPassInfo { // generated part idxInTech: number; curDefs: IDefineMap; + states: PassOverrides; } - -export type PassOverrides = RecursivePartial; +export type PassOverrides = RecursivePartial; const _type2fn = { [GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, @@ -135,6 +135,7 @@ export class Pass { // pipeline state const device = this._device; this._fillinPipelineInfo(info); + this._fillinPipelineInfo(info.states); for (const u of shaderInfo.blocks) { if (u.name.startsWith('CC')) { continue; } @@ -171,11 +172,13 @@ export class Pass { for (const u of shaderInfo.samplers) { this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding); const inf = info.properties && info.properties[u.name]; + if (inf && inf.sampler) { this._samplers[u.binding] = samplerLib.getSampler(device, inf.sampler); } const texName = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; const texture = builtinResMgr.get(texName); if (texture) { this._textureViews[u.binding] = texture.getGFXTextureView()!; - this._samplers[u.binding] = samplerLib.getSampler(device, texture.getGFXSamplerInfo()); + const samplerInfo = texture.getGFXSamplerInfo(); + if (!this._samplers[u.binding] || samplerInfo.length) { this._samplers[u.binding] = samplerLib.getSampler(device, samplerInfo); } } else { console.warn('illegal texture default value ' + texName); } } diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 3a5129ccd9..cd59e51abd 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -100,6 +100,8 @@ class ProgramLib { * programLib.define(program); */ public define (prog: IShaderInfo) { + const cur = this._templates[prog.name]; + if (cur && cur.hash === prog.hash) { return; } const tmpl = Object.assign({ id: ++_shdID }, prog) as IProgramInfo; if (!tmpl.localsInited) { insertBuiltinBindings(tmpl, localBindingsDesc, 'locals'); tmpl.localsInited = true; } @@ -157,7 +159,7 @@ class ProgramLib { return name + defs.reduce((acc, cur) => cur.result ? `${acc}|${cur.name}${cur.result}` : acc, ''); } - public getGFXShader (device: GFXDevice, name: string, defines: IDefineMap = {}, pipeline: RenderPipeline) { + public getGFXShader (device: GFXDevice, name: string, defines: IDefineMap, pipeline: RenderPipeline) { Object.assign(defines, pipeline.macros); const key = this.getKey(name, defines); let program = this._cache[key]; diff --git a/cocos/renderer/core/sampler-lib.ts b/cocos/renderer/core/sampler-lib.ts index db37cac841..9c387618d9 100644 --- a/cocos/renderer/core/sampler-lib.ts +++ b/cocos/renderer/core/sampler-lib.ts @@ -3,6 +3,22 @@ import { GFXDevice } from '../../gfx/device'; import { GFXSampler, IGFXSamplerInfo } from '../../gfx/sampler'; +export enum SamplerInfoIndex { + minFilter, + magFilter, + mipFilter, + addressU, + addressV, + addressW, + maxAnisotropy, + cmpFunc, + minLOD, + maxLOD, + mipLODBias, + borderColor, + total = borderColor + 4, +} + const gfxInfo: IGFXSamplerInfo = {}; class SamplerLib { @@ -12,19 +28,22 @@ class SamplerLib { const hash = info.toString(); const cache = this._cache[hash]; if (cache) { return cache; } - gfxInfo.minFilter = info[0]; - gfxInfo.magFilter = info[1]; - gfxInfo.mipFilter = info[2]; - gfxInfo.addressU = info[3]; - gfxInfo.addressV = info[4]; - gfxInfo.addressW = info[5]; - gfxInfo.maxAnisotropy = info[6]; - if (info.length > 7) { - gfxInfo.cmpFunc = info[7]; - gfxInfo.borderColor = { r: info[8], g: info[9], b: info[10], a: info[11] }; - gfxInfo.minLOD = info[12]; - gfxInfo.maxLOD = info[13]; - gfxInfo.mipLODBias = info[14]; + gfxInfo.minFilter = info[SamplerInfoIndex.minFilter]; + gfxInfo.magFilter = info[SamplerInfoIndex.magFilter]; + gfxInfo.mipFilter = info[SamplerInfoIndex.mipFilter]; + gfxInfo.addressU = info[SamplerInfoIndex.addressU]; + gfxInfo.addressV = info[SamplerInfoIndex.addressV]; + gfxInfo.addressW = info[SamplerInfoIndex.addressW]; + gfxInfo.maxAnisotropy = info[SamplerInfoIndex.maxAnisotropy]; + if (info.length > SamplerInfoIndex.cmpFunc) { + gfxInfo.cmpFunc = info[SamplerInfoIndex.cmpFunc]; + gfxInfo.minLOD = info[SamplerInfoIndex.minLOD]; + gfxInfo.maxLOD = info[SamplerInfoIndex.maxLOD]; + gfxInfo.mipLODBias = info[SamplerInfoIndex.mipLODBias]; + if (info.length >= SamplerInfoIndex.total) { + const ofs = SamplerInfoIndex.borderColor; + gfxInfo.borderColor = { r: info[ofs], g: info[ofs + 1], b: info[ofs + 2], a: info[ofs + 3] }; + } } const sampler = this._cache[hash] = device.createSampler(gfxInfo); return sampler; @@ -32,4 +51,3 @@ class SamplerLib { } export const samplerLib = new SamplerLib(); -cc.samplerLib = samplerLib; diff --git a/cocos/renderer/index.ts b/cocos/renderer/index.ts index b1cd8bc636..7627fd7675 100644 --- a/cocos/renderer/index.ts +++ b/cocos/renderer/index.ts @@ -7,6 +7,10 @@ export { addStage }; export { RenderQueue, PassStage } from './core/constants'; export { Pass } from './core/pass'; export { Effect } from './core/effect'; +export { programLib } from './core/program-lib'; +import { samplerLib } from './core/sampler-lib'; +cc.samplerLib = samplerLib; +export { samplerLib }; export { Light } from './scene/light'; export { Camera } from './scene/camera'; diff --git a/cocos/renderer/scene/light.ts b/cocos/renderer/scene/light.ts index 7cc06b9512..a60218b39b 100644 --- a/cocos/renderer/scene/light.ts +++ b/cocos/renderer/scene/light.ts @@ -1,8 +1,34 @@ import { Vec3 } from '../../core/value-types'; -import { ColorTemperatureToRGB } from '../../pipeline/define'; import { Node } from '../../scene-graph/node'; import { RenderScene } from './render-scene'; +// Color temperature (in Kelvin) to RGB +export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) { + if (kelvin < 1000.0) { + kelvin = 1000.0; + } else if (kelvin > 15000.0) { + kelvin = 15000.0; + } + + // Approximate Planckian locus in CIE 1960 UCS + const kSqr = kelvin * kelvin; + const u = (0.860117757 + 1.54118254e-4 * kelvin + 1.28641212e-7 * kSqr) / ( 1.0 + 8.42420235e-4 * kelvin + 7.08145163e-7 * kSqr); + const v = (0.317398726 + 4.22806245e-5 * kelvin + 4.20481691e-8 * kSqr) / ( 1.0 - 2.89741816e-5 * kelvin + 1.61456053e-7 * kSqr); + + const d = (2.0 * u - 8.0 * v + 4.0); + const x = 3.0 * u / d; + const y = 2.0 * v / d; + const z = 1.0 - x - y; + + const X = 1.0 / y * x; + const Z = 1.0 / y * z; + + // XYZ to RGB with BT.709 primaries + rgb.x = 3.2404542 * X + -1.5371385 + -0.4985314 * Z; + rgb.y = -0.9692660 * X + 1.8760108 + 0.0415560 * Z; + rgb.z = 0.0556434 * X + -0.2040259 + 1.0572252 * Z; +} + export enum LightType { DIRECTIONAL, SPHERE, diff --git a/cocos/renderer/scene/planar-shadow.ts b/cocos/renderer/scene/planar-shadow.ts index 36ea6ef8d7..267b2f743e 100644 --- a/cocos/renderer/scene/planar-shadow.ts +++ b/cocos/renderer/scene/planar-shadow.ts @@ -1,10 +1,13 @@ -import { Color, Vec3 } from '../../core/value-types'; +import { Color, Quat, Vec3 } from '../../core/value-types'; import { color4, vec3 } from '../../core/vmath'; import { UBOShadow } from '../../pipeline/define'; -import { Light } from './light'; +import { DirectionalLight } from './directional-light'; import { RenderScene } from './render-scene'; +import { SphereLight } from './sphere-light'; +const _forward = new Vec3(0, 0, -1); const _v3 = new Vec3(); +const _qt = new Quat(); export class PlanarShadow { @@ -51,12 +54,12 @@ export class PlanarShadow { } // tslint:disable: one-variable-per-declaration - public update (light: Light) { + public updateSphereLight (light: SphereLight) { light.node.getWorldPosition(_v3); const n = this._normal, d = this._distance + this._offset; + const NdL = vec3.dot(n, _v3); const lx = _v3.x, ly = _v3.y, lz = _v3.z; const nx = n.x, ny = n.y, nz = n.z; - const NdL = vec3.dot(n, _v3); const m = this._data; m[0] = NdL - d - lx * nx; m[1] = -ly * nx; @@ -75,5 +78,31 @@ export class PlanarShadow { m[14] = lz * d; m[15] = NdL; } + + public updateDirLight (light: DirectionalLight) { + light.node.getWorldRotation(_qt); + vec3.transformQuat(_v3, _forward, _qt); + const n = this._normal, d = this._distance + this._offset; + const NdL = vec3.dot(n, _v3), scale = 1 / NdL; + const lx = _v3.x * scale, ly = _v3.y * scale, lz = _v3.z * scale; + const nx = n.x, ny = n.y, nz = n.z; + const m = this._data; + m[0] = 1 - nx * lx; + m[1] = -nx * ly; + m[2] = -nx * lz; + m[3] = 0; + m[4] = -ny * lx; + m[5] = 1 - ny * ly; + m[6] = -ny * lz; + m[7] = 0; + m[8] = -nz * lx; + m[9] = -nz * ly; + m[10] = 1 - nz * lz; + m[11] = 0; + m[12] = lx * d; + m[13] = ly * d; + m[14] = lz * d; + m[15] = 1; + } // tslint:enable: one-variable-per-declaration } diff --git a/cocos/renderer/scene/skybox.ts b/cocos/renderer/scene/skybox.ts index 87da09c4da..649fe8e08e 100644 --- a/cocos/renderer/scene/skybox.ts +++ b/cocos/renderer/scene/skybox.ts @@ -21,7 +21,7 @@ export class Skybox extends Model { if (val === this._isRGBE) { return; } this._isRGBE = val; this._material.destroy(); - this._material.initialize({ defines: { USE_RGBE_CUBEMAP: val } }); + this._initMaterial(); this.setSubModelMaterial(0, this._material); this._updateBindingLayout(); } @@ -33,18 +33,12 @@ export class Skybox extends Model { protected _cubemap = this._default; protected _isRGBE = false; - protected _material: Material; + protected _material = new Material(); constructor (scene: RenderScene) { super(scene, null); this._scene = scene; - - this._material = new Material(); - this._material.initialize({ - effectName: 'builtin-skybox', - defines: { USE_RGBE_CUBEMAP: this._isRGBE }, - }); - this._material.setProperty('cubeMap', this._cubemap); + this._initMaterial(); const mesh = createMesh(box({ width: 2, height: 2, length: 2 })); const subMeshData = mesh.renderingMesh!.getSubmesh(0)!; @@ -52,6 +46,14 @@ export class Skybox extends Model { this._updateBindingLayout(); } + protected _initMaterial () { + this._material.initialize({ + effectName: 'builtin-skybox', + defines: { USE_RGBE_CUBEMAP: this._isRGBE }, + }); + this._material.setProperty('cubeMap', this._cubemap); + } + protected _updateBindingLayout () { this._matPSORecord.get(this._material)![0].pipelineLayout.layouts[0].update(); } diff --git a/playground/gizmo.html b/playground/gizmo.html index e3329adfe3..9da38938a5 100644 --- a/playground/gizmo.html +++ b/playground/gizmo.html @@ -43,7 +43,6 @@ const { vec3, quat } = cc.vmath; - function onStart() { const root = cc.director.root; const scene = new cc.Scene('scene'); @@ -60,6 +59,18 @@ effectName: 'builtin-unlit', defines: { USE_COLOR: true }, }); + const material2 = new cc.Material(); + material2.initialize({ + effectName: 'builtin-unlit', + defines: { USE_COLOR: true }, + states: { + depthStencilState: { depthTest: false, depthWrite: false }, + rasterizerState: { cullMode: cc.GFXCullMode.NONE }, + blendState: { targets: [ + { blend: true, blendDst: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA, blendDstAlpha: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA } + ] } + } + }); const createArrow = (color, rotation) => { const arrow = new cc.Node('arrow'); @@ -80,10 +91,9 @@ primitiveMode: cc.GFXPrimitiveMode.LINE_LIST, }); - bodyModel.material = material; - bodyModel.material.setProperty('color', color); bodyModel.material.overridePipelineStates({ primitive: cc.GFXPrimitiveMode.LINE_LIST }); + bodyModel.material.setProperty('color', color); return arrow; }; const createBorderPlane = (color, position, rotation) => { @@ -101,15 +111,8 @@ const ibInfo = mesh.struct.primitives[0].indices.range; submesh.ibuffer = mesh.data.buffer.slice(ibInfo.offset, ibInfo.offset + ibInfo.length); - planeModel.material = material; + planeModel.material = material2; planeModel.material.setProperty('color', color.lerp(cc.color(0, 0, 0, 0), 0.5)); - planeModel.material.overridePipelineStates({ - depthStencilState: { depthTest: false, depthWrite: false }, - rasterizerState: { cullMode: cc.GFXCullMode.NONE }, - blendState: { targets: [ - { blend: true, blendDst: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA, blendDstAlpha: cc.GFXBlendFactor.ONE_MINUS_SRC_ALPHA } - ] } - }); const border = new cc.Node('border'); border.parent = borderPlane; const borderModel = border.addComponent(cc.ModelComponent); @@ -119,8 +122,8 @@ primitiveMode: cc.GFXPrimitiveMode.LINE_LIST, }); borderModel.material = material; - borderModel.material.setProperty('color', color); borderModel.material.overridePipelineStates({ primitive: cc.GFXPrimitiveMode.LINE_LIST }); + borderModel.material.setProperty('color', color); return borderPlane; }; diff --git a/playground/planarShadow.html b/playground/planarShadow.html index 16c2c9a710..8a73ee44cf 100644 --- a/playground/planarShadow.html +++ b/playground/planarShadow.html @@ -69,6 +69,7 @@ const lightNode = new cc.Node('Light'); lightNode.parent = rt; lightNode.setPosition(-10, 10, -10); + lightNode.setRotationFromEuler(-50, 0, 0); const lightComp = lightNode.addComponent(cc.DirectionalLightComponent); // parsed effect file is embedded in cocos/3d/builtin/effects.js @@ -109,6 +110,26 @@ // material.setProperty('matLightPlaneProj', getLightPlaneProj(cc.v3(-10, altitude + 10, -10), // light // cc.geometry.plane.create(nm.x, nm.y, nm.z, cc.vmath.vec3.dot(nm, models.plane.node.getWorldPosition())))); + // const { vec3, quat } = cc.vmath; + // const L = vec3.transformQuat(cc.v3(), cc.v3(0, 0, -1), quat.fromEuler(cc.quat(), 10, 20, 30)); + // const N = vec3.transformQuat(cc.v3(), cc.v3(0, 1, 0), quat.fromEuler(cc.quat(), 10, 0, 0)), d = 0; + // const sp = cc.primitives.sphere(); + // const pos = sp.positions; + // const V = cc.v3(); + // for (let i = 0; i < pos.length; i += 3) { + // vec3.set(V, pos[i], pos[i+1], pos[i+2]); + // const scale = (d - vec3.dot(V, N)) / vec3.dot(N, L); + // pos[i] = V.x + scale * L.x; + // pos[i+1] = V.y + scale * L.y; + // pos[i+2] = V.z + scale * L.z; + // } + + // const spNode = new cc.Node('test'); + // spNode.parent = rt; + // const spCom = spNode.addComponent('cc.ModelComponent'); + // spCom.material = cc.builtinResMgr.get('default-material'); + // spCom.mesh = cc.utils.createMesh(sp); + cc.director.runSceneImmediate(scene); } cc.game.run({ id: 'canvas' }, onStart);