diff --git a/.vscode/launch.json b/.vscode/launch.json index 1ee10e49ed..0d7b47731b 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -2,10 +2,11 @@ "version": "0.2.0", "configurations": [ { - "type": "node", + "type": "chrome", "request": "launch", - "name": "Generate declaration", - "program": "${workspaceFolder}\\scripts\\generate-declaration-cli.js" + "name": "Launch Chrome", + "url": "http://localhost:8002/playground/simple.html", + "webRoot": "${workspaceFolder}" } ] } \ No newline at end of file diff --git a/globals.d.ts b/@types/globals.d.ts similarity index 91% rename from globals.d.ts rename to @types/globals.d.ts index 344997f078..8fd63efef3 100644 --- a/globals.d.ts +++ b/@types/globals.d.ts @@ -37,14 +37,24 @@ declare const CC_QQPLAY: boolean; declare const CC_RUNTIME: boolean; declare const CC_SUPPORT_JIT: boolean; -declare const cc: any; +declare const cc : { + // polyfills: { + // destroyObject? (object: any): void; + // }; + [x: string]: any; +}; -type RecursivePartial = { +declare type RecursivePartial = { [P in keyof T]?: T[P] extends Array ? Array> : T[P] extends ReadonlyArray ? ReadonlyArray> : RecursivePartial; }; +declare interface IWritableArrayLike { + readonly length: number; + [index: number]: T; +} + declare module "webgl-debug" { export function makeDebugContext( webGLRenderingContext: WebGLRenderingContext, diff --git a/wx.d.ts b/@types/wx.d.ts similarity index 100% rename from wx.d.ts rename to @types/wx.d.ts diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 3e247da122..3da5baceeb 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -101,18 +101,18 @@ 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":[0.6, 0.2, 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}, "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":[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"}]} ], "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", "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 SmoothDistAtt(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 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.r, 0.04, 1.0);\n float metallic = clamp(pbr.g, 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 = SmoothDistAtt(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_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` }, "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 SmoothDistAtt(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 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.r, 0.04, 1.0);\n float metallic = clamp(pbr.g, 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 = SmoothDistAtt(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_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` }, "builtins": {"globals":{"blocks":["CCGlobal"], "samplers":[]}, "locals":{"blocks":["CCLocal", "CCSkinning", "CCForwardLight"], "samplers":["cc_jointsTexture"]}}, "defines": [ @@ -123,6 +123,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":"USE_ALPHA_TEST", "type":"boolean", "defines":[]}, {"name":"CC_USE_HDR", "type":"boolean", "defines":[]} ], @@ -150,14 +152,16 @@ export default [ "name": "builtin-standard|planar-shadow-vs:vert|planar-shadow-fs:frag", "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};\nvec4 frag () {\n return cc_shadowColor;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\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` }, "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;\nvec4 frag () {\n return cc_shadowColor;\n}\nvoid main() { gl_FragColor = frag(); }\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` }, "builtins": {"globals":{"blocks":["CCGlobal", "CCShadow"], "samplers":[]}, "locals":{"blocks":["CCLocal"], "samplers":[]}}, - "defines": [], + "defines": [ + {"name":"CC_USE_HDR", "type":"boolean", "defines":[]} + ], "blocks": [], "samplers": [], "dependencies": {} @@ -167,7 +171,7 @@ 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, "sampler":{"minFilter":2, "magFilter":2, "mipFilter":0}}}}]} + {"name":"tonemap", "passes":[{"depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-tonemap|tonemap-vs:vert|tonemap-fs:frag", "properties":{"u_texSampler":{"type":29}}}]} ], "shaders": [ { diff --git a/cocos/3d/framework/directional-light-component.ts b/cocos/3d/framework/directional-light-component.ts index 218ee81545..c03fe3a0c6 100644 --- a/cocos/3d/framework/directional-light-component.ts +++ b/cocos/3d/framework/directional-light-component.ts @@ -34,7 +34,7 @@ import { LightComponent } from './light-component'; export class DirectionalLightComponent extends LightComponent { @property - protected _intensity = 10000; + protected _illuminance = 65000; protected _type = LightType.DIRECTIONAL; protected _light: DirectionalLight | null = null; @@ -45,12 +45,12 @@ export class DirectionalLightComponent extends LightComponent { * !#ch 光源强度 */ @property - get intensity () { - return this._intensity; + get illuminance () { + return this._illuminance; } - set intensity (val) { - this._intensity = val; - if (this._light) { this._light.illuminance = this._intensity; } + set illuminance (val) { + this._illuminance = val; + if (this._light) { this._light.illuminance = this._illuminance; } } protected _createLight (scene?: RenderScene) { @@ -61,7 +61,7 @@ export class DirectionalLightComponent extends LightComponent { return; } this._light = scene.mainLight; - this.intensity = this._intensity; + this.illuminance = this._illuminance; super._createLight(scene); } diff --git a/cocos/3d/framework/particle/particle-system-component.ts b/cocos/3d/framework/particle/particle-system-component.ts index 16109f3d64..1e2735d97c 100644 --- a/cocos/3d/framework/particle/particle-system-component.ts +++ b/cocos/3d/framework/particle/particle-system-component.ts @@ -238,10 +238,10 @@ export class ParticleSystemComponent extends Component { this.renderer = null; } - private onLoad () { + protected onLoad () { // HACK, TODO this.renderer = this.getComponent(ParticleSystemRenderer); - this.renderer.onInit(); + this.renderer!.onInit(); this.shapeModule.onInit(this); this.textureAnimationModule.onInit(this); @@ -251,17 +251,17 @@ export class ParticleSystemComponent extends Component { // this._system.add(this); } - private onDestroy () { + protected onDestroy () { // this._system.remove(this); } - private onEnable () { + protected onEnable () { if (this.playOnAwake) { this.play(); } } - private onDisable () { + protected onDisable () { } @@ -434,7 +434,7 @@ export class ParticleSystemComponent extends Component { } } - private update (dt) { + protected update (dt) { const scaledDeltaTime = dt * this.simulationSpeed; if (this._isPlaying) { this._time += scaledDeltaTime; diff --git a/cocos/3d/physics/instance.ts b/cocos/3d/physics/instance.ts index eb6c3b45af..fa4d8f93fb 100644 --- a/cocos/3d/physics/instance.ts +++ b/cocos/3d/physics/instance.ts @@ -1,5 +1,5 @@ import { Vec3 } from '../../core/value-types'; -import { BoxShapeBase, ICreateBodyOptions, PhysicsWorldBase, RigidBodyBase } from './api'; +import { BoxShapeBase, ICreateBodyOptions, PhysicsWorldBase, RigidBodyBase, SphereShapeBase } from './api'; import { BoxShape, PhysicsWorld, RigidBody, SphereShape } from './impl-selector'; import { RaycastResult } from './raycast-result'; @@ -15,7 +15,7 @@ export function createBoxShape (size: Vec3): BoxShapeBase { return new BoxShape(size); } -export function createSphereShape (radius: number): SphereShape { +export function createSphereShape (radius: number): SphereShapeBase { return new SphereShape(radius); } diff --git a/cocos/assets/asset.d.ts b/cocos/assets/asset.d.ts deleted file mode 100644 index c64c1aa2c6..0000000000 --- a/cocos/assets/asset.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -import { RawAsset } from "./raw-asset"; - -export class Asset extends RawAsset { - protected _native: string; - public loaded: boolean; - - public _nativeAsset: any; - public nativeUrl: string; - - static preventDeferredLoadDependents: boolean; - static preventPreloadNativeObject: boolean; - static deserialize(data: string): object; - - public createNode: (err: string, node: object) => void | null; - public toString(): string; - public serialize(): string; - protected _setRawAsset(filename: string, inLibrary: boolean): void; -} diff --git a/cocos/assets/asset.js b/cocos/assets/asset.ts similarity index 78% rename from cocos/assets/asset.js rename to cocos/assets/asset.ts index 050dcdfabc..c270cfa8ec 100644 --- a/cocos/assets/asset.js +++ b/cocos/assets/asset.ts @@ -25,6 +25,7 @@ ****************************************************************************/ import { ccclass, property } from '../core/data/class-decorator'; +import { Node } from '../scene-graph'; import { RawAsset } from './raw-asset'; /** @@ -50,20 +51,6 @@ import { RawAsset } from './raw-asset'; */ @ccclass('cc.Asset') export class Asset extends RawAsset { - constructor () { - super(); - /** - * !#en - * Whether the asset is loaded or not - * !#zh - * 该资源是否已经成功加载 - * - * @property loaded - * @type {Boolean} - */ - this.loaded = true; - } - /** * !#en * Returns the url of this asset's native object, if none it will returns an empty string. @@ -74,18 +61,18 @@ export class Asset extends RawAsset { * @readOnly */ @property({ - visible: false + visible: false, }) get nativeUrl () { if (this._native) { - var name = this._native; + const name = this._native; if (name.charCodeAt(0) === 47) { // '/' // remove library tag // not imported in library, just created on-the-fly return name.slice(1); } if (cc.AssetLibrary) { - var base = cc.AssetLibrary.getLibUrlNoExt(this._uuid, true); + const base = cc.AssetLibrary.getLibUrlNoExt(this._uuid, true); if (name.charCodeAt(0) === 46) { // '.' // imported in dir where json exist return base + name; @@ -102,15 +89,6 @@ export class Asset extends RawAsset { return ''; } - /** - * Serializable url for native asset. - * @property {String} _native - * @default "" - * @private - */ - @property - _native = "" - /** * The underlying native asset of this asset if one is available. * This property can be used to access additional details or functionality releated to the asset. @@ -121,24 +99,12 @@ export class Asset extends RawAsset { * @type {any} */ @property - get _nativeAsset () { + get _nativeAsset (): any { + return null; } set _nativeAsset (obj) { } - /** - * 应 AssetDB 要求提供这个方法 - * - * @method deserialize - * @param {String} data - * @return {Asset} - * @static - * @private - */ - static deserialize (data) { - return cc.deserialize(data); - } - /** * !#en Indicates whether its dependent raw assets can support deferred load if the owner scene (or prefab) is marked as `asyncLoadAssets`. * !#zh 当场景或 Prefab 被标记为 `asyncLoadAssets`,禁止延迟加载该资源所依赖的其它 RawAsset。 @@ -147,7 +113,7 @@ export class Asset extends RawAsset { * @default false * @static */ - static preventDeferredLoadDependents = false; + public static preventDeferredLoadDependents = false; /** * !#en Indicates whether its native object should be preloaded from native url. @@ -157,13 +123,45 @@ export class Asset extends RawAsset { * @default false * @static */ - static preventPreloadNativeObject = false; + public static preventPreloadNativeObject = false; + + /** + * 应 AssetDB 要求提供这个方法 + * + * @method deserialize + * @param {String} data + * @return {Asset} + * @static + * @private + */ + public static deserialize (data) { + return cc.deserialize(data); + } + /** + * !#en + * Whether the asset is loaded or not + * !#zh + * 该资源是否已经成功加载 + */ + public loaded = true; + + /** + * Serializable url for native asset. For internal usage. + * @default "" + */ + @property + public _native: string | undefined = ''; + + constructor () { + super(); + } /** * Returns the string representation of the object. * * The `Asset` object overrides the `toString()` method of the `Object` object. - * JavaScript calls the toString() method automatically when an asset is to be represented as a text value or when a texture is referred to in a string concatenation. + * JavaScript calls the toString() method automatically when an asset is to + * be represented as a text value or when a texture is referred to in a string concatenation. * * For assets of the native type, it will return `this.nativeUrl`. * Otherwise, an empty string is returned. @@ -172,7 +170,7 @@ export class Asset extends RawAsset { * @method toString * @return {String} */ - toString () { + public toString () { return this.nativeUrl; } @@ -183,20 +181,19 @@ export class Asset extends RawAsset { * @return {String} * @private */ - serialize () { - return Editor.serialize(this); - } + // public serialize () { + // return Editor.serialize(this); + // } /** * Set native file name for this asset. * @seealso nativeUrl * - * @method _setRawAsset - * @param {String} filename - * @param {Boolean} [inLibrary=true] + * @param filename + * @param [inLibrary=true] * @private */ - _setRawAsset (filename, inLibrary) { + public _setRawAsset (filename: string, inLibrary?: boolean) { if (inLibrary !== false) { this._native = filename || undefined; } @@ -204,21 +201,25 @@ export class Asset extends RawAsset { this._native = '/' + filename; // simply use '/' to tag location where is not in the library } } + + /** + * !#en + * Create a new node using this asset in the scene.
+ * If this type of asset dont have its corresponding node type, this method should be null. + * !#zh + * 使用该资源在场景中创建一个新节点。
+ * 如果这类资源没有相应的节点类型,该方法应该是空的。 + */ + public createNode? (callback: CreateNodeCallback): void; } /** - * !#en - * Create a new node using this asset in the scene.
- * If this type of asset dont have its corresponding node type, this method should be null. - * !#zh - * 使用该资源在场景中创建一个新节点。
- * 如果这类资源没有相应的节点类型,该方法应该是空的。 - * - * @method createNode - * @param {Function} callback - * @param {String} callback.error - null or the error info - * @param {Object} callback.node - the created node or null + * @param error - null or the error info + * @param node - the created node or null */ +type CreateNodeCallback = (error: Error | null, node: Node) => void; + +// @ts-ignore Asset.prototype.createNode = null; cc.Asset = Asset; diff --git a/cocos/assets/raw-asset.d.ts b/cocos/assets/raw-asset.d.ts deleted file mode 100644 index a7d7b2e319..0000000000 --- a/cocos/assets/raw-asset.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -import { CCObject } from '../core/data/object'; - -export class RawAsset extends CCObject { - _uuid: string; - public constructor(); - static isRawAssetType(ctor: Function): boolean; -} diff --git a/cocos/assets/raw-asset.js b/cocos/assets/raw-asset.ts similarity index 89% rename from cocos/assets/raw-asset.js rename to cocos/assets/raw-asset.ts index 52b902900a..3212db829c 100644 --- a/cocos/assets/raw-asset.js +++ b/cocos/assets/raw-asset.ts @@ -24,9 +24,9 @@ THE SOFTWARE. ****************************************************************************/ -import { isChildClassOf } from '../core/utils/js'; -import { CCObject } from '../core/data/object'; import { ccclass } from '../core/data/class-decorator'; +import { CCObject } from '../core/data/object'; +import { isChildClassOf } from '../core/utils/js'; /** * !#en @@ -39,30 +39,28 @@ import { ccclass } from '../core/data/class-decorator'; */ @ccclass('cc.RawAsset') export class RawAsset extends CCObject { + /** + * For internal usage. + */ + public static isRawAssetType (ctor: Function) { + return isChildClassOf(ctor, cc.RawAsset) && !isChildClassOf(ctor, cc.Asset); + } + + /** + * For internal usage. + */ + // @ts-ignore + public _uuid: string; + constructor () { super(); - /** - * @property _uuid - * @type {String} - * @private - */ + Object.defineProperty(this, '_uuid', { value: '', writable: true, // enumerable is false by default, to avoid uuid being assigned to empty string during destroy }); } - - /** - * @method isRawAssetType - * @param {Function} ctor - * @returns {Boolean} - * @static - * @private - */ - static isRawAssetType (ctor) { - return isChildClassOf(ctor, cc.RawAsset) && !isChildClassOf(ctor, cc.Asset); - } } cc.RawAsset = RawAsset; diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index 4b8ea5aede..a058eb61d1 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -201,13 +201,13 @@ export class TextureBase extends EventTargetFactory(Asset) { protected _mipFilter: number = Filter.LINEAR; @property - protected _wrapU: number = WrapMode.REPEAT; + protected _wrapS: number = WrapMode.REPEAT; @property - protected _wrapV: number = WrapMode.REPEAT; + protected _wrapT: number = WrapMode.REPEAT; @property - protected _wrapW: number = WrapMode.REPEAT; + protected _wrapR: number = WrapMode.REPEAT; @property protected _anisotropy = 16; @@ -308,14 +308,15 @@ export class TextureBase extends EventTargetFactory(Asset) { * If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}. * !#zh 设置纹理包装模式。 * 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。 - * @param wrapU - * @param wrapV + * @param wrapS + * @param wrapT + * @param wrapR */ - public setWrapMode (wrapU: WrapMode, wrapV: WrapMode, wrapW?: WrapMode) { - if (wrapU !== this._wrapU) { this._wrapU = wrapU; this._samplerInfo[3] = wrapU; } - if (wrapV !== this._wrapV) { this._wrapV = wrapV; this._samplerInfo[4] = wrapV; } - if (wrapW === undefined) { return; } - if (wrapW !== this._wrapW) { this._wrapW = wrapW; this._samplerInfo[5] = wrapW; } + 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 (wrapR === undefined) { return; } + if (wrapR !== this._wrapR) { this._wrapR = wrapR; this._samplerInfo[5] = wrapR; } } /** @@ -406,7 +407,7 @@ export class TextureBase extends EventTargetFactory(Asset) { */ public _serialize (): any { return this._minFilter + ',' + this._magFilter + ',' + - this._wrapU + ',' + this._wrapV + ',' + + this._wrapS + ',' + this._wrapT + ',' + (this._premultiplyAlpha ? 1 : 0) + ',' + this._mipFilter + ',' + this._anisotropy + ',' + (this._flipY ? 1 : 0) + ',' + @@ -527,9 +528,9 @@ export class TextureBase extends EventTargetFactory(Asset) { }; if (source instanceof HTMLElement) { - gfxDevice.copyImageSourceToTexture([source], this._texture, [region]); + gfxDevice.copyTexImagesToTexture([source], this._texture, [region]); } else { - gfxDevice.copyBufferToTexture(source, this._texture, [region]); + gfxDevice.copyBuffersToTexture([source], this._texture, [region]); } } diff --git a/cocos/core/vmath/color3.ts b/cocos/core/vmath/color3.ts index 5cbaf9da2c..ddd1fa7cff 100644 --- a/cocos/core/vmath/color3.ts +++ b/cocos/core/vmath/color3.ts @@ -1,4 +1,3 @@ -import { IWritableArrayLike } from './fwd-decls'; import { EPSILON } from './utils'; /** diff --git a/cocos/core/vmath/color4.ts b/cocos/core/vmath/color4.ts index 1672fa754e..e177ec8714 100644 --- a/cocos/core/vmath/color4.ts +++ b/cocos/core/vmath/color4.ts @@ -1,4 +1,3 @@ -import { IWritableArrayLike } from './fwd-decls'; import { EPSILON } from './utils'; // tslint:disable: one-variable-per-declaration diff --git a/cocos/core/vmath/fwd-decls.d.ts b/cocos/core/vmath/fwd-decls.d.ts deleted file mode 100644 index 32db0b281f..0000000000 --- a/cocos/core/vmath/fwd-decls.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface IWritableArrayLike { - readonly length: number; - [index: number]: T; -} diff --git a/cocos/core/vmath/mat2.ts b/cocos/core/vmath/mat2.ts index a17d43356b..28b6667ead 100644 --- a/cocos/core/vmath/mat2.ts +++ b/cocos/core/vmath/mat2.ts @@ -1,4 +1,3 @@ -import { IWritableArrayLike } from './fwd-decls'; import { EPSILON } from './utils'; import vec2 from './vec2'; diff --git a/cocos/core/vmath/mat23.ts b/cocos/core/vmath/mat23.ts index 19cb3be97c..9351e7da58 100644 --- a/cocos/core/vmath/mat23.ts +++ b/cocos/core/vmath/mat23.ts @@ -1,4 +1,3 @@ -import { IWritableArrayLike } from './fwd-decls'; import { EPSILON } from './utils'; import vec2 from './vec2'; diff --git a/cocos/core/vmath/quat.ts b/cocos/core/vmath/quat.ts index 9784c5eb23..71014b478b 100644 --- a/cocos/core/vmath/quat.ts +++ b/cocos/core/vmath/quat.ts @@ -1,4 +1,3 @@ -import { IWritableArrayLike } from './fwd-decls'; import mat3 from './mat3'; import { toDegree } from './utils'; import vec3 from './vec3'; diff --git a/cocos/core/vmath/vec2.ts b/cocos/core/vmath/vec2.ts index ef45af29c4..8b7a5b02a5 100644 --- a/cocos/core/vmath/vec2.ts +++ b/cocos/core/vmath/vec2.ts @@ -1,4 +1,3 @@ -import { IWritableArrayLike } from './fwd-decls'; import mat2 from './mat2'; import mat23 from './mat23'; import mat3 from './mat3'; diff --git a/cocos/core/vmath/vec3.ts b/cocos/core/vmath/vec3.ts index 8e43374fc8..00ada6c5f5 100644 --- a/cocos/core/vmath/vec3.ts +++ b/cocos/core/vmath/vec3.ts @@ -1,4 +1,3 @@ -import { IWritableArrayLike } from './fwd-decls'; import mat3 from './mat3'; import mat4 from './mat4'; import quat from './quat'; diff --git a/cocos/core/vmath/vec4.ts b/cocos/core/vmath/vec4.ts index 378e09e867..e8143a0ee0 100644 --- a/cocos/core/vmath/vec4.ts +++ b/cocos/core/vmath/vec4.ts @@ -1,4 +1,3 @@ -import { IWritableArrayLike } from './fwd-decls'; import mat4 from './mat4'; import quat from './quat'; import { EPSILON, random } from './utils'; diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index 905c3142ae..4250f80401 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -191,8 +191,8 @@ export abstract class GFXDevice { public abstract createWindow (info: IGFXWindowInfo): GFXWindow; public abstract present (); - public abstract copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]); - public abstract copyImageSourceToTexture (source: CanvasImageSource[], texture: GFXTexture, regions: GFXBufferTextureCopy[]); + public abstract copyBuffersToTexture (buffers: ArrayBuffer[], texture: GFXTexture, regions: GFXBufferTextureCopy[]); + public abstract copyTexImagesToTexture (texImages: TexImageSource[], texture: GFXTexture, regions: GFXBufferTextureCopy[]); public abstract copyFramebufferToBuffer (srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]); public hasFeature (feature: GFXFeature): boolean { diff --git a/cocos/gfx/texture.ts b/cocos/gfx/texture.ts index 8e10ab1898..d024740c2a 100644 --- a/cocos/gfx/texture.ts +++ b/cocos/gfx/texture.ts @@ -78,6 +78,7 @@ export abstract class GFXTexture extends GFXObject { protected _arrayLayer: number = 1; protected _mipLevel: number = 1; protected _flags: GFXTextureFlags = GFXTextureFlagBit.NONE; + protected _isPowerOf2: boolean = false; protected _size: number = 0; protected _buffer: ArrayBuffer | null = null; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 95f6a722a8..f4e3f5bebc 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -793,14 +793,20 @@ export function WebGLCmdFuncCreateTexture (device: WebGLGFXDevice, gpuTexture: W } } - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, WebGLRenderingContext.CLAMP_TO_EDGE); - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, WebGLRenderingContext.CLAMP_TO_EDGE); - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, WebGLRenderingContext.LINEAR); - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MAG_FILTER, WebGLRenderingContext.LINEAR); - gpuTexture.glWrapS = WebGLRenderingContext.CLAMP_TO_EDGE; - gpuTexture.glWrapT = WebGLRenderingContext.CLAMP_TO_EDGE; + if (gpuTexture.isPowerOf2) { + gpuTexture.glWrapS = WebGLRenderingContext.REPEAT; + gpuTexture.glWrapT = WebGLRenderingContext.REPEAT; + } else { + gpuTexture.glWrapS = WebGLRenderingContext.CLAMP_TO_EDGE; + gpuTexture.glWrapT = WebGLRenderingContext.CLAMP_TO_EDGE; + } gpuTexture.glMinFilter = WebGLRenderingContext.LINEAR; gpuTexture.glMagFilter = WebGLRenderingContext.LINEAR; + + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, gpuTexture.glWrapS); + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, gpuTexture.glWrapT); + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter); + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter); } break; @@ -844,14 +850,20 @@ export function WebGLCmdFuncCreateTexture (device: WebGLGFXDevice, gpuTexture: W } } - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, WebGLRenderingContext.CLAMP_TO_EDGE); - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, WebGLRenderingContext.CLAMP_TO_EDGE); - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, WebGLRenderingContext.LINEAR); - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MAG_FILTER, WebGLRenderingContext.LINEAR); - gpuTexture.glWrapS = WebGLRenderingContext.CLAMP_TO_EDGE; - gpuTexture.glWrapT = WebGLRenderingContext.CLAMP_TO_EDGE; + if (gpuTexture.isPowerOf2) { + gpuTexture.glWrapS = WebGLRenderingContext.REPEAT; + gpuTexture.glWrapT = WebGLRenderingContext.REPEAT; + } else { + gpuTexture.glWrapS = WebGLRenderingContext.CLAMP_TO_EDGE; + gpuTexture.glWrapT = WebGLRenderingContext.CLAMP_TO_EDGE; + } gpuTexture.glMinFilter = WebGLRenderingContext.LINEAR; gpuTexture.glMagFilter = WebGLRenderingContext.LINEAR; + + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, gpuTexture.glWrapS); + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, gpuTexture.glWrapT); + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter); + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter); } break; @@ -1283,6 +1295,8 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web let gpuShader: WebGLGPUShader | null = null; let gpuInputAssembler: IWebGLGPUInputAssembler | null = null; let glPrimitive = WebGLRenderingContext.TRIANGLES; + let glWrapS; + let glWrapT; for (let i = 0; i < cmdPackage.cmds.length; ++i) { const cmd = cmdPackage.cmds.array[i]; @@ -1935,15 +1949,22 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web if (glTexUnit) { const gpuSampler = gpuBinding.gpuSampler; - - if (gpuTexture.glWrapS !== gpuSampler.glWrapS) { - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, gpuSampler.glWrapS); - gpuTexture.glWrapS = gpuSampler.glWrapS; + if (gpuTexture.isPowerOf2) { + glWrapS = gpuSampler.glWrapS; + glWrapT = gpuSampler.glWrapT; + } else { + glWrapS = WebGLRenderingContext.CLAMP_TO_EDGE; + glWrapT = WebGLRenderingContext.CLAMP_TO_EDGE; } - if (gpuTexture.glWrapT !== gpuSampler.glWrapT) { - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, gpuSampler.glWrapT); - gpuTexture.glWrapT = gpuSampler.glWrapT; + if (gpuTexture.glWrapS !== glWrapS) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, glWrapS); + gpuTexture.glWrapS = glWrapS; + } + + if (gpuTexture.glWrapT !== glWrapT) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, glWrapT); + gpuTexture.glWrapT = glWrapT; } if (gpuTexture.glMinFilter !== gpuSampler.glMinFilter) { @@ -2287,9 +2308,9 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { const cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId]; - WebGLCmdFuncCopyBufferToTexture( + WebGLCmdFuncCopyBuffersToTexture( device, - (cmd5.gpuBuffer as WebGLGPUBuffer).buffer as GFXBufferSource, + [(cmd5.gpuBuffer as WebGLGPUBuffer).buffer!], cmd5.gpuTexture as WebGLGPUTexture, cmd5.regions); @@ -2299,22 +2320,16 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } // for } -export function WebGLCmdFuncCopyBufferToTexture ( +export function WebGLCmdFuncCopyTexImagesToTexture ( device: WebGLGFXDevice, - buffer: GFXBufferSource, + texImages: TexImageSource[], gpuTexture: WebGLGPUTexture, regions: GFXBufferTextureCopy[]) { const gl = device.gl; - - const buff = buffer as ArrayBuffer; - const fmtInfo: IGFXFormatInfo = GFXFormatInfos[gpuTexture.format]; let m = 0; - let w = 1; - let h = 1; + let n = 0; let f = 0; - let buffOffset = 0; - switch (gpuTexture.glTarget) { case WebGLRenderingContext.TEXTURE_2D: { const glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; @@ -2323,48 +2338,12 @@ export function WebGLCmdFuncCopyBufferToTexture ( glTexUnit.glTexture = gpuTexture.glTexture; } - const isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; - if (!isCompressed) { - for (const region of regions) { - buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - - w = region.texExtent.width; - h = region.texExtent.height; - - for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = buff.slice(buffOffset, buffOffset + memSize); - const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); - - gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } - } - } else { - for (const region of regions) { - buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - - w = region.texExtent.width; - h = region.texExtent.height; - - for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = buff.slice(buffOffset, buffOffset + memSize); - const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); - - gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } + for (const region of regions) { + n = 0; + for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, + gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); } } break; @@ -2376,53 +2355,100 @@ export function WebGLCmdFuncCopyBufferToTexture ( glTexUnit.glTexture = gpuTexture.glTexture; } - const isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; - if (!isCompressed) { - for (const region of regions) { - buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; - for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; - - const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount; - for (m = region.texSubres.baseMipLevel; m < mcount; ++m) { - const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = buff.slice(buffOffset, buffOffset + memSize); - const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); - - gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } - } - } - } else { - for (const region of regions) { - buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; - for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; - - const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount; - for (m = region.texSubres.baseMipLevel; m < mcount; ++m) { - const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = buff.slice(buffOffset, buffOffset + memSize); - const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); - - gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } + for (const region of regions) { + n = 0; + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { + const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount; + for (m = region.texSubres.baseMipLevel; m < mcount; ++m) { + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, + region.texOffset.x, region.texOffset.y, + gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); + } + } + } + break; + } + default: { + console.error('Unsupported GL texture type, copy buffer to texture failed.'); + } + } + + if (gpuTexture.flags & GFXTextureFlagBit.GEN_MIPMAP) { + gl.generateMipmap(gpuTexture.glTarget); + } +} + +export function WebGLCmdFuncCopyBuffersToTexture ( + device: WebGLGFXDevice, + buffers: ArrayBuffer[], + gpuTexture: WebGLGPUTexture, + regions: GFXBufferTextureCopy[]) { + + const gl = device.gl; + let m = 0; + let n = 0; + let w = 1; + let h = 1; + let f = 0; + const fmtInfo: IGFXFormatInfo = GFXFormatInfos[gpuTexture.format]; + const isCompressed = fmtInfo.isCompressed; + switch (gpuTexture.glTarget) { + case WebGLRenderingContext.TEXTURE_2D: { + const glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + for (const region of regions) { + n = 0; + w = region.texExtent.width; + h = region.texExtent.height; + + for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + const pixels = !fmtInfo.isFloating ? new Uint8Array(buffers[n++]) : new Float32Array(buffers[n++]); + + if (!isCompressed) { + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, pixels); + } else { + gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); + } + + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + break; + } + case WebGLRenderingContext.TEXTURE_CUBE_MAP: { + const glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + for (const region of regions) { + n = 0; + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { + w = region.texExtent.width; + h = region.texExtent.height; + + const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount; + for (m = region.texSubres.baseMipLevel; m < mcount; ++m) { + const pixels = !fmtInfo.isFloating ? new Uint8Array(buffers[n++]) : new Float32Array(buffers[n++]); + + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, pixels); + + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); } } } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 61d9778de9..acde4cbf78 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -25,9 +25,7 @@ import { WebGLGFXBindingLayout } from './webgl-binding-layout'; import { WebGLGFXBuffer } from './webgl-buffer'; import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; -import { - WebGLCmdFuncCopyBufferToTexture, -} from './webgl-commands'; +import { WebGLCmdFuncCopyBuffersToTexture, WebGLCmdFuncCopyTexImagesToTexture } from './webgl-commands'; import { WebGLGFXFramebuffer } from './webgl-framebuffer'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { WebGLGFXPipelineLayout } from './webgl-pipeline-layout'; @@ -463,49 +461,22 @@ export class WebGLGFXDevice extends GFXDevice { (this._cmdAllocator as WebGLGFXCommandAllocator).releaseCmds(); } - public copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { - WebGLCmdFuncCopyBufferToTexture( + public copyBuffersToTexture (buffers: ArrayBuffer[], texture: GFXTexture, regions: GFXBufferTextureCopy[]) { + WebGLCmdFuncCopyBuffersToTexture( this, - buffer, + buffers, (texture as WebGLGFXTexture).gpuTexture, regions); } - public copyImageSourceToTexture ( - source: CanvasImageSource[], + public copyTexImagesToTexture ( + texImages: TexImageSource[], texture: GFXTexture, regions: GFXBufferTextureCopy[]) { - if (!this._canvas2D) { return; } - const context = this._canvas2D.getContext('2d'); - if (!context) { return; } - - const data: Uint8ClampedArray[] = []; - const faces = source.length / regions.length; - let imgSrc: CanvasImageSource; - - for (let j = 0; j < regions.length; j++) { - for (let i = 0; i < faces; i++) { - const level = regions[j].texSubres.baseMipLevel; - this._canvas2D.width = texture.width >> level; - this._canvas2D.height = texture.height >> level; - imgSrc = source[j * faces + i]; - - if (imgSrc.width <= 0 || imgSrc.height <= 0) { - return ; - } - - context.drawImage(imgSrc, 0, 0); - data.push(context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height).data); - } - } - - const buffer = new Uint8ClampedArray(data.reduce((acc, cur) => acc + cur.length, 0)); - data.reduce((acc, cur) => { buffer.set(cur, acc); return acc + cur.length; }, 0); - - WebGLCmdFuncCopyBufferToTexture( + WebGLCmdFuncCopyTexImagesToTexture( this, - buffer, + texImages, (texture as WebGLGFXTexture).gpuTexture, regions); } diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index fcefb3ed18..aea5aeb1a2 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -54,6 +54,7 @@ export class WebGLGPUTexture { public arrayLayer: number = 1; public mipLevel: number = 1; public flags: GFXTextureFlags = GFXTextureFlagBit.NONE; + public isPowerOf2: boolean = false; public glTarget: GLenum = 0; public glInternelFmt: GLenum = 0; diff --git a/cocos/gfx/webgl/webgl-sampler.ts b/cocos/gfx/webgl/webgl-sampler.ts index 23b03ec2b5..0b3c74c3d7 100644 --- a/cocos/gfx/webgl/webgl-sampler.ts +++ b/cocos/gfx/webgl/webgl-sampler.ts @@ -81,9 +81,9 @@ export class WebGLGFXSampler extends GFXSampler { let glMinFilter = WebGLRenderingContext.NONE; let glMagFilter = WebGLRenderingContext.NONE; - const minFilter = (info.minFilter !== undefined ? info.minFilter : GFXFilter.LINEAR); - const magFilter = (info.magFilter !== undefined ? info.magFilter : GFXFilter.LINEAR); - const mipFilter = (info.mipFilter !== undefined ? info.mipFilter : GFXFilter.NONE); + const minFilter = this._state.minFilter; + const magFilter = this._state.magFilter; + const mipFilter = this._state.mipFilter; if (minFilter === GFXFilter.LINEAR || minFilter === GFXFilter.ANISOTROPIC) { if (mipFilter === GFXFilter.LINEAR || mipFilter === GFXFilter.ANISOTROPIC) { @@ -109,9 +109,9 @@ export class WebGLGFXSampler extends GFXSampler { glMagFilter = WebGLRenderingContext.NEAREST; } - const glWrapS = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.CLAMP_TO_EDGE); - const glWrapT = (info.addressV !== undefined ? WebGLWraps[info.addressV] : WebGLRenderingContext.CLAMP_TO_EDGE); - const glWrapR = (info.addressW !== undefined ? WebGLWraps[info.addressW] : WebGLRenderingContext.CLAMP_TO_EDGE); + const glWrapS = WebGLWraps[this._state.addressU]; + const glWrapT = WebGLWraps[this._state.addressV]; + const glWrapR = WebGLWraps[this._state.addressW]; this._gpuSampler = { glMinFilter, diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/gfx/webgl/webgl-texture.ts index b459088bb5..28fb91393a 100644 --- a/cocos/gfx/webgl/webgl-texture.ts +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -5,6 +5,10 @@ import { WebGLCmdFuncCreateTexture, WebGLCmdFuncDestroyTexture } from './webgl-c import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUTexture } from './webgl-gpu-objects'; +function IsPowerOf2 (x: number): boolean{ + return x > 0 && (x & (x - 1)) === 0; +} + export class WebGLGFXTexture extends GFXTexture { public get gpuTexture (): WebGLGPUTexture { @@ -41,6 +45,8 @@ export class WebGLGFXTexture extends GFXTexture { this._flags = info.flags; } + this._isPowerOf2 = IsPowerOf2(this._width) && IsPowerOf2(this._height); + this._size = GFXFormatSurfaceSize(this._format, this.width, this.height, this.depth, this.mipLevel) * this._arrayLayer; @@ -101,6 +107,7 @@ export class WebGLGFXTexture extends GFXTexture { arrayLayer: Math.max(info.arrayLayer || 1, 1), mipLevel: Math.max(info.mipLevel || 1, 1), flags: info.flags || GFXTextureFlagBit.NONE, + isPowerOf2: this._isPowerOf2, glTarget: 0, glInternelFmt: 0, diff --git a/cocos/gfx/webgl2/WebGL2.d.ts b/cocos/gfx/webgl2/WebGL2.d.ts index 652f094597..7582d8341b 100644 --- a/cocos/gfx/webgl2/WebGL2.d.ts +++ b/cocos/gfx/webgl2/WebGL2.d.ts @@ -749,7 +749,7 @@ interface WebGL2RenderingContextBase { compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr); compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint); - ompressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr); + compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr); compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint); compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr); compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint); diff --git a/cocos/gfx/webgl2/webgl2-commands.ts b/cocos/gfx/webgl2/webgl2-commands.ts index 7420d8a158..35d02f2f08 100644 --- a/cocos/gfx/webgl2/webgl2-commands.ts +++ b/cocos/gfx/webgl2/webgl2-commands.ts @@ -956,6 +956,23 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2GFXDevice, gpuTexture: h = Math.max(1, h >> 1); } } + + /* + if (gpuTexture.isPowerOf2) { + gpuTexture.glWrapS = WebGL2RenderingContext.REPEAT; + gpuTexture.glWrapT = WebGL2RenderingContext.REPEAT; + } else { + gpuTexture.glWrapS = WebGL2RenderingContext.CLAMP_TO_EDGE; + gpuTexture.glWrapT = WebGL2RenderingContext.CLAMP_TO_EDGE; + } + gpuTexture.glMinFilter = WebGL2RenderingContext.LINEAR; + gpuTexture.glMagFilter = WebGL2RenderingContext.LINEAR; + + gl.texParameteri(gpuTexture.glTarget, WebGL2RenderingContext.TEXTURE_WRAP_S, gpuTexture.glWrapS); + gl.texParameteri(gpuTexture.glTarget, WebGL2RenderingContext.TEXTURE_WRAP_T, gpuTexture.glWrapT); + gl.texParameteri(gpuTexture.glTarget, WebGL2RenderingContext.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter); + gl.texParameteri(gpuTexture.glTarget, WebGL2RenderingContext.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter); + */ } break; } @@ -996,6 +1013,23 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2GFXDevice, gpuTexture: } } } + + /* + if (gpuTexture.isPowerOf2) { + gpuTexture.glWrapS = WebGL2RenderingContext.REPEAT; + gpuTexture.glWrapT = WebGL2RenderingContext.REPEAT; + } else { + gpuTexture.glWrapS = WebGL2RenderingContext.CLAMP_TO_EDGE; + gpuTexture.glWrapT = WebGL2RenderingContext.CLAMP_TO_EDGE; + } + gpuTexture.glMinFilter = WebGL2RenderingContext.LINEAR; + gpuTexture.glMagFilter = WebGL2RenderingContext.LINEAR; + + gl.texParameteri(gpuTexture.glTarget, WebGL2RenderingContext.TEXTURE_WRAP_S, gpuTexture.glWrapS); + gl.texParameteri(gpuTexture.glTarget, WebGL2RenderingContext.TEXTURE_WRAP_T, gpuTexture.glWrapT); + gl.texParameteri(gpuTexture.glTarget, WebGL2RenderingContext.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter); + gl.texParameteri(gpuTexture.glTarget, WebGL2RenderingContext.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter); + */ } break; } @@ -1482,6 +1516,8 @@ 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]; @@ -1979,6 +2015,15 @@ 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; @@ -2313,9 +2358,9 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W } case WebGL2Cmd.COPY_BUFFER_TO_TEXTURE: { const cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId]; - WebGL2CmdFuncCopyBufferToTexture( + WebGL2CmdFuncCopyBuffersToTexture( device, - (cmd5.gpuBuffer as WebGL2GPUBuffer).buffer as GFXBufferSource, + [(cmd5.gpuBuffer as WebGL2GPUBuffer).buffer!], cmd5.gpuTexture as WebGL2GPUTexture, cmd5.regions); @@ -2325,22 +2370,16 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W } // for } -export function WebGL2CmdFuncCopyBufferToTexture ( +export function WebGL2CmdFuncCopyTexImagesToTexture ( device: WebGL2GFXDevice, - buffer: GFXBufferSource, + texImages: TexImageSource[], gpuTexture: WebGL2GPUTexture, regions: GFXBufferTextureCopy[]) { const gl = device.gl; - - const buff = buffer as ArrayBuffer; - const fmtInfo: IGFXFormatInfo = GFXFormatInfos[gpuTexture.format]; let m = 0; - let w = 1; - let h = 1; + let n = 0; let f = 0; - let buffOffset = 0; - switch (gpuTexture.glTarget) { case WebGL2RenderingContext.TEXTURE_2D: { const glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; @@ -2349,48 +2388,12 @@ export function WebGL2CmdFuncCopyBufferToTexture ( glTexUnit.glTexture = gpuTexture.glTexture; } - const isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; - if (!isCompressed) { - for (const region of regions) { - buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - - w = region.texExtent.width; - h = region.texExtent.height; - - for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = buff.slice(buffOffset, buffOffset + memSize); - const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); - - gl.texSubImage2D(WebGL2RenderingContext.TEXTURE_2D, m, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } - } - } else { - for (const region of regions) { - buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - - w = region.texExtent.width; - h = region.texExtent.height; - - for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = buff.slice(buffOffset, buffOffset + memSize); - const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); - - gl.compressedTexSubImage2D(WebGL2RenderingContext.TEXTURE_2D, m, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } + for (const region of regions) { + n = 0; + for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + gl.texSubImage2D(WebGL2RenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, + gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); } } break; @@ -2402,53 +2405,106 @@ export function WebGL2CmdFuncCopyBufferToTexture ( glTexUnit.glTexture = gpuTexture.glTexture; } - const isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; - if (!isCompressed) { - for (const region of regions) { - buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; - for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; - - const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount; - for (m = region.texSubres.baseMipLevel; m < mcount; ++m) { - const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = buff.slice(buffOffset, buffOffset + memSize); - const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); - - gl.texSubImage2D(WebGL2RenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } - } - } - } else { - for (const region of regions) { - buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; - for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; - - const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount; - for (m = region.texSubres.baseMipLevel; m < mcount; ++m) { - const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = buff.slice(buffOffset, buffOffset + memSize); - const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); - - gl.compressedTexSubImage2D(WebGL2RenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } + for (const region of regions) { + n = 0; + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { + const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount; + for (m = region.texSubres.baseMipLevel; m < mcount; ++m) { + gl.texSubImage2D(WebGL2RenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, + region.texOffset.x, region.texOffset.y, + gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); + } + } + } + break; + } + default: { + console.error('Unsupported GL texture type, copy buffer to texture failed.'); + } + } + + if (gpuTexture.flags & GFXTextureFlagBit.GEN_MIPMAP) { + gl.generateMipmap(gpuTexture.glTarget); + } +} + +export function WebGL2CmdFuncCopyBuffersToTexture ( + device: WebGL2GFXDevice, + buffers: ArrayBuffer[], + gpuTexture: WebGL2GPUTexture, + regions: GFXBufferTextureCopy[]) { + + const gl = device.gl; + let m = 0; + let n = 0; + let w = 1; + let h = 1; + let f = 0; + const fmtInfo: IGFXFormatInfo = GFXFormatInfos[gpuTexture.format]; + const isCompressed = fmtInfo.isCompressed; + switch (gpuTexture.glTarget) { + case WebGL2RenderingContext.TEXTURE_2D: { + const glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGL2RenderingContext.TEXTURE_2D, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + for (const region of regions) { + + n = 0; + w = region.texExtent.width; + h = region.texExtent.height; + + for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + const pixels = !fmtInfo.isFloating ? new Uint8Array(buffers[n++]) : new Float32Array(buffers[n++]); + + if (!isCompressed) { + gl.texSubImage2D(WebGL2RenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, pixels); + } else { + gl.compressedTexSubImage2D(WebGL2RenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); + } + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + break; + } + case WebGL2RenderingContext.TEXTURE_CUBE_MAP: { + const glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGL2RenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + for (const region of regions) { + n = 0; + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { + w = region.texExtent.width; + h = region.texExtent.height; + + const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount; + for (m = region.texSubres.baseMipLevel; m < mcount; ++m) { + const pixels = !fmtInfo.isFloating ? new Uint8Array(buffers[n++]) : new Float32Array(buffers[n++]); + + if (!isCompressed) { + gl.texSubImage2D(WebGL2RenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, pixels); + } else { + gl.compressedTexSubImage2D(WebGL2RenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); + } + + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); } } } diff --git a/cocos/gfx/webgl2/webgl2-device.ts b/cocos/gfx/webgl2/webgl2-device.ts index 45c39eba56..98f483c46a 100644 --- a/cocos/gfx/webgl2/webgl2-device.ts +++ b/cocos/gfx/webgl2/webgl2-device.ts @@ -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 { WebGL2CmdFuncCopyBufferToTexture } from './webgl2-commands'; +import { WebGL2CmdFuncCopyTexImagesToTexture, WebGL2CmdFuncCopyBuffersToTexture } from './webgl2-commands'; import { WebGL2GFXFramebuffer } from './webgl2-framebuffer'; import { WebGL2GFXInputAssembler } from './webgl2-input-assembler'; import { WebGL2GFXPipelineLayout } from './webgl2-pipeline-layout'; @@ -382,49 +382,22 @@ export class WebGL2GFXDevice extends GFXDevice { (this._cmdAllocator as WebGL2GFXCommandAllocator).releaseCmds(); } - public copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { - WebGL2CmdFuncCopyBufferToTexture( + public copyBuffersToTexture (buffers: ArrayBuffer[], texture: GFXTexture, regions: GFXBufferTextureCopy[]) { + WebGL2CmdFuncCopyBuffersToTexture( this, - buffer, + buffers, (texture as WebGL2GFXTexture).gpuTexture, regions); } - public copyImageSourceToTexture ( - source: CanvasImageSource[], + public copyTexImagesToTexture ( + texImages: TexImageSource[], texture: GFXTexture, regions: GFXBufferTextureCopy[]) { - if (!this._canvas2D) { return; } - const context = this._canvas2D.getContext('2d'); - if (!context) { return; } - - const data: Uint8ClampedArray[] = []; - const faces = source.length / regions.length; - let imgSrc: CanvasImageSource; - - for (let j = 0; j < regions.length; j++) { - for (let i = 0; i < faces; i++) { - const level = regions[j].texSubres.baseMipLevel; - this._canvas2D.width = texture.width >> level; - this._canvas2D.height = texture.height >> level; - imgSrc = source[j * faces + i]; - - if (imgSrc.width <= 0 || imgSrc.height <= 0) { - return ; - } - - context.drawImage(imgSrc, 0, 0); - data.push(context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height).data); - } - } - - const buffer = new Uint8ClampedArray(data.reduce((acc, cur) => acc + cur.length, 0)); - data.reduce((acc, cur) => { buffer.set(cur, acc); return acc + cur.length; }, 0); - - WebGL2CmdFuncCopyBufferToTexture( + WebGL2CmdFuncCopyTexImagesToTexture( this, - buffer, + texImages, (texture as WebGL2GFXTexture).gpuTexture, regions); } diff --git a/cocos/gfx/webgl2/webgl2-gpu-objects.ts b/cocos/gfx/webgl2/webgl2-gpu-objects.ts index b53b53f9bf..5a430c75a1 100644 --- a/cocos/gfx/webgl2/webgl2-gpu-objects.ts +++ b/cocos/gfx/webgl2/webgl2-gpu-objects.ts @@ -56,6 +56,7 @@ export class WebGL2GPUTexture { public arrayLayer: number = 1; public mipLevel: number = 1; public flags: GFXTextureFlags = GFXTextureFlagBit.NONE; + public isPowerOf2: boolean = false; public glTarget: GLenum = 0; public glInternelFmt: GLenum = 0; diff --git a/cocos/gfx/webgl2/webgl2-texture.ts b/cocos/gfx/webgl2/webgl2-texture.ts index 5174e76661..ed5161e9e6 100644 --- a/cocos/gfx/webgl2/webgl2-texture.ts +++ b/cocos/gfx/webgl2/webgl2-texture.ts @@ -5,6 +5,10 @@ import { WebGL2CmdFuncCreateTexture, WebGL2CmdFuncDestroyTexture } from './webgl import { WebGL2GFXDevice } from './webgl2-device'; import { WebGL2GPUTexture } from './webgl2-gpu-objects'; +function IsPowerOf2 (x: number): boolean{ + return x > 0 && (x & (x - 1)) === 0; +} + export class WebGL2GFXTexture extends GFXTexture { public get gpuTexture (): WebGL2GPUTexture { @@ -41,6 +45,8 @@ export class WebGL2GFXTexture extends GFXTexture { this._flags = info.flags; } + this._isPowerOf2 = IsPowerOf2(this._width) && IsPowerOf2(this._height); + this._size = GFXFormatSurfaceSize(this._format, this.width, this.height, this.depth, this.mipLevel) * this._arrayLayer; @@ -101,6 +107,7 @@ export class WebGL2GFXTexture extends GFXTexture { arrayLayer: Math.max(info.arrayLayer || 1, 1), mipLevel: Math.max(info.mipLevel || 1, 1), flags: info.flags || GFXTextureFlagBit.NONE, + isPowerOf2: this._isPowerOf2, glTarget: 0, glInternelFmt: 0, diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index 087939b9eb..1078ebf430 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -181,7 +181,7 @@ export class ForwardPipeline extends RenderPipeline { _vec4Array[1] *= tempRGB.y; _vec4Array[2] *= tempRGB.z; } - _vec4Array[3] = (light as SphereLight).luminance; + _vec4Array[3] = (light as SphereLight).luminance * 10000.0; this._uboLights.view.set(_vec4Array, UBOForwardLight.SPHERE_LIGHT_COLOR_OFFSET + sphereNum * 4); sphereNum++; break; @@ -204,7 +204,7 @@ export class ForwardPipeline extends RenderPipeline { _vec4Array[1] *= tempRGB.y; _vec4Array[2] *= tempRGB.z; } - _vec4Array[3] = (light as SpotLight).luminance; + _vec4Array[3] = (light as SpotLight).luminance * 10000.0; this._uboLights.view.set(_vec4Array, UBOForwardLight.SPOT_LIGHT_COLOR_OFFSET + spotNum * 4); spotNum++; break; diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/renderer/models/skinning-model.ts index d049490d8d..85c28adb1f 100644 --- a/cocos/renderer/models/skinning-model.ts +++ b/cocos/renderer/models/skinning-model.ts @@ -8,10 +8,11 @@ import { GFXBuffer } from '../../gfx/buffer'; import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; import { GFXFeature } from '../../gfx/device'; import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { UBOSkinning, UNIFORM_JOINTS_TEXTURE } from '../../pipeline/define'; import { Node } from '../../scene-graph/node'; +import { samplerLib } from '../core/sampler-lib'; import { Model } from '../scene/model'; import { RenderScene } from '../scene/render-scene'; -import { UBOSkinning, UNIFORM_JOINTS_TEXTURE } from '../../pipeline/define'; const textureSizeBuffer = new Float32Array(4); @@ -94,7 +95,7 @@ export class SkinningModel extends Model { if (this._jointStorage && isTextureStorage(this._jointStorage)) { const jointTexture = this._jointStorage.texture; const view = jointTexture.getGFXTextureView(); - const sampler = jointTexture.getGFXSampler(); + const sampler = samplerLib.getSampler(this._device, jointTexture.getGFXSamplerInfo()); if (view && sampler) { pso.pipelineLayout.layouts[0].bindTextureView(UNIFORM_JOINTS_TEXTURE.binding, view); pso.pipelineLayout.layouts[0].bindSampler(UNIFORM_JOINTS_TEXTURE.binding, sampler); diff --git a/cocos/renderer/scene/sphere-light.ts b/cocos/renderer/scene/sphere-light.ts index 46e54a5aca..ed73118086 100644 --- a/cocos/renderer/scene/sphere-light.ts +++ b/cocos/renderer/scene/sphere-light.ts @@ -29,7 +29,7 @@ export class SphereLight extends Light { set luminance (lum: number) { this._luminance = lum; - this._luminousPower = this._luminance * 4.0 * Math.PI; + this._luminousPower = this._luminance * (4.0 * this._size * this._size * Math.PI * Math.PI); } get luminance (): number { @@ -38,7 +38,7 @@ export class SphereLight extends Light { set luminousPower (lm: number) { this._luminousPower = lm; - this._luminance = this._luminousPower / 4.0 / Math.PI; + this._luminance = this._luminousPower / (4.0 * this._size * this._size * Math.PI * Math.PI); } get luminousPower (): number { @@ -51,7 +51,7 @@ export class SphereLight extends Light { protected _size: number = 0.15; protected _range: number = 1.0; - protected _luminance: number = 10000.0; + protected _luminance: number = 0.0; protected _luminousPower: number = 0.0; protected _pos: Vec3; protected _aabb: aabb; @@ -59,7 +59,7 @@ export class SphereLight extends Light { constructor (scene: RenderScene, name: string, node: Node) { super(scene, name, node); this._type = LightType.SPHERE; - this._luminousPower = this._luminance * 4.0 * Math.PI; + this.luminousPower = 1700.0; this._aabb = aabb.create(); this._pos = v3(); } diff --git a/cocos/renderer/scene/spot-light.ts b/cocos/renderer/scene/spot-light.ts index a7b7caac3d..56b66119fe 100644 --- a/cocos/renderer/scene/spot-light.ts +++ b/cocos/renderer/scene/spot-light.ts @@ -48,7 +48,7 @@ export class SpotLight extends Light { set luminance (lum: number) { this._luminance = lum; - this._luminousPower = this._luminance * 4.0 * Math.PI; + this._luminousPower = this._luminance * (4.0 * this._size * this._size * Math.PI * Math.PI); } get luminance (): number { @@ -57,7 +57,7 @@ export class SpotLight extends Light { set luminousPower (lm: number) { this._luminousPower = lm; - this._luminance = this._luminousPower / 4.0 / Math.PI; + this._luminance = this._luminousPower / (4.0 * this._size * this._size * Math.PI * Math.PI); } get luminousPower (): number { @@ -88,7 +88,7 @@ export class SpotLight extends Light { constructor (scene: RenderScene, name: string, node: Node) { super(scene, name, node); this._type = LightType.SPOT; - this._luminousPower = this._luminance * 4.0 * Math.PI; + this.luminousPower = 1700.0; this._aabb = aabb.create(); this._frustum = frustum.create(); this._pos = v3(); diff --git a/cocos/scene-graph/base-node.ts b/cocos/scene-graph/base-node.ts index 12ae03870c..9235a93c5a 100644 --- a/cocos/scene-graph/base-node.ts +++ b/cocos/scene-graph/base-node.ts @@ -31,6 +31,7 @@ import { EventType } from '../core/platform/event-manager/event-enum'; import IdGenerator from '../core/utils/id-generator'; import * as js from '../core/utils/js'; import { baseNodePolyfill } from './base-node-dev'; +import { Scene } from './scene'; type Constructor = new (...args: any[]) => T; @@ -46,6 +47,8 @@ const Deactivating = CCObject.Flags.Deactivating; const idGenerator = new IdGenerator('Node'); +const NullScene = null as unknown as Scene; + function getConstructor (typeOrClassName: string | Function): Function | null { if (!typeOrClassName) { cc.errorID(3804); @@ -219,9 +222,13 @@ export class BaseNode extends CCObject { this.setParent(value); } + get scene () { + return this._scene; + } + public static _setScene (node: BaseNode) { if (node instanceof cc.Scene) { - node._scene = node; + node._scene = node as Scene; } else { if (node._parent == null) { cc.error('Node %s(%s) has not attached to a scene.', node.name, node.uuid); @@ -330,7 +337,7 @@ export class BaseNode extends CCObject { * !#zh 此节点属于哪个场景。 * @type {cc.Scene}} */ - protected _scene: any = null; + protected _scene: Scene = NullScene; protected _activeInHierarchy = false; @@ -345,10 +352,6 @@ export class BaseNode extends CCObject { */ protected __eventTargets: any[] = []; - get scene () { - return this._scene; - } - /** * @method constructor * @param {String} [name] @@ -378,7 +381,7 @@ export class BaseNode extends CCObject { * @example * node.setParent(newNode); */ - public setParent (value: this | null) { + public setParent (value: this | null, keepWorldTransform: boolean) { if (this._parent === value) { return; } @@ -386,9 +389,10 @@ export class BaseNode extends CCObject { if (CC_DEBUG && oldParent && (oldParent._objFlags & Deactivating)) { cc.errorID(3821); } - this._parent = value || null; - this._onSetParent(oldParent); + this._parent = value; + + this._onSetParent(oldParent, keepWorldTransform); if (value) { if (CC_DEBUG && (value._objFlags & Deactivating)) { @@ -1067,7 +1071,27 @@ export class BaseNode extends CCObject { public emit? (type: string, ...args: any[]): void; - protected _onSetParent (oldParent: this | null) { + // Do remove component, only used internally. + public _removeComponent (component: Component) { + if (!component) { + cc.errorID(3814); + return; + } + + if (!(this._objFlags & Destroying)) { + const i = this._components.indexOf(component); + if (i !== -1) { + this._components.splice(i, 1); + if ((CC_EDITOR || CC_TEST) && cc.engine) { + delete cc.engine.attachedObjsForEditor[component._id]; + } + } else if ((component.node as BaseNode) !== this) { + cc.errorID(3815); + } + } + } + + protected _onSetParent (oldParent: this | null, keepWorldTransform: boolean) { if (this._parent) { if ((oldParent == null || oldParent._scene !== this._parent._scene) && this._parent._scene != null) { this.walk((node) => { @@ -1230,26 +1254,6 @@ export class BaseNode extends CCObject { return destroyByParent; } - // do remove component, only used internally - protected _removeComponent (component: Component) { - if (!component) { - cc.errorID(3814); - return; - } - - if (!(this._objFlags & Destroying)) { - const i = this._components.indexOf(component); - if (i !== -1) { - this._components.splice(i, 1); - if ((CC_EDITOR || CC_TEST) && cc.engine) { - delete cc.engine.attachedObjsForEditor[component._id]; - } - } else if ((component.node as BaseNode) !== this) { - cc.errorID(3815); - } - } - } - protected _disableChildComps () { // leave this._activeInHierarchy unmodified for (const component of this._components) { diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index f3e31b3762..4492f5c53c 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -141,10 +141,37 @@ class Node extends BaseNode { // =============================== /** - * invalidate all children after relevant events + * hierarchical events */ - public _onSetParent (oldParent: this) { - super._onSetParent(oldParent); + public setParent (value: this | null, keepWorldTransform: boolean = false) { + if (keepWorldTransform) { this.updateWorldTransform(); } + super.setParent(value, keepWorldTransform); + } + + public _onSetParent (oldParent: this | null, keepWorldTransform: boolean) { + super._onSetParent(oldParent, keepWorldTransform); + if (keepWorldTransform) { + const parent = this._parent; + const local = this._lpos; + if (parent) { + parent.updateWorldTransform(); + vec3.sub(local, this._pos, parent._pos); + vec3.transformQuat(local, local, quat.conjugate(q_a, parent._rot)); + vec3.div(local, local, parent._scale); + quat.mul(this._lrot, quat.conjugate(q_a, parent._rot), this._rot); + vec3.div(this._lscale, this._scale, parent._scale); + } else { + vec3.copy(this._lpos, this._pos); + quat.copy(this._lrot, this._rot); + vec3.copy(this._lscale, this._scale); + } + this._eulerDirty = true; + } else { + vec3.copy(this._pos, this._lpos); + quat.copy(this._rot, this._lrot); + vec3.copy(this._scale, this._lscale); + } + this.invalidateChildren(); } diff --git a/cocos/scene-graph/scene.ts b/cocos/scene-graph/scene.ts index 058a19a98f..c5ba414f38 100644 --- a/cocos/scene-graph/scene.ts +++ b/cocos/scene-graph/scene.ts @@ -54,7 +54,10 @@ export class Scene extends Node { @property public _globals = new SceneGlobals(); - protected _renderScene: RenderScene | null = null; + /** + * For internal usage. + */ + public _renderScene: RenderScene | null = null; protected _inited = !cc.game._isCloning; protected _prefabSyncedInLiveReload = false; @@ -82,7 +85,7 @@ export class Scene extends Node { return this._globals; } - protected _onHierarchyChanged () { } + public _onHierarchyChanged () { } protected _instantiate () { } protected _load () { diff --git a/playground/planarShadow.html b/playground/planarShadow.html index f86e900d90..16c2c9a710 100644 --- a/playground/planarShadow.html +++ b/playground/planarShadow.html @@ -104,6 +104,7 @@ models.plane.node.setRotation(qt); scene.globals.planarShadow.setPlaneFromNode(models.plane.node); + scene.globals.planarShadow.shadowColor = cc.color('#2a4e90'); // 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())))); diff --git a/playground/simple.html b/playground/simple.html index 1b2cf12532..9dc08b874e 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -59,6 +59,7 @@ const root = cc.director.root; const scene = new cc.Scene(); + const cameraNode = new cc.Node('Camera'); cameraNode.parent = scene; cameraNode.setPosition(1, 1, 4); @@ -161,6 +162,17 @@ }); }); + const n0 = new cc.Node(); + n0.parent = scene; + n0.setWorldPosition(0, 0, 10); + const n1 = new cc.Node(); + n1.parent = n0; + console.log(n1.getPosition()); + console.log(n1.getWorldPosition()); + n1.parent = scene; + console.log(n1.getPosition()); + console.log(n1.getWorldPosition()); + cc.director.runSceneImmediate(scene); } cc.game.run({ id: 'canvas' }, onStart); diff --git a/tsconfig-gendecls.json b/tsconfig-gendecls.json index 06f6855670..49991e1a0b 100644 --- a/tsconfig-gendecls.json +++ b/tsconfig-gendecls.json @@ -12,8 +12,7 @@ "emitDeclarationOnly": true, "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ "sourceMap": true, /* Generates corresponding '.map' file. */ - "outFile": "./bin/ts-out/cocos-3d.js", /* Concatenate and emit output to single file. */ - "outDir": "./bin/ts-out", /* Redirect output structure to the directory. */ + "outFile": "index.js", /* Concatenate and emit output to single file. */ "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "removeComments": true, /* Do not emit comments to output. */ @@ -44,7 +43,12 @@ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ + "types": [ + "./@types/globals", + "./@types/ammo.js", + "./@types/wx", + "./cocos/gfx/webgl2/WebGL2", + ], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ @@ -61,16 +65,5 @@ }, "files": [ "index.ts", - "globals.d.ts", - "wx.d.ts", - "cocos/gfx/webgl2/WebGL2.d.ts", - "cocos/core/vmath/fwd-decls.d.ts", ], - "exclude": [ - "cocos/2d", - "docs", - "bin" - ] - //"include" : ["./source"] - //"exclude" : ["js"] } diff --git a/tsconfig.json b/tsconfig.json index 1a3b22f6f3..dee4bcf66a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -43,7 +43,12 @@ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ + "types": [ + "./@types/globals", + "./@types/ammo.js", + "./@types/wx", + "./cocos/gfx/webgl2/WebGL2", + ], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */