From 0822ab1045aedd8d65248b8ac9ae1afc257d888b Mon Sep 17 00:00:00 2001 From: SijieWang Date: Mon, 18 Jul 2022 10:34:45 +0800 Subject: [PATCH 001/111] [Optimize] export CCClass.isCCClassOrFastDefined (#12043) --- cocos/core/data/class.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index f5370ab9af..c5a9c32306 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -359,6 +359,8 @@ export function isCCClassOrFastDefined (constructor: Constructor) { return constructor?.hasOwnProperty?.('__values__'); } +CCClass.isCCClassOrFastDefined = isCCClassOrFastDefined; + /** * Return all super classes. * @param constructor The Constructor. From 3da86aed53fdcd1e5a083f5d75fc8b78ed7eadc3 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Mon, 18 Jul 2022 11:32:50 +0800 Subject: [PATCH 002/111] [optimize] shadow pass texture sampling without alpha test (#12005) --- .../render-to-shadowmap/fs.chunk | 5 +-- .../default-functions/standard-fs.chunk | 7 ++++ editor/assets/effects/builtin-standard.effect | 7 ++-- editor/assets/effects/builtin-toon.effect | 6 ++-- .../dcc/imported-metallic-roughness.effect | 34 ++++++++++++++----- .../dcc/imported-specular-glossiness.effect | 32 ++++++++--------- ...urfaces-imported-metallic-roughness.effect | 29 ++++++++++++++++ ...rfaces-imported-specular-glossiness.effect | 26 ++++++++++---- .../assets/effects/surfaces/standard.effect | 24 ++++++++++--- editor/assets/effects/surfaces/toon.effect | 23 +++++-------- 10 files changed, 133 insertions(+), 60 deletions(-) diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk index 33614ecd79..e1824dc45d 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk @@ -3,8 +3,9 @@ in highp vec2 v_clip_depth; layout(location = 0) out vec4 fragColorX; void main () { - // for alpha clip - SurfacesFragmentModifyBaseColorAndTransparency(); + // better performance than SurfacesFragmentModifyBaseColorAndTransparency + SurfacesFragmentAlphaClipOnly(); + highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; // spot use linear diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk index 16ba4c5344..10234ffc44 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk @@ -5,6 +5,13 @@ vec4 SurfacesFragmentModifyBaseColorAndTransparency() } #endif +#ifndef CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY +// for base shape without color usage, such as render-to-shadow +void SurfacesFragmentAlphaClipOnly() +{ +} +#endif + #ifndef CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL vec3 SurfacesFragmentModifyWorldNormal() diff --git a/editor/assets/effects/builtin-standard.effect b/editor/assets/effects/builtin-standard.effect index 69fa82c50b..bf63e71f8a 100644 --- a/editor/assets/effects/builtin-standard.effect +++ b/editor/assets/effects/builtin-standard.effect @@ -368,11 +368,10 @@ CCProgram shadow-caster-fs %{ vec4 frag () { vec4 baseColor = albedo; - #if USE_ALBEDO_MAP - baseColor *= texture(albedoMap, ALBEDO_UV); - #endif - #if USE_ALPHA_TEST + #if USE_ALBEDO_MAP + baseColor *= texture(albedoMap, ALBEDO_UV); + #endif if (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; #endif diff --git a/editor/assets/effects/builtin-toon.effect b/editor/assets/effects/builtin-toon.effect index 7c9a6badec..a36b279efc 100644 --- a/editor/assets/effects/builtin-toon.effect +++ b/editor/assets/effects/builtin-toon.effect @@ -309,11 +309,11 @@ CCProgram shadow-caster-fs %{ vec4 frag () { vec4 baseColor = baseColor; - #if USE_BASE_COLOR_MAP - baseColor *= texture(baseColorMap, v_uv); - #endif #if USE_ALPHA_TEST + #if USE_BASE_COLOR_MAP + baseColor *= texture(baseColorMap, v_uv); + #endif if (baseColor.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard; #endif diff --git a/editor/assets/effects/dcc/imported-metallic-roughness.effect b/editor/assets/effects/dcc/imported-metallic-roughness.effect index cc26af5ded..57d9153dc4 100644 --- a/editor/assets/effects/dcc/imported-metallic-roughness.effect +++ b/editor/assets/effects/dcc/imported-metallic-roughness.effect @@ -57,6 +57,8 @@ CCEffect %{ albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + alphaSource: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + alphaSourceMap: { value: grey, editor: { parent: USE_OPACITY_MAP } } - name: transparent passes: - vert: standard-vs @@ -435,19 +437,33 @@ CCProgram shadow-caster-fs %{ #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) #endif - #if USE_ALPHA_TEST - #pragma define-meta ALPHA_TEST_CHANNEL options([a, r]) + #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) + + #if USE_OPACITY_MAP + #pragma define-meta ALPHA_SOURCE_CHANNEL options([r, g, b, a]) + uniform sampler2D alphaSourceMap; #endif vec4 frag () { - vec4 baseColor = albedo; - - #if USE_ALBEDO_MAP - baseColor *= texture(albedoMap, ALBEDO_UV); - #endif - #if USE_ALPHA_TEST - if (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; + float alpha = albedo.a; + #if USE_ALBEDO_MAP + alpha = texture(albedoMap, TEXTURE_UV).a; + #endif + #if ALPHA_SOURCE_IS_OPACITY + #if USE_OPACITY_MAP + alpha = 1.0 - texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + alpha = 1.0 - alphaSource; + #endif + #else + #if USE_OPACITY_MAP + alpha = texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + alpha = alphaSource; + #endif + #endif + if (alpha < albedoScaleAndCutoff.w) discard; #endif highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect b/editor/assets/effects/dcc/imported-specular-glossiness.effect index e7bbd5f9ed..92b87d1eb8 100644 --- a/editor/assets/effects/dcc/imported-specular-glossiness.effect +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect @@ -52,11 +52,13 @@ CCEffect %{ rasterizerState: cullMode: front properties: - tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } - mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } - albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } - mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } + transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - name: transparent passes: - vert: standard-vs @@ -446,19 +448,13 @@ CCProgram shadow-caster-fs %{ #endif vec4 frag () { - vec4 baseColor = diffuseColor; - #if USE_ALBEDO_MAP - vec4 texColor = texture(albedoMap, TEXTURE_UV); - baseColor *= texColor; - #endif - - #if USE_TRANSPARENCY_MAP - baseColor.a = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; - #endif - - #if USE_ALPHA_TEST - if (baseColor.a < albedoScaleAndCutoff.w) discard; - #endif + #if USE_ALPHA_TEST + float alpha = 1.0; + #if USE_TRANSPARENCY_MAP + alpha = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; + #endif + if (alpha < albedoScaleAndCutoff.w) discard; + #endif highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; // spot use linear diff --git a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect index a7e51a0614..f0e0515a49 100644 --- a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect +++ b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect @@ -57,6 +57,8 @@ CCEffect %{ albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + alphaSource: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + alphaSourceMap: { value: grey, editor: { parent: USE_OPACITY_MAP } } - name: transparent passes: - vert: standard-vs @@ -225,6 +227,33 @@ CCProgram surface-fragment %{ return baseColor; } + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() + { + #if USE_ALPHA_TEST + float alpha = albedo.a; + #if USE_ALBEDO_MAP + alpha = texture(albedoMap, TEXTURE_UV).a; + #endif + + #if ALPHA_SOURCE_IS_OPACITY + #if USE_OPACITY_MAP + alpha = 1.0 - texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + alpha = 1.0 - alphaSource; + #endif + #else + #if USE_OPACITY_MAP + alpha = texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + alpha = alphaSource; + #endif + #endif + + if (alpha < albedoScaleAndCutoff.w) discard; + #endif + } + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL vec3 SurfacesFragmentModifyWorldNormal() { diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect index fff8749109..3fc592b0c0 100644 --- a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect @@ -19,7 +19,7 @@ CCEffect %{ specularMap: { value: grey, editor: { parent: '!HAS_EXPORTED_METALLIC' } } specularFactor: { value: 1.0, editor: { parent: '!HAS_EXPORTED_METALLIC' } } transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } - transparencyFactor: { value: 0.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } normalStrength: { value: 1.0, target: normalScale, editor: { displayName: bumpFactor, parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } normalMap: { value: normal } @@ -52,11 +52,13 @@ CCEffect %{ rasterizerState: cullMode: front properties: - tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } - mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } - albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } - mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } + transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - name: transparent passes: - vert: standard-vs @@ -238,6 +240,18 @@ CCProgram surface-fragment %{ return baseColor; } + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() + { + #if USE_ALPHA_TEST + float alpha = 1.0; + #if USE_TRANSPARENCY_MAP + alpha = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; + #endif + if (alpha < albedoScaleAndCutoff.w) discard; + #endif + } + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL vec3 SurfacesFragmentModifyWorldNormal() { diff --git a/editor/assets/effects/surfaces/standard.effect b/editor/assets/effects/surfaces/standard.effect index 54a73ad84b..3aa5030fe6 100644 --- a/editor/assets/effects/surfaces/standard.effect +++ b/editor/assets/effects/surfaces/standard.effect @@ -193,7 +193,7 @@ CCProgram surface-fragment %{ baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear baseColor.a *= FSInput_vertexColor.a; #endif - + #if USE_ALBEDO_MAP vec4 texColor = texture(albedoMap, ALBEDO_UV); texColor.rgb = SRGBToLinear(texColor.rgb); @@ -208,10 +208,26 @@ CCProgram surface-fragment %{ return baseColor; } + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() + { + #if USE_ALPHA_TEST + float alpha = albedo.ALPHA_TEST_CHANNEL; + #if USE_VERTEX_COLOR + alpha *= FSInput_vertexColor.a; + #endif + #if USE_ALBEDO_MAP + alpha = texture(albedoMap, ALBEDO_UV).ALPHA_TEST_CHANNEL; + #endif + + if (alpha < albedoScaleAndCutoff.w) discard; + #endif + } + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL vec3 SurfacesFragmentModifyWorldNormal() { - vec3 normal = FSInput_worldNormal; + vec3 normal = FSInput_worldNormal; #if USE_NORMAL_MAP vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5); normal = CalculateNormalFromTangentSpace(nmmp, emissiveScaleParam.w, normal.xyz, FSInput_worldTangent, FSInput_mirrorNormal); @@ -223,8 +239,8 @@ CCProgram surface-fragment %{ #define CC_SURFACES_FRAGMENT_MODIFY_ANISOTROPY_PARAMS vec4 SurfacesFragmentModifyAnisotropyParams() { - float anisotropyRotation = anisotropyParam.y; - float anisotropyShape = anisotropyParam.x; + float anisotropyRotation = anisotropyParam.y; + float anisotropyShape = anisotropyParam.x; #if IS_ANISOTROPY && USE_ANISOTROPY_ROTATION_MAP anisotropyRotation = fract(anisotropyRotation + texture(anisotropyRotationMap, DEFAULT_UV).x); #endif diff --git a/editor/assets/effects/surfaces/toon.effect b/editor/assets/effects/surfaces/toon.effect index 380a66dbe8..5460bca9dd 100644 --- a/editor/assets/effects/surfaces/toon.effect +++ b/editor/assets/effects/surfaces/toon.effect @@ -171,28 +171,23 @@ CCProgram surface-fragment %{ #endif } - // only for render-to-shadow-map or misc usage - #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY - vec4 SurfacesFragmentModifyBaseColorAndTransparency() + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() { - vec4 color = baseColor; - #if USE_BASE_COLOR_MAP - vec4 texColor = texture(baseColorMap, FSInput_texcoord); - texColor.rgb = SRGBToLinear(texColor.rgb); - color *= texColor; - #endif - #if USE_ALPHA_TEST - if (color.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard; + float alpha = baseColor.ALPHA_TEST_CHANNEL; + #if USE_BASE_COLOR_MAP + alpha = texture(baseColorMap, FSInput_texcoord).ALPHA_TEST_CHANNEL; + #endif + + if (alpha < colorScaleAndCutoff.w) discard; #endif - - return color; } #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL vec3 SurfacesFragmentModifyWorldNormal() { - vec3 normal = FSInput_worldNormal; + vec3 normal = FSInput_worldNormal; #if USE_NORMAL_MAP vec3 nmmp = texture(normalMap, FSInput_texcoord).xyz - vec3(0.5); normal = CalculateNormalFromTangentSpace(nmmp, emissiveScaleAndStrenth.w, normal.xyz, FSInput_worldTangent, FSInput_mirrorNormal); From ec0a051840b47521df349ae806ec3319e92218c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Mon, 18 Jul 2022 11:33:39 +0800 Subject: [PATCH 003/111] V3.6.0 opt fill vertex buffers (#12046) * optimize fillVertexBuffers --- native/cocos/2d/renderer/Batcher2d.h | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/native/cocos/2d/renderer/Batcher2d.h b/native/cocos/2d/renderer/Batcher2d.h index c1673d3fcd..bc413ec988 100644 --- a/native/cocos/2d/renderer/Batcher2d.h +++ b/native/cocos/2d/renderer/Batcher2d.h @@ -95,17 +95,12 @@ private: uint8_t stride = drawInfo->getStride(); uint32_t size = drawInfo->getVbCount() * stride; float* vbBuffer = drawInfo->getVbBuffer(); - - Vec3 temp; - uint32_t offset = 0; for (int i = 0; i < size; i += stride) { Render2dLayout* curLayout = drawInfo->getRender2dLayout(i); - temp.transformMat4(curLayout->position, matrix); - - offset = i; - vbBuffer[offset++] = temp.x; - vbBuffer[offset++] = temp.y; - vbBuffer[offset++] = temp.z; + // make sure that the layout of Vec3 is three consecutive floats + static_assert(sizeof(Vec3) == 3 * sizeof(float)); + // cast to reduce value copy instructions + reinterpret_cast(vbBuffer + i)->transformMat4(curLayout->position, matrix); } } From f9db1777a2777a4970933cef9176e47213313024 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Mon, 18 Jul 2022 11:40:20 +0800 Subject: [PATCH 004/111] [optimize] avoid calculate dir lighting and shadows with lightmap (#12027) --- .../chunks/legacy/shading-standard-base.chunk | 60 +++++++++---------- .../lighting-flow/common-flow.chunk | 50 +++++++++------- .../module-functions/standard-fs.chunk | 11 +--- 3 files changed, 59 insertions(+), 62 deletions(-) diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk b/editor/assets/chunks/legacy/shading-standard-base.chunk index 336727e4e2..85b2e0a578 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk @@ -100,38 +100,36 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { vec3 N = normalize(s.normal); vec3 V = normalize(cc_cameraPos.xyz - position); - float NV = max(abs(dot(N, V)), 0.0); - specular = BRDFApprox(specular, s.roughness, NV); - - vec3 L = normalize(-cc_mainLitDir.xyz); - vec3 H = normalize(L + V); - float NH = max(dot(N, H), 0.0); - float NL = max(dot(N, L), 0.0); - vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w; - vec3 diffuseContrib = diffuse / PI; - - // Cook-Torrance Microfacet Specular BRDF - vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N); - vec3 dirlightContrib = (diffuseContrib + specularContrib); - - float shadow = 1.0; - #if CC_RECEIVE_SHADOW - if (NL > 0.0 && cc_mainLitDir.w > 0.0) { - if (cc_shadowLPNNInfo.w > 0.0) { - shadow = CCCSMFactorBase(position, N, s.shadowBias); - } else { - shadow = CCShadowFactorBase(shadowPos, N, s.shadowBias); - } - } - #endif - - dirlightContrib *= shadow; - finalColor *= dirlightContrib; - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD - if (s.lightmap_test > EPSILON_LOWP) { - finalColor = diffuse * s.lightmap.rgb * shadow; - } + vec3 finalColor = diffuse * s.lightmap.rgb; + #else + float NV = max(abs(dot(N, V)), 0.0); + specular = BRDFApprox(specular, s.roughness, NV); + + vec3 L = normalize(-cc_mainLitDir.xyz); + vec3 H = normalize(L + V); + float NH = max(dot(N, H), 0.0); + float NL = max(dot(N, L), 0.0); + vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w; + vec3 diffuseContrib = diffuse / PI; + + // Cook-Torrance Microfacet Specular BRDF + vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N); + vec3 dirlightContrib = (diffuseContrib + specularContrib); + + float shadow = 1.0; + #if CC_RECEIVE_SHADOW + if (NL > 0.0 && cc_mainLitDir.w > 0.0) { + if (cc_shadowLPNNInfo.w > 0.0) { + shadow = CCCSMFactorBase(position, N, s.shadowBias); + } else { + shadow = CCShadowFactorBase(shadowPos, N, s.shadowBias); + } + } + #endif + + dirlightContrib *= shadow; + finalColor *= dirlightContrib; #endif float fAmb = 0.5 - N.y * 0.5; diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index a6bf1324e4..2124986c01 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -61,23 +61,37 @@ CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, -cc_mainLitDir.xyz); - CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); - CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor); - - // CCSurfacesLightingCalculateShadow: - lightingResult.shadow = 1.0; - #if CC_RECEIVE_SHADOW - if (cc_mainLitDir.w > 0.0) { - if (CCSurfacesLightingEnableShadow(lightingData.NoL)) { - if (cc_shadowLPNNInfo.w > 0.0) { - lightingResult.shadow = CCCSMFactorBase(surfaceData.worldPos, lightingData.N, shadowBias); - } else { - vec4 shadowPos = cc_matLightViewProj * vec4(surfaceData.worldPos, 1.0); - lightingResult.shadow = CCShadowFactorBase(shadowPos, lightingData.N, shadowBias); + // CCSurfacesLightingCalculateBaked: + lightingResult.lightmapColor = vec3(0.0); + #if CC_SURFACES_USE_LIGHT_MAP && !USE_BATCHING && !CC_FORWARD_ADD + vec4 lightmap = GetLightMapColor(cc_lightingMap, FSInput_lightMapUV.xy, FSInput_lightMapUV.z); + lightingResult.lightmapColor = lightmap.rgb; + // lightingResult.shadow/ao *= lightmap.a; + + // static dir light + lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); + lightingResult.shadow = lightingResult.ao = 1.0; + // dynamic & stationary dir light + #else + CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); + + CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor); + + // CCSurfacesLightingCalculateShadow: + lightingResult.shadow = 1.0; + #if CC_RECEIVE_SHADOW + if (cc_mainLitDir.w > 0.0) { + if (CCSurfacesLightingEnableShadow(lightingData.NoL)) { + if (cc_shadowLPNNInfo.w > 0.0) { + lightingResult.shadow = CCCSMFactorBase(surfaceData.worldPos, lightingData.N, shadowBias); + } else { + vec4 shadowPos = cc_matLightViewProj * vec4(surfaceData.worldPos, 1.0); + lightingResult.shadow = CCShadowFactorBase(shadowPos, lightingData.N, shadowBias); + } } } - } + #endif #endif // apply SSR, local probe & global probe @@ -85,14 +99,6 @@ // CCSurfacesLightingCalculateTransmittence(lightingResult, lightingData, shadowPos); - // CCSurfacesLightingCalculateBaked: - lightingResult.lightmapColor = vec3(0.0); - #if CC_SURFACES_USE_LIGHT_MAP && !USE_BATCHING && !CC_FORWARD_ADD - vec4 lightmap = GetLightMapColor(cc_lightingMap, FSInput_lightMapUV.xy, FSInput_lightMapUV.z); - lightingResult.lightmapColor = lightmap.rgb; - // lightingResult.shadow/ao *= lightmap.a; - #endif - // apply screen-space shadow and ao // lightingResult.shadow/ao *= XXX; diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk index b5917fb879..ab4ec5037e 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -113,15 +113,8 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li color.xyz += lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting; color.xyz += lightingResult.directSpecular * lightingResult.specularColorWithLighting; #else - #if CC_SURFACES_USE_LIGHT_MAP && !USE_BATCHING && !CC_FORWARD_ADD - float lum = FSInput_lightMapUV.z; - float lightmapCoef = step(lum, EPSILON_LOWP); - #else - float lightmapCoef = 0.0; - #endif - - color.xyz += ( - mix(lightingResult.directDiffuse, lightingResult.lightmapColor, lightmapCoef) * lightingResult.diffuseColorWithLighting + color.xyz += lightingResult.lightmapColor * lightingResult.diffuseColorWithLighting + + (lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting) * lightingResult.shadow; From 615e3437bc58821e74fbfca17a18ce9efa8232f2 Mon Sep 17 00:00:00 2001 From: PP Date: Mon, 18 Jul 2022 11:44:13 +0800 Subject: [PATCH 005/111] ban transform es6 to es5 on Bytedance platform (#12035) --- templates/bytedance-mini-game/project.config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/bytedance-mini-game/project.config.json b/templates/bytedance-mini-game/project.config.json index 61d9dcba0c..b8fdb18c37 100644 --- a/templates/bytedance-mini-game/project.config.json +++ b/templates/bytedance-mini-game/project.config.json @@ -1,7 +1,7 @@ { "setting": { "urlCheck": true, - "es6": true, + "es6": false, "postcss": true, "minified": true, "newFeature": true From 56c26db7f5b2aa1aa7182741f3d649f86dfce46e Mon Sep 17 00:00:00 2001 From: Santy-Wang Date: Mon, 18 Jul 2022 11:48:04 +0800 Subject: [PATCH 006/111] optimize renderEntity and renderDrawInfo padding (#12042) * adjust padding * optimize padding * use default constructor --- cocos/2d/renderer/native-2d.ts | 8 ++----- cocos/2d/renderer/render-draw-info.ts | 14 +----------- cocos/2d/renderer/render-entity.ts | 2 +- native/cocos/2d/renderer/RenderDrawInfo.cpp | 21 +++-------------- native/cocos/2d/renderer/RenderDrawInfo.h | 23 +++++-------------- native/cocos/2d/renderer/RenderEntity.cpp | 9 +------- native/cocos/2d/renderer/RenderEntity.h | 25 ++++++++------------- native/cocos/2d/renderer/StencilManager.h | 2 +- 8 files changed, 23 insertions(+), 81 deletions(-) diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index 59b219f318..517cdd252a 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -4,10 +4,7 @@ import { Node } from '../../core/scene-graph'; import { Model } from '../../core/renderer/scene'; export declare class NativeRenderDrawInfo { - constructor(batcher: NativeBatcher2d); - - // get batcher ():NativeBatcher2d { return new NativeBatcher2d(); } - // set batcher (batcher: NativeBatcher2d) {} + constructor(); get accId(): number; set accId(accId: number); @@ -71,11 +68,10 @@ export declare class NativeRenderDrawInfo { setRender2dBufferToNative(data: TypedArray, stride: number, size: number); syncSharedBufferToNative(data: TypedArray); - getAttrSharedBufferForJS(): ArrayBufferLike; } export declare class NativeRenderEntity { - constructor(batcher: NativeBatcher2d); + constructor(); addDynamicRenderDrawInfo(drawInfo: NativeRenderDrawInfo); setDynamicRenderDrawInfo(drawInfo: NativeRenderDrawInfo, index: number); diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts index 1e4d410f26..95dc606c90 100644 --- a/cocos/2d/renderer/render-draw-info.ts +++ b/cocos/2d/renderer/render-draw-info.ts @@ -47,9 +47,6 @@ export class RenderDrawInfo { // SharedBuffer of pos/uv/color protected declare _render2dBuffer: Float32Array; - // SharedBuffer of extra attributes - protected declare _sharedBuffer: Int32Array; - protected _vertexCount = 0; protected _stride = 0; @@ -74,11 +71,9 @@ export class RenderDrawInfo { this._nativeObj = nativeDrawInfo; } if (!this._nativeObj) { - this._nativeObj = new NativeRenderDrawInfo(director.root!.batcher2D.nativeObj); + this._nativeObj = new NativeRenderDrawInfo(); } } - - this.initSharedBuffer(); } public clear () { @@ -281,11 +276,4 @@ export class RenderDrawInfo { this._nativeObj.setRender2dBufferToNative(this._render2dBuffer, this._stride, this._vertexCount * this._stride); } } - - private initSharedBuffer () { - if (JSB) { - //this._sharedBuffer = new Int32Array(RenderDrawInfoSharedBufferView.count); - this._sharedBuffer = new Int32Array(this._nativeObj.getAttrSharedBufferForJS()); - } - } } diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index 2faffde36b..6bb89e4500 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -119,7 +119,7 @@ export class RenderEntity { constructor (entityType: RenderEntityType) { if (JSB) { if (!this._nativeObj) { - this._nativeObj = new NativeRenderEntity(director.root!.batcher2D.nativeObj); + this._nativeObj = new NativeRenderEntity(); } this.setRenderEntityType(entityType); diff --git a/native/cocos/2d/renderer/RenderDrawInfo.cpp b/native/cocos/2d/renderer/RenderDrawInfo.cpp index 2f0db9cd34..4bc9a773c5 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.cpp +++ b/native/cocos/2d/renderer/RenderDrawInfo.cpp @@ -27,14 +27,9 @@ #include "2d/renderer/Batcher2d.h" #include "base/TypeDef.h" #include "renderer/gfx-base/GFXDevice.h" +#include "core/Root.h" namespace cc { -RenderDrawInfo::RenderDrawInfo() : RenderDrawInfo(nullptr) { -} - -RenderDrawInfo::RenderDrawInfo(Batcher2d* batcher) : _batcher(batcher) { - _attrSharedBufferActor.initialize(&_drawInfoAttrLayout, sizeof(DrawInfoAttrLayout)); -} RenderDrawInfo::RenderDrawInfo(index_t bufferId, uint32_t vertexOffset, uint32_t indexOffset) { // NOLINT(bugprone-easily-swappable-parameters) _bufferId = bufferId; @@ -42,26 +37,20 @@ RenderDrawInfo::RenderDrawInfo(index_t bufferId, uint32_t vertexOffset, uint32_t _indexOffset = indexOffset; _stride = 0; _size = 0; - _batcher = nullptr; - - _attrSharedBufferActor.initialize(&_drawInfoAttrLayout, sizeof(DrawInfoAttrLayout)); } RenderDrawInfo::~RenderDrawInfo() { destroy(); } -void RenderDrawInfo::setBatcher(Batcher2d* batcher) { - _batcher = batcher; -} - void RenderDrawInfo::setAccId(index_t id) { _accId = id; } void RenderDrawInfo::setBufferId(index_t bufferId) { + CC_ASSERT(Root::getInstance()->getBatcher2D()); _bufferId = bufferId; - _meshBuffer = _batcher->getMeshBuffer(_accId, _bufferId); + _meshBuffer = Root::getInstance()->getBatcher2D()->getMeshBuffer(_accId, _bufferId); } void RenderDrawInfo::setVertexOffset(uint32_t vertexOffset) { @@ -142,10 +131,6 @@ void RenderDrawInfo::setRender2dBufferToNative(uint8_t* buffer, uint8_t stride, _sharedBuffer = buffer; } -se::Object* RenderDrawInfo::getAttrSharedBufferForJS() const { - return _attrSharedBufferActor.getSharedArrayBufferObject(); -} - gfx::InputAssembler* RenderDrawInfo::requestIA(gfx::Device* device) { if (_nextFreeIAHandle >= _iaPool.size()) { initIAInfo(device); diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index 3568e31587..af56a32276 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -49,7 +49,7 @@ struct DrawInfoAttrLayout { uint32_t enabledIndex{1}; }; -enum class RenderDrawInfoType { +enum class RenderDrawInfoType: uint8_t { COMP, MODEL, IA @@ -58,8 +58,7 @@ enum class RenderDrawInfoType { class Batcher2d; class RenderDrawInfo final { public: - RenderDrawInfo(); - explicit RenderDrawInfo(Batcher2d* batcher); + RenderDrawInfo() = default; RenderDrawInfo(index_t bufferId, uint32_t vertexOffset, uint32_t indexOffset); ~RenderDrawInfo(); @@ -109,10 +108,6 @@ public: void setRender2dBufferToNative(uint8_t* buffer, uint8_t stride, uint32_t size); - inline Batcher2d* getBatcher() const { return _batcher; } - void setBatcher(Batcher2d* batcher); - se::Object* getAttrSharedBufferForJS() const; - inline Render2dLayout* getRender2dLayout(uint32_t dataOffset) { return reinterpret_cast(_sharedBuffer + dataOffset * sizeof(float)); } @@ -129,18 +124,10 @@ private: void destroy(); gfx::InputAssembler* initIAInfo(gfx::Device* device); - - // weak reference - Batcher2d* _batcher{nullptr}; - // weak reference uint8_t* _sharedBuffer{nullptr}; - uint8_t _stride{0}; uint32_t _size{0}; - DrawInfoAttrLayout _drawInfoAttrLayout; - bindings::NativeMemorySharedToScriptActor _attrSharedBufferActor; - index_t _bufferId{0}; index_t _accId{0}; uint32_t _vertexOffset{0}; @@ -161,14 +148,16 @@ private: uint32_t _vbCount{0}; uint32_t _ibCount{0}; + uint8_t _stride{0}; bool _vertDirty{false}; + bool _isMeshBuffer{false}; + RenderDrawInfoType _drawInfoType{RenderDrawInfoType::COMP}; // weak reference scene::Model* _model{nullptr}; ccstd::hash_t _dataHash{0}; uint32_t _stencilStage{0}; - bool _isMeshBuffer{false}; // weak reference Material* _material{nullptr}; // weak reference @@ -179,8 +168,6 @@ private: uint32_t _blendHash{0}; - RenderDrawInfoType _drawInfoType{RenderDrawInfoType::COMP}; - gfx::InputAssemblerInfo _iaInfo; ccstd::vector _attributes{ gfx::Attribute{gfx::ATTR_NAME_POSITION, gfx::Format::RGB32F}, diff --git a/native/cocos/2d/renderer/RenderEntity.cpp b/native/cocos/2d/renderer/RenderEntity.cpp index 073f5f39c7..cbdc1e9fc9 100644 --- a/native/cocos/2d/renderer/RenderEntity.cpp +++ b/native/cocos/2d/renderer/RenderEntity.cpp @@ -28,14 +28,7 @@ #include "bindings/utils/BindingUtils.h" namespace cc { -RenderEntity::RenderEntity() : RenderEntity(nullptr) { -} - -RenderEntity::RenderEntity(Batcher2d* batcher) : _batcher(batcher) { - for (auto& drawInfo : _staticDrawInfos) { - drawInfo.setBatcher(_batcher); - } - +RenderEntity::RenderEntity() { _entitySharedBufferActor.initialize(&_entityAttrLayout, sizeof(EntityAttrLayout)); } diff --git a/native/cocos/2d/renderer/RenderEntity.h b/native/cocos/2d/renderer/RenderEntity.h index 14a7fb079c..bb2ff6ac3b 100644 --- a/native/cocos/2d/renderer/RenderEntity.h +++ b/native/cocos/2d/renderer/RenderEntity.h @@ -36,7 +36,7 @@ namespace cc { class Batcher2d; -enum class RenderEntityType { +enum class RenderEntityType: uint8_t { STATIC, DYNAMIC }; @@ -58,7 +58,6 @@ public: static constexpr uint32_t STATIC_DRAW_INFO_CAPACITY = 4; RenderEntity(); - explicit RenderEntity(Batcher2d* batcher); ~RenderEntity() override; void addDynamicRenderDrawInfo(RenderDrawInfo* drawInfo); @@ -106,26 +105,20 @@ public: private: CC_DISALLOW_COPY_MOVE_ASSIGN(RenderEntity); - - uint32_t _staticDrawInfoSize{0}; - std::array _staticDrawInfos; - ccstd::vector _dynamicDrawInfos; - - // weak reference - Batcher2d* _batcher{nullptr}; // weak reference Node* _node{nullptr}; StencilStage _stencilStage{StencilStage::DISABLED}; RenderEntityType _renderEntityType{RenderEntityType::STATIC}; - - EntityAttrLayout _entityAttrLayout; - - bindings::NativeMemorySharedToScriptActor _entitySharedBufferActor; - - float _opacity{1.0F}; - bool _isMask{false}; bool _isSubMask{false}; + + EntityAttrLayout _entityAttrLayout; + float _opacity{1.0F}; + uint32_t _staticDrawInfoSize{0}; + + bindings::NativeMemorySharedToScriptActor _entitySharedBufferActor; + std::array _staticDrawInfos; + ccstd::vector _dynamicDrawInfos; bool _isMaskInverted{false}; }; } // namespace cc diff --git a/native/cocos/2d/renderer/StencilManager.h b/native/cocos/2d/renderer/StencilManager.h index c182c0ab13..edfc9e3a1c 100644 --- a/native/cocos/2d/renderer/StencilManager.h +++ b/native/cocos/2d/renderer/StencilManager.h @@ -35,7 +35,7 @@ namespace cc { class RenderEntity; -enum class StencilStage { +enum class StencilStage: uint8_t { // Stencil disabled DISABLED = 0, // Clear stencil buffer From 3030a15efa0f7f359574c12860cbc817f9a8e97b Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Mon, 18 Jul 2022 11:53:53 +0800 Subject: [PATCH 007/111] [ci skip][AUTO]: Automated code generating update: 34cde05fa14ead3af3b26057b90329cd64090929 (#12042) (#12051) Co-authored-by: cocos-robot --- native/cocos/bindings/auto/jsb_2d_auto.cpp | 72 ++++------------------ native/cocos/bindings/auto/jsb_2d_auto.h | 1 - 2 files changed, 11 insertions(+), 62 deletions(-) diff --git a/native/cocos/bindings/auto/jsb_2d_auto.cpp b/native/cocos/bindings/auto/jsb_2d_auto.cpp index c64906f74a..0dfbbb02c6 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.cpp +++ b/native/cocos/bindings/auto/jsb_2d_auto.cpp @@ -267,26 +267,6 @@ static bool js_2d_RenderDrawInfo_getAccId(se::State& s) // NOLINT(readability-id } SE_BIND_FUNC_AS_PROP_GET(js_2d_RenderDrawInfo_getAccId) -static bool js_2d_RenderDrawInfo_getAttrSharedBufferForJS(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - if (nullptr == cobj) return true; - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - se::Object* result = cobj->getAttrSharedBufferForJS(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_2d_RenderDrawInfo_getAttrSharedBufferForJS) - static bool js_2d_RenderDrawInfo_getBlendHash(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -1173,23 +1153,6 @@ static bool js_2d_RenderDrawInfo_constructor(se::State& s) // NOLINT(readability CC_UNUSED bool ok = true; const auto& args = s.args(); size_t argc = args.size(); - do { - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - auto *ptr = JSB_MAKE_PRIVATE_OBJECT(cc::RenderDrawInfo, arg0.value()); - s.thisObject()->setPrivateObject(ptr); - return true; - } - } while(false); - do { - if (argc == 0) { - auto *ptr = JSB_MAKE_PRIVATE_OBJECT(cc::RenderDrawInfo); - s.thisObject()->setPrivateObject(ptr); - return true; - } - } while(false); do { if (argc == 3) { HolderType arg0 = {}; @@ -1206,6 +1169,13 @@ static bool js_2d_RenderDrawInfo_constructor(se::State& s) // NOLINT(readability return true; } } while(false); + do { + if (argc == 0) { + auto *ptr = JSB_MAKE_PRIVATE_OBJECT(cc::RenderDrawInfo); + s.thisObject()->setPrivateObject(ptr); + return true; + } + } while(false); SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } @@ -1244,7 +1214,6 @@ bool js_register_2d_RenderDrawInfo(se::Object* obj) // NOLINT(readability-identi cls->defineProperty("blendHash", _SE(js_2d_RenderDrawInfo_getBlendHash_asGetter), _SE(js_2d_RenderDrawInfo_setBlendHash_asSetter)); cls->defineProperty("model", _SE(js_2d_RenderDrawInfo_getModel_asGetter), _SE(js_2d_RenderDrawInfo_setModel_asSetter)); cls->defineProperty("drawInfoType", _SE(js_2d_RenderDrawInfo_getDrawInfoType_asGetter), _SE(js_2d_RenderDrawInfo_setDrawInfoType_asSetter)); - cls->defineFunction("getAttrSharedBufferForJS", _SE(js_2d_RenderDrawInfo_getAttrSharedBufferForJS)); cls->defineFunction("getMeshBuffer", _SE(js_2d_RenderDrawInfo_getMeshBuffer)); cls->defineFunction("requestIA", _SE(js_2d_RenderDrawInfo_requestIA)); cls->defineFunction("resetMeshIA", _SE(js_2d_RenderDrawInfo_resetMeshIA)); @@ -1743,30 +1712,11 @@ SE_BIND_FUNC_AS_PROP_SET(js_2d_RenderEntity_setStencilStage) SE_DECLARE_FINALIZE_FUNC(js_cc_RenderEntity_finalize) -static bool js_2d_RenderEntity_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor_overloaded.c +static bool js_2d_RenderEntity_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c { - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - do { - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - auto *ptr = JSB_MAKE_PRIVATE_OBJECT(cc::RenderEntity, arg0.value()); - s.thisObject()->setPrivateObject(ptr); - return true; - } - } while(false); - do { - if (argc == 0) { - auto *ptr = JSB_MAKE_PRIVATE_OBJECT(cc::RenderEntity); - s.thisObject()->setPrivateObject(ptr); - return true; - } - } while(false); - SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); - return false; + auto *ptr = JSB_MAKE_PRIVATE_OBJECT(cc::RenderEntity); + s.thisObject()->setPrivateObject(ptr); + return true; } SE_BIND_CTOR(js_2d_RenderEntity_constructor, __jsb_cc_RenderEntity_class, js_cc_RenderEntity_finalize) diff --git a/native/cocos/bindings/auto/jsb_2d_auto.h b/native/cocos/bindings/auto/jsb_2d_auto.h index 24f0f35620..6b290c65ab 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.h +++ b/native/cocos/bindings/auto/jsb_2d_auto.h @@ -37,7 +37,6 @@ extern se::Class * __jsb_cc_RenderDrawInfo_class; // NOLINT bool js_register_cc_RenderDrawInfo(se::Object *obj); // NOLINT -SE_DECLARE_FUNC(js_2d_RenderDrawInfo_getAttrSharedBufferForJS); SE_DECLARE_FUNC(js_2d_RenderDrawInfo_getMeshBuffer); SE_DECLARE_FUNC(js_2d_RenderDrawInfo_requestIA); SE_DECLARE_FUNC(js_2d_RenderDrawInfo_resetMeshIA); From 3025bcd012cd3e461b11bfb2b23d2884580c538a Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 18 Jul 2022 14:10:16 +0800 Subject: [PATCH 008/111] [v3.6.0] Optimize se::Object::getPrivateData, math::IsEqualF, Vec3::transformMat4 (#12039) --- .../workflows/native-compile-platforms.yml | 2 +- native/cocos/bindings/jswrapper/v8/Object.cpp | 3 + native/cocos/bindings/jswrapper/v8/Object.h | 3 +- native/cocos/core/assets/Font.cpp | 4 +- native/cocos/math/Mat4.h | 2 +- native/cocos/math/Math.cpp | 165 +++--------------- native/cocos/math/Math.h | 33 ++-- native/cocos/math/MathUtil.cpp | 7 - native/cocos/math/Quaternion.cpp | 6 +- native/cocos/math/Vec3.cpp | 77 +++++++- native/cocos/math/Vec3.h | 4 + .../canvas/CanvasRenderingContext2D.cpp | 4 +- .../renderer/gfx-gles2/GLES2CommandBuffer.cpp | 24 +-- .../cocos/renderer/gfx-gles2/GLES2Texture.cpp | 2 +- .../renderer/gfx-gles3/GLES3CommandBuffer.cpp | 24 +-- .../cocos/renderer/gfx-gles3/GLES3Texture.cpp | 2 +- .../gfx-metal/MTLRenderCommandEncoder.h | 6 +- native/cocos/renderer/gfx-metal/MTLUtils.mm | 4 +- .../DescriptorSetLayoutValidator.cpp | 2 +- .../gfx-validator/DeviceValidator.cpp | 8 +- .../renderer/gfx-vulkan/VKCommandBuffer.cpp | 20 +-- .../renderer/pipeline/ClusterLightCulling.h | 2 +- native/cocos/renderer/pipeline/Define.h | 14 +- native/tests/unit-test/src/utils.h | 2 +- .../generate_compile_commands_android.sh | 2 + templates/cmake/android.cmake | 6 + 26 files changed, 188 insertions(+), 240 deletions(-) mode change 100755 => 100644 native/cocos/math/Math.cpp diff --git a/.github/workflows/native-compile-platforms.yml b/.github/workflows/native-compile-platforms.yml index 5d0d36e63c..08c38cc3ed 100644 --- a/.github/workflows/native-compile-platforms.yml +++ b/.github/workflows/native-compile-platforms.yml @@ -127,7 +127,7 @@ jobs: # To speedup CI, compile arm64-v8a only # sed -i "s@^PROP_APP_ABI.*@PROP_APP_ABI=armeabi-v7a:arm64-v8a:x86@g" gradle.properties - sed -i "s@^PROP_APP_ABI.*@PROP_APP_ABI=arm64-v8a@g" gradle.properties + sed -i "s@^PROP_APP_ABI.*@PROP_APP_ABI=armeabi-v7a:arm64-v8a@g" gradle.properties echo "Compile Android - cmake ..." echo "ANDORID_NDK ${ANDROID_NDK} or ${ANDROID_NDK_HOME}" diff --git a/native/cocos/bindings/jswrapper/v8/Object.cpp b/native/cocos/bindings/jswrapper/v8/Object.cpp index 30f9910c48..7c89467805 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.cpp +++ b/native/cocos/bindings/jswrapper/v8/Object.cpp @@ -577,7 +577,10 @@ void Object::setPrivateObject(PrivateObjectBase *data) { _privateObject = data; if (data != nullptr) { + _privateData = data->getRaw(); NativePtrToObjectMap::emplace(data->getRaw(), this); + } else { + _privateData = nullptr; } } diff --git a/native/cocos/bindings/jswrapper/v8/Object.h b/native/cocos/bindings/jswrapper/v8/Object.h index 99abec92bf..defeb47d90 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.h +++ b/native/cocos/bindings/jswrapper/v8/Object.h @@ -300,7 +300,7 @@ public: * @return A void* that is the object's private data, if the object has private data, otherwise nullptr. */ inline void *getPrivateData() const { - return _privateObject ? _privateObject->getRaw() : nullptr; + return _privateData; } /** @@ -455,6 +455,7 @@ private: uint32_t _rootCount{0}; PrivateObjectBase *_privateObject{nullptr}; + void *_privateData{nullptr}; V8FinalizeFunc _finalizeCb{nullptr}; bool _clearMappingInFinalizer{true}; diff --git a/native/cocos/core/assets/Font.cpp b/native/cocos/core/assets/Font.cpp index 57977e9476..9873c2d261 100644 --- a/native/cocos/core/assets/Font.cpp +++ b/native/cocos/core/assets/Font.cpp @@ -53,7 +53,7 @@ FontFaceInfo::FontFaceInfo(uint32_t size) FontFaceInfo::FontFaceInfo(uint32_t size, uint32_t width, uint32_t height) : fontSize(size), textureWidth(width), textureHeight(height) { - CC_ASSERT(math::IsPowerOfTwo(width) && math::IsPowerOfTwo(height)); // Font texture size must be power of 2. + CC_ASSERT(math::isPowerOfTwo(width) && math::isPowerOfTwo(height)); // Font texture size must be power of 2. // preload digit & alphabet characters by default for (auto i = 0U; i < 128; i++) { @@ -65,7 +65,7 @@ FontFaceInfo::FontFaceInfo(uint32_t size, uint32_t width, uint32_t height) FontFaceInfo::FontFaceInfo(uint32_t size, uint32_t width, uint32_t height, ccstd::vector chars) : fontSize(size), textureWidth(width), textureHeight(height), preLoadedCharacters(std::move(chars)) { - CC_ASSERT(math::IsPowerOfTwo(width) && math::IsPowerOfTwo(height)); // Font texture size must be power of 2. + CC_ASSERT(math::isPowerOfTwo(width) && math::isPowerOfTwo(height)); // Font texture size must be power of 2. } /** diff --git a/native/cocos/math/Mat4.h b/native/cocos/math/Mat4.h index d42daa0334..aa4d25b322 100644 --- a/native/cocos/math/Mat4.h +++ b/native/cocos/math/Mat4.h @@ -73,7 +73,7 @@ NS_CC_MATH_BEGIN * * @see Transform */ -class CC_DLL Mat4 { +class CC_DLL alignas(16) Mat4 { public: // //temp add conversion // operator kmMat4() const diff --git a/native/cocos/math/Math.cpp b/native/cocos/math/Math.cpp old mode 100755 new mode 100644 index fd8721ddcb..71fdc386bd --- a/native/cocos/math/Math.cpp +++ b/native/cocos/math/Math.cpp @@ -1,161 +1,36 @@ #include "math/Math.h" #include +#include #include #include -#include namespace cc { namespace math { -const float PI = (float)(3.14159265358979323846264338327950288419716939937511); -; -const float PI_2 = math::PI * 2.0f; -const float PI_DIV2 = math::PI * 0.5f; -const float PI_DIV3 = math::PI / 3.0f; -const float PI_DIV4 = math::PI / 4.0f; -const float PI_DIV5 = math::PI / 5.0f; -const float PI_DIV6 = math::PI / 6.0f; -const float PI_DIV8 = math::PI / 8.0f; -const float PI_SQR = (float)(9.86960440108935861883449099987615113531369940724079); -const float PI_INV = (float)(0.31830988618379067153776752674502872406891929148091); +const float PI = static_cast(3.14159265358979323846264338327950288419716939937511); + +const float PI_2 = math::PI * 2.0F; +const float PI_DIV2 = math::PI * 0.5F; +const float PI_DIV3 = math::PI / 3.0F; +const float PI_DIV4 = math::PI / 4.0F; +const float PI_DIV5 = math::PI / 5.0F; +const float PI_DIV6 = math::PI / 6.0F; +const float PI_DIV8 = math::PI / 8.0F; +const float PI_SQR = static_cast(9.86960440108935861883449099987615113531369940724079); +const float PI_INV = static_cast(0.31830988618379067153776752674502872406891929148091); const float EPSILON = std::numeric_limits::epsilon(); -const float LOW_EPSILON = (float)(1e-04); +const float LOW_EPSILON = static_cast(1e-04); const float POS_INFINITY = std::numeric_limits::infinity(); const float NEG_INFINITY = -std::numeric_limits::infinity(); -; -const float LN2 = std::log(2.0f); -const float LN10 = std::log(10.0f); -const float LN2_INV = 1.0f / LN2; -const float LN10_INV = 1.0f / LN10; -const float DEG_TO_RAD = (float)0.01745329; -const float RAD_TO_DEG = (float)57.29577; + +const float LN2 = std::log(2.0F); +const float LN10 = std::log(10.0F); +const float LN2_INV = 1.0F / LN2; +const float LN10_INV = 1.0F / LN10; +const float DEG_TO_RAD = static_cast(0.01745329); +const float RAD_TO_DEG = static_cast(57.29577); const float MIN_FLOAT = 1.175494351e-38F; const float MAX_FLOAT = 3.402823466e+38F; -const uint16_t CRC16_TABLE[256] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0}; - -const uint32_t CRC32_TABLE[] = { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, - 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, - 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, - 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, - 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, - 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, - 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, - 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, - 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, - 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, - 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, - 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, - 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, - 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, - 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, - 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, - 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, - 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, - 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, - 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, - 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, - 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, - 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, - 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, - 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, - 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, - 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, - 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, - 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, - 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, - 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, - 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, - 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, - 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, - 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, - 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, - 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, - 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, - 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, - 0x2D02EF8D}; - -inline void CRCUpdateB(uint32_t &crc, uint8_t b) { - crc = CRC32_TABLE[(crc ^ b) & 0xFF] ^ (crc >> 8); -} - -uint32_t CRC32(const char *str) { - uint32_t crc = 0xFFFFFFFF; - size_t length = strlen(str); - - for (size_t i = 0; i < length; ++i) { - CRCUpdateB(crc, (uint8_t)str[i]); - } - - CRCUpdateB(crc, (uint8_t)length); - return crc; -} - -uint32_t CRC32NoCase(const char *str) { - uint32_t crc = 0xFFFFFFFF; - size_t length = strlen(str); - - for (size_t i = 0; i < length; ++i) { - CRCUpdateB(crc, (uint8_t)tolower((char)str[i])); - } - - CRCUpdateB(crc, (uint8_t)length); - return crc; -} - -uint16_t CRC16(const char *str) { - size_t length = strlen(str); - uint16_t crc = 0; - for (size_t i = 0; i < length; ++i) { - crc = (crc << 8) ^ CRC16_TABLE[((crc >> 8) ^ *str++) & 0x00FF]; - } - return crc; -} - } // namespace math } // namespace cc diff --git a/native/cocos/math/Math.h b/native/cocos/math/Math.h index 3377c34d4a..0e2c78848c 100644 --- a/native/cocos/math/Math.h +++ b/native/cocos/math/Math.h @@ -24,8 +24,9 @@ ****************************************************************************/ #pragma once -#include "base/Macros.h" #include +#include +#include "base/Macros.h" namespace cc { namespace math { @@ -53,36 +54,26 @@ extern CC_DLL const float RAD_TO_DEG; extern CC_DLL const float MIN_FLOAT; extern CC_DLL const float MAX_FLOAT; -uint16_t CRC16(const char *str); -uint32_t CRC32(const char *str); -uint32_t CRC32NoCase(const char *str); - template -inline T Abs(T x) { - return x > 0 ? x : -x; -} - -template -inline T Sgn(T x) { +inline T sgn(T x) { return (x < T(0) ? T(-1) : (x > T(0) ? T(1) : T(0))); } template -inline T Sqr(T x) { - return x * x; -} - -template -inline bool IsPowerOfTwo(T n) { +inline bool isPowerOfTwo(T n) { return (n & (n - 1)) == 0; } -inline bool IsEqualF(float lhs, float rhs, float precision = 0.000001f) { - return (Abs(lhs - rhs) < precision); +inline bool isEqualF(float lhs, float rhs, float precision = 0.000001F) { + return (std::abs(lhs - rhs) < precision); } -inline bool IsNotEqualF(float lhs, float rhs, float precision = 0.000001f) { - return (Abs(lhs - rhs) > precision); +inline bool isNotEqualF(float lhs, float rhs, float precision = 0.000001F) { + return (std::abs(lhs - rhs) > precision); +} + +inline bool isNotZeroF(float v, float precision = 0.000001F) { + return (std::abs(v) > precision); } } // namespace math diff --git a/native/cocos/math/MathUtil.cpp b/native/cocos/math/MathUtil.cpp index dc1f4a992b..110d5618c8 100644 --- a/native/cocos/math/MathUtil.cpp +++ b/native/cocos/math/MathUtil.cpp @@ -38,10 +38,6 @@ This file was modified to fit the cocos2d-x project #if defined(__arm64__) #define USE_NEON64 #define INCLUDE_NEON64 - #elif defined(__ARM_NEON__) - #define USE_NEON32 - #define INCLUDE_NEON32 - #else #endif #elif (CC_PLATFORM == CC_PLATFORM_ANDROID) #if defined(__arm64__) || defined(__aarch64__) @@ -49,10 +45,7 @@ This file was modified to fit the cocos2d-x project #define INCLUDE_NEON64 #elif defined(__ARM_NEON__) #define INCLUDE_NEON32 - #else #endif -#else - #endif #if defined(__SSE__) diff --git a/native/cocos/math/Quaternion.cpp b/native/cocos/math/Quaternion.cpp index 229fe95375..9662c4e8f8 100644 --- a/native/cocos/math/Quaternion.cpp +++ b/native/cocos/math/Quaternion.cpp @@ -331,9 +331,9 @@ void Quaternion::toEuler(const Quaternion &q, bool outerZ, Vec3 *out) { heading = atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz) * r2d; attitude = asin(2 * test) * r2d; if (outerZ) { - bank = static_cast(-180.F * math::Sgn(bank + 1e-6) + bank); - heading = static_cast(-180.F * math::Sgn(heading + 1e-6) + heading); - attitude = static_cast(180.F * math::Sgn(attitude + 1e-6) - attitude); + bank = static_cast(-180.F * math::sgn(bank + 1e-6) + bank); + heading = static_cast(-180.F * math::sgn(heading + 1e-6) + heading); + attitude = static_cast(180.F * math::sgn(attitude + 1e-6) - attitude); } } out->x = bank; diff --git a/native/cocos/math/Vec3.cpp b/native/cocos/math/Vec3.cpp index cfe4f881bb..ac55924209 100644 --- a/native/cocos/math/Vec3.cpp +++ b/native/cocos/math/Vec3.cpp @@ -27,6 +27,32 @@ #include "math/MathUtil.h" #include "math/Quaternion.h" +#if (CC_PLATFORM == CC_PLATFORM_ANDROID) + #include +#endif + +#if (CC_PLATFORM == CC_PLATFORM_IOS) + #if defined(__arm64__) + #define USE_NEON64 + #define INCLUDE_NEON64 + #endif +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID) + #if defined(__arm64__) || defined(__aarch64__) + #define USE_NEON64 + #define INCLUDE_NEON64 + #elif defined(__ARM_NEON__) + #define INCLUDE_NEON32 + #endif +#endif + +#if defined(USE_NEON64) || defined(USE_NEON32) || defined(INCLUDE_NEON32) + #include "enoki/array.h" + #ifndef ENOKI_ARM_NEON + #error "ENOKI_ARM_NEON isn't enabled!" + #endif +using SimdVec4 = enoki::Array; +#endif + NS_CC_MATH_BEGIN Vec3::Vec3(float xx, float yy, float zz) @@ -192,15 +218,62 @@ void Vec3::transformMat3(const Vec3 &v, const Mat3 &m) { z = ix * m.m[2] + iy * m.m[5] + iz * m.m[8]; } -void Vec3::transformMat4(const Vec3 &v, const Mat4 &m) { +void Vec3::transformMat4Neon(const Vec3 &v, const Mat4 &m) { +#if defined(USE_NEON64) || defined(USE_NEON32) || defined(INCLUDE_NEON32) + alignas(16) float tmpV0[4]; + + auto row0 = enoki::load(&m.m[0]); + auto row1 = enoki::load(&m.m[4]); + auto row2 = enoki::load(&m.m[8]); + auto row3 = enoki::load(&m.m[12]); + + row0 *= v.x; + row1 *= v.y; + row2 *= v.z; + + row0 = row0 + row1 + row2 + row3; + enoki::store(tmpV0, row0); + float rhw; + + if (CC_PREDICT_TRUE(math::isNotZeroF(tmpV0[3]))) { + rhw = 1.F / tmpV0[3]; + } else { + rhw = 1.F; + } + + SimdVec4 tmpV1{rhw}; + row0 *= tmpV1; + enoki::store(tmpV0, row0); + + x = tmpV0[0]; + y = tmpV0[1]; + z = tmpV0[2]; +#endif +} + +void Vec3::transformMat4C(const Vec3 &v, const Mat4 &m) { alignas(16) float tmp[4] = {v.x, v.y, v.z, 1.0F}; MathUtil::transformVec4(m.m, tmp, tmp); - float rhw = math::IsNotEqualF(tmp[3], 0.0F) ? 1 / tmp[3] : 1; + float rhw = math::isNotZeroF(tmp[3]) ? 1.F / tmp[3] : 1.F; x = tmp[0] * rhw; y = tmp[1] * rhw; z = tmp[2] * rhw; } +void Vec3::transformMat4(const Vec3 &v, const Mat4 &m) { +#if defined(USE_NEON64) + transformMat4Neon(v, m); +#elif defined(INCLUDE_NEON32) + if (CC_PREDICT_TRUE(MathUtil::isNeon32Enabled())) { + transformMat4Neon(v, m); + } else { + transformMat4C(v, m); + } +#else + transformMat4C(v, m); +#endif +} + void Vec3::transformMat4(const Vec3 &v, const Mat4 &m, Vec3 *dst) { dst->transformMat4(v, m); } diff --git a/native/cocos/math/Vec3.h b/native/cocos/math/Vec3.h index 246280776b..7d58f94a41 100644 --- a/native/cocos/math/Vec3.h +++ b/native/cocos/math/Vec3.h @@ -615,6 +615,10 @@ public: static const Vec3 UNIT_Z; /** equals to Vec3(0,0,-1) */ static const Vec3 FORWARD; + +private: + void transformMat4C(const Vec3 &v, const Mat4 &m); + void transformMat4Neon(const Vec3 &v, const Mat4 &m); }; /** diff --git a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp index b3b3d66427..5f271d7611 100644 --- a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp +++ b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp @@ -161,14 +161,14 @@ void CanvasRenderingContext2D::fetchData() { void CanvasRenderingContext2D::setWidth(float width) { //SE_LOGD("CanvasRenderingContext2D::set__width: %f\n", width); - if (math::IsEqualF(width, _width)) return; + if (math::isEqualF(width, _width)) return; _width = width; _isBufferSizeDirty = true; } void CanvasRenderingContext2D::setHeight(float height) { //SE_LOGD("CanvasRenderingContext2D::set__height: %f\n", height); - if (math::IsEqualF(height, _height)) return; + if (math::isEqualF(height, _height)) return; _height = height; _isBufferSizeDirty = true; } diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp index 025586f7a4..43c525fdff 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp @@ -174,8 +174,8 @@ void GLES2CommandBuffer::setViewport(const Viewport &vp) { (_curDynamicStates.viewport.top != vp.top) || (_curDynamicStates.viewport.width != vp.width) || (_curDynamicStates.viewport.height != vp.height) || - math::IsNotEqualF(_curDynamicStates.viewport.minDepth, vp.minDepth) || - math::IsNotEqualF(_curDynamicStates.viewport.maxDepth, vp.maxDepth)) { + math::isNotEqualF(_curDynamicStates.viewport.minDepth, vp.minDepth) || + math::isNotEqualF(_curDynamicStates.viewport.maxDepth, vp.maxDepth)) { _curDynamicStates.viewport = vp; _isStateInvalid = true; } @@ -192,16 +192,16 @@ void GLES2CommandBuffer::setScissor(const Rect &rect) { } void GLES2CommandBuffer::setLineWidth(float width) { - if (math::IsNotEqualF(_curDynamicStates.lineWidth, width)) { + if (math::isNotEqualF(_curDynamicStates.lineWidth, width)) { _curDynamicStates.lineWidth = width; _isStateInvalid = true; } } void GLES2CommandBuffer::setDepthBias(float constant, float clamp, float slope) { - if (math::IsNotEqualF(_curDynamicStates.depthBiasConstant, constant) || - math::IsNotEqualF(_curDynamicStates.depthBiasClamp, clamp) || - math::IsNotEqualF(_curDynamicStates.depthBiasSlope, slope)) { + if (math::isNotEqualF(_curDynamicStates.depthBiasConstant, constant) || + math::isNotEqualF(_curDynamicStates.depthBiasClamp, clamp) || + math::isNotEqualF(_curDynamicStates.depthBiasSlope, slope)) { _curDynamicStates.depthBiasConstant = constant; _curDynamicStates.depthBiasClamp = clamp; _curDynamicStates.depthBiasSlope = slope; @@ -210,10 +210,10 @@ void GLES2CommandBuffer::setDepthBias(float constant, float clamp, float slope) } void GLES2CommandBuffer::setBlendConstants(const Color &constants) { - if (math::IsNotEqualF(_curDynamicStates.blendConstant.x, constants.x) || - math::IsNotEqualF(_curDynamicStates.blendConstant.y, constants.y) || - math::IsNotEqualF(_curDynamicStates.blendConstant.z, constants.z) || - math::IsNotEqualF(_curDynamicStates.blendConstant.w, constants.w)) { + if (math::isNotEqualF(_curDynamicStates.blendConstant.x, constants.x) || + math::isNotEqualF(_curDynamicStates.blendConstant.y, constants.y) || + math::isNotEqualF(_curDynamicStates.blendConstant.z, constants.z) || + math::isNotEqualF(_curDynamicStates.blendConstant.w, constants.w)) { _curDynamicStates.blendConstant.x = constants.x; _curDynamicStates.blendConstant.y = constants.y; _curDynamicStates.blendConstant.z = constants.z; @@ -223,8 +223,8 @@ void GLES2CommandBuffer::setBlendConstants(const Color &constants) { } void GLES2CommandBuffer::setDepthBound(float minBounds, float maxBounds) { - if (math::IsNotEqualF(_curDynamicStates.depthMinBounds, minBounds) || - math::IsNotEqualF(_curDynamicStates.depthMaxBounds, maxBounds)) { + if (math::isNotEqualF(_curDynamicStates.depthMinBounds, minBounds) || + math::isNotEqualF(_curDynamicStates.depthMaxBounds, maxBounds)) { _curDynamicStates.depthMinBounds = minBounds; _curDynamicStates.depthMaxBounds = maxBounds; _isStateInvalid = true; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp index 5cdc09da51..02ee59c222 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp @@ -55,7 +55,7 @@ void GLES2Texture::doInit(const TextureInfo & /*info*/) { _gpuTexture->samples = _info.samples; _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; - _gpuTexture->isPowerOf2 = math::IsPowerOfTwo(_info.width) && math::IsPowerOfTwo(_info.height); + _gpuTexture->isPowerOf2 = math::isPowerOfTwo(_info.width) && math::isPowerOfTwo(_info.height); _gpuTexture->glTexture = static_cast(reinterpret_cast(_info.externalRes)); cmdFuncGLES2CreateTexture(GLES2Device::getInstance(), _gpuTexture); diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp index 74d5932464..49d92fb169 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp @@ -175,8 +175,8 @@ void GLES3CommandBuffer::setViewport(const Viewport &vp) { (_curDynamicStates.viewport.top != vp.top) || (_curDynamicStates.viewport.width != vp.width) || (_curDynamicStates.viewport.height != vp.height) || - math::IsNotEqualF(_curDynamicStates.viewport.minDepth, vp.minDepth) || - math::IsNotEqualF(_curDynamicStates.viewport.maxDepth, vp.maxDepth)) { + math::isNotEqualF(_curDynamicStates.viewport.minDepth, vp.minDepth) || + math::isNotEqualF(_curDynamicStates.viewport.maxDepth, vp.maxDepth)) { _curDynamicStates.viewport = vp; _isStateInvalid = true; } @@ -193,16 +193,16 @@ void GLES3CommandBuffer::setScissor(const Rect &rect) { } void GLES3CommandBuffer::setLineWidth(float width) { - if (math::IsNotEqualF(_curDynamicStates.lineWidth, width)) { + if (math::isNotEqualF(_curDynamicStates.lineWidth, width)) { _curDynamicStates.lineWidth = width; _isStateInvalid = true; } } void GLES3CommandBuffer::setDepthBias(float constant, float clamp, float slope) { - if (math::IsNotEqualF(_curDynamicStates.depthBiasConstant, constant) || - math::IsNotEqualF(_curDynamicStates.depthBiasClamp, clamp) || - math::IsNotEqualF(_curDynamicStates.depthBiasSlope, slope)) { + if (math::isNotEqualF(_curDynamicStates.depthBiasConstant, constant) || + math::isNotEqualF(_curDynamicStates.depthBiasClamp, clamp) || + math::isNotEqualF(_curDynamicStates.depthBiasSlope, slope)) { _curDynamicStates.depthBiasConstant = constant; _curDynamicStates.depthBiasClamp = clamp; _curDynamicStates.depthBiasSlope = slope; @@ -211,10 +211,10 @@ void GLES3CommandBuffer::setDepthBias(float constant, float clamp, float slope) } void GLES3CommandBuffer::setBlendConstants(const Color &constants) { - if (math::IsNotEqualF(_curDynamicStates.blendConstant.x, constants.x) || - math::IsNotEqualF(_curDynamicStates.blendConstant.y, constants.y) || - math::IsNotEqualF(_curDynamicStates.blendConstant.z, constants.z) || - math::IsNotEqualF(_curDynamicStates.blendConstant.w, constants.w)) { + if (math::isNotEqualF(_curDynamicStates.blendConstant.x, constants.x) || + math::isNotEqualF(_curDynamicStates.blendConstant.y, constants.y) || + math::isNotEqualF(_curDynamicStates.blendConstant.z, constants.z) || + math::isNotEqualF(_curDynamicStates.blendConstant.w, constants.w)) { _curDynamicStates.blendConstant.x = constants.x; _curDynamicStates.blendConstant.y = constants.y; _curDynamicStates.blendConstant.z = constants.z; @@ -224,8 +224,8 @@ void GLES3CommandBuffer::setBlendConstants(const Color &constants) { } void GLES3CommandBuffer::setDepthBound(float minBounds, float maxBounds) { - if (math::IsNotEqualF(_curDynamicStates.depthMinBounds, minBounds) || - math::IsNotEqualF(_curDynamicStates.depthMaxBounds, maxBounds)) { + if (math::isNotEqualF(_curDynamicStates.depthMinBounds, minBounds) || + math::isNotEqualF(_curDynamicStates.depthMaxBounds, maxBounds)) { _curDynamicStates.depthMinBounds = minBounds; _curDynamicStates.depthMaxBounds = maxBounds; _isStateInvalid = true; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp index 334a23a666..fc152113b8 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp @@ -56,7 +56,7 @@ void GLES3Texture::doInit(const TextureInfo & /*info*/) { _gpuTexture->samples = _info.samples; _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; - _gpuTexture->isPowerOf2 = math::IsPowerOfTwo(_info.width) && math::IsPowerOfTwo(_info.height); + _gpuTexture->isPowerOf2 = math::isPowerOfTwo(_info.width) && math::isPowerOfTwo(_info.height); _gpuTexture->glTexture = static_cast(reinterpret_cast(_info.externalRes)); cmdFuncGLES3CreateTexture(GLES3Device::getInstance(), _gpuTexture); diff --git a/native/cocos/renderer/gfx-metal/MTLRenderCommandEncoder.h b/native/cocos/renderer/gfx-metal/MTLRenderCommandEncoder.h index 7056f5f780..3126252fad 100644 --- a/native/cocos/renderer/gfx-metal/MTLRenderCommandEncoder.h +++ b/native/cocos/renderer/gfx-metal/MTLRenderCommandEncoder.h @@ -177,9 +177,9 @@ public: inline void setDepthBias(float depthBias, float clamp, float slope) { if (_isDepthBiasSet && - math::IsEqualF(_depthBias, depthBias) && - math::IsEqualF(_clamp, clamp) && - math::IsEqualF(_slope, slope)) { + math::isEqualF(_depthBias, depthBias) && + math::isEqualF(_clamp, clamp) && + math::isEqualF(_slope, slope)) { return; } diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index 8cb0dc3571..846863812a 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -878,9 +878,9 @@ MTLSamplerAddressMode mu::toMTLSamplerAddressMode(Address mode) { int mu::toMTLSamplerBorderColor(const Color &color) { #if (CC_PLATFORM == CC_PLATFORM_MACOS) float diff = color.x - 0.5f; - if (math::IsEqualF(color.w, 0.f)) + if (math::isEqualF(color.w, 0.f)) return MTLSamplerBorderColorTransparentBlack; - else if (math::IsEqualF(diff, 0.f)) + else if (math::isEqualF(diff, 0.f)) return MTLSamplerBorderColorOpaqueBlack; else return MTLSamplerBorderColorOpaqueWhite; diff --git a/native/cocos/renderer/gfx-validator/DescriptorSetLayoutValidator.cpp b/native/cocos/renderer/gfx-validator/DescriptorSetLayoutValidator.cpp index de32db9a9e..a1f57af774 100644 --- a/native/cocos/renderer/gfx-validator/DescriptorSetLayoutValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DescriptorSetLayoutValidator.cpp @@ -71,7 +71,7 @@ void DescriptorSetLayoutValidator::doInit(const DescriptorSetLayoutInfo &info) { for (const auto &binding : bindings) { CC_ASSERT(binding.binding != INVALID_BINDING); CC_ASSERT(binding.descriptorType != DescriptorType::UNKNOWN); - CC_ASSERT(math::IsPowerOfTwo(toNumber(binding.descriptorType))); + CC_ASSERT(math::isPowerOfTwo(toNumber(binding.descriptorType))); CC_ASSERT(binding.count); CC_ASSERT(binding.stageFlags != ShaderStageFlagBit::NONE); for (const Sampler *sampler : binding.immutableSamplers) { diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp index 84a0da9712..71be99fd5f 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp @@ -270,11 +270,11 @@ Sampler *DeviceValidator::getSampler(const SamplerInfo &info) { GeneralBarrier *DeviceValidator::getGeneralBarrier(const GeneralBarrierInfo &info) { if (info.prevAccesses > AccessFlagBit::PRESENT) { // Write access should appear on its own. - CC_ASSERT(math::IsPowerOfTwo(toNumber(info.prevAccesses))); + CC_ASSERT(math::isPowerOfTwo(toNumber(info.prevAccesses))); } if (info.nextAccesses > AccessFlagBit::PRESENT) { // Write access should appear on its own. - CC_ASSERT(math::IsPowerOfTwo(toNumber(info.nextAccesses))); + CC_ASSERT(math::isPowerOfTwo(toNumber(info.nextAccesses))); } /////////// execute /////////// @@ -285,11 +285,11 @@ GeneralBarrier *DeviceValidator::getGeneralBarrier(const GeneralBarrierInfo &inf TextureBarrier *DeviceValidator::getTextureBarrier(const TextureBarrierInfo &info) { if (info.prevAccesses > AccessFlagBit::PRESENT) { // Write access should appear on its own. - CC_ASSERT(math::IsPowerOfTwo(toNumber(info.prevAccesses))); + CC_ASSERT(math::isPowerOfTwo(toNumber(info.prevAccesses))); } if (info.nextAccesses > AccessFlagBit::PRESENT) { // Write access should appear on its own. - CC_ASSERT(math::IsPowerOfTwo(toNumber(info.nextAccesses))); + CC_ASSERT(math::isPowerOfTwo(toNumber(info.nextAccesses))); } /////////// execute /////////// diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index 0402fbfceb..921d194022 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -278,16 +278,16 @@ void CCVKCommandBuffer::setScissor(const Rect &rect) { } void CCVKCommandBuffer::setLineWidth(float width) { - if (math::IsNotEqualF(_curDynamicStates.lineWidth, width)) { + if (math::isNotEqualF(_curDynamicStates.lineWidth, width)) { _curDynamicStates.lineWidth = width; vkCmdSetLineWidth(_gpuCommandBuffer->vkCommandBuffer, width); } } void CCVKCommandBuffer::setDepthBias(float constant, float clamp, float slope) { - if (math::IsNotEqualF(_curDynamicStates.depthBiasConstant, constant) || - math::IsNotEqualF(_curDynamicStates.depthBiasClamp, clamp) || - math::IsNotEqualF(_curDynamicStates.depthBiasSlope, slope)) { + if (math::isNotEqualF(_curDynamicStates.depthBiasConstant, constant) || + math::isNotEqualF(_curDynamicStates.depthBiasClamp, clamp) || + math::isNotEqualF(_curDynamicStates.depthBiasSlope, slope)) { _curDynamicStates.depthBiasConstant = constant; _curDynamicStates.depthBiasClamp = clamp; _curDynamicStates.depthBiasSlope = slope; @@ -296,10 +296,10 @@ void CCVKCommandBuffer::setDepthBias(float constant, float clamp, float slope) { } void CCVKCommandBuffer::setBlendConstants(const Color &constants) { - if (math::IsNotEqualF(_curDynamicStates.blendConstant.x, constants.x) || - math::IsNotEqualF(_curDynamicStates.blendConstant.y, constants.y) || - math::IsNotEqualF(_curDynamicStates.blendConstant.z, constants.z) || - math::IsNotEqualF(_curDynamicStates.blendConstant.w, constants.w)) { + if (math::isNotEqualF(_curDynamicStates.blendConstant.x, constants.x) || + math::isNotEqualF(_curDynamicStates.blendConstant.y, constants.y) || + math::isNotEqualF(_curDynamicStates.blendConstant.z, constants.z) || + math::isNotEqualF(_curDynamicStates.blendConstant.w, constants.w)) { _curDynamicStates.blendConstant.x = constants.x; _curDynamicStates.blendConstant.y = constants.y; _curDynamicStates.blendConstant.z = constants.z; @@ -309,8 +309,8 @@ void CCVKCommandBuffer::setBlendConstants(const Color &constants) { } void CCVKCommandBuffer::setDepthBound(float minBounds, float maxBounds) { - if (math::IsNotEqualF(_curDynamicStates.depthMinBounds, minBounds) || - math::IsNotEqualF(_curDynamicStates.depthMaxBounds, maxBounds)) { + if (math::isNotEqualF(_curDynamicStates.depthMinBounds, minBounds) || + math::isNotEqualF(_curDynamicStates.depthMaxBounds, maxBounds)) { _curDynamicStates.depthMinBounds = minBounds; _curDynamicStates.depthMaxBounds = maxBounds; vkCmdSetDepthBounds(_gpuCommandBuffer->vkCommandBuffer, minBounds, maxBounds); diff --git a/native/cocos/renderer/pipeline/ClusterLightCulling.h b/native/cocos/renderer/pipeline/ClusterLightCulling.h index bc352b23e0..7ebbe2ce63 100644 --- a/native/cocos/renderer/pipeline/ClusterLightCulling.h +++ b/native/cocos/renderer/pipeline/ClusterLightCulling.h @@ -78,7 +78,7 @@ private: static bool isProjMatChange(const Mat4 &curProj, const Mat4 &oldProj) { for (uint32_t i = 0; i < sizeof(curProj.m) / sizeof(float); i++) { - if (math::IsNotEqualF(curProj.m[i], oldProj.m[i])) { + if (math::isNotEqualF(curProj.m[i], oldProj.m[i])) { return true; } } diff --git a/native/cocos/renderer/pipeline/Define.h b/native/cocos/renderer/pipeline/Define.h index 6a09891526..ef086b76b6 100644 --- a/native/cocos/renderer/pipeline/Define.h +++ b/native/cocos/renderer/pipeline/Define.h @@ -171,7 +171,7 @@ inline bool opaqueCompareFn(const RenderPass &a, const RenderPass &b) { return a.hash < b.hash; } - if (math::IsNotEqualF(a.depth, b.depth)) { + if (math::isNotEqualF(a.depth, b.depth)) { return a.depth < b.depth; } @@ -182,12 +182,12 @@ inline bool transparentCompareFn(const RenderPass &a, const RenderPass &b) { if (a.priority != b.priority) { return a.priority < b.priority; } - + if (a.hash != b.hash) { return a.hash < b.hash; } - if (math::IsNotEqualF(a.depth, b.depth)) { + if (math::isNotEqualF(a.depth, b.depth)) { return b.depth < a.depth; } @@ -350,7 +350,7 @@ struct CC_DLL UBOSkinning { static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; static gfx::UniformBlock layout; static const ccstd::string NAME; - static void initLayout (uint capacity); + static void initLayout(uint capacity); }; struct CC_DLL UBOMorph { @@ -420,7 +420,7 @@ struct CC_DLL UBOGlobal { static constexpr uint32_t DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET = UBOGlobal::DEBUG_VIEW_MODE_OFFSET + 4; static constexpr uint32_t DEBUG_VIEW_COMPOSITE_PACK_2_OFFSET = UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + 4; static constexpr uint32_t DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET = UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_2_OFFSET + 4; - + static constexpr uint32_t COUNT = UBOGlobal::DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET + 4; static constexpr uint32_t SIZE = UBOGlobal::COUNT * 4; @@ -516,9 +516,9 @@ const uint32_t CAMERA_DEFAULT_MASK = ~static_cast(LayerList::UI_2D) & uint32_t nextPow2(uint32_t val); -bool supportsR16HalfFloatTexture(const gfx::Device* device); +bool supportsR16HalfFloatTexture(const gfx::Device *device); -bool supportsR32FloatTexture(const gfx::Device* device); +bool supportsR32FloatTexture(const gfx::Device *device); extern CC_DLL uint32_t skyboxFlag; diff --git a/native/tests/unit-test/src/utils.h b/native/tests/unit-test/src/utils.h index da80d6c298..b1d988e7ca 100644 --- a/native/tests/unit-test/src/utils.h +++ b/native/tests/unit-test/src/utils.h @@ -30,7 +30,7 @@ THE SOFTWARE. static std::string logLabel; static bool IsEqualF(float l, float r) { - return cc::math::IsEqualF(l, r); + return cc::math::isEqualF(l, r); }; static void ExpectEq(bool lf, bool rt) { EXPECT_EQ(lf, rt) << "ERROR in: " << logLabel; diff --git a/native/utils/generate_compile_commands_android.sh b/native/utils/generate_compile_commands_android.sh index d1ed631e49..7d156c0cc9 100755 --- a/native/utils/generate_compile_commands_android.sh +++ b/native/utils/generate_compile_commands_android.sh @@ -28,6 +28,8 @@ cmake -Sbuild -Bbuild -DCC_USE_GLES2=ON -DCC_USE_VULKAN=ON -DCC_USE_GLES3=ON \ -DCMAKE_TOOLCHAIN_FILE="$ndk_path/build/cmake/android.toolchain.cmake" \ -DANDROID_PLATFORM=android-21 \ -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_C_FLAGS="-mfpu=neon-fp16" \ + -DCMAKE_CXX_FLAGS="-mfpu=neon-fp16" \ -G "$GENERATER" $MAKE_BIN cp build/compile_commands.json . \ No newline at end of file diff --git a/templates/cmake/android.cmake b/templates/cmake/android.cmake index 4eb9ddba77..cbcadf09da 100644 --- a/templates/cmake/android.cmake +++ b/templates/cmake/android.cmake @@ -5,6 +5,12 @@ macro(cc_android_before_target target_name) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsigned-char -ffunction-sections -fdata-sections -fstrict-aliasing") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsigned-char -ffunction-sections -fdata-sections -fstrict-aliasing -frtti -fexceptions") + +if("${ANDROID_ABI}" STREQUAL "armeabi-v7a") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfpu=neon-fp16") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpu=neon-fp16") +endif() + set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fvisibility=default -fno-omit-frame-pointer") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -fvisibility=hidden") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fvisibility=default -fno-omit-frame-pointer") From 1fd70ef5e7fe84893f45d7ddab270fcfa438c385 Mon Sep 17 00:00:00 2001 From: Zhang mingzhen <32831993+Zhmz@users.noreply.github.com> Date: Mon, 18 Jul 2022 15:42:02 +0800 Subject: [PATCH 009/111] UIOpacity and UIRenderer recursion bug (#12015) * optimize JSB sync in every frame * opacity bug, enabled doesn't sync to native * UIOpacity and UIRenderer recursion * avoid parameters are undefined * resolve circular dependency * exclude UIMeshRenderer in setEntityColorDirtyRecursively * exclude UIMeshRenderer in UIOpacity setEntityLocalOpacityDirtyRecursively * blend hash should put into passdirty Co-authored-by: zhangmingzhen --- cocos/2d/components/ui-opacity.ts | 45 +++++++++++++++++++++----- cocos/2d/framework/ui-renderer.ts | 9 +++++- cocos/2d/renderer/render-data.ts | 20 ++++++++++-- cocos/2d/renderer/render-entity.ts | 1 - native/cocos/2d/renderer/Batcher2d.cpp | 6 +++- 5 files changed, 68 insertions(+), 13 deletions(-) diff --git a/cocos/2d/components/ui-opacity.ts b/cocos/2d/components/ui-opacity.ts index 3e1e11f2eb..a02016f1de 100644 --- a/cocos/2d/components/ui-opacity.ts +++ b/cocos/2d/components/ui-opacity.ts @@ -28,6 +28,7 @@ import { JSB } from 'internal:constants'; import { Component } from '../../core/components/component'; import { clampf } from '../../core/utils/misc'; import { UIRenderer } from '../framework/ui-renderer'; +import { Node } from '../../core/scene-graph'; /** * @en @@ -66,16 +67,44 @@ export class UIOpacity extends Component { this._opacity = value; this.node._uiProps.localOpacity = value / 255; - this.setEntityColorDirtyRecursively(true); + this.setEntityLocalOpacityDirtyRecursively(true); } - private setEntityColorDirtyRecursively (dirty: boolean) { + private setEntityLocalOpacityDirtyRecursively (dirty: boolean) { if (JSB) { - const render = this.node._uiProps.uiComp as UIRenderer; - if (render) { - render.setEntityOpacity(this.node._uiProps.localOpacity); + // const render = this.node._uiProps.uiComp as UIRenderer; + // if (render) { + // render.setEntityOpacity(this.node._uiProps.localOpacity); + // } + // UIRenderer.setEntityColorDirtyRecursively(this.node, dirty); + + UIOpacity.setEntityLocalOpacityDirtyRecursively(this.node, dirty, 1); + } + } + + // for UIOpacity + public static setEntityLocalOpacityDirtyRecursively (node: Node, dirty: boolean, interruptParentOpacity: number) { + const render = node._uiProps.uiComp as UIRenderer; + const uiOp = node.getComponent(UIOpacity); + let interruptOpacity = interruptParentOpacity;// if there is no UIOpacity component, it should always equal to 1. + + if (render && render.color) { // exclude UIMeshRenderer which has not color + render.renderEntity.colorDirty = dirty; + render.renderEntity.color = render.color;// necessity to be considering + if (uiOp) { + render.renderEntity.localOpacity = interruptOpacity * uiOp.opacity / 255; + } else { + // there is a just UIRenderer but no UIOpacity on the node, we should just transport the parentOpacity to the node. + render.renderEntity.localOpacity = interruptOpacity; } - UIRenderer.setEntityColorDirtyRecursively(this.node, dirty); + interruptOpacity = 1; + } else if (uiOp) { + // there is a just UIOpacity but no UIRenderer on the node. + interruptOpacity = uiOp.opacity / 255; + } + + for (let i = 0; i < node.children.length; i++) { + UIOpacity.setEntityLocalOpacityDirtyRecursively(node.children[i], dirty || (interruptOpacity < 1), interruptOpacity); } } @@ -84,11 +113,11 @@ export class UIOpacity extends Component { public onEnable () { this.node._uiProps.localOpacity = this._opacity / 255; - this.setEntityColorDirtyRecursively(true); + this.setEntityLocalOpacityDirtyRecursively(true); } public onDisable () { this.node._uiProps.localOpacity = 1; - this.setEntityColorDirtyRecursively(true); + this.setEntityLocalOpacityDirtyRecursively(true); } } diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index 059c48c5a0..989bf99238 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -464,13 +464,14 @@ export class UIRenderer extends Renderer { this._assembler.updateColor(this); // Need update rendFlag when opacity changes from 0 to !0 or 0 to !0 this._renderFlag = this._canRender(); + this.setEntityEnabled(this._renderFlag); } } // for common public static setEntityColorDirtyRecursively (node: Node, dirty: boolean) { const render = node._uiProps.uiComp as UIRenderer; - if (render) { + if (render && render.color) { // exclude UIMeshRenderer which has not color render._renderEntity.colorDirty = dirty; render._renderEntity.color = render.color;// necessity to be considering } @@ -497,6 +498,12 @@ export class UIRenderer extends Renderer { } } + public setEntityEnabled (enabled: boolean) { + if (JSB) { + this._renderEntity.enabled = enabled; + } + } + /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index 1a96a925fe..fb24872feb 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -173,11 +173,12 @@ export class BaseRenderData { if (!this._renderDrawInfo) { this._renderDrawInfo = new RenderDrawInfo(); // for no resize() invoking components - this.setRenderDrawInfoAttributes(); + //this.setRenderDrawInfoAttributes(); renderEntity.addDynamicRenderDrawInfo(this._renderDrawInfo); } } + this.setRenderDrawInfoAttributes(); this.drawInfoType = drawInfoType; } } @@ -479,6 +480,11 @@ export class RenderData extends BaseRenderData { this.blendHash = comp.blendHash; this.passDirty = false; this.hashDirty = true; + + if (this._renderDrawInfo) { + this._renderDrawInfo.setMaterial(this.material); + this._renderDrawInfo.setBlendHash(this.blendHash); + } } if (this.nodeDirty) { const renderScene = comp.node.scene ? comp._getRenderScene() : null; @@ -494,15 +500,25 @@ export class RenderData extends BaseRenderData { this.textureHash = frame.getHash(); this.textureDirty = false; this.hashDirty = true; + + if (this._renderDrawInfo) { + this._renderDrawInfo.setTexture(this.frame ? this.frame.getGFXTexture() : null); + this._renderDrawInfo.setTextureHash(this.textureHash); + this._renderDrawInfo.setSampler(this.frame ? this.frame.getGFXSampler() : null); + } } if (this.hashDirty) { this.updateHash(); + + if (this._renderDrawInfo) { + this._renderDrawInfo.setDataHash(this.dataHash); + } } // Hack Do not update pre frame if (JSB && this.multiOwner === false) { // for sync vData and iData address to native - this.setRenderDrawInfoAttributes(); + //this.setRenderDrawInfoAttributes(); // sync shared buffer to native this.copyRenderDataToSharedBuffer(); } diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index 6bb89e4500..2a2b0871c1 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -1,6 +1,5 @@ import { JSB } from 'internal:constants'; import { NativeRenderEntity } from './native-2d'; -import { UIRenderer } from '../framework/ui-renderer'; import { Batcher2D } from './batcher-2d'; import { RenderData } from './render-data'; import { RenderDrawInfo } from './render-draw-info'; diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index 96dd1bfeab..bfaded6b10 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -111,7 +111,8 @@ void Batcher2d::walk(Node* node, float parentOpacity) { // NOLINT(misc-no-recurs const auto& children = node->getChildren(); for (const auto& child : children) { - float thisOpacity = entity ? entity->getOpacity() : 1; + // we should find parent opacity recursively upwards if it doesn't have an entity. + float thisOpacity = entity ? entity->getOpacity() : parentOpacity; walk(child, thisOpacity); } @@ -207,6 +208,9 @@ CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawI //Mask node _stencilManager->pushMask(); _stencilManager->clear(entity); + + handleColor(entity, drawInfo, parentOpacity); + } else if (isSubMask) { //Mask Comp _stencilManager->enterLevel(entity); From ab733d5644728fd9b7b6837bd11abc8d1711f28b Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 18 Jul 2022 16:39:26 +0800 Subject: [PATCH 010/111] [v3.6.0] Fix some potential memory issues (#12045) * Fix deleting IntrusivePtr _pipeline object in Rot.cpp. * Remove unused code. * Avoid nullptr dereference in SceneCulling.cpp * Fix memory leaks for some objective-c code. * [dragonbones] Avoid extra memory allocation and copy in CCFactory.cpp * [dragonbones] DragonBonesData::binary needed to be 'freed' rather than 'delete'd. * [dragonbones] Fix using delete to release memory allocated by 'new[]' in SlotColorTimelineState. * Remove variable srcOffset & dstOffset in Mesh::merge --- native/cocos/2d/renderer/Batcher2d.h | 1 - native/cocos/2d/renderer/UIMeshBuffer.cpp | 1 - native/cocos/3d/assets/Mesh.cpp | 27 ++++++------------- .../bindings/jswrapper/v8/ScriptEngine.cpp | 3 --- .../bindings/manual/jsb_scene_manual.cpp | 1 - native/cocos/core/Root.cpp | 2 +- .../dragonbones-creator-support/CCFactory.cpp | 15 +++++------ .../dragonbones/animation/TimelineState.h | 6 ++--- .../dragonbones/model/DragonBonesData.cpp | 7 ++--- .../dragonbones/parser/JSONDataParser.cpp | 3 ++- .../cocos/platform/apple/JsbBridgeWrapper.mm | 4 ++- native/cocos/platform/mac/AppDelegate.mm | 3 +++ native/cocos/renderer/gfx-metal/MTLShader.mm | 4 ++- .../cocos/renderer/pipeline/SceneCulling.cpp | 2 +- 14 files changed, 34 insertions(+), 45 deletions(-) diff --git a/native/cocos/2d/renderer/Batcher2d.h b/native/cocos/2d/renderer/Batcher2d.h index bc413ec988..4749b4c0e2 100644 --- a/native/cocos/2d/renderer/Batcher2d.h +++ b/native/cocos/2d/renderer/Batcher2d.h @@ -74,7 +74,6 @@ private: bool _isInit = false; inline void fillIndexBuffers(RenderDrawInfo* drawInfo) { // NOLINT(readability-convert-member-functions-to-static) - uint32_t vertexOffset = drawInfo->getVertexOffset(); uint16_t* ib = drawInfo->getIDataBuffer(); UIMeshBuffer* buffer = drawInfo->getMeshBuffer(); diff --git a/native/cocos/2d/renderer/UIMeshBuffer.cpp b/native/cocos/2d/renderer/UIMeshBuffer.cpp index f5d52d08d5..5c24813f96 100644 --- a/native/cocos/2d/renderer/UIMeshBuffer.cpp +++ b/native/cocos/2d/renderer/UIMeshBuffer.cpp @@ -101,7 +101,6 @@ void UIMeshBuffer::uploadBuffers() { uint32_t indexCount = getIndexOffset(); uint32_t byteCount = getByteOffset(); - uint32_t dataCount = byteCount >> 2; gfx::InputAssembler* ia = _iaPool[0]; gfx::BufferList vBuffers = ia->getVertexBuffers(); diff --git a/native/cocos/3d/assets/Mesh.cpp b/native/cocos/3d/assets/Mesh.cpp index d72015b069..a58865c9dd 100644 --- a/native/cocos/3d/assets/Mesh.cpp +++ b/native/cocos/3d/assets/Mesh.cpp @@ -601,8 +601,6 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid // merge vertex buffer uint32_t vertCount = 0; uint32_t vertStride = 0; - uint32_t srcOffset = 0; - uint32_t dstOffset = 0; uint32_t srcAttrOffset = 0; uint32_t srcVBOffset = 0; @@ -620,18 +618,14 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid const auto &bundle = _struct.vertexBundles[i]; auto &dstBundle = mesh->_struct.vertexBundles[i]; - srcOffset = bundle.view.offset; - dstOffset = dstBundle.view.offset; vertStride = bundle.view.stride; vertCount = bundle.view.count + dstBundle.view.count; auto *vb = ccnew ArrayBuffer(vertCount * vertStride); Uint8Array vbView(vb); - Uint8Array srcVBView = _data.subarray(srcOffset, srcOffset + bundle.view.length); - srcOffset += srcVBView.length(); - Uint8Array dstVBView = mesh->_data.subarray(dstOffset, dstOffset + dstBundle.view.length); - dstOffset += dstVBView.length(); + Uint8Array srcVBView = _data.subarray(bundle.view.offset, bundle.view.offset + bundle.view.length); + Uint8Array dstVBView = mesh->_data.subarray(dstBundle.view.offset, dstBundle.view.offset + dstBundle.view.length); vbView.set(srcVBView); @@ -705,9 +699,6 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid idxCount = prim.indexView.value().count; idxCount += dstPrim.indexView.value().count; - srcOffset = prim.indexView.value().offset; - dstOffset = dstPrim.indexView.value().offset; - if (idxCount < 256) { idxStride = 1; } else if (idxCount < 65536) { @@ -732,11 +723,11 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid // merge src indices if (prim.indexView.value().stride == 2) { - srcIBView = Uint16Array(_data.buffer(), srcOffset, prim.indexView.value().count); + srcIBView = Uint16Array(_data.buffer(), prim.indexView.value().offset, prim.indexView.value().count); } else if (prim.indexView.value().stride == 1) { - srcIBView = Uint8Array(_data.buffer(), srcOffset, prim.indexView.value().count); + srcIBView = Uint8Array(_data.buffer(), prim.indexView.value().offset, prim.indexView.value().count); } else { // Uint32 - srcIBView = Uint32Array(_data.buffer(), srcOffset, prim.indexView.value().count); + srcIBView = Uint32Array(_data.buffer(), prim.indexView.value().offset, prim.indexView.value().count); } // if (idxStride == prim.indexView.value().stride) { @@ -762,16 +753,15 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid } } } - srcOffset += prim.indexView.value().length; // merge dst indices uint32_t indexViewStride = dstPrim.indexView.value().stride; if (indexViewStride == 2) { - dstIBView = Uint16Array(mesh->_data.buffer(), dstOffset, dstPrim.indexView->count); + dstIBView = Uint16Array(mesh->_data.buffer(), dstPrim.indexView.value().offset, dstPrim.indexView->count); } else if (indexViewStride == 1) { - dstIBView = Uint8Array(mesh->_data.buffer(), dstOffset, dstPrim.indexView->count); + dstIBView = Uint8Array(mesh->_data.buffer(), dstPrim.indexView.value().offset, dstPrim.indexView->count); } else { // Uint32 - dstIBView = Uint32Array(mesh->_data.buffer(), dstOffset, dstPrim.indexView->count); + dstIBView = Uint32Array(mesh->_data.buffer(), dstPrim.indexView.value().offset, dstPrim.indexView->count); } for (uint32_t n = 0; n < dstPrim.indexView.value().count; ++n) { if (idxStride == 2) { @@ -785,7 +775,6 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid vertBatchCount + getTypedArrayValue(dstIBView, n); } } - dstOffset += dstPrim.indexView.value().length; IBufferView indexView; indexView.offset = bufferBlob.getLength(); diff --git a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp index 94e24ce32e..494de05183 100644 --- a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp @@ -438,14 +438,11 @@ void ScriptEngine::onPromiseRejectCallback(v8::PromiseRejectMessage msg) { ss << stackStr << std::endl; } //Check event immediately, for certain case throw exception. - const char *eventName; switch (event) { case v8::kPromiseRejectWithNoHandler: - eventName = "unhandledRejectedPromise"; getInstance()->pushPromiseExeception(msg.GetPromise(), "unhandledRejectedPromise", ss.str().c_str()); break; case v8::kPromiseHandlerAddedAfterReject: - eventName = "handlerAddedAfterPromiseRejected"; getInstance()->pushPromiseExeception(msg.GetPromise(), "handlerAddedAfterPromiseRejected", ss.str().c_str()); break; case v8::kPromiseRejectAfterResolved: diff --git a/native/cocos/bindings/manual/jsb_scene_manual.cpp b/native/cocos/bindings/manual/jsb_scene_manual.cpp index 6808cd2a4c..ac9b572c18 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual.cpp @@ -622,7 +622,6 @@ static bool js_Model_setInstancedAttribute(se::State &s) // NOLINT(readability-i SE_PRECONDITION2(cobj, false, "Invalid Native Object"); const auto &args = s.args(); size_t argc = args.size(); - auto *thiz = s.thisObject(); CC_UNUSED bool ok = true; if (argc == 2) { ccstd::string name; diff --git a/native/cocos/core/Root.cpp b/native/cocos/core/Root.cpp index 819b1bffbc..8a726c3ed1 100644 --- a/native/cocos/core/Root.cpp +++ b/native/cocos/core/Root.cpp @@ -221,7 +221,7 @@ bool Root::setRenderPipeline(pipeline::RenderPipeline *rppl /* = nullptr*/) { if (!_pipeline->activate(_mainWindow->getSwapchain())) { if (isCreateDefaultPipeline) { - CC_SAFE_DESTROY_AND_DELETE(_pipeline); + CC_SAFE_DESTROY(_pipeline); } _pipeline = nullptr; diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCFactory.cpp b/native/cocos/editor-support/dragonbones-creator-support/CCFactory.cpp index 71c199f928..f656c7a082 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCFactory.cpp +++ b/native/cocos/editor-support/dragonbones-creator-support/CCFactory.cpp @@ -95,11 +95,9 @@ DragonBonesData *CCFactory::loadDragonBonesData(const std::string &filePath, con } else { cc::Data cocos2dData; cc::FileUtils::getInstance()->getContents(fullpath, &cocos2dData); - const auto binary = (unsigned char *)malloc(sizeof(unsigned char) * cocos2dData.getSize()); - memcpy(binary, cocos2dData.getBytes(), cocos2dData.getSize()); - const auto data = parseDragonBonesData((char *)binary, name, scale); - - return data; + uint8_t *binary = cocos2dData.takeBuffer(); + // NOTE: binary is freed in DragonBonesData::_onClear + return parseDragonBonesData(reinterpret_cast(binary), name, scale); } } @@ -120,10 +118,9 @@ DragonBonesData *CCFactory::parseDragonBonesDataByPath(const std::string &filePa if (cc::FileUtils::getInstance()->isFileExist(filePath)) { cc::Data cocos2dData; cc::FileUtils::getInstance()->getContents(fullpath, &cocos2dData); - const auto binary = (unsigned char *)malloc(sizeof(unsigned char) * cocos2dData.getSize()); - memcpy(binary, cocos2dData.getBytes(), cocos2dData.getSize()); - - return parseDragonBonesData((char *)binary, name, scale); + uint8_t *binary = cocos2dData.takeBuffer(); + // NOTE: binary is freed in DragonBonesData::_onClear + return parseDragonBonesData(reinterpret_cast(binary), name, scale); } } else { return parseDragonBonesData(filePath.c_str(), name, scale); diff --git a/native/cocos/editor-support/dragonbones/animation/TimelineState.h b/native/cocos/editor-support/dragonbones/animation/TimelineState.h index 14213056c5..60f4382892 100644 --- a/native/cocos/editor-support/dragonbones/animation/TimelineState.h +++ b/native/cocos/editor-support/dragonbones/animation/TimelineState.h @@ -128,9 +128,9 @@ public: ~SlotColorTimelineState() { _onClear(); - delete _current; - delete _delta; - delete _result; + delete[] _current; + delete[] _delta; + delete[] _result; } protected: diff --git a/native/cocos/editor-support/dragonbones/model/DragonBonesData.cpp b/native/cocos/editor-support/dragonbones/model/DragonBonesData.cpp index 8be62eb83a..8257331d31 100644 --- a/native/cocos/editor-support/dragonbones/model/DragonBonesData.cpp +++ b/native/cocos/editor-support/dragonbones/model/DragonBonesData.cpp @@ -10,11 +10,13 @@ void DragonBonesData::_onClear() { } if (binary != nullptr) { - delete binary; + free(const_cast(binary)); + binary = nullptr; } if (userData != nullptr) { userData->returnToPool(); + userData = nullptr; } autoSearch = false; @@ -25,14 +27,13 @@ void DragonBonesData::_onClear() { cachedFrames.clear(); armatureNames.clear(); armatures.clear(); - binary = nullptr; + intArray = nullptr; floatArray = nullptr; frameIntArray = nullptr; frameFloatArray = nullptr; frameArray = nullptr; timelineArray = nullptr; - userData = nullptr; } void DragonBonesData::addArmature(ArmatureData* value) { diff --git a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp index 822d6991ac..4a4d0cf702 100644 --- a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp +++ b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp @@ -1598,7 +1598,8 @@ DragonBonesData *JSONDataParser::_parseDragonBonesData(const rapidjson::Value &r const auto l5 = _frameArray.size() * 2; const auto l6 = _timelineArray.size() * 2; - auto binary = new char[l1 + l2 + l3 + l4 + l5 + l6]; + // NOTE: binary is freed in DragonBonesData::_onClear + char* binary = static_cast(malloc((l1 + l2 + l3 + l4 + l5 + l6) * sizeof(char))); auto intArray = (int16_t *)binary; auto floatArray = (float *)(binary + l1); auto frameIntArray = (int16_t *)(binary + l1 + l2); diff --git a/native/cocos/platform/apple/JsbBridgeWrapper.mm b/native/cocos/platform/apple/JsbBridgeWrapper.mm index 9e814d3e30..4d4b8e9135 100644 --- a/native/cocos/platform/apple/JsbBridgeWrapper.mm +++ b/native/cocos/platform/apple/JsbBridgeWrapper.mm @@ -57,7 +57,9 @@ static ICallback cb = ^void(NSString* _event, NSString* _arg) { - (void)addScriptEventListener:(NSString*)eventName listener:(OnScriptEventListener)listener { if (![cbDictionnary objectForKey:eventName]) { - [cbDictionnary setValue:[NSMutableArray new] forKey:eventName]; + NSMutableArray *newArr = [[NSMutableArray alloc] init]; + [cbDictionnary setValue:newArr forKey:eventName]; + [newArr release]; } NSMutableArray* arr = [cbDictionnary objectForKey:eventName]; if (![arr containsObject:listener]) { diff --git a/native/cocos/platform/mac/AppDelegate.mm b/native/cocos/platform/mac/AppDelegate.mm index 1b481e87de..4160ee49e9 100644 --- a/native/cocos/platform/mac/AppDelegate.mm +++ b/native/cocos/platform/mac/AppDelegate.mm @@ -57,6 +57,9 @@ ViewController* viewController = [[ViewController alloc] initWithSize:rect]; _window.contentViewController = viewController; _window.contentView = viewController.view; + [viewController release]; + viewController = nil; + [_window.contentView setWantsBestResolutionOpenGLSurface:YES]; [_window makeKeyAndOrderFront:nil]; [[NSNotificationCenter defaultCenter] addObserver:self diff --git a/native/cocos/renderer/gfx-metal/MTLShader.mm b/native/cocos/renderer/gfx-metal/MTLShader.mm index 6a85807821..33ae651d70 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.mm +++ b/native/cocos/renderer/gfx-metal/MTLShader.mm @@ -149,7 +149,6 @@ bool CCMTLShader::createMTLFunction(const ShaderStage& stage) { size_t unitSize = sizeof(std::remove_pointer::type); ccstd::string mtlShaderSrc = mu::spirv2MSL(spirv->getOutputData(), spirv->getOutputSize() / unitSize, stage.stage, _gpuShader); - NSString* rawSrc = [NSString stringWithUTF8String:stage.source.c_str()]; NSString* shader = [NSString stringWithUTF8String:mtlShaderSrc.c_str()]; NSError* error = nil; MTLCompileOptions* opts = [[MTLCompileOptions alloc] init]; @@ -163,12 +162,14 @@ bool CCMTLShader::createMTLFunction(const ShaderStage& stage) { if (!library) { CC_LOG_ERROR("Can not compile %s shader: %s", shaderStage.c_str(), [[error localizedDescription] UTF8String]); CC_LOG_ERROR("%s", stage.source.c_str()); + [opts release]; return false; } } else { //delayed instance and pretend tobe specialized function. _gpuShader->specializeColor = false; _gpuShader->shaderSrc = [shader retain]; + [opts release]; CC_ASSERT(_gpuShader->shaderSrc != nil); return true; } @@ -177,6 +178,7 @@ bool CCMTLShader::createMTLFunction(const ShaderStage& stage) { if (!library) { CC_LOG_ERROR("Can not compile %s shader: %s", shaderStage.c_str(), [[error localizedDescription] UTF8String]); CC_LOG_ERROR("%s", stage.source.c_str()); + [opts release]; return false; } } diff --git a/native/cocos/renderer/pipeline/SceneCulling.cpp b/native/cocos/renderer/pipeline/SceneCulling.cpp index e2b0c54989..31aae24490 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.cpp +++ b/native/cocos/renderer/pipeline/SceneCulling.cpp @@ -272,7 +272,7 @@ void sceneCulling(const RenderPipeline* pipeline, scene::Camera* camera) { (visibility & static_cast(model->getVisFlags()))) { const auto *modelWorldBounds = model->getWorldBounds(); - if (!modelWorldBounds && skyBox->getModel() != model) { + if (!modelWorldBounds && (skyBox == nullptr || skyBox->getModel() != model)) { sceneData->addRenderObject(genRenderObject(model, camera)); } } From b72ba1db7ea261ac2fac90b1868fa0d861d173d8 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Tue, 19 Jul 2022 08:55:26 +0800 Subject: [PATCH 011/111] fix the calculation of projection of shadow, should consider clipSpaceSignY (#12036) --- cocos/core/pipeline/pipeline-ubo.ts | 5 ++++- cocos/core/pipeline/render-additive-light-queue.ts | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/cocos/core/pipeline/pipeline-ubo.ts b/cocos/core/pipeline/pipeline-ubo.ts index a36e2856b1..45e8a117e5 100644 --- a/cocos/core/pipeline/pipeline-ubo.ts +++ b/cocos/core/pipeline/pipeline-ubo.ts @@ -294,6 +294,8 @@ export class PipelineUBO { const csmLayers = sceneData.csmLayers; const sv = shadowBufferView; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; + const cap = pipeline.device.capabilities; + switch (light.type) { case LightType.DIRECTIONAL: { const mainLight = light as DirectionalLight; @@ -363,7 +365,8 @@ export class PipelineUBO { Mat4.invert(_matShadowView, (light as any).node.getWorldMatrix()); Mat4.toArray(sv, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - Mat4.perspective(_matShadowProj, (light as any).angle, 1.0, 0.001, (light as any).range); + Mat4.perspective(_matShadowProj, (light as any).angle, 1.0, 0.001, (light as any).range, + true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0); Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); Mat4.toArray(sv, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); diff --git a/cocos/core/pipeline/render-additive-light-queue.ts b/cocos/core/pipeline/render-additive-light-queue.ts index 1416d82419..f169c54790 100644 --- a/cocos/core/pipeline/render-additive-light-queue.ts +++ b/cocos/core/pipeline/render-additive-light-queue.ts @@ -333,6 +333,7 @@ export class RenderAdditiveLightQueue { const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; const globalDSManager: GlobalDSManager = this._pipeline.globalDSManager; const validPunctualLights = sceneData.validPunctualLights; + const cap = this._pipeline.device.capabilities; for (let i = 0; i < validPunctualLights.length; i++) { const light = validPunctualLights[i]; @@ -375,7 +376,8 @@ export class RenderAdditiveLightQueue { Mat4.invert(_matShadowView, (light as SpotLight).node!.getWorldMatrix()); // light proj - Mat4.perspective(_matShadowViewProj, (light as SpotLight).angle, 1.0, 0.001, (light as SpotLight).range); + Mat4.perspective(_matShadowViewProj, (light as SpotLight).angle, 1.0, 0.001, (light as SpotLight).range, + true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0); matShadowProj = _matShadowViewProj.clone(); matShadowInvProj = _matShadowViewProj.clone().invert(); From 51d999e0e62cb40117f5b0b648831945d1990326 Mon Sep 17 00:00:00 2001 From: zhakesi Date: Tue, 19 Jul 2022 10:53:42 +0800 Subject: [PATCH 012/111] native batcher2d tiled-map addUserNode complete (#12059) --- cocos/2d/renderer/native-2d.ts | 3 ++ cocos/2d/renderer/render-draw-info.ts | 11 +++++ cocos/2d/renderer/render-entity.ts | 1 + cocos/tiledmap/assembler/simple.ts | 2 +- cocos/tiledmap/tiled-layer.ts | 51 ++++++++++++++++----- native/cocos/2d/renderer/Batcher2d.cpp | 27 ++++++++--- native/cocos/2d/renderer/RenderDrawInfo.cpp | 4 ++ native/cocos/2d/renderer/RenderDrawInfo.h | 3 ++ native/cocos/2d/renderer/RenderEntity.h | 3 +- native/tools/tojs/2d.ini | 2 +- 10 files changed, 85 insertions(+), 22 deletions(-) diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index 517cdd252a..177ea728c3 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -66,6 +66,9 @@ export declare class NativeRenderDrawInfo { get drawInfoType(): number; set drawInfoType(drawInfoType: number); + get subNode(): Node; + set subNode(node: Node); + setRender2dBufferToNative(data: TypedArray, stride: number, size: number); syncSharedBufferToNative(data: TypedArray); } diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts index 95dc606c90..8cbc487086 100644 --- a/cocos/2d/renderer/render-draw-info.ts +++ b/cocos/2d/renderer/render-draw-info.ts @@ -42,6 +42,8 @@ export class RenderDrawInfo { protected _drawInfoType :RenderDrawInfoType = RenderDrawInfoType.COMP; + protected _subNode: Node | null = null; + protected declare _nativeObj: NativeRenderDrawInfo; // SharedBuffer of pos/uv/color @@ -234,6 +236,15 @@ export class RenderDrawInfo { this._drawInfoType = drawInfoType; } + public setSubNode (node : Node) { + if (JSB) { + if (this._subNode !== node) { + this._nativeObj.subNode = node; + } + } + this._subNode = node; + } + public initRender2dBuffer (vertexCount: number, stride: number) { if (JSB) { this._stride = stride; diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index 2a2b0871c1..fb14e3d7d2 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -10,6 +10,7 @@ import { Stage } from './stencil-manager'; export enum RenderEntityType { STATIC, DYNAMIC, + CROSSED, } export enum RenderEntityFloatSharedBufferView { diff --git a/cocos/tiledmap/assembler/simple.ts b/cocos/tiledmap/assembler/simple.ts index 05ae0ad5f3..94f97473cd 100644 --- a/cocos/tiledmap/assembler/simple.ts +++ b/cocos/tiledmap/assembler/simple.ts @@ -408,7 +408,7 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: const nodes = comp.requestSubNodesData(); const celData = comp.getNodesByRowCol(row, col); if (celData && celData.count > 0) { - (nodes as any).subNodes = comp.getNodesByRowCol(row, col)!.list as any; + (nodes as any).subNodes = celData.list as any; } } diff --git a/cocos/tiledmap/tiled-layer.ts b/cocos/tiledmap/tiled-layer.ts index df74c36afa..22a1717af0 100644 --- a/cocos/tiledmap/tiled-layer.ts +++ b/cocos/tiledmap/tiled-layer.ts @@ -226,7 +226,6 @@ export class TiledLayer extends UIRenderer { dataComp = node.addComponent(TiledUserNodeData); node.parent = this.node; - // node._renderFlag |= RenderFlow.FLAG_BREAK_FLOW; this._userNodeMap[node.uuid] = dataComp; dataComp._row = -1; @@ -1380,12 +1379,28 @@ export class TiledLayer extends UIRenderer { } public requestTiledRenderData () { + const arr = this._tiledDataArray as any[]; + while (arr.length > 0 && arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) { + arr.pop(); + } + if (arr.length > 0) { + const last = arr[arr.length - 1]; + if (last.renderData && last.renderData.vertexCount === 0) { + return last as TiledRenderData; + } + } const comb = { renderData: null, texture: null }; this._tiledDataArray.push(comb); return (comb as TiledRenderData); } public requestSubNodesData () { + const arr = this._tiledDataArray as any[]; + if (arr.length > 0) { + if (arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) { + return arr[arr.length - 1] as TiledSubNodeData; + } + } const renderData: (TiledUserNodeData | null)[] = []; const comb = { subNodes: renderData }; this._tiledDataArray.push(comb); @@ -1442,7 +1457,7 @@ export class TiledLayer extends UIRenderer { } protected createRenderEntity () { - return new RenderEntity(RenderEntityType.DYNAMIC); + return new RenderEntity(RenderEntityType.CROSSED); } private fillIndicesBuffer (renderData: RenderData, drawInfo: RenderDrawInfo) { @@ -1469,19 +1484,30 @@ export class TiledLayer extends UIRenderer { public prepareDrawData () { const entity = this.renderEntity; entity.clearDynamicRenderDrawInfos(); - for (let i = 0; i < this._tiledDataArray.length; i++) { - this._tiledDataArrayIdx = i; - const m = this._tiledDataArray[i]; - //const batch2d = director.root!.batcher2D; + const tiledDataArray = this._tiledDataArray; + let idx = 0; + tiledDataArray.forEach((m) => { if ((m as TiledSubNodeData).subNodes) { // 提前处理 User Nodes - // (m as TiledSubNodeData).subNodes.forEach((c) => { - // if (c) batch2d.walk(c.node); - // }); + (m as TiledSubNodeData).subNodes.forEach((c) => { + if (c) { + if (!this._drawInfoList[idx]) { + this._drawInfoList[idx] = new RenderDrawInfo(); + } + const drawInfo = this._drawInfoList[idx]; + drawInfo.setSubNode(c.node); + entity.setDynamicRenderDrawInfo(drawInfo, idx); + idx++; + } + }); } else { const td = m as TiledRenderData; if (td.texture) { - const drawInfo = this.requestDrawInfo(i); + if (!this._drawInfoList[idx]) { + this._drawInfoList[idx] = new RenderDrawInfo(); + this._drawInfoList[idx].setDrawInfoType(RenderDrawInfoType.IA); + } + const drawInfo = this._drawInfoList[idx]; td.renderData!.fillDrawInfoAttributes(drawInfo); drawInfo.setTexture(td.texture.getGFXTexture()); drawInfo.setTextureHash(td.texture.getHash()); @@ -1489,9 +1515,10 @@ export class TiledLayer extends UIRenderer { drawInfo.setBlendHash(this.blendHash); drawInfo.setMaterial(this.getRenderMaterial(0)!); this.fillIndicesBuffer(td.renderData!, drawInfo); - entity.setDynamicRenderDrawInfo(drawInfo, i); + entity.setDynamicRenderDrawInfo(drawInfo, idx); + idx++; } } - } + }); } } diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index bfaded6b10..1e20fd495c 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -90,7 +90,7 @@ void Batcher2d::walk(Node* node, float parentOpacity) { // NOLINT(misc-no-recurs if (!node->isActiveInHierarchy()) { return; } - + bool breakWalk = false; auto* entity = static_cast(node->getUserData()); if (entity && entity->isEnabled()) { RenderEntityType entityType = entity->getRenderEntityType(); @@ -106,14 +106,27 @@ void Batcher2d::walk(Node* node, float parentOpacity) { // NOLINT(misc-no-recurs for (auto* drawInfo : drawInfos) { handleDrawInfo(entity, drawInfo, node, parentOpacity); } + } else if (entityType == RenderEntityType::CROSSED) { + //for tiledmap + ccstd::vector& drawInfos = entity->getDynamicRenderDrawInfos(); + for (auto* drawInfo : drawInfos) { + if (drawInfo->getSubNode()) { + walk(drawInfo->getSubNode(), entity->getOpacity()); + } else { + handleDrawInfo(entity, drawInfo, node, parentOpacity); + } + + } + breakWalk = true; } } - - const auto& children = node->getChildren(); - for (const auto& child : children) { - // we should find parent opacity recursively upwards if it doesn't have an entity. - float thisOpacity = entity ? entity->getOpacity() : parentOpacity; - walk(child, thisOpacity); + if (!breakWalk) { + const auto& children = node->getChildren(); + for (const auto& child : children) { + // we should find parent opacity recursively upwards if it doesn't have an entity. + float thisOpacity = entity ? entity->getOpacity() : parentOpacity; + walk(child, thisOpacity); + } } // post assembler diff --git a/native/cocos/2d/renderer/RenderDrawInfo.cpp b/native/cocos/2d/renderer/RenderDrawInfo.cpp index 4bc9a773c5..c76bc25847 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.cpp +++ b/native/cocos/2d/renderer/RenderDrawInfo.cpp @@ -125,6 +125,10 @@ void RenderDrawInfo::setDrawInfoType(uint32_t type) { _drawInfoType = static_cast(type); } +void RenderDrawInfo::setSubNode(Node *node) { + _subNode = node; +} + void RenderDrawInfo::setRender2dBufferToNative(uint8_t* buffer, uint8_t stride, uint32_t size) { // NOLINT(bugprone-easily-swappable-parameters) _stride = stride; _size = size; diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index af56a32276..d614930f8d 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -103,6 +103,8 @@ public: void setModel(scene::Model* model); inline uint32_t getDrawInfoType() const { return static_cast(_drawInfoType); } void setDrawInfoType(uint32_t type); + inline Node* getSubNode() const { return _subNode; } + void setSubNode(Node *node); inline RenderDrawInfoType getEnumDrawInfoType() const { return _drawInfoType; } @@ -165,6 +167,7 @@ private: uint32_t _textureHash{0}; // weak reference gfx::Sampler* _sampler{nullptr}; + Node* _subNode{nullptr}; uint32_t _blendHash{0}; diff --git a/native/cocos/2d/renderer/RenderEntity.h b/native/cocos/2d/renderer/RenderEntity.h index bb2ff6ac3b..a7ecc0b62f 100644 --- a/native/cocos/2d/renderer/RenderEntity.h +++ b/native/cocos/2d/renderer/RenderEntity.h @@ -38,7 +38,8 @@ class Batcher2d; enum class RenderEntityType: uint8_t { STATIC, - DYNAMIC + DYNAMIC, + CROSSED, }; struct EntityAttrLayout { diff --git a/native/tools/tojs/2d.ini b/native/tools/tojs/2d.ini index 2dbdbef3fa..fa3952ccde 100644 --- a/native/tools/tojs/2d.ini +++ b/native/tools/tojs/2d.ini @@ -53,7 +53,7 @@ skip = RenderDrawInfo::[getBatcher setBatcher parseAttrLayout getRender2dLayout rename_functions = -getter_setter = RenderDrawInfo::[bufferId accId vertexOffset indexOffset vbBuffer ibBuffer vDataBuffer iDataBuffer vbCount ibCount vertDirty dataHash isMeshBuffer material texture textureHash sampler blendHash model drawInfoType], +getter_setter = RenderDrawInfo::[bufferId accId vertexOffset indexOffset vbBuffer ibBuffer vDataBuffer iDataBuffer vbCount ibCount vertDirty dataHash isMeshBuffer material texture textureHash sampler blendHash model drawInfoType subNode], UIMeshBuffer::[vData iData], RenderEntity::[node staticDrawInfoSize stencilStage isMask isSubMask isMaskInverted] From b6e1fe4d6a9f09741c608d0cc545a74f4bef8609 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Tue, 19 Jul 2022 11:13:37 +0800 Subject: [PATCH 013/111] Slim Render Draw Info (#12053) * Slim Render Draw Info * fix CI * safe delete Co-authored-by: ChiaNing --- native/cocos/2d/renderer/Batcher2d.cpp | 1 + native/cocos/2d/renderer/Batcher2d.h | 8 +++++ native/cocos/2d/renderer/RenderDrawInfo.cpp | 35 +++++++++++---------- native/cocos/2d/renderer/RenderDrawInfo.h | 16 +++------- 4 files changed, 33 insertions(+), 27 deletions(-) diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index 1e20fd495c..d37e960c1f 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -54,6 +54,7 @@ Batcher2d::~Batcher2d() { // NOLINT for (auto* drawBatch : _batches) { delete drawBatch; } + _attributes.clear(); } void Batcher2d::syncMeshBuffersToNative(uint32_t accId, ccstd::vector&& buffers) { diff --git a/native/cocos/2d/renderer/Batcher2d.h b/native/cocos/2d/renderer/Batcher2d.h index 4749b4c0e2..3047f2f2fd 100644 --- a/native/cocos/2d/renderer/Batcher2d.h +++ b/native/cocos/2d/renderer/Batcher2d.h @@ -59,6 +59,7 @@ public: UIMeshBuffer* getMeshBuffer(uint32_t accId, uint32_t bufferId); gfx::Device* getDevice(); + inline ccstd::vector* getDefaultAttribute() { return &_attributes; } void updateDescriptorSet(); @@ -175,6 +176,13 @@ private: UIMeshBufferMap _meshBuffersMap; + // DefaultAttribute + ccstd::vector _attributes{ + gfx::Attribute{gfx::ATTR_NAME_POSITION, gfx::Format::RGB32F}, + gfx::Attribute{gfx::ATTR_NAME_TEX_COORD, gfx::Format::RG32F}, + gfx::Attribute{gfx::ATTR_NAME_COLOR, gfx::Format::RGBA32F}, + }; + CC_DISALLOW_COPY_MOVE_ASSIGN(Batcher2d); }; } // namespace cc diff --git a/native/cocos/2d/renderer/RenderDrawInfo.cpp b/native/cocos/2d/renderer/RenderDrawInfo.cpp index c76bc25847..1f844d655d 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.cpp +++ b/native/cocos/2d/renderer/RenderDrawInfo.cpp @@ -147,12 +147,12 @@ gfx::InputAssembler* RenderDrawInfo::requestIA(gfx::Device* device) { void RenderDrawInfo::uploadBuffers() { if (_vbCount == 0 || _ibCount == 0) return; - auto size = _vbCount * _vertexFormatBytes; + uint32_t size = _vbCount * 9 * sizeof(float);// magic Number gfx::Buffer* vBuffer = _vbGFXBuffer; vBuffer->resize(size); vBuffer->update(_vDataBuffer); gfx::Buffer* iBuffer = _ibGFXBuffer; - auto iSize = _ibCount * 2; + uint32_t iSize = _ibCount * 2; iBuffer->resize(iSize); iBuffer->update(_iDataBuffer); } @@ -163,14 +163,16 @@ void RenderDrawInfo::resetMeshIA() { void RenderDrawInfo::destroy() { _nextFreeIAHandle = 0; - _attributes.clear(); //TODO(): Should use _iaPool to delete vb, ib. - delete _iaInfo.indexBuffer; - if (!_iaInfo.vertexBuffers.empty()) { - // only one vb - delete _iaInfo.vertexBuffers[0]; - _iaInfo.vertexBuffers.clear(); + if (_iaInfo != nullptr) { + CC_SAFE_DELETE(_iaInfo->indexBuffer); + if (!_iaInfo->vertexBuffers.empty()) { + // only one vb + CC_SAFE_DELETE(_iaInfo->vertexBuffers[0]); + _iaInfo->vertexBuffers.clear(); + } + CC_SAFE_DELETE(_iaInfo); } for (auto* ia : _iaPool) { @@ -178,24 +180,25 @@ void RenderDrawInfo::destroy() { // delete ia->getIndexBuffer(); // // only one vertex buffer // delete ia->getVertexBuffers()[0]; - delete ia; + CC_SAFE_DELETE(ia); } _iaPool.clear(); } gfx::InputAssembler* RenderDrawInfo::initIAInfo(gfx::Device* device) { if (_iaPool.empty()) { - uint32_t vbStride = _vertexFormatBytes; // hack + _iaInfo = new gfx::InputAssemblerInfo(); + uint32_t vbStride = 9 * sizeof(float);// magic Number uint32_t ibStride = sizeof(uint16_t); auto* vertexBuffer = device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, - gfx::MemoryUsageBit::DEVICE, + gfx::MemoryUsageBit::DEVICE | gfx::MemoryUsageBit::HOST, vbStride * 3, vbStride, }); auto* indexBuffer = device->createBuffer({ gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, - gfx::MemoryUsageBit::DEVICE, + gfx::MemoryUsageBit::DEVICE | gfx::MemoryUsageBit::HOST, ibStride * 3, ibStride, }); @@ -203,11 +206,11 @@ gfx::InputAssembler* RenderDrawInfo::initIAInfo(gfx::Device* device) { _vbGFXBuffer = vertexBuffer; _ibGFXBuffer = indexBuffer; - _iaInfo.attributes = _attributes; - _iaInfo.vertexBuffers.emplace_back(vertexBuffer); - _iaInfo.indexBuffer = indexBuffer; + _iaInfo->attributes = *(Root::getInstance()->getBatcher2D()->getDefaultAttribute()); + _iaInfo->vertexBuffers.emplace_back(vertexBuffer); + _iaInfo->indexBuffer = indexBuffer; } - auto* ia = device->createInputAssembler(_iaInfo); + auto* ia = device->createInputAssembler(*_iaInfo); _iaPool.emplace_back(ia); return ia; diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index d614930f8d..833465532b 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -171,21 +171,15 @@ private: uint32_t _blendHash{0}; - gfx::InputAssemblerInfo _iaInfo; - ccstd::vector _attributes{ - gfx::Attribute{gfx::ATTR_NAME_POSITION, gfx::Format::RGB32F}, - gfx::Attribute{gfx::ATTR_NAME_TEX_COORD, gfx::Format::RG32F}, - gfx::Attribute{gfx::ATTR_NAME_COLOR, gfx::Format::RGBA32F}, - }; - uint32_t _vertexFormatBytes = 9 * sizeof(float); // Affected by _attributes // magic Number - - //TODO(): it is not a good way to cache IA here. - // manage memory manually - ccstd::vector _iaPool; uint32_t _nextFreeIAHandle{0}; // weak reference gfx::Buffer* _vbGFXBuffer{nullptr}; // weak reference gfx::Buffer* _ibGFXBuffer{nullptr}; + + gfx::InputAssemblerInfo* _iaInfo{nullptr}; + //TODO(): it is not a good way to cache IA here. + // manage memory manually + ccstd::vector _iaPool; }; } // namespace cc From ddfa13e4cff0586dda07a33952e7875607dc3ce9 Mon Sep 17 00:00:00 2001 From: Santy-Wang Date: Tue, 19 Jul 2022 11:36:25 +0800 Subject: [PATCH 014/111] optimize a bit jsb call (#12065) --- cocos/2d/components/sprite.ts | 4 ++-- cocos/2d/components/ui-mesh-renderer.ts | 6 ++++-- cocos/2d/framework/ui-renderer.ts | 12 ++++++++---- cocos/2d/utils/dynamic-atlas/atlas-manager.ts | 2 +- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/cocos/2d/components/sprite.ts b/cocos/2d/components/sprite.ts index 3ed18783e3..50924edf6e 100644 --- a/cocos/2d/components/sprite.ts +++ b/cocos/2d/components/sprite.ts @@ -25,7 +25,7 @@ */ import { ccclass, help, executionOrder, menu, tooltip, displayOrder, type, range, editable, serializable, visible } from 'cc.decorator'; -import { EDITOR } from 'internal:constants'; +import { BUILD, EDITOR } from 'internal:constants'; import { SpriteAtlas } from '../assets/sprite-atlas'; import { SpriteFrame } from '../assets/sprite-frame'; import { Vec2 } from '../../core/math'; @@ -616,7 +616,7 @@ export class Sprite extends UIRenderer { private _applySpriteSize () { if (this._spriteFrame) { - if (!this._spriteFrame.isDefault) { + if (BUILD || !this._spriteFrame.isDefault) { if (SizeMode.RAW === this._sizeMode) { const size = this._spriteFrame.originalSize; this.node._uiProps.uiTransformComp!.setContentSize(size); diff --git a/cocos/2d/components/ui-mesh-renderer.ts b/cocos/2d/components/ui-mesh-renderer.ts index ca585daa8b..3bb3df2990 100644 --- a/cocos/2d/components/ui-mesh-renderer.ts +++ b/cocos/2d/components/ui-mesh-renderer.ts @@ -25,7 +25,7 @@ */ import { ccclass, help, executionOrder, menu, executeInEditMode } from 'cc.decorator'; -import { JSB } from 'internal:constants'; +import { DEBUG, JSB } from 'internal:constants'; import { ModelRenderer } from '../../core/components/model-renderer'; import { RenderPriority } from '../../core/pipeline/define'; import { IBatcher } from '../renderer/i-batcher'; @@ -241,7 +241,9 @@ export class UIMeshRenderer extends Component { } get renderEntity () { - assert(this._renderEntity); + if (DEBUG) { + assert(this._renderEntity, 'this._renderEntity should not be invalid'); + } return this._renderEntity; } diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index 989bf99238..74ed58e0de 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ -import { EDITOR, JSB } from 'internal:constants'; +import { DEBUG, EDITOR, JSB } from 'internal:constants'; import { ccclass, executeInEditMode, requireComponent, disallowMultiple, tooltip, type, displayOrder, serializable, override, visible, displayName, disallowAnimation, @@ -285,7 +285,9 @@ export class UIRenderer extends Renderer { } get renderEntity () { - assert(this._renderEntity); + if (DEBUG) { + assert(this._renderEntity, 'this._renderEntity should not be invalid'); + } return this._renderEntity; } @@ -434,8 +436,10 @@ export class UIRenderer extends Renderer { protected _postRender (render: IBatcher) { } protected _canRender () { - return this.isValid - && this.getMaterial(0) !== null + if (DEBUG) { + assert(this.isValid, 'this component should not be invalid!'); + } + return this.getMaterial(0) !== null && this.enabled && (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy) && this._color.a > 0; diff --git a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts index 3c84eb9010..1a8d60d23c 100644 --- a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts +++ b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts @@ -240,7 +240,7 @@ export class DynamicAtlasManager extends System { * @param frame the sprite frame that will be packed in the dynamic atlas. */ public packToDynamicAtlas (comp, frame) { - if (EDITOR && !legacyCC.GAME_VIEW) return; + if ((EDITOR && !legacyCC.GAME_VIEW) || !this._enabled) return; if (frame && !frame._original && frame.packable && frame.texture && frame.texture.width > 0 && frame.texture.height > 0) { const packedFrame = this.insertSpriteFrame(frame); From b6e14e8b354891e6f0766e486aa694a32cb12d7b Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Tue, 19 Jul 2022 11:40:28 +0800 Subject: [PATCH 015/111] [ci skip][AUTO]: Automated code generating update: 2c279f69cdc821e2d096b4f5d5d3e3173d4c975d (#12053) (#12064) Co-authored-by: cocos-robot --- native/cocos/bindings/auto/jsb_2d_auto.cpp | 62 ++++++++++++++++++++++ native/cocos/bindings/auto/jsb_2d_auto.h | 1 + 2 files changed, 63 insertions(+) diff --git a/native/cocos/bindings/auto/jsb_2d_auto.cpp b/native/cocos/bindings/auto/jsb_2d_auto.cpp index 0dfbbb02c6..44ec354345 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.cpp +++ b/native/cocos/bindings/auto/jsb_2d_auto.cpp @@ -527,6 +527,26 @@ static bool js_2d_RenderDrawInfo_getSampler(se::State& s) // NOLINT(readability- } SE_BIND_FUNC_AS_PROP_GET(js_2d_RenderDrawInfo_getSampler) +static bool js_2d_RenderDrawInfo_getSubNode(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::Node* result = cobj->getSubNode(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC_AS_PROP_GET(js_2d_RenderDrawInfo_getSubNode) + static bool js_2d_RenderDrawInfo_getTexture(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -990,6 +1010,26 @@ static bool js_2d_RenderDrawInfo_setSampler(se::State& s) // NOLINT(readability- } SE_BIND_FUNC_AS_PROP_SET(js_2d_RenderDrawInfo_setSampler) +static bool js_2d_RenderDrawInfo_setSubNode(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setSubNode(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC_AS_PROP_SET(js_2d_RenderDrawInfo_setSubNode) + static bool js_2d_RenderDrawInfo_setTexture(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -1214,6 +1254,7 @@ bool js_register_2d_RenderDrawInfo(se::Object* obj) // NOLINT(readability-identi cls->defineProperty("blendHash", _SE(js_2d_RenderDrawInfo_getBlendHash_asGetter), _SE(js_2d_RenderDrawInfo_setBlendHash_asSetter)); cls->defineProperty("model", _SE(js_2d_RenderDrawInfo_getModel_asGetter), _SE(js_2d_RenderDrawInfo_setModel_asSetter)); cls->defineProperty("drawInfoType", _SE(js_2d_RenderDrawInfo_getDrawInfoType_asGetter), _SE(js_2d_RenderDrawInfo_setDrawInfoType_asSetter)); + cls->defineProperty("subNode", _SE(js_2d_RenderDrawInfo_getSubNode_asGetter), _SE(js_2d_RenderDrawInfo_setSubNode_asSetter)); cls->defineFunction("getMeshBuffer", _SE(js_2d_RenderDrawInfo_getMeshBuffer)); cls->defineFunction("requestIA", _SE(js_2d_RenderDrawInfo_requestIA)); cls->defineFunction("resetMeshIA", _SE(js_2d_RenderDrawInfo_resetMeshIA)); @@ -1765,6 +1806,26 @@ bool js_register_2d_RenderEntity(se::Object* obj) // NOLINT(readability-identifi se::Object* __jsb_cc_Batcher2d_proto = nullptr; // NOLINT se::Class* __jsb_cc_Batcher2d_class = nullptr; // NOLINT +static bool js_2d_Batcher2d_getDefaultAttribute(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + std::vector* result = cobj->getDefaultAttribute(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_2d_Batcher2d_getDefaultAttribute) + static bool js_2d_Batcher2d_handleColor(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -1983,6 +2044,7 @@ bool js_register_2d_Batcher2d(se::Object* obj) // NOLINT(readability-identifier- #if CC_DEBUG cls->defineStaticProperty("isJSBClass", _SE(js_2d_getter_return_true), nullptr); #endif + cls->defineFunction("getDefaultAttribute", _SE(js_2d_Batcher2d_getDefaultAttribute)); cls->defineFunction("handleColor", _SE(js_2d_Batcher2d_handleColor)); cls->defineFunction("handlePostRender", _SE(js_2d_Batcher2d_handlePostRender)); cls->defineFunction("initialize", _SE(js_2d_Batcher2d_initialize)); diff --git a/native/cocos/bindings/auto/jsb_2d_auto.h b/native/cocos/bindings/auto/jsb_2d_auto.h index 6b290c65ab..f54e4f5d07 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.h +++ b/native/cocos/bindings/auto/jsb_2d_auto.h @@ -68,6 +68,7 @@ extern se::Class * __jsb_cc_Batcher2d_class; // NOLINT bool js_register_cc_Batcher2d(se::Object *obj); // NOLINT +SE_DECLARE_FUNC(js_2d_Batcher2d_getDefaultAttribute); SE_DECLARE_FUNC(js_2d_Batcher2d_handleColor); SE_DECLARE_FUNC(js_2d_Batcher2d_handlePostRender); SE_DECLARE_FUNC(js_2d_Batcher2d_initialize); From 12625f09d8fff7875f2ae44bd9752057b90ddd49 Mon Sep 17 00:00:00 2001 From: Zhang mingzhen <32831993+Zhmz@users.noreply.github.com> Date: Tue, 19 Jul 2022 13:35:54 +0800 Subject: [PATCH 016/111] RenderDrawInfo code sorting (#12055) * remove blendHash and DrawInfoAttrLayout * remove code in cpp * remove blend hash in ts * remove blendhash of middleware in ts * remove rebundant code * remove stencilStage in drawinfo Co-authored-by: zhangmingzhen --- cocos/2d/renderer/native-2d.ts | 3 -- cocos/2d/renderer/render-data.ts | 5 --- cocos/2d/renderer/render-draw-info.ts | 11 +---- cocos/tiledmap/tiled-layer.ts | 1 - native/cocos/2d/renderer/RenderDrawInfo.cpp | 4 -- native/cocos/2d/renderer/RenderDrawInfo.h | 9 ---- native/cocos/bindings/auto/jsb_2d_auto.cpp | 41 ------------------- native/tools/tojs/2d.ini | 2 +- platforms/native/engine/jsb-dragonbones.js | 1 - platforms/native/engine/jsb-spine-skeleton.js | 1 - 10 files changed, 2 insertions(+), 76 deletions(-) diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index 177ea728c3..8d76283afc 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -57,9 +57,6 @@ export declare class NativeRenderDrawInfo { get sampler(): Sampler | null; set sampler(sampler: Sampler | null); - get blendHash(): number; - set blendHash(blendHash: number); - get model(): Model | null; set model(model: Model | null); diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index fb24872feb..c9344004fc 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -302,9 +302,6 @@ export class RenderData extends BaseRenderData { } set blendHash (val: number) { this._blendHash = val; - if (this._renderDrawInfo) { - this._renderDrawInfo.setBlendHash(val); - } } public indices: Uint16Array | null = null; @@ -387,7 +384,6 @@ export class RenderData extends BaseRenderData { this._renderDrawInfo.setTexture(this.frame ? this.frame.getGFXTexture() : null); this._renderDrawInfo.setTextureHash(this.textureHash); this._renderDrawInfo.setSampler(this.frame ? this.frame.getGFXSampler() : null); - this._renderDrawInfo.setBlendHash(this.blendHash); } } @@ -483,7 +479,6 @@ export class RenderData extends BaseRenderData { if (this._renderDrawInfo) { this._renderDrawInfo.setMaterial(this.material); - this._renderDrawInfo.setBlendHash(this.blendHash); } } if (this.nodeDirty) { diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts index 8cbc487086..343c466f18 100644 --- a/cocos/2d/renderer/render-draw-info.ts +++ b/cocos/2d/renderer/render-draw-info.ts @@ -36,7 +36,7 @@ export class RenderDrawInfo { protected _texture: Texture | null = null; protected _textureHash: number | undefined; protected _sampler: Sampler | null = null; - protected _blendHash: number | undefined; + //protected _blendHash: number | undefined; protected _model: Model | undefined; @@ -210,15 +210,6 @@ export class RenderDrawInfo { this._sampler = sampler; } - public setBlendHash (blendHash: number) { - if (JSB) { - if (this._blendHash !== blendHash) { - this._nativeObj.blendHash = blendHash; - } - } - this._blendHash = blendHash; - } - public setModel (model: Model) { if (JSB) { if (this._model !== model) { diff --git a/cocos/tiledmap/tiled-layer.ts b/cocos/tiledmap/tiled-layer.ts index 22a1717af0..94464da9d2 100644 --- a/cocos/tiledmap/tiled-layer.ts +++ b/cocos/tiledmap/tiled-layer.ts @@ -1512,7 +1512,6 @@ export class TiledLayer extends UIRenderer { drawInfo.setTexture(td.texture.getGFXTexture()); drawInfo.setTextureHash(td.texture.getHash()); drawInfo.setSampler(td.texture.getGFXSampler()); - drawInfo.setBlendHash(this.blendHash); drawInfo.setMaterial(this.getRenderMaterial(0)!); this.fillIndicesBuffer(td.renderData!, drawInfo); entity.setDynamicRenderDrawInfo(drawInfo, idx); diff --git a/native/cocos/2d/renderer/RenderDrawInfo.cpp b/native/cocos/2d/renderer/RenderDrawInfo.cpp index 1f844d655d..97ec1af8a3 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.cpp +++ b/native/cocos/2d/renderer/RenderDrawInfo.cpp @@ -113,10 +113,6 @@ void RenderDrawInfo::setSampler(gfx::Sampler* sampler) { _sampler = sampler; } -void RenderDrawInfo::setBlendHash(uint32_t blendHash) { - _blendHash = blendHash; -} - void RenderDrawInfo::setModel(scene::Model* model) { _model = model; } diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index 833465532b..6a40bebcd1 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -45,10 +45,6 @@ struct Render2dLayout { Vec4 color; }; -struct DrawInfoAttrLayout { - uint32_t enabledIndex{1}; -}; - enum class RenderDrawInfoType: uint8_t { COMP, MODEL, @@ -97,8 +93,6 @@ public: void setTextureHash(uint32_t textureHash); inline gfx::Sampler* getSampler() const { return _sampler; } void setSampler(gfx::Sampler* sampler); - inline uint32_t getBlendHash() const { return _blendHash; } - void setBlendHash(uint32_t blendHash); inline scene::Model* getModel() const { return _model; } void setModel(scene::Model* model); inline uint32_t getDrawInfoType() const { return static_cast(_drawInfoType); } @@ -159,7 +153,6 @@ private: scene::Model* _model{nullptr}; ccstd::hash_t _dataHash{0}; - uint32_t _stencilStage{0}; // weak reference Material* _material{nullptr}; // weak reference @@ -169,8 +162,6 @@ private: gfx::Sampler* _sampler{nullptr}; Node* _subNode{nullptr}; - uint32_t _blendHash{0}; - uint32_t _nextFreeIAHandle{0}; // weak reference gfx::Buffer* _vbGFXBuffer{nullptr}; diff --git a/native/cocos/bindings/auto/jsb_2d_auto.cpp b/native/cocos/bindings/auto/jsb_2d_auto.cpp index 44ec354345..c31e45d560 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.cpp +++ b/native/cocos/bindings/auto/jsb_2d_auto.cpp @@ -267,26 +267,6 @@ static bool js_2d_RenderDrawInfo_getAccId(se::State& s) // NOLINT(readability-id } SE_BIND_FUNC_AS_PROP_GET(js_2d_RenderDrawInfo_getAccId) -static bool js_2d_RenderDrawInfo_getBlendHash(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - if (nullptr == cobj) return true; - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getBlendHash(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC_AS_PROP_GET(js_2d_RenderDrawInfo_getBlendHash) - static bool js_2d_RenderDrawInfo_getBufferId(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -746,26 +726,6 @@ static bool js_2d_RenderDrawInfo_setAccId(se::State& s) // NOLINT(readability-id } SE_BIND_FUNC_AS_PROP_SET(js_2d_RenderDrawInfo_setAccId) -static bool js_2d_RenderDrawInfo_setBlendHash(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - if (nullptr == cobj) return true; - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - cobj->setBlendHash(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC_AS_PROP_SET(js_2d_RenderDrawInfo_setBlendHash) - static bool js_2d_RenderDrawInfo_setBufferId(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -1251,7 +1211,6 @@ bool js_register_2d_RenderDrawInfo(se::Object* obj) // NOLINT(readability-identi cls->defineProperty("texture", _SE(js_2d_RenderDrawInfo_getTexture_asGetter), _SE(js_2d_RenderDrawInfo_setTexture_asSetter)); cls->defineProperty("textureHash", _SE(js_2d_RenderDrawInfo_getTextureHash_asGetter), _SE(js_2d_RenderDrawInfo_setTextureHash_asSetter)); cls->defineProperty("sampler", _SE(js_2d_RenderDrawInfo_getSampler_asGetter), _SE(js_2d_RenderDrawInfo_setSampler_asSetter)); - cls->defineProperty("blendHash", _SE(js_2d_RenderDrawInfo_getBlendHash_asGetter), _SE(js_2d_RenderDrawInfo_setBlendHash_asSetter)); cls->defineProperty("model", _SE(js_2d_RenderDrawInfo_getModel_asGetter), _SE(js_2d_RenderDrawInfo_setModel_asSetter)); cls->defineProperty("drawInfoType", _SE(js_2d_RenderDrawInfo_getDrawInfoType_asGetter), _SE(js_2d_RenderDrawInfo_setDrawInfoType_asSetter)); cls->defineProperty("subNode", _SE(js_2d_RenderDrawInfo_getSubNode_asGetter), _SE(js_2d_RenderDrawInfo_setSubNode_asSetter)); diff --git a/native/tools/tojs/2d.ini b/native/tools/tojs/2d.ini index fa3952ccde..92fd0d4e76 100644 --- a/native/tools/tojs/2d.ini +++ b/native/tools/tojs/2d.ini @@ -53,7 +53,7 @@ skip = RenderDrawInfo::[getBatcher setBatcher parseAttrLayout getRender2dLayout rename_functions = -getter_setter = RenderDrawInfo::[bufferId accId vertexOffset indexOffset vbBuffer ibBuffer vDataBuffer iDataBuffer vbCount ibCount vertDirty dataHash isMeshBuffer material texture textureHash sampler blendHash model drawInfoType subNode], +getter_setter = RenderDrawInfo::[bufferId accId vertexOffset indexOffset vbBuffer ibBuffer vDataBuffer iDataBuffer vbCount ibCount vertDirty dataHash isMeshBuffer material texture textureHash sampler model drawInfoType subNode], UIMeshBuffer::[vData iData], RenderEntity::[node staticDrawInfoSize stencilStage isMask isSubMask isMaskInverted] diff --git a/platforms/native/engine/jsb-dragonbones.js b/platforms/native/engine/jsb-dragonbones.js index 507637ab11..e25c514d3a 100644 --- a/platforms/native/engine/jsb-dragonbones.js +++ b/platforms/native/engine/jsb-dragonbones.js @@ -781,7 +781,6 @@ const cacheManager = require('./jsb-cache-manager'); drawInfo.setTexture(realTexture.getGFXTexture()); drawInfo.setTextureHash(realTexture.getHash()); drawInfo.setSampler(realTexture.getGFXSampler()); - drawInfo.setBlendHash(this.blendHash); drawInfo.setMaterial(this.material); renderData.fillDrawInfoAttributes(drawInfo); diff --git a/platforms/native/engine/jsb-spine-skeleton.js b/platforms/native/engine/jsb-spine-skeleton.js index e902cb60bc..44746906aa 100644 --- a/platforms/native/engine/jsb-spine-skeleton.js +++ b/platforms/native/engine/jsb-spine-skeleton.js @@ -890,7 +890,6 @@ const cacheManager = require('./jsb-cache-manager'); drawInfo.setTexture(realTexture.getGFXTexture()); drawInfo.setTextureHash(realTexture.getHash()); drawInfo.setSampler(realTexture.getGFXSampler()); - drawInfo.setBlendHash(this.blendHash); drawInfo.setMaterial(this.material); renderData.fillDrawInfoAttributes(drawInfo); From fefd8efcda5bfd4dc74287366084a3d38fa28db9 Mon Sep 17 00:00:00 2001 From: yangchao <1162485779@qq.com> Date: Tue, 19 Jul 2022 13:42:21 +0800 Subject: [PATCH 017/111] mac server mod (#12054) * mac server mod Co-authored-by: bravetwo --- native/CMakeLists.txt | 3 ++- native/cocos/audio/apple/AudioEngine-inl.mm | 2 +- native/cocos/platform/mac/MacPlatform.mm | 2 +- native/cocos/platform/mac/View.h | 2 -- native/cocos/platform/mac/modules/SystemWindow.h | 2 +- native/cocos/platform/mac/modules/SystemWindow.mm | 6 +++++- 6 files changed, 10 insertions(+), 7 deletions(-) diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 184add1a9d..fb87d0fb4a 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -63,6 +63,7 @@ set(CC_USE_METAL ${CC_USE_METAL} CACHE INTERNAL "") if(USE_SERVER_MODE) set(CC_USE_VULKAN OFF) + set(CC_USE_METAL OFF) set(CC_USE_GLES3 OFF) set(CC_USE_GLES2 OFF) add_definitions(-DCC_SERVER_MODE) @@ -492,7 +493,7 @@ cocos_source_files( cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.cpp cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h ) -if(USE_SERVER_MODE) +if(USE_SERVER_MODE AND (NOT MACOSX)) cocos_source_files( cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.cpp cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.h diff --git a/native/cocos/audio/apple/AudioEngine-inl.mm b/native/cocos/audio/apple/AudioEngine-inl.mm index cecaba063d..c268367dd7 100644 --- a/native/cocos/audio/apple/AudioEngine-inl.mm +++ b/native/cocos/audio/apple/AudioEngine-inl.mm @@ -39,7 +39,7 @@ #include "base/Utils.h" #include "base/memory/Memory.h" #include "platform/FileUtils.h" -#include "AudioDecoder.h"" +#include "AudioDecoder.h" using namespace cc; diff --git a/native/cocos/platform/mac/MacPlatform.mm b/native/cocos/platform/mac/MacPlatform.mm index 5fc3593397..e8e82585d2 100644 --- a/native/cocos/platform/mac/MacPlatform.mm +++ b/native/cocos/platform/mac/MacPlatform.mm @@ -118,7 +118,7 @@ int32_t MacPlatform::init() { registerInterface(std::make_shared()); registerInterface(std::make_shared()); registerInterface(std::make_shared()); - registerInterface(std::make_shared()); + registerInterface(std::make_shared(this)); registerInterface(std::make_shared()); return 0; } diff --git a/native/cocos/platform/mac/View.h b/native/cocos/platform/mac/View.h index 890da35fb3..e49a72b8b5 100644 --- a/native/cocos/platform/mac/View.h +++ b/native/cocos/platform/mac/View.h @@ -28,8 +28,6 @@ @interface View : NSView -#ifdef CC_USE_METAL @property (nonatomic, assign) id device; -#endif @end diff --git a/native/cocos/platform/mac/modules/SystemWindow.h b/native/cocos/platform/mac/modules/SystemWindow.h index 9b6f59a8d0..4d90c808e4 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.h +++ b/native/cocos/platform/mac/modules/SystemWindow.h @@ -33,7 +33,7 @@ namespace cc { class SystemWindow : public ISystemWindow { public: - SystemWindow(); + SystemWindow(IEventDispatch *delegate); ~SystemWindow() override; bool createWindow(const char* title, diff --git a/native/cocos/platform/mac/modules/SystemWindow.mm b/native/cocos/platform/mac/modules/SystemWindow.mm index 3abd7af9a7..e6c88fb325 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.mm +++ b/native/cocos/platform/mac/modules/SystemWindow.mm @@ -33,7 +33,7 @@ namespace { namespace cc { -SystemWindow::SystemWindow() = default; +SystemWindow::SystemWindow(IEventDispatch *delegate) {} SystemWindow::~SystemWindow() = default; @@ -47,7 +47,9 @@ bool SystemWindow::createWindow(const char *title, _height = h; AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; NSString *aString = [NSString stringWithUTF8String:title]; +#if !defined(CC_SERVER_MODE) [delegate createLeftBottomWindow:aString width:w height:h]; +#endif return true; } @@ -62,7 +64,9 @@ bool SystemWindow::createWindow(const char *title, _height = h; AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; NSString *aString = [NSString stringWithUTF8String:title]; +#if !defined(CC_SERVER_MODE) [delegate createWindow:aString xPos:x yPos:y width:w height:h]; +#endif return true; } void SystemWindow::closeWindow() { From b741bd3dd509bed1057a84153c23e32ea9411677 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Tue, 19 Jul 2022 14:46:21 +0800 Subject: [PATCH 018/111] fix the validation errors about renderpass and swapchain (#11945) * fix the valication error that framebuffer mismatch renderpass --- native/cocos/renderer/gfx-base/GFXDef.cpp | 7 +++++-- native/cocos/renderer/gfx-base/GFXRenderPass.cpp | 6 ++---- native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp | 1 + 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/native/cocos/renderer/gfx-base/GFXDef.cpp b/native/cocos/renderer/gfx-base/GFXDef.cpp index 031658075a..486b11d23b 100644 --- a/native/cocos/renderer/gfx-base/GFXDef.cpp +++ b/native/cocos/renderer/gfx-base/GFXDef.cpp @@ -28,6 +28,7 @@ #include "base/std/hash/hash.h" #include "GFXDef.h" +#include "GFXRenderPass.h" #include "GFXTexture.h" namespace cc { @@ -114,18 +115,19 @@ ccstd::hash_t Hasher::operator()(const FramebufferInfo &info) c // render pass is mostly irrelevant ccstd::hash_t seed; if (info.depthStencilTexture) { - seed = (static_cast(info.colorTextures.size()) + 1) * 3; + seed = (static_cast(info.colorTextures.size()) + 1) * 3 + 1; ccstd::hash_combine(seed, info.depthStencilTexture); ccstd::hash_combine(seed, info.depthStencilTexture->getRaw()); ccstd::hash_combine(seed, info.depthStencilTexture->getHash()); } else { - seed = static_cast(info.colorTextures.size()) * 3; + seed = static_cast(info.colorTextures.size()) * 3 + 1; } for (auto *colorTexture : info.colorTextures) { ccstd::hash_combine(seed, colorTexture); ccstd::hash_combine(seed, colorTexture->getRaw()); ccstd::hash_combine(seed, colorTexture->getHash()); } + ccstd::hash_combine(seed, info.renderPass->getHash()); return seed; } @@ -146,6 +148,7 @@ bool operator==(const FramebufferInfo &lhs, const FramebufferInfo &rhs) { break; } } + res = lhs.renderPass->getHash() == rhs.renderPass->getHash(); if (res) { res = lhs.depthStencilTexture->getRaw() == rhs.depthStencilTexture->getRaw() && lhs.depthStencilTexture->getHash() == rhs.depthStencilTexture->getHash(); diff --git a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp index 147e1a5c81..e9151ae271 100644 --- a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp +++ b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp @@ -43,12 +43,10 @@ RenderPass::~RenderPass() = default; ccstd::hash_t RenderPass::computeHash() { ccstd::hash_t seed = static_cast(_colorAttachments.size()) * 2 + 3; for (const ColorAttachment &ca : _colorAttachments) { - ccstd::hash_combine(seed, ca.format); - ccstd::hash_combine(seed, ca.sampleCount); + ccstd::hash_combine(seed, ca); } const auto &ds = _depthStencilAttachment; - ccstd::hash_combine(seed, ds.format); - ccstd::hash_combine(seed, ds.sampleCount); + ccstd::hash_combine(seed, ds); ccstd::hash_combine(seed, _subpasses); return seed; diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp index 796779fadb..5f98de50bd 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp @@ -193,6 +193,7 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { _gpuSwapchain->createInfo.imageExtent = imageExtent; _gpuSwapchain->createInfo.imageUsage = imageUsage; _gpuSwapchain->createInfo.imageArrayLayers = 1; + _gpuSwapchain->createInfo.preTransform = surfaceCapabilities.currentTransform; _gpuSwapchain->createInfo.compositeAlpha = compositeAlpha; _gpuSwapchain->createInfo.presentMode = swapchainPresentMode; _gpuSwapchain->createInfo.clipped = VK_TRUE; // Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area From 3d91d97527f627e3c1b5d8b25253276fb785cb38 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Tue, 19 Jul 2022 14:49:39 +0800 Subject: [PATCH 019/111] [bug] retrieve getShadowPassIndex from submodel (#12057) --- .../render-shadow-map-batched-queue.ts | 33 +++++++------------ .../pipeline/ShadowMapBatchedQueue.cpp | 25 +++++++------- .../renderer/pipeline/ShadowMapBatchedQueue.h | 2 +- 3 files changed, 23 insertions(+), 37 deletions(-) diff --git a/cocos/core/pipeline/render-shadow-map-batched-queue.ts b/cocos/core/pipeline/render-shadow-map-batched-queue.ts index 56febd8d64..14dd0733cf 100644 --- a/cocos/core/pipeline/render-shadow-map-batched-queue.ts +++ b/cocos/core/pipeline/render-shadow-map-batched-queue.ts @@ -40,23 +40,14 @@ import { Camera, DirectionalLight, SpotLight } from '../renderer/scene'; import { shadowCulling } from './scene-culling'; const _phaseID = getPhaseID('shadow-caster'); -const _shadowPassIndices: number[] = []; -function getShadowPassIndex (subModels: SubModel[], shadowPassIndices: number[]) { - shadowPassIndices.length = 0; - let hasShadowPass = false; - for (let j = 0; j < subModels.length; j++) { - const { passes } = subModels[j]; - let shadowPassIndex = -1; - for (let k = 0; k < passes.length; k++) { - if (passes[k].phase === _phaseID) { - shadowPassIndex = k; - hasShadowPass = true; - break; - } +function getShadowPassIndex (subModel: SubModel) : number { + const passes = subModel.passes; + for (let k = 0; k < passes.length; k++) { + if (passes[k].phase === _phaseID) { + return k; } - shadowPassIndices.push(shadowPassIndex); } - return hasShadowPass; + return -1; } /** @@ -100,8 +91,7 @@ export class RenderShadowMapBatchedQueue { for (let i = 0; i < dirShadowObjects.length; i++) { const ro = dirShadowObjects[i]; const model = ro.model; - if (!getShadowPassIndex(model.subModels, _shadowPassIndices)) { continue; } - this.add(model, _shadowPassIndices); + this.add(model); } } @@ -114,12 +104,11 @@ export class RenderShadowMapBatchedQueue { for (let i = 0; i < castShadowObjects.length; i++) { const ro = castShadowObjects[i]; const model = ro.model; - if (!getShadowPassIndex(model.subModels, _shadowPassIndices)) { continue; } if (model.worldBounds) { if (!intersect.aabbFrustum(model.worldBounds, spotLight.frustum)) { continue; } } - this.add(model, _shadowPassIndices); + this.add(model); } } break; @@ -143,12 +132,12 @@ export class RenderShadowMapBatchedQueue { this._batchedQueue.clear(); } - public add (model: Model, _shadowPassIndices: number[]) { + public add (model: Model) { const subModels = model.subModels; for (let j = 0; j < subModels.length; j++) { const subModel = subModels[j]; - const shadowPassIdx = _shadowPassIndices[j]; - if (shadowPassIdx < 0) { return; } + const shadowPassIdx = getShadowPassIndex(subModel); + if (shadowPassIdx < 0) { continue; } const pass = subModel.passes[shadowPassIdx]; const batchingScheme = pass.batchingScheme; diff --git a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp index 0bb5fba489..f6c43caf01 100644 --- a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp +++ b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp @@ -123,13 +123,12 @@ void ShadowMapBatchedQueue::clear() { } void ShadowMapBatchedQueue::add(const scene::Model *model) { - // this assumes light pass index is the same for all subModels - const auto shadowPassIdx = getShadowPassIndex(model); - if (shadowPassIdx == -1) { - return; - } - for (const auto &subModel : model->getSubModels()) { + const auto shadowPassIdx = getShadowPassIndex(subModel); + if (shadowPassIdx == -1) { + continue; + } + const auto *pass = subModel->getPass(shadowPassIdx); const auto batchingScheme = pass->getBatchingScheme(); @@ -174,15 +173,13 @@ void ShadowMapBatchedQueue::destroy() { CC_SAFE_DELETE(_instancedQueue) } -int ShadowMapBatchedQueue::getShadowPassIndex(const scene::Model *model) const { - for (const auto &subModel : model->getSubModels()) { - int i = 0; - for (const auto &pass : subModel->getPasses()) { - if (pass->getPhase() == _phaseID) { - return i; - } - ++i; +int ShadowMapBatchedQueue::getShadowPassIndex(const scene::SubModel *subModel) const { + int i = 0; + for (const auto &pass : subModel->getPasses()) { + if (pass->getPhase() == _phaseID) { + return i; } + ++i; } return -1; } diff --git a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.h b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.h index 8481ea6bbb..64ba12e788 100644 --- a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.h +++ b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.h @@ -52,7 +52,7 @@ public: void recordCommandBuffer(gfx::Device *, gfx::RenderPass *, gfx::CommandBuffer *) const; private: - int getShadowPassIndex(const scene::Model *model) const; + int getShadowPassIndex(const scene::SubModel *subModel) const; // weak reference RenderPipeline *_pipeline{nullptr}; From 74ebf33dc576d698c7c94b8db1a4631db3030938 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Tue, 19 Jul 2022 17:16:29 +0800 Subject: [PATCH 020/111] fix mask default material bug (#12070) Co-authored-by: ChiaNing --- cocos/2d/components/mask.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/components/mask.ts b/cocos/2d/components/mask.ts index fed0237cb2..b3b0c99150 100644 --- a/cocos/2d/components/mask.ts +++ b/cocos/2d/components/mask.ts @@ -656,7 +656,7 @@ export class Mask extends UIRenderer { } protected _updateBuiltinMaterial (): Material { - return this._clearStencilMtl!; + return builtinResMgr.get('default-clear-stencil'); } protected _updateMaterial () { From d9c93a57c7281abca02eda9233f603acb48500a5 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Tue, 19 Jul 2022 17:18:38 +0800 Subject: [PATCH 021/111] remove blend state on fillPass function (#12068) Co-authored-by: ChiaNing --- cocos/2d/renderer/draw-batch.ts | 11 ++--------- native/cocos/2d/renderer/Batcher2d.cpp | 6 +++--- native/cocos/scene/DrawBatch2D.cpp | 9 ++------- native/cocos/scene/DrawBatch2D.h | 2 +- native/cocos/scene/Pass.cpp | 4 ++-- native/cocos/scene/Pass.h | 2 +- native/tools/tojs/scene.ini | 2 +- 7 files changed, 12 insertions(+), 24 deletions(-) diff --git a/cocos/2d/renderer/draw-batch.ts b/cocos/2d/renderer/draw-batch.ts index 4f079da6ad..47f852b318 100644 --- a/cocos/2d/renderer/draw-batch.ts +++ b/cocos/2d/renderer/draw-batch.ts @@ -133,15 +133,8 @@ export class DrawBatch2D { if (bsHash === -1) { bsHash = 0; } hashFactor = (dssHash << 16) | bsHash; - if (JSB) { - const nativeDSS = dss._nativeObj ? dss._nativeObj : dss; - const nativeBS = bs._nativeObj ? bs._nativeObj : bs; - // @ts-expect-error hack for UI use pass object - passInUse._initPassFromTarget(mtlPass, nativeDSS, nativeBS, hashFactor); - } else { - // @ts-expect-error hack for UI use pass object - passInUse._initPassFromTarget(mtlPass, dss, bs, hashFactor); - } + // @ts-expect-error hack for UI use pass object + passInUse._initPassFromTarget(mtlPass, dss, bs, hashFactor); this._shaders[i] = passInUse.getShaderVariant(patches)!; diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index d37e960c1f..ab32a02397 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -254,7 +254,7 @@ CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawI curdrawBatch->setDescriptorSet(submodel->getDescriptorSet()); curdrawBatch->setUseLocalFlag(nullptr); - curdrawBatch->fillPass(renderMat, depthStencil, dssHash, nullptr, 0, &(submodel->getPatches())); + curdrawBatch->fillPass(renderMat, depthStencil, dssHash, &(submodel->getPatches())); _batches.push_back(curdrawBatch); } } else if (drawInfoType == RenderDrawInfoType::IA) { @@ -296,7 +296,7 @@ CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawI curdrawBatch->setVisFlags(_currLayer); curdrawBatch->setInputAssembler(ia); curdrawBatch->setUseLocalFlag(nullptr); // todo usLocal - curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash, nullptr, 0); + curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash); const auto& pass = curdrawBatch->getPasses().at(0); curdrawBatch->setDescriptorSet(getDescriptorSet(_currTexture, _currSampler, pass->getLocalSetLayout())); @@ -353,7 +353,7 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) { curdrawBatch->setVisFlags(_currLayer); curdrawBatch->setInputAssembler(ia); curdrawBatch->setUseLocalFlag(nullptr); // todo usLocal - curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash, nullptr, 0); + curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash); const auto& pass = curdrawBatch->getPasses().at(0); curdrawBatch->setDescriptorSet(getDescriptorSet(_currTexture, _currSampler, pass->getLocalSetLayout())); diff --git a/native/cocos/scene/DrawBatch2D.cpp b/native/cocos/scene/DrawBatch2D.cpp index 1f91ff60db..c3b171b6f0 100644 --- a/native/cocos/scene/DrawBatch2D.cpp +++ b/native/cocos/scene/DrawBatch2D.cpp @@ -34,10 +34,9 @@ namespace scene { void DrawBatch2D::clear() { } -void DrawBatch2D::fillPass(Material *mat, const gfx::DepthStencilState *depthStencilState, ccstd::hash_t dsHash, const gfx::BlendState *blendState, ccstd::hash_t bsHash, const ccstd::vector *patches) { +void DrawBatch2D::fillPass(Material *mat, const gfx::DepthStencilState *depthStencilState, ccstd::hash_t dsHash, const ccstd::vector *patches) { const auto &passes = mat->getPasses(); if (passes->empty()) return; - uint32_t hashFactor = 0; _shaders.clear(); if (_passes.size() < passes->size()) { auto num = static_cast(passes->size() - _passes.size()); @@ -51,11 +50,7 @@ void DrawBatch2D::fillPass(Material *mat, const gfx::DepthStencilState *depthSte auto &passInUse = _passes[i]; pass->update(); if (!depthStencilState) depthStencilState = pass->getDepthStencilState(); - if (!blendState) blendState = pass->getBlendState(); - // 可能有负值问题 - // if (bsHash == -1) {bsHash = 0;} - hashFactor = (dsHash << 16) | bsHash; - passInUse->initPassFromTarget(pass, *depthStencilState, *blendState, hashFactor); + passInUse->initPassFromTarget(pass, *depthStencilState, dsHash); _shaders.push_back(patches ? passInUse->getShaderVariant(*patches) : passInUse->getShaderVariant()); } } diff --git a/native/cocos/scene/DrawBatch2D.h b/native/cocos/scene/DrawBatch2D.h index 33b50da1b8..00ccfdea9e 100644 --- a/native/cocos/scene/DrawBatch2D.h +++ b/native/cocos/scene/DrawBatch2D.h @@ -47,7 +47,7 @@ public: ~DrawBatch2D() override = default; void clear(); - void fillPass(Material *mat, const gfx::DepthStencilState *depthStencilState, ccstd::hash_t dsHash, const gfx::BlendState *blendState, ccstd::hash_t bsHash, const ccstd::vector *patches = nullptr); + void fillPass(Material *mat, const gfx::DepthStencilState *depthStencilState, ccstd::hash_t dsHash, const ccstd::vector *patches = nullptr); inline void setInputAssembler(gfx::InputAssembler *ia) { _inputAssembler = ia; } inline void setDescriptorSet(gfx::DescriptorSet *descriptorSet) { _descriptorSet = descriptorSet; } diff --git a/native/cocos/scene/Pass.cpp b/native/cocos/scene/Pass.cpp index 31b147113a..eb94073fa7 100644 --- a/native/cocos/scene/Pass.cpp +++ b/native/cocos/scene/Pass.cpp @@ -629,14 +629,14 @@ void Pass::syncBatchingScheme() { } } -void Pass::initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, const gfx::BlendState &bs, ccstd::hash_t hashFactor) { +void Pass::initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, ccstd::hash_t hashFactor) { _priority = target->_priority; _stage = target->_stage; _phase = target->_phase; _batchingScheme = target->_batchingScheme; _primitive = target->_primitive; _dynamicStates = target->_dynamicStates; - _blendState = bs; // cjh lifecycle? + _blendState = *target->getBlendState(); _depthStencilState = dss; _descriptorSet = target->_descriptorSet; _rs = *target->getRasterizerState(); diff --git a/native/cocos/scene/Pass.h b/native/cocos/scene/Pass.h index abc52549fd..a5124f536d 100644 --- a/native/cocos/scene/Pass.h +++ b/native/cocos/scene/Pass.h @@ -297,7 +297,7 @@ public: inline gfx::PipelineLayout *getPipelineLayout() const { return _pipelineLayout; } // Only for UI - void initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, const gfx::BlendState &bs, ccstd::hash_t hashFactor); + void initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, ccstd::hash_t hashFactor); // internal use /** diff --git a/native/tools/tojs/scene.ini b/native/tools/tojs/scene.ini index c02df65b0c..29df408689 100644 --- a/native/tools/tojs/scene.ini +++ b/native/tools/tojs/scene.ini @@ -68,7 +68,7 @@ classes = Light DirectionalLight SpotLight SphereLight Model SubModel Pass Rende # add a single "*" as functions. See bellow for several examples. A special class name is "*", which # will apply to all class names. This is a convenience wildcard to be able to skip similar named # functions from all classes. -skip = Pass::[getBlocks], +skip = Pass::[getBlocks initPassFromTarget], AABB::[getBoundary aabbAabb aabbFrustum aabbPlan merge transform transformExtentM4 setCenter getCenter isValid setValid setHalfExtents getHalfExtents set fromPoints], Model::[getEventProcessor getOctreeNode setOctreeNode updateOctree], SkinningModel::[uploadJointData], From eaab33e7d46ffddfdcf9008bf85210dad0f88d15 Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Tue, 19 Jul 2022 17:47:30 +0800 Subject: [PATCH 022/111] [ci skip][AUTO]: Automated code generating update: 0fe6abc85cec4e94d8382ed2f45fe5ba60c8d458 (#12068) (#12077) Co-authored-by: cocos-robot --- native/cocos/bindings/auto/jsb_scene_auto.cpp | 27 ------------------- native/cocos/bindings/auto/jsb_scene_auto.h | 1 - 2 files changed, 28 deletions(-) diff --git a/native/cocos/bindings/auto/jsb_scene_auto.cpp b/native/cocos/bindings/auto/jsb_scene_auto.cpp index 74d495b904..b99ada7f44 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.cpp +++ b/native/cocos/bindings/auto/jsb_scene_auto.cpp @@ -15108,32 +15108,6 @@ static bool js_scene_Pass_getUniform(se::State& s) // NOLINT(readability-identif } SE_BIND_FUNC(js_scene_Pass_getUniform) -static bool js_scene_Pass_initPassFromTarget(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - if (nullptr == cobj) return true; - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 4) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - HolderType arg3 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - cobj->initPassFromTarget(arg0.value(), arg1.value(), arg2.value(), arg3.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 4); - return false; -} -SE_BIND_FUNC(js_scene_Pass_initPassFromTarget) - static bool js_scene_Pass_initialize(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -15604,7 +15578,6 @@ bool js_register_scene_Pass(se::Object* obj) // NOLINT(readability-identifier-na cls->defineFunction("getRootBlock", _SE(js_scene_Pass_getRootBlock)); cls->defineFunction("getShaderVariant", _SE(js_scene_Pass_getShaderVariant)); cls->defineFunction("getUniform", _SE(js_scene_Pass_getUniform)); - cls->defineFunction("_initPassFromTarget", _SE(js_scene_Pass_initPassFromTarget)); cls->defineFunction("initialize", _SE(js_scene_Pass_initialize)); cls->defineFunction("overridePipelineStates", _SE(js_scene_Pass_overridePipelineStates)); cls->defineFunction("resetTexture", _SE(js_scene_Pass_resetTexture)); diff --git a/native/cocos/bindings/auto/jsb_scene_auto.h b/native/cocos/bindings/auto/jsb_scene_auto.h index 7214dfdf8a..7abe080276 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.h +++ b/native/cocos/bindings/auto/jsb_scene_auto.h @@ -499,7 +499,6 @@ SE_DECLARE_FUNC(js_scene_Pass_getPassInfoFull); SE_DECLARE_FUNC(js_scene_Pass_getRootBlock); SE_DECLARE_FUNC(js_scene_Pass_getShaderVariant); SE_DECLARE_FUNC(js_scene_Pass_getUniform); -SE_DECLARE_FUNC(js_scene_Pass_initPassFromTarget); SE_DECLARE_FUNC(js_scene_Pass_initialize); SE_DECLARE_FUNC(js_scene_Pass_overridePipelineStates); SE_DECLARE_FUNC(js_scene_Pass_resetTexture); From c2b821e10519602fd0094313b2a00f7869c89742 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Tue, 19 Jul 2022 18:47:35 +0800 Subject: [PATCH 023/111] fix data exception caused by parseInt (#12078) --- cocos/core/assets/texture-cube.jsb.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/core/assets/texture-cube.jsb.ts b/cocos/core/assets/texture-cube.jsb.ts index 4eed88162d..765920f9d9 100644 --- a/cocos/core/assets/texture-cube.jsb.ts +++ b/cocos/core/assets/texture-cube.jsb.ts @@ -200,7 +200,9 @@ textureCubeProto._deserialize = function (serializedData: ITextureCubeSerializeD const data = serializedData; jsb.TextureBase.prototype._deserialize.call(this, data.base, handle); this.isRGBE = data.rgbe; - this._mipmapMode = parseInt(data.mipmapMode); + if (data.mipmapMode != undefined) { + this._mipmapMode = data.mipmapMode; + } if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { const mipmapAtlas = data.mipmapAtlas; const mipmapLayout = data.mipmapLayout; From 9a7204143fcd9aa02def7895af0f445032f9bfab Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 19 Jul 2022 19:23:11 +0800 Subject: [PATCH 024/111] Fix crash of spine test on Android, revert Mat4 and use enoki::load_unaligned in Vec3::transformMat4Neon (#12076) --- native/cocos/math/Mat4.h | 2 +- native/cocos/math/Vec3.cpp | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/native/cocos/math/Mat4.h b/native/cocos/math/Mat4.h index aa4d25b322..d42daa0334 100644 --- a/native/cocos/math/Mat4.h +++ b/native/cocos/math/Mat4.h @@ -73,7 +73,7 @@ NS_CC_MATH_BEGIN * * @see Transform */ -class CC_DLL alignas(16) Mat4 { +class CC_DLL Mat4 { public: // //temp add conversion // operator kmMat4() const diff --git a/native/cocos/math/Vec3.cpp b/native/cocos/math/Vec3.cpp index ac55924209..4deee0d715 100644 --- a/native/cocos/math/Vec3.cpp +++ b/native/cocos/math/Vec3.cpp @@ -222,10 +222,10 @@ void Vec3::transformMat4Neon(const Vec3 &v, const Mat4 &m) { #if defined(USE_NEON64) || defined(USE_NEON32) || defined(INCLUDE_NEON32) alignas(16) float tmpV0[4]; - auto row0 = enoki::load(&m.m[0]); - auto row1 = enoki::load(&m.m[4]); - auto row2 = enoki::load(&m.m[8]); - auto row3 = enoki::load(&m.m[12]); + auto row0 = enoki::load_unaligned(&m.m[0]); + auto row1 = enoki::load_unaligned(&m.m[4]); + auto row2 = enoki::load_unaligned(&m.m[8]); + auto row3 = enoki::load_unaligned(&m.m[12]); row0 *= v.x; row1 *= v.y; From 616968d7bd821e3c21b46245b9fb683dc0aa23d7 Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 19 Jul 2022 23:23:25 +0800 Subject: [PATCH 025/111] Adjust code struct and remove unneeded variables in Node (#12069) --- native/cocos/core/scene-graph/Node.cpp | 4 -- native/cocos/core/scene-graph/Node.h | 91 +++++++++++--------------- 2 files changed, 39 insertions(+), 56 deletions(-) diff --git a/native/cocos/core/scene-graph/Node.cpp b/native/cocos/core/scene-graph/Node.cpp index e994925b1f..fc4ab22564 100644 --- a/native/cocos/core/scene-graph/Node.cpp +++ b/native/cocos/core/scene-graph/Node.cpp @@ -39,11 +39,7 @@ namespace cc { uint32_t Node::clearFrame{0}; uint32_t Node::clearRound{1000}; const uint32_t Node::TRANSFORM_ON{1 << 0}; -const uint32_t Node::DESTROYING{static_cast(CCObject::Flags::DESTROYING)}; -const uint32_t Node::DEACTIVATING{static_cast(CCObject::Flags::DEACTIVATING)}; -const uint32_t Node::DONT_DESTROY{static_cast(CCObject::Flags::DONT_DESTROY)}; uint32_t Node::globalFlagChangeVersion{0}; -// namespace { const ccstd::string EMPTY_NODE_NAME; diff --git a/native/cocos/core/scene-graph/Node.h b/native/cocos/core/scene-graph/Node.h index 0d8b136c16..fd753b4390 100644 --- a/native/cocos/core/scene-graph/Node.h +++ b/native/cocos/core/scene-graph/Node.h @@ -70,12 +70,8 @@ public: using Super = BaseNode; static const uint32_t TRANSFORM_ON; - static const uint32_t DESTROYING; - static const uint32_t DEACTIVATING; - static const uint32_t DONT_DESTROY; static Node *instantiate(Node *cloned, bool isSyncedNode); - static void setScene(Node *); /** @@ -104,6 +100,8 @@ public: explicit Node(const ccstd::string &name); ~Node() override; + virtual void onPostActivated(bool active) {} + void setParent(Node *parent, bool isKeepWorld = false); Scene *getScene() const; @@ -255,7 +253,6 @@ public: _activeInHierarchy = (v ? 1 : 0); } - virtual void onPostActivated(bool active) {} inline const ccstd::vector> &getChildren() const { return _children; } inline Node *getParent() const { return _parent; } inline NodeEventProcessor *getEventProcessor() const { return _eventProcessor; } @@ -297,6 +294,7 @@ public: inline void setPosition(float x, float y, float z) { setPositionInternal(x, y, z, false); } inline void setPositionInternal(float x, float y, bool calledFromJS) { setPositionInternal(x, y, _localPosition.z, calledFromJS); } void setPositionInternal(float x, float y, float z, bool calledFromJS); + // It is invoked after deserialization. It only sets position value, not triggers other logic. inline void setPositionForJS(float x, float y, float z) { _localPosition.set(x, y, z); } /** * @en Get position in local coordinate system, please try to pass `out` vector and reuse it to avoid garbage. @@ -622,30 +620,20 @@ public: bool onPreDestroy() override; bool onPreDestroyBase(); -protected: - static index_t getIdxOfChild(const ccstd::vector> &, Node *); - - void onSetParent(Node *oldParent, bool keepWorldTransform); - - virtual void updateScene(); - - void onHierarchyChanged(Node *); - void onHierarchyChangedBase(Node *oldParent); - - virtual void onBatchCreated(bool dontChildPrefab); - -#if CC_EDITOR - inline void notifyEditorAttached(bool attached) { - emit(EventTypesToJS::NODE_EDITOR_ATTACHED, attached); - } -#endif - - static uint32_t clearFrame; - static uint32_t clearRound; + std::function onSiblingIndexChanged{nullptr}; + // For deserialization + ccstd::string _id; + Node *_parent{nullptr}; private: - // increase on every frame, used to identify the frame - static uint32_t globalFlagChangeVersion; + static index_t getIdxOfChild(const ccstd::vector> &, Node *); + + virtual void onBatchCreated(bool dontChildPrefab); + virtual void updateScene(); + + void onSetParent(Node *oldParent, bool keepWorldTransform); + void onHierarchyChanged(Node *); + void onHierarchyChangedBase(Node *oldParent); inline void notifyLocalPositionUpdated() { emit(EventTypesToJS::NODE_LOCAL_POSITION_UPDATED, _localPosition.x, _localPosition.y, _localPosition.z); @@ -666,40 +654,34 @@ private: _localScale.x, _localScale.y, _localScale.z); } -protected: +#if CC_EDITOR + inline void notifyEditorAttached(bool attached) { + emit(EventTypesToJS::NODE_EDITOR_ATTACHED, attached); + } +#endif + + // increase on every frame, used to identify the frame + static uint32_t globalFlagChangeVersion; + + static uint32_t clearFrame; + static uint32_t clearRound; + Scene *_scene{nullptr}; NodeEventProcessor *_eventProcessor{nullptr}; + IntrusivePtr _userData; - Mat4 _worldMatrix{Mat4::IDENTITY}; - - /* set _hasChangedFlagsVersion to globalFlagChangeVersion when `_hasChangedFlags` updated. - * `globalFlagChangeVersion == _hasChangedFlagsVersion` means that "_hasChangedFlags is dirty in current frametime". - */ - uint32_t _hasChangedFlagsVersion{0}; - uint32_t _hasChangedFlags{0}; - - bool _eulerDirty{false}; - -public: - std::function onSiblingIndexChanged{nullptr}; - // For deserialization - ccstd::string _id; - Node *_parent{nullptr}; - -private: ccstd::vector> _children; + bindings::NativeMemorySharedToScriptActor _sharedMemoryActor; // local transform Vec3 _localPosition{Vec3::ZERO}; - Quaternion _localRotation{Quaternion::identity()}; Vec3 _localScale{Vec3::ONE}; + Quaternion _localRotation{Quaternion::identity()}; // world transform Vec3 _worldPosition{Vec3::ZERO}; - Quaternion _worldRotation{Quaternion::identity()}; Vec3 _worldScale{Vec3::ONE}; - // Vec3 _euler{0, 0, 0}; - - IntrusivePtr _userData; + Quaternion _worldRotation{Quaternion::identity()}; + Mat4 _worldMatrix{Mat4::IDENTITY}; // Shared memory with JS // NOTE: TypeArray created in node.jsb.ts _ctor should have the same memory layout @@ -712,9 +694,14 @@ private: uint8_t _isStatic{0}; // Uint8: 2 uint8_t _padding{0}; // Uint8: 3 - bindings::NativeMemorySharedToScriptActor _sharedMemoryActor; + /* set _hasChangedFlagsVersion to globalFlagChangeVersion when `_hasChangedFlags` updated. + * `globalFlagChangeVersion == _hasChangedFlagsVersion` means that "_hasChangedFlags is dirty in current frametime". + */ + uint32_t _hasChangedFlagsVersion{0}; + uint32_t _hasChangedFlags{0}; + + bool _eulerDirty{false}; - // friend class NodeActivator; friend class Scene; From 02655fa8faabeff56167a2545e9ad973cd27853a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Wed, 20 Jul 2022 08:59:56 +0800 Subject: [PATCH 026/111] use cmath std::fabs instead of cstdlib std::abs (#12075) --- native/cocos/math/Math.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/native/cocos/math/Math.h b/native/cocos/math/Math.h index 0e2c78848c..1b73eeebe8 100644 --- a/native/cocos/math/Math.h +++ b/native/cocos/math/Math.h @@ -24,8 +24,8 @@ ****************************************************************************/ #pragma once +#include #include -#include #include "base/Macros.h" namespace cc { @@ -65,15 +65,15 @@ inline bool isPowerOfTwo(T n) { } inline bool isEqualF(float lhs, float rhs, float precision = 0.000001F) { - return (std::abs(lhs - rhs) < precision); + return (std::fabs(lhs - rhs) < precision); } inline bool isNotEqualF(float lhs, float rhs, float precision = 0.000001F) { - return (std::abs(lhs - rhs) > precision); + return (std::fabs(lhs - rhs) > precision); } inline bool isNotZeroF(float v, float precision = 0.000001F) { - return (std::abs(v) > precision); + return (std::fabs(v) > precision); } } // namespace math From 2be3554f9f7ecc2f859585b8cda28c2101c08f0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Wed, 20 Jul 2022 10:41:31 +0800 Subject: [PATCH 027/111] modify the type of albedoScaled and transparencyFactor multiplied by baseColor.a (#12071) --- .../dcc/imported-specular-glossiness.effect | 49 ++++++++++----- ...rfaces-imported-specular-glossiness.effect | 62 +++++++++---------- 2 files changed, 62 insertions(+), 49 deletions(-) diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect b/editor/assets/effects/dcc/imported-specular-glossiness.effect index 92b87d1eb8..05af1fb76c 100644 --- a/editor/assets/effects/dcc/imported-specular-glossiness.effect +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect @@ -10,7 +10,7 @@ CCEffect %{ mainTexture: { value: grey, target: albedoMap, editor: { displayName: DiffuseMap } } mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, linear: true, editor: { displayName: DiffuseColor, type: color } } albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } emissiveMap: { value: grey } shininessExponentMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } @@ -53,9 +53,9 @@ CCEffect %{ cullMode: front properties: tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } - mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } - albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, editor: { displayName: Albedo, type: color } } + albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } + alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST } } mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } @@ -80,10 +80,7 @@ CCEffect %{ CCProgram shared-ubos %{ uniform Constants { - vec4 tilingOffset; - vec4 albedo; - vec4 albedoScaleAndCutoff; - + vec4 tilingOffset; vec4 diffuseColor; vec4 specularColor; vec4 emissive; @@ -300,6 +297,7 @@ CCProgram standard-fs %{ #if USE_ALBEDO_MAP vec4 texColor = texture(albedoMap, TEXTURE_UV); texColor.rgb = SRGBToLinear(texColor.rgb); + texColor.a *= transparencyFactor; baseColor *= texColor; #else baseColor *= diffuseColor; @@ -307,11 +305,11 @@ CCProgram standard-fs %{ baseColor.rgb *= diffuseFactor; #if USE_TRANSPARENCY_MAP - baseColor.a = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; + baseColor.a = texture(transparencyMap, TEXTURE_UV).a; #endif #if USE_ALPHA_TEST - if (baseColor.a < albedoScaleAndCutoff.w) discard; + if (baseColor.a < alphaThreshold) discard; #endif #if CC_RECEIVE_SHADOW @@ -405,6 +403,11 @@ CCProgram shadow-caster-vs %{ out highp vec2 v_clip_depth; + #if USE_VERTEX_COLOR + in vec4 a_color; + out lowp vec4 v_color; + #endif + vec4 vert () { StandardVertInput In; CCVertInput(In); @@ -420,6 +423,10 @@ CCProgram shadow-caster-vs %{ v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw; #endif + #if USE_VERTEX_COLOR + v_color = a_color; + #endif + v_clip_depth = clipPos.zw; return clipPos; @@ -447,14 +454,24 @@ CCProgram shadow-caster-fs %{ uniform sampler2D transparencyMap; #endif + #if USE_VERTEX_COLOR + in lowp vec4 v_color; + #endif + vec4 frag () { - #if USE_ALPHA_TEST - float alpha = 1.0; - #if USE_TRANSPARENCY_MAP - alpha = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; - #endif - if (alpha < albedoScaleAndCutoff.w) discard; + #if USE_ALPHA_TEST + float alpha = diffuseColor.a; + #if USE_VERTEX_COLOR + alpha *= v_color.a; #endif + #if USE_ALBEDO_MAP + alpha *= texture(albedoMap, TEXTURE_UV).a * transparencyFactor; + #endif + #if USE_TRANSPARENCY_MAP + alpha = texture(transparencyMap, TEXTURE_UV).a; + #endif + if (alpha < alphaThreshold) discard; + #endif highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; // spot use linear diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect index 3fc592b0c0..47c620cd7f 100644 --- a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect @@ -10,7 +10,7 @@ CCEffect %{ mainTexture: { value: grey, target: albedoMap, editor: { displayName: DiffuseMap } } mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, linear: true, editor: { displayName: DiffuseColor, type: color } } albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } emissiveMap: { value: grey } shininessExponentMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } @@ -53,9 +53,9 @@ CCEffect %{ cullMode: front properties: tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } - mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } - albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, editor: { displayName: Albedo, type: color } } + albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } + alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST } } mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } @@ -80,10 +80,7 @@ CCEffect %{ CCProgram shared-ubos %{ uniform Constants { - vec4 tilingOffset; - vec4 albedo; - vec4 albedoScaleAndCutoff; - + vec4 tilingOffset; vec4 diffuseColor; vec4 specularColor; vec4 emissive; @@ -223,32 +220,21 @@ CCProgram surface-fragment %{ return vec4(inSpecular, specularFactor); } - #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY - vec4 SurfacesFragmentModifyBaseColorAndTransparency() - { - //diffuse - vec4 baseColor = vec4(1.0); - - #if USE_TRANSPARENCY_MAP - baseColor.a = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; - #endif - - #if USE_ALPHA_TEST - if (baseColor.a < albedoScaleAndCutoff.w) discard; - #endif - - return baseColor; - } - #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY void SurfacesFragmentAlphaClipOnly() { #if USE_ALPHA_TEST - float alpha = 1.0; - #if USE_TRANSPARENCY_MAP - alpha = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; + float alpha = diffuseColor.a; + #if USE_VERTEX_COLOR + alpha *= FSInput_vertexColor.a; #endif - if (alpha < albedoScaleAndCutoff.w) discard; + #if USE_ALBEDO_MAP + alpha *= texture(albedoMap, TEXTURE_UV).a * transparencyFactor; + #endif + #if USE_TRANSPARENCY_MAP + alpha = texture(transparencyMap, TEXTURE_UV).a; + #endif + if (alpha < alphaThreshold) discard; #endif } @@ -278,7 +264,7 @@ CCProgram surface-fragment %{ #include void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData) { - vec4 baseColor = diffuseColor; + vec4 baseColor = vec4(1.0); #if USE_VERTEX_COLOR baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear baseColor.a *= FSInput_vertexColor.a; @@ -286,9 +272,19 @@ CCProgram surface-fragment %{ #if USE_ALBEDO_MAP vec4 texColor = texture(albedoMap, TEXTURE_UV); texColor.rgb = SRGBToLinear(texColor.rgb); - baseColor = texColor; + texColor.a *= transparencyFactor; + baseColor *= texColor; #else - baseColor.rgb *= diffuseFactor; + baseColor *= diffuseColor; + #endif + baseColor.rgb *= diffuseFactor; + + #if USE_TRANSPARENCY_MAP + baseColor.a = texture(transparencyMap, TEXTURE_UV).a; + #endif + + #if USE_ALPHA_TEST + if (baseColor.a < alphaThreshold) discard; #endif vec4 specularColorAndFactor = getSpecularColorAndFactor(); @@ -325,7 +321,7 @@ CCProgram surface-fragment %{ #endif baseColor.rgb = albedo; - surfaceData.baseColor.rgb = baseColor.rgb; + surfaceData.baseColor = baseColor; surfaceData.specularIntensity = inSpecularIntensity * 0.5; surfaceData.roughness = 1.0 - inGlossiness; surfaceData.metallic = inMetallic; From a2aecfe2434b32b6256ca1e1ae1f37d02857913e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Wed, 20 Jul 2022 10:47:33 +0800 Subject: [PATCH 028/111] [bug] fix macro of material is invalid and set value of HDR for PipelineSceneData with native engine (#12074) --- native/cocos/scene/Skybox.cpp | 25 +++++++++++++++++-------- native/cocos/scene/Skybox.h | 5 +---- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/native/cocos/scene/Skybox.cpp b/native/cocos/scene/Skybox.cpp index b0cf66390e..fccfd909be 100644 --- a/native/cocos/scene/Skybox.cpp +++ b/native/cocos/scene/Skybox.cpp @@ -166,6 +166,7 @@ TextureCube *SkyboxInfo::getDiffuseMap() const { void SkyboxInfo::activate(Skybox *resource) { _resource = resource; // weak reference + Root::getInstance()->getPipeline()->getPipelineSceneData()->setHDR(_useHDR); if (_resource != nullptr) { _resource->initialize(*this); setEnvLightingType(this->_envLightingType); @@ -306,15 +307,14 @@ void Skybox::activate() { _activated = true; } +void Skybox::setUseHDR(bool val) { + Root::getInstance()->getPipeline()->getPipelineSceneData()->setHDR(val); + _useHDR = val; + setEnvMaps(_envmapHDR, _envmapLDR); +} + void Skybox::updatePipeline() const { - if (isEnabled() && _material != nullptr) { - _material->recompileShaders({{"USE_RGBE_CUBEMAP", isRGBE()}}); - } - - if (_model != nullptr && _material != nullptr) { - _model->setSubModelMaterial(0, _material); - } - + Root *root = Root::getInstance(); auto *pipeline = root->getPipeline(); @@ -377,6 +377,15 @@ void Skybox::updatePipeline() const { valueChanged = true; } + //set the macro value first before update the material + if (isEnabled() && _material != nullptr) { + _material->recompileShaders({ {"USE_RGBE_CUBEMAP", isRGBE()} }); + } + + if (_model != nullptr && _material != nullptr) { + _model->setSubModelMaterial(0, _material); + } + if (valueChanged && _activated) { root->onGlobalPipelineStateChanged(); } diff --git a/native/cocos/scene/Skybox.h b/native/cocos/scene/Skybox.h index f7ffe8f8c6..70f49dbc9e 100644 --- a/native/cocos/scene/Skybox.h +++ b/native/cocos/scene/Skybox.h @@ -223,10 +223,7 @@ public: * @zh 是否启用HDR? */ inline bool isUseHDR() const { return _useHDR; } - inline void setUseHDR(bool val) { - _useHDR = val; - setEnvMaps(_envmapHDR, _envmapLDR); - } + void setUseHDR(bool val); /** * @en Whether use environment lighting From 131fb74b327e17e6ee3cdd83e4e112492ebd9d46 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 20 Jul 2022 11:09:24 +0800 Subject: [PATCH 029/111] Fix the parameter of TextureCube::setImage, support to pass nullptr to it, keep the same logic as which in web (#12062) --- cocos/core/assets/texture-cube.jsb.ts | 4 ++++ native/cocos/bindings/manual/jsb_assets_manual.cpp | 1 + native/cocos/core/assets/TextureCube.cpp | 10 +++++++--- native/cocos/core/assets/TextureCube.h | 10 +++++----- native/cocos/core/builtin/BuiltinResMgr.cpp | 2 +- native/tools/tojs/render.ini | 2 +- 6 files changed, 19 insertions(+), 10 deletions(-) diff --git a/cocos/core/assets/texture-cube.jsb.ts b/cocos/core/assets/texture-cube.jsb.ts index 765920f9d9..03f64fa601 100644 --- a/cocos/core/assets/texture-cube.jsb.ts +++ b/cocos/core/assets/texture-cube.jsb.ts @@ -27,6 +27,7 @@ import { legacyCC } from '../global-exports'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; import { js } from '../utils/js'; import './simple-texture'; +import { EDITOR, TEST } from 'internal:constants'; const textureCubeProto: any = jsb.TextureCube.prototype; interface ITextureCubeSerializeData { @@ -67,6 +68,9 @@ enum MipmapMode { } textureCubeProto.createNode = null!; +declare const jsb: any; + +// @ts-expect-error jsb.TextureCube is exported from cpp export type TextureCube = jsb.TextureCube; export const TextureCube: any = jsb.TextureCube; diff --git a/native/cocos/bindings/manual/jsb_assets_manual.cpp b/native/cocos/bindings/manual/jsb_assets_manual.cpp index 5d9f85a859..ed94996817 100644 --- a/native/cocos/bindings/manual/jsb_assets_manual.cpp +++ b/native/cocos/bindings/manual/jsb_assets_manual.cpp @@ -24,6 +24,7 @@ ****************************************************************************/ #include "bindings/auto/jsb_assets_auto.h" +#include "core/data/JSBNativeDataHolder.h" #include "core/event/EventTypesToJS.h" #include "jsb_scene_manual.h" diff --git a/native/cocos/core/assets/TextureCube.cpp b/native/cocos/core/assets/TextureCube.cpp index dece94df95..f7ffe2ce82 100644 --- a/native/cocos/core/assets/TextureCube.cpp +++ b/native/cocos/core/assets/TextureCube.cpp @@ -168,10 +168,14 @@ void TextureCube::setMipmapAtlasForJS(const TextureCubeMipmapAtlasInfo &value) { _mipmapAtlas = value; } -void TextureCube::setImage(const ITextureCubeMipmap &value) { - _mipmaps.clear(); - _mipmaps.emplace_back(value); +void TextureCube::setImage(const ITextureCubeMipmap *value) { + if (value != nullptr) { + setMipmaps({*value}); + } else { + setMipmaps({}); + } } + void TextureCube::reset(const ITextureCubeCreateInfo &info) { _width = info.width; _height = info.height; diff --git a/native/cocos/core/assets/TextureCube.h b/native/cocos/core/assets/TextureCube.h index fef986b88a..e0525962da 100644 --- a/native/cocos/core/assets/TextureCube.h +++ b/native/cocos/core/assets/TextureCube.h @@ -203,7 +203,7 @@ public: return _mipmaps.empty() ? nullptr : &_mipmaps[0]; } - void setImage(const ITextureCubeMipmap &value); + void setImage(const ITextureCubeMipmap *value); /** * @en Reset the current texture with given size, pixel format and mipmap images. @@ -248,19 +248,19 @@ public: bool validate() const override; // + /*@serializable*/ + MipmapMode _mipmapMode{MipmapMode::NONE}; + /*@serializable*/ bool isRGBE{false}; +private: /*@serializable*/ ccstd::vector _mipmaps; - /*@serializable*/ - MipmapMode _mipmapMode{MipmapMode::NONE}; - /*@serializable*/ TextureCubeMipmapAtlasInfo _mipmapAtlas; -private: CC_DISALLOW_COPY_MOVE_ASSIGN(TextureCube); }; diff --git a/native/cocos/core/builtin/BuiltinResMgr.cpp b/native/cocos/core/builtin/BuiltinResMgr.cpp index 9ceb76479e..71e0d4a47c 100644 --- a/native/cocos/core/builtin/BuiltinResMgr.cpp +++ b/native/cocos/core/builtin/BuiltinResMgr.cpp @@ -239,7 +239,7 @@ void BuiltinResMgr::initTextureCubeWithUuid(const ccstd::string &uuid, const uin mipmap.bottom = ccnew ImageAsset(); mipmap.bottom->setNativeAsset(imageSource); - texture->setImage(mipmap); + texture->setImage(&mipmap); texture->initialize(); _resources.emplace(texture->getUuid(), texture); diff --git a/native/tools/tojs/render.ini b/native/tools/tojs/render.ini index c5c4719a78..b5239bad81 100644 --- a/native/tools/tojs/render.ini +++ b/native/tools/tojs/render.ini @@ -30,7 +30,7 @@ headers = %(cocosdir)s/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h hpp_headers = -cpp_headers = cocos/bindings/auto/jsb_gfx_auto.h cocos/bindings/auto/jsb_scene_auto.h cocos/renderer/pipeline/custom/LayoutGraphJsb.h cocos/renderer/pipeline/custom/RenderCommonJsb.h cocos/renderer/pipeline/custom/RenderGraphJsb.h +cpp_headers = cocos/bindings/auto/jsb_gfx_auto.h cocos/bindings/auto/jsb_scene_auto.h cocos/renderer/pipeline/custom/LayoutGraphJsb.h cocos/renderer/pipeline/custom/RenderCommonJsb.h cocos/renderer/pipeline/custom/RenderGraphJsb.h cocos/renderer/pipeline/GeometryRenderer.h cocos/renderer/pipeline/GlobalDescriptorSetManager.h replace_headers = From 50ffa3b39a483d6e42892f8b6a6e8d17cd397efb Mon Sep 17 00:00:00 2001 From: timlyeee <43355299+timlyeee@users.noreply.github.com> Date: Wed, 20 Jul 2022 11:18:09 +0800 Subject: [PATCH 030/111] V3.6.0 get language with LocaleList on Android7+ (#12073) * get language by using system language settings --- .../android/java/src/com/cocos/lib/CocosHelper.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/CocosHelper.java b/native/cocos/platform/android/java/src/com/cocos/lib/CocosHelper.java index 94afb55ab3..aa215b065f 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/CocosHelper.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/CocosHelper.java @@ -41,6 +41,7 @@ import android.net.Uri; import android.os.BatteryManager; import android.os.Build; import android.os.Environment; +import android.os.LocaleList; import android.os.ParcelFileDescriptor; import android.os.Vibrator; import android.util.Log; @@ -210,11 +211,19 @@ public class CocosHelper { } public static String getCurrentLanguage() { - return Locale.getDefault().getLanguage(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + return LocaleList.getDefault().get(0).getLanguage(); + } else { + return Locale.getDefault().getLanguage(); + } } public static String getCurrentLanguageCode() { - return Locale.getDefault().toString(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + return LocaleList.getDefault().get(0).toString(); + } else { + return Locale.getDefault().toString(); + } } public static String getDeviceModel() { From ac4e685a359c7d07498e7a35413f26d6c094db3c Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Wed, 20 Jul 2022 11:21:45 +0800 Subject: [PATCH 031/111] [ci skip][AUTO]: Automated code generating update: 6cb7a5b0ed1bdc2ced3964086975e5241c93a795 (#12062) (#12081) Co-authored-by: cocos-robot --- .../cocos/bindings/auto/jsb_assets_auto.cpp | 60 +++++++++---------- .../cocos/bindings/auto/jsb_render_auto.cpp | 2 + 2 files changed, 32 insertions(+), 30 deletions(-) diff --git a/native/cocos/bindings/auto/jsb_assets_auto.cpp b/native/cocos/bindings/auto/jsb_assets_auto.cpp index d31a313921..7d8a6f69e3 100644 --- a/native/cocos/bindings/auto/jsb_assets_auto.cpp +++ b/native/cocos/bindings/auto/jsb_assets_auto.cpp @@ -15428,7 +15428,7 @@ static bool js_assets_TextureCube_setImage(se::State& s) // NOLINT(readability-i size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 1) { - HolderType arg0 = {}; + HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); cobj->setImage(arg0.value()); @@ -15539,34 +15539,6 @@ static bool js_assets_TextureCube_fromTexture2DArray_static(se::State& s) // NOL } SE_BIND_FUNC(js_assets_TextureCube_fromTexture2DArray_static) -static bool js_assets_TextureCube_get_isRGBE(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - if (nullptr == cobj) return true; - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->isRGBE, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->isRGBE, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_assets_TextureCube_get_isRGBE) - -static bool js_assets_TextureCube_set_isRGBE(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->isRGBE, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_assets_TextureCube_set_isRGBE) - static bool js_assets_TextureCube_get__mipmapMode(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -15595,6 +15567,34 @@ static bool js_assets_TextureCube_set__mipmapMode(se::State& s) // NOLINT(readab } SE_BIND_PROP_SET(js_assets_TextureCube_set__mipmapMode) +static bool js_assets_TextureCube_get_isRGBE(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->isRGBE, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->isRGBE, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_assets_TextureCube_get_isRGBE) + +static bool js_assets_TextureCube_set_isRGBE(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->isRGBE, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_assets_TextureCube_set_isRGBE) + SE_DECLARE_FINALIZE_FUNC(js_cc_TextureCube_finalize) static bool js_assets_TextureCube_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c @@ -15618,8 +15618,8 @@ bool js_register_assets_TextureCube(se::Object* obj) // NOLINT(readability-ident #if CC_DEBUG cls->defineStaticProperty("isJSBClass", _SE(js_assets_getter_return_true), nullptr); #endif - cls->defineProperty("isRGBE", _SE(js_assets_TextureCube_get_isRGBE), _SE(js_assets_TextureCube_set_isRGBE)); cls->defineProperty("_mipmapMode", _SE(js_assets_TextureCube_get__mipmapMode), _SE(js_assets_TextureCube_set__mipmapMode)); + cls->defineProperty("isRGBE", _SE(js_assets_TextureCube_get_isRGBE), _SE(js_assets_TextureCube_set_isRGBE)); cls->defineProperty("mipmapAtlas", _SE(js_assets_TextureCube_getMipmapAtlas_asGetter), _SE(js_assets_TextureCube_setMipmapAtlas_asSetter)); cls->defineProperty("image", _SE(js_assets_TextureCube_getImage_asGetter), _SE(js_assets_TextureCube_setImage_asSetter)); cls->defineProperty("mipmaps", _SE(js_assets_TextureCube_getMipmaps_asGetter), _SE(js_assets_TextureCube_setMipmaps_asSetter)); diff --git a/native/cocos/bindings/auto/jsb_render_auto.cpp b/native/cocos/bindings/auto/jsb_render_auto.cpp index b8cd75f1e9..e14be9e157 100644 --- a/native/cocos/bindings/auto/jsb_render_auto.cpp +++ b/native/cocos/bindings/auto/jsb_render_auto.cpp @@ -9,6 +9,8 @@ #include "cocos/renderer/pipeline/custom/LayoutGraphJsb.h" #include "cocos/renderer/pipeline/custom/RenderCommonJsb.h" #include "cocos/renderer/pipeline/custom/RenderGraphJsb.h" +#include "cocos/renderer/pipeline/GeometryRenderer.h" +#include "cocos/renderer/pipeline/GlobalDescriptorSetManager.h" #ifndef JSB_ALLOC #define JSB_ALLOC(kls, ...) new (std::nothrow) kls(__VA_ARGS__) From cae515bd175d092d9c632db749408373d4170949 Mon Sep 17 00:00:00 2001 From: yangchao <1162485779@qq.com> Date: Wed, 20 Jul 2022 13:36:21 +0800 Subject: [PATCH 032/111] update external-config.json (#12084) --- native/external-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/external-config.json b/native/external-config.json index 57ba479f82..682ddb16f6 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3d-gfx-126" + "checkout": "v3d-gfx-127" } } From 8ef9c6b12d64d8e03d5628b720e4e0ca446bf453 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Wed, 20 Jul 2022 14:36:30 +0800 Subject: [PATCH 033/111] reduce log (#12092) --- native/tools/bindings-generator/generator.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/native/tools/bindings-generator/generator.py b/native/tools/bindings-generator/generator.py index 8467a14942..61bb01c1bc 100755 --- a/native/tools/bindings-generator/generator.py +++ b/native/tools/bindings-generator/generator.py @@ -355,8 +355,7 @@ def native_name_from_type(ntype, underlying=False): decl = ntype.get_declaration() etype = ntype.element_type esize = ntype.element_count - logger.info("found a const array: " + - str(etype.spelling) + "[" + str(esize) + "], treat as std::array<,"+ str(esize)+">") + # logger.info("found a const array: " + str(etype.spelling) + "[" + str(esize) + "], treat as std::array<,"+ str(esize)+">") # return "decltype(" + str(etype.spelling) + " _[" + str(esize) + "])" return "std::array<%s, %s>" % (etype.spelling, esize) else: @@ -2167,7 +2166,7 @@ class Generator(object): if len(parts) > 1: nn = parts.pop() return self.scriptname_from_native("::".join(parts)+"::", nn) - logger.error("The namespace (%s), '%s' conversion wasn't set in 'ns_map' section of the conversions.yaml" % (namespace_class_name, namespace_name)) + # logger.error("The namespace (%s), '%s' conversion wasn't set in 'ns_map' section of the conversions.yaml" % (namespace_class_name, namespace_name)) return "nowhere" else: return namespace_class_name.replace("*", "").replace("const ", "") From 71e5e3d3455ac0aa54f9200551153f468433dd58 Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Wed, 20 Jul 2022 14:37:14 +0800 Subject: [PATCH 034/111] fix impl.ts typo & doc refine (#12091) --- cocos/native-binding/impl.ts | 2 +- cocos/native-binding/index.ts | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index 2e76019e99..6cdb99890c 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -3,7 +3,7 @@ const globalJsb = globalThis.jsb ?? {}; export const native = { DownloaderHints: globalJsb.DownloaderHints, Downloader: globalJsb.Downloader, - zipUtils: globalJsb.ZipUtils, + zipUtils: globalJsb.zipUtils, fileUtils: globalJsb.fileUtils, DebugRenderer: globalJsb.DebugRenderer, }; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index 629c15dec2..f920bde7a6 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -61,6 +61,7 @@ export declare namespace native { * @example * ```ts * let downloader = new native.Downloader(); // create a Downloader object by default constructor + * ``` */ constructor(); @@ -75,6 +76,7 @@ export declare namespace native { * tempFileNameSuffix: ".tmp" * }; * let downloader = new native.Downloader(hints); // create a Downloader object with DownloaderHints + * ``` */ constructor (hints: DownloaderHints); @@ -88,6 +90,7 @@ export declare namespace native { * @example * ```ts * let task = downloader.createDownloadTask('https://example.com/exampleFile.zip', native.fileUtils.getWritablePath()); + * ``` */ createDownloadTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; @@ -101,6 +104,7 @@ export declare namespace native { * downloader.onSuccess = (task) => { * console.log('Success!'); // call when task download success * }; + * ``` */ onSuccess: (task: DownloaderTask) => void | undefined; @@ -118,6 +122,7 @@ export declare namespace native { * console.log(bytesReceived, totalBytesReceived); // download data info * console.log(totalBytesReceived / totalBytesExpected * 100).toFixed(1) + '%'); // progress prompt * }; + * ``` */ onProgress: (task: DownloaderTask, bytesReceived: number, totalBytesReceived: number, totalBytesExpected: number) => void | undefined; @@ -148,6 +153,7 @@ export declare namespace native { * @example * ```ts * let task = downloader.createDownloadFileTask('https://example.com/exampleFile.zip', native.fileUtils.getWritablePath()); + * ``` */ createDownloadFileTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; @@ -162,6 +168,7 @@ export declare namespace native { * downloader.setOnFileTaskSuccess((task)=>{ * console.log('Success!'); // call when task download success * }); + * ``` */ setOnFileTaskSuccess (onSucceed: (task: DownloaderTask) => void): void; @@ -177,6 +184,7 @@ export declare namespace native { * console.log(bytesReceived, totalBytesReceived); // download data info * console.log(totalBytesReceived / totalBytesExpected * 100).toFixed(1) + '%'); // progress prompt * }); + * ``` */ setOnTaskProgress (onProgress: (task: DownloaderTask, bytesReceived: number, totalBytesReceived: number, totalBytesExpected: number) => void): void; @@ -191,6 +199,7 @@ export declare namespace native { * downloader.setOnTaskError((task, errorCode, errorCodeInternal, errorStr)=>{ * console.log('Error:', errorStr); * }); + * ``` */ setOnTaskError (onError: (task: DownloaderTask, errorCode: number, errorCodeInternal: number, errorStr: string) => void): void; } From 68a99727296e4512e84878e300314bd6fb282fa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Wed, 20 Jul 2022 15:30:16 +0800 Subject: [PATCH 035/111] update readme (#12095) --- native/tools/bindings-generator/README.md | 33 +++++---------------- native/tools/tojs/README.mdown | 36 +++++------------------ 2 files changed, 14 insertions(+), 55 deletions(-) diff --git a/native/tools/bindings-generator/README.md b/native/tools/bindings-generator/README.md index 23d9eb13d5..b335a2c1cb 100644 --- a/native/tools/bindings-generator/README.md +++ b/native/tools/bindings-generator/README.md @@ -1,12 +1,12 @@ # What's new * Add a prebuilt libclang 12.0 in `libclang/`for linux, mac and windows. -* If you want use the prebuilt libclang 12.0 work with Android NDK, then `only the NDK r21 (or higher version) can work corrently` with it. +* If you want use the prebuilt libclang 12.0 work with Android NDK, then `only the NDK r21 can work corrently` with it. # Requirements -* python2.7 or 3.x (64-bit) -* py-yaml -* cheetah or cheetah3 (depend on your python version) +* python 3.x (64-bit) +* py-yaml version 5.4.1 +* cheetah3 * libclang binary files # Usage @@ -47,8 +47,8 @@ Included in this repository is a simple test. Use this to confirm the generator * Install python dependices by pip. ```bash - sudo easy_install pip - sudo pip install PyYAML Cheetah + sudo easy_install pip3 + sudo pip3 install PyYAML==5.4.1 Cheetah3 ``` * Download NDK r21 from [google](https://developer.android.com/ndk/downloads/index.html) @@ -58,31 +58,12 @@ Included in this repository is a simple test. Use this to confirm the generator export NDK_ROOT=/path/to/android-ndk-r21 ./test.sh ``` - -### Ubuntu Linux 12.04 64bit -* Install python - ```bash - sudo apt-get install python2.7 - ``` -* Install python dependices by pip. - ```bash - sudo apt-get install python-pip - sudo pip install PyYAML Cheetah - ``` -* Download NDK r21 from [google](https://developer.android.com/ndk/downloads/index.html) -* If you are using python installed from other way, copy user.cfg.sample and rename it as `user.cfg` then set the absolute path to python `PYTHON_BIN` in `user.cfg` -* Run follow command, it will generate a `userconf.ini`, and check the values in it if it occorus any error. - ```bash - export NDK_ROOT=/path/to/android-ndk-r21 - ./test.sh - ``` - ### Windows 7 64bit * Download python3 (`64bit`) from (https://www.python.org). * Add the installed path of python (e.g. C:\Python39) to PATH environment variable, if not already added in the installer. * Install python dependices by pip. ```bash - pip install PyYAML Cheetah3 + python -m pip install PyYAML==5.4.1 Cheetah3 ``` * Download NDK r21 or above from [google](https://developer.android.com/ndk/downloads/index.html) * Set the environment variables (`PYTHON_ROOT` and `NDK_ROOT`) or just them in `test.bat`. diff --git a/native/tools/tojs/README.mdown b/native/tools/tojs/README.mdown index 2e51b6e901..860d2abfb4 100644 --- a/native/tools/tojs/README.mdown +++ b/native/tools/tojs/README.mdown @@ -4,7 +4,7 @@ How to Use bindings-generator On Windows: ------------ -* Make sure you have installed `android-ndk-r22`. +* Make sure you have installed `android-ndk-r21`. * Download and install python3.6+ (64bit) from ( ).(higher than python3.6) * Add the installed path of python (e.g. C:\Python310) to windows environment variable named 'PATH'. * Execute the following command from the command processor to install **PyYAML** and **Cheetah**: @@ -14,52 +14,30 @@ On Windows: ``` * Set environment variables (`NDK_ROOT`) and `PYTHON_BIN` -* Go to "cocos2d-x/tools/tojs" folder, and run "genbindings.py". The generated codes will be under "cocos\bindings\auto". +* Go to "native/tools/tojs" folder, and run "genbindings.py". The generated codes will be under "cocos\bindings\auto". On MAC: ---------- -* The OSX 10.10 has a built-in python2.7 and if your os don't have python2.7 then use [Homebrew](http://brew.sh/) to install the python and use pip install the python dependencies. +* The macOS since 12.3 has a built-in python3, and if your os don't have python3 then use [Homebrew](http://brew.sh/) to install the python and use pip install the python dependencies.
-	brew install python
+	brew install python3
 
* Install python dependices by pip.
-    sudo easy_install pip
-    sudo pip install PyYAML
-	sudo pip install Cheetah
+   python -m pip install PyYAML==5.4.1 Cheetah3
 
-* Download NDK r16 or later from [Android Ndk](https://developer.android.com/ndk/downloads/index.html) +* Download NDK r21 or later from [Android Ndk](https://developer.android.com/ndk/downloads/index.html) * Run
-	export NDK_ROOT=/path/to/android-ndk-r16
+	export NDK_ROOT=/path/to/android-ndk-r21
     ./genbindings.py
 
-On Ubuntu Linux 12.04 64bit ------------- - -* Install python -
-	sudo apt-get install python2.7
-
-* Install python dependices by pip. -
-	sudo apt-get install python-pip
-	sudo pip install PyYAML
-	sudo pip install Cheetah
-
-* Download NDK r16 or later from [Android Ndk](https://developer.android.com/ndk/downloads/index.html) -* Go to "cocos2d-x/tools/tojs", Run -
-	export NDK_ROOT=/path/to/android-ndk-r16
-    ./genbindings.py
-
- # Steps of establishing associations by JSB between framework and native ## Create ts and cpp classes From 5b9b98f759b1300440183b357bd3543d14ac4165 Mon Sep 17 00:00:00 2001 From: timlyeee <43355299+timlyeee@users.noreply.github.com> Date: Wed, 20 Jul 2022 15:32:15 +0800 Subject: [PATCH 036/111] V3.6.0 reflection refact (#12096) * Move reflection and bridge implementation from jsb to native * remove from jsb.d.ts * remove jss --- @types/jsb.d.ts | 51 ------- cocos/native-binding/impl.ts | 128 ++++++++++++++++++ cocos/native-binding/index.ts | 78 ++++++++++- platforms/native/engine/index.js | 3 - platforms/native/engine/jsb-bridge-wrapper.js | 88 ------------ platforms/native/engine/jsb-bridge.js | 43 ------ platforms/native/engine/jsb-reflection.js | 45 ------ 7 files changed, 204 insertions(+), 232 deletions(-) delete mode 100644 platforms/native/engine/jsb-bridge-wrapper.js delete mode 100644 platforms/native/engine/jsb-bridge.js delete mode 100644 platforms/native/engine/jsb-reflection.js diff --git a/@types/jsb.d.ts b/@types/jsb.d.ts index 588f5e757c..f8c0a5a4f5 100644 --- a/@types/jsb.d.ts +++ b/@types/jsb.d.ts @@ -148,57 +148,6 @@ declare namespace jsb { export function getOriginalPCMBuffer (url: string, channelID: number): ArrayBuffer | undefined; } - export namespace reflection{ - /** - * https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html - * call OBJC/Java static methods - * - * @param className - * @param methodName - * @param methodSignature - * @param parameters - */ - export function callStaticMethod (className: string, methodName: string, methodSignature: string, ...parameters:any): any; - } - export namespace bridge{ - /** - * send to native with at least one argument. - */ - export function sendToNative(arg0: string, arg1?: string): void; - /** - * save your own callback controller with a js function, - * use jsb.bridge.onNative = (arg0: String, arg1: String)=>{...} - * @param args : received from native - */ - export function onNative(arg0: string, arg1?: string|null): void; - } - /** - * Listener for jsbBridgeWrapper's event. - * It takes one argument as string which is transferred by jsbBridge. - */ - export type OnNativeEventListener = (arg: string) => void; - export namespace jsbBridgeWrapper { - /** If there's no event registered, the wrapper will create one */ - export function addNativeEventListener(eventName: string, listener: OnNativeEventListener); - /** - * Dispatch the event registered on Objective-C, Java etc. - * No return value in JS to tell you if it works. - */ - export function dispatchEventToNative(eventName: string, arg?: string); - /** - * Remove all listeners relative. - */ - export function removeAllListenersForEvent(eventName: string); - /** - * Remove the listener specified - */ - export function removeNativeEventListener(eventName: string, listener: OnNativeEventListener); - /** - * Remove all events, use it carefully! - */ - export function removeAllListeners(); - } - export interface ManifestAsset { md5: string; path: string; diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index 6cdb99890c..3ab2feb497 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -1,3 +1,128 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://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 { legacyCC } from "../core/global-exports"; + +Object.defineProperty(globalThis.jsb, 'reflection', { + get () { + if (globalThis.jsb.__bridge !== undefined) return globalThis.jsb.__bridge; + if (window.JavascriptJavaBridge && (legacyCC.sys.os === legacyCC.sys.OS.ANDROID || legacyCC.sys.os === legacyCC.sys.OS.OHOS)) { + globalThis.jsb.__bridge = new JavascriptJavaBridge(); + } else if (window.JavaScriptObjCBridge && (legacyCC.sys.os === legacyCC.sys.OS.IOS || legacyCC.sys.os === legacyCC.sys.OS.OSX)) { + globalThis.jsb.__bridge = new JavaScriptObjCBridge(); + } else { + globalThis.jsb.__bridge = null; + } + return globalThis.jsb.__bridge; + }, + enumerable: true, + configurable: true, + set (value) { + globalThis.jsb.__bridge = value; + }, +}); +Object.defineProperty(globalThis.jsb, 'bridge', { + get () { + if (globalThis.jsb.__ccbridge !== undefined) return globalThis.jsb.__ccbridge; + if (window.ScriptNativeBridge && legacyCC.sys.os === legacyCC.sys.OS.ANDROID || legacyCC.sys.os === legacyCC.sys.OS.IOS || legacyCC.sys.os === legacyCC.sys.OS.OSX || legacyCC.sys.os === legacyCC.sys.OS.OHOS) { + globalThis.jsb.__ccbridge = new ScriptNativeBridge(); + } else { + globalThis.jsb.__ccbridge = null; + } + return globalThis.jsb.__ccbridge; + }, + enumerable: true, + configurable: true, + set (value) { + globalThis.jsb.__ccbridge = value; + }, +}); +const JsbBridgeWrapper = { + eventMap: new Map(), + addNativeEventListener (eventName, listener) { + if (!this.eventMap.get(eventName)) { + this.eventMap.set(eventName, []); + } + const arr = this.eventMap.get(eventName); + if (!arr.find(listener)) { + arr.push(listener); + } + }, + dispatchEventToNative (eventName, arg) { + jsb.bridge.sendToNative(eventName, arg); + }, + removeAllListenersForEvent (eventName) { + return this.eventMap.delete(eventName); + }, + removeNativeEventListener (eventName, listener) { + const arr = this.eventMap.get(eventName); + if (!arr) { + return false; + } + for (let i = 0, l = arr.length; i < l; i++) { + if (arr[i] === listener) { + arr.splice(i, 1); + return true; + } + } + return true; + }, + removeAllListeners () { + this.eventMap.clear(); + }, + triggerEvent (eventName, arg) { + const arr = this.eventMap.get(eventName); + if (!arr) { + console.error(`${eventName} does not exist`); + return; + } + arr.map((listener) => listener.call(null, arg)); + }, +}; + +Object.defineProperty(globalThis.jsb, 'jsbBridgeWrapper', { + get () { + if (globalThis.jsb.__JsbBridgeWrapper !== undefined) return globalThis.jsb.__JsbBridgeWrapper; + + if (window.ScriptNativeBridge && legacyCC.sys.os === legacyCC.sys.OS.ANDROID || legacyCC.sys.os === legacyCC.sys.OS.IOS || legacyCC.sys.os === legacyCC.sys.OS.OSX || legacyCC.sys.os === legacyCC.sys.OS.OHOS) { + globalThis.jsb.__JsbBridgeWrapper = JsbBridgeWrapper; + globalThis.jsb.bridge.onNative = (methodName, arg1) => { + console.log(`Trigger event: ${methodName} with argeter: ${arg1}`); + globalThis.jsb.__JsbBridgeWrapper.triggerEvent(methodName, arg1); + }; + } else { + globalThis.jsb.__JsbBridgeWrapper = null; + } + return globalThis.jsb.__JsbBridgeWrapper; + }, + enumerable: true, + configurable: true, + set (value) { + globalThis.jsb.__JsbBridgeWrapper = value; + }, +}); + const globalJsb = globalThis.jsb ?? {}; export const native = { @@ -6,4 +131,7 @@ export const native = { zipUtils: globalJsb.zipUtils, fileUtils: globalJsb.fileUtils, DebugRenderer: globalJsb.DebugRenderer, + reflection: globalJsb.reflection, + bridge: globalJsb.bridge, + jsbBridgeWrapper: globalJsb.jsbBridgeWrapper, }; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index f920bde7a6..c141164ec8 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -1,3 +1,27 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://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. + */ /* eslint-disable @typescript-eslint/no-namespace */ import type { Color } from '../core/math/color'; @@ -847,7 +871,7 @@ export declare namespace native { * @en DebugRenderer class used to output debug text on screen * @zh 用于输出屏幕调试文字的调试渲染器类 */ - export class DebugRenderer { + export class DebugRenderer { /** * @en get DebugRenderer instance * @zh 获取调试渲染器实例 @@ -863,5 +887,55 @@ export declare namespace native { * @param info @en the output text information @zh 输出的文本属性 */ addText(text:string, screenPos: Vec2, info?: DebugTextInfo): void; - } + } + export namespace reflection{ + /** + * https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html + * call OBJC/Java static methods + * + * @param className + * @param methodName + * @param methodSignature + * @param parameters + */ + export function callStaticMethod (className: string, methodName: string, methodSignature: string, ...parameters:any): any; + } + export namespace bridge{ + /** + * send to native with at least one argument. + */ + export function sendToNative(arg0: string, arg1?: string): void; + /** + * save your own callback controller with a js function, + * use jsb.bridge.onNative = (arg0: String, arg1: String)=>{...} + * @param args : received from native + */ + export function onNative(arg0: string, arg1?: string|null): void; + } + /** + * Listener for jsbBridgeWrapper's event. + * It takes one argument as string which is transferred by jsbBridge. + */ + export type OnNativeEventListener = (arg: string) => void; + export namespace jsbBridgeWrapper { + /** If there's no event registered, the wrapper will create one */ + export function addNativeEventListener(eventName: string, listener: OnNativeEventListener); + /** + * Dispatch the event registered on Objective-C, Java etc. + * No return value in JS to tell you if it works. + */ + export function dispatchEventToNative(eventName: string, arg?: string); + /** + * Remove all listeners relative. + */ + export function removeAllListenersForEvent(eventName: string); + /** + * Remove the listener specified + */ + export function removeNativeEventListener(eventName: string, listener: OnNativeEventListener); + /** + * Remove all events, use it carefully! + */ + export function removeAllListeners(); + } } diff --git a/platforms/native/engine/index.js b/platforms/native/engine/index.js index 7af523b66b..1987139121 100644 --- a/platforms/native/engine/index.js +++ b/platforms/native/engine/index.js @@ -22,9 +22,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -require('./jsb-reflection.js'); -require('./jsb-bridge.js'); -require('./jsb-bridge-wrapper.js'); require('./jsb-assets-manager.js'); require('./jsb-game.js'); diff --git a/platforms/native/engine/jsb-bridge-wrapper.js b/platforms/native/engine/jsb-bridge-wrapper.js deleted file mode 100644 index 6a71e32f5c..0000000000 --- a/platforms/native/engine/jsb-bridge-wrapper.js +++ /dev/null @@ -1,88 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - https://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. - ****************************************************************************/ -const JsbBridgeWrapper = { - eventMap: new Map(), - addNativeEventListener (eventName, listener) { - if (!this.eventMap.get(eventName)) { - this.eventMap.set(eventName, []); - } - const arr = this.eventMap.get(eventName); - if (!arr.find(listener)) { - arr.push(listener); - } - }, - dispatchEventToNative (eventName, arg) { - jsb.bridge.sendToNative(eventName, arg); - }, - removeAllListenersForEvent (eventName) { - return this.eventMap.delete(eventName); - }, - removeNativeEventListener (eventName, listener) { - const arr = this.eventMap.get(eventName); - if (!arr) { - return false; - } - for (let i = 0, l = arr.length; i < l; i++) { - if (arr[i] === listener) { - arr.splice(i, 1); - return true; - } - } - return true; - }, - removeAllListeners () { - this.eventMap.clear(); - }, - triggerEvent (eventName, arg) { - const arr = this.eventMap.get(eventName); - if (!arr) { - console.error(`${eventName} does not exist`); - return; - } - arr.map((listener) => listener.call(null, arg)); - }, -}; - -Object.defineProperty(jsb, 'jsbBridgeWrapper', { - get () { - if (jsb.__JsbBridgeWrapper !== undefined) return jsb.__JsbBridgeWrapper; - - if (window.ScriptNativeBridge && cc.sys.os === cc.sys.OS.ANDROID || cc.sys.os === cc.sys.OS.IOS || cc.sys.os === cc.sys.OS.OSX || cc.sys.os === cc.sys.OS.OHOS) { - jsb.__JsbBridgeWrapper = JsbBridgeWrapper; - jsb.bridge.onNative = (methodName, arg1) => { - console.log(`Trigger event: ${methodName} with argeter: ${arg1}`); - jsb.__JsbBridgeWrapper.triggerEvent(methodName, arg1); - }; - } else { - jsb.__JsbBridgeWrapper = null; - } - return jsb.__JsbBridgeWrapper; - }, - enumerable: true, - configurable: true, - set (value) { - jsb.__JsbBridgeWrapper = value; - }, -}); diff --git a/platforms/native/engine/jsb-bridge.js b/platforms/native/engine/jsb-bridge.js deleted file mode 100644 index 2f9643ad52..0000000000 --- a/platforms/native/engine/jsb-bridge.js +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - https://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. - ****************************************************************************/ - -// JS to Native bridges -// set to lazy -Object.defineProperty(jsb, 'bridge', { - get () { - if (jsb.__ccbridge !== undefined) return jsb.__ccbridge; - if (window.ScriptNativeBridge && cc.sys.os === cc.sys.OS.ANDROID || cc.sys.os === cc.sys.OS.IOS || cc.sys.os === cc.sys.OS.OSX || cc.sys.os === cc.sys.OS.OHOS) { - jsb.__ccbridge = new ScriptNativeBridge(); - } else { - jsb.__ccbridge = null; - } - return jsb.__ccbridge; - }, - enumerable: true, - configurable: true, - set (value) { - jsb.__ccbridge = value; - }, -}); diff --git a/platforms/native/engine/jsb-reflection.js b/platforms/native/engine/jsb-reflection.js deleted file mode 100644 index c68a3940cd..0000000000 --- a/platforms/native/engine/jsb-reflection.js +++ /dev/null @@ -1,45 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - https://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. - ****************************************************************************/ - -// JS to Native bridges -// set to lazy -Object.defineProperty(jsb, 'reflection', { - get () { - if (jsb.__bridge !== undefined) return jsb.__bridge; - if (window.JavascriptJavaBridge && (cc.sys.os === cc.sys.OS.ANDROID || cc.sys.os === cc.sys.OS.OHOS)) { - jsb.__bridge = new JavascriptJavaBridge(); - } else if (window.JavaScriptObjCBridge && (cc.sys.os === cc.sys.OS.IOS || cc.sys.os === cc.sys.OS.OSX)) { - jsb.__bridge = new JavaScriptObjCBridge(); - } else { - jsb.__bridge = null; - } - return jsb.__bridge; - }, - enumerable: true, - configurable: true, - set (value) { - jsb.__bridge = value; - }, -}); From 3c264e53ac0b0fc24cb8f2bc14018a03063b8e56 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 20 Jul 2022 17:02:17 +0800 Subject: [PATCH 037/111] Revert "V3.6.0 reflection refact (#12096)" (#12102) This reverts commit 5b9b98f759b1300440183b357bd3543d14ac4165. --- @types/jsb.d.ts | 51 +++++++ cocos/native-binding/impl.ts | 128 ------------------ cocos/native-binding/index.ts | 78 +---------- platforms/native/engine/index.js | 3 + platforms/native/engine/jsb-bridge-wrapper.js | 88 ++++++++++++ platforms/native/engine/jsb-bridge.js | 43 ++++++ platforms/native/engine/jsb-reflection.js | 45 ++++++ 7 files changed, 232 insertions(+), 204 deletions(-) create mode 100644 platforms/native/engine/jsb-bridge-wrapper.js create mode 100644 platforms/native/engine/jsb-bridge.js create mode 100644 platforms/native/engine/jsb-reflection.js diff --git a/@types/jsb.d.ts b/@types/jsb.d.ts index f8c0a5a4f5..588f5e757c 100644 --- a/@types/jsb.d.ts +++ b/@types/jsb.d.ts @@ -148,6 +148,57 @@ declare namespace jsb { export function getOriginalPCMBuffer (url: string, channelID: number): ArrayBuffer | undefined; } + export namespace reflection{ + /** + * https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html + * call OBJC/Java static methods + * + * @param className + * @param methodName + * @param methodSignature + * @param parameters + */ + export function callStaticMethod (className: string, methodName: string, methodSignature: string, ...parameters:any): any; + } + export namespace bridge{ + /** + * send to native with at least one argument. + */ + export function sendToNative(arg0: string, arg1?: string): void; + /** + * save your own callback controller with a js function, + * use jsb.bridge.onNative = (arg0: String, arg1: String)=>{...} + * @param args : received from native + */ + export function onNative(arg0: string, arg1?: string|null): void; + } + /** + * Listener for jsbBridgeWrapper's event. + * It takes one argument as string which is transferred by jsbBridge. + */ + export type OnNativeEventListener = (arg: string) => void; + export namespace jsbBridgeWrapper { + /** If there's no event registered, the wrapper will create one */ + export function addNativeEventListener(eventName: string, listener: OnNativeEventListener); + /** + * Dispatch the event registered on Objective-C, Java etc. + * No return value in JS to tell you if it works. + */ + export function dispatchEventToNative(eventName: string, arg?: string); + /** + * Remove all listeners relative. + */ + export function removeAllListenersForEvent(eventName: string); + /** + * Remove the listener specified + */ + export function removeNativeEventListener(eventName: string, listener: OnNativeEventListener); + /** + * Remove all events, use it carefully! + */ + export function removeAllListeners(); + } + export interface ManifestAsset { md5: string; path: string; diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index 3ab2feb497..6cdb99890c 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -1,128 +1,3 @@ -/* - Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. - - https://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 { legacyCC } from "../core/global-exports"; - -Object.defineProperty(globalThis.jsb, 'reflection', { - get () { - if (globalThis.jsb.__bridge !== undefined) return globalThis.jsb.__bridge; - if (window.JavascriptJavaBridge && (legacyCC.sys.os === legacyCC.sys.OS.ANDROID || legacyCC.sys.os === legacyCC.sys.OS.OHOS)) { - globalThis.jsb.__bridge = new JavascriptJavaBridge(); - } else if (window.JavaScriptObjCBridge && (legacyCC.sys.os === legacyCC.sys.OS.IOS || legacyCC.sys.os === legacyCC.sys.OS.OSX)) { - globalThis.jsb.__bridge = new JavaScriptObjCBridge(); - } else { - globalThis.jsb.__bridge = null; - } - return globalThis.jsb.__bridge; - }, - enumerable: true, - configurable: true, - set (value) { - globalThis.jsb.__bridge = value; - }, -}); -Object.defineProperty(globalThis.jsb, 'bridge', { - get () { - if (globalThis.jsb.__ccbridge !== undefined) return globalThis.jsb.__ccbridge; - if (window.ScriptNativeBridge && legacyCC.sys.os === legacyCC.sys.OS.ANDROID || legacyCC.sys.os === legacyCC.sys.OS.IOS || legacyCC.sys.os === legacyCC.sys.OS.OSX || legacyCC.sys.os === legacyCC.sys.OS.OHOS) { - globalThis.jsb.__ccbridge = new ScriptNativeBridge(); - } else { - globalThis.jsb.__ccbridge = null; - } - return globalThis.jsb.__ccbridge; - }, - enumerable: true, - configurable: true, - set (value) { - globalThis.jsb.__ccbridge = value; - }, -}); -const JsbBridgeWrapper = { - eventMap: new Map(), - addNativeEventListener (eventName, listener) { - if (!this.eventMap.get(eventName)) { - this.eventMap.set(eventName, []); - } - const arr = this.eventMap.get(eventName); - if (!arr.find(listener)) { - arr.push(listener); - } - }, - dispatchEventToNative (eventName, arg) { - jsb.bridge.sendToNative(eventName, arg); - }, - removeAllListenersForEvent (eventName) { - return this.eventMap.delete(eventName); - }, - removeNativeEventListener (eventName, listener) { - const arr = this.eventMap.get(eventName); - if (!arr) { - return false; - } - for (let i = 0, l = arr.length; i < l; i++) { - if (arr[i] === listener) { - arr.splice(i, 1); - return true; - } - } - return true; - }, - removeAllListeners () { - this.eventMap.clear(); - }, - triggerEvent (eventName, arg) { - const arr = this.eventMap.get(eventName); - if (!arr) { - console.error(`${eventName} does not exist`); - return; - } - arr.map((listener) => listener.call(null, arg)); - }, -}; - -Object.defineProperty(globalThis.jsb, 'jsbBridgeWrapper', { - get () { - if (globalThis.jsb.__JsbBridgeWrapper !== undefined) return globalThis.jsb.__JsbBridgeWrapper; - - if (window.ScriptNativeBridge && legacyCC.sys.os === legacyCC.sys.OS.ANDROID || legacyCC.sys.os === legacyCC.sys.OS.IOS || legacyCC.sys.os === legacyCC.sys.OS.OSX || legacyCC.sys.os === legacyCC.sys.OS.OHOS) { - globalThis.jsb.__JsbBridgeWrapper = JsbBridgeWrapper; - globalThis.jsb.bridge.onNative = (methodName, arg1) => { - console.log(`Trigger event: ${methodName} with argeter: ${arg1}`); - globalThis.jsb.__JsbBridgeWrapper.triggerEvent(methodName, arg1); - }; - } else { - globalThis.jsb.__JsbBridgeWrapper = null; - } - return globalThis.jsb.__JsbBridgeWrapper; - }, - enumerable: true, - configurable: true, - set (value) { - globalThis.jsb.__JsbBridgeWrapper = value; - }, -}); - const globalJsb = globalThis.jsb ?? {}; export const native = { @@ -131,7 +6,4 @@ export const native = { zipUtils: globalJsb.zipUtils, fileUtils: globalJsb.fileUtils, DebugRenderer: globalJsb.DebugRenderer, - reflection: globalJsb.reflection, - bridge: globalJsb.bridge, - jsbBridgeWrapper: globalJsb.jsbBridgeWrapper, }; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index c141164ec8..f920bde7a6 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -1,27 +1,3 @@ -/* - Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. - - https://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. - */ /* eslint-disable @typescript-eslint/no-namespace */ import type { Color } from '../core/math/color'; @@ -871,7 +847,7 @@ export declare namespace native { * @en DebugRenderer class used to output debug text on screen * @zh 用于输出屏幕调试文字的调试渲染器类 */ - export class DebugRenderer { + export class DebugRenderer { /** * @en get DebugRenderer instance * @zh 获取调试渲染器实例 @@ -887,55 +863,5 @@ export declare namespace native { * @param info @en the output text information @zh 输出的文本属性 */ addText(text:string, screenPos: Vec2, info?: DebugTextInfo): void; - } - export namespace reflection{ - /** - * https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html - * call OBJC/Java static methods - * - * @param className - * @param methodName - * @param methodSignature - * @param parameters - */ - export function callStaticMethod (className: string, methodName: string, methodSignature: string, ...parameters:any): any; - } - export namespace bridge{ - /** - * send to native with at least one argument. - */ - export function sendToNative(arg0: string, arg1?: string): void; - /** - * save your own callback controller with a js function, - * use jsb.bridge.onNative = (arg0: String, arg1: String)=>{...} - * @param args : received from native - */ - export function onNative(arg0: string, arg1?: string|null): void; - } - /** - * Listener for jsbBridgeWrapper's event. - * It takes one argument as string which is transferred by jsbBridge. - */ - export type OnNativeEventListener = (arg: string) => void; - export namespace jsbBridgeWrapper { - /** If there's no event registered, the wrapper will create one */ - export function addNativeEventListener(eventName: string, listener: OnNativeEventListener); - /** - * Dispatch the event registered on Objective-C, Java etc. - * No return value in JS to tell you if it works. - */ - export function dispatchEventToNative(eventName: string, arg?: string); - /** - * Remove all listeners relative. - */ - export function removeAllListenersForEvent(eventName: string); - /** - * Remove the listener specified - */ - export function removeNativeEventListener(eventName: string, listener: OnNativeEventListener); - /** - * Remove all events, use it carefully! - */ - export function removeAllListeners(); - } + } } diff --git a/platforms/native/engine/index.js b/platforms/native/engine/index.js index 1987139121..7af523b66b 100644 --- a/platforms/native/engine/index.js +++ b/platforms/native/engine/index.js @@ -22,6 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +require('./jsb-reflection.js'); +require('./jsb-bridge.js'); +require('./jsb-bridge-wrapper.js'); require('./jsb-assets-manager.js'); require('./jsb-game.js'); diff --git a/platforms/native/engine/jsb-bridge-wrapper.js b/platforms/native/engine/jsb-bridge-wrapper.js new file mode 100644 index 0000000000..6a71e32f5c --- /dev/null +++ b/platforms/native/engine/jsb-bridge-wrapper.js @@ -0,0 +1,88 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ +const JsbBridgeWrapper = { + eventMap: new Map(), + addNativeEventListener (eventName, listener) { + if (!this.eventMap.get(eventName)) { + this.eventMap.set(eventName, []); + } + const arr = this.eventMap.get(eventName); + if (!arr.find(listener)) { + arr.push(listener); + } + }, + dispatchEventToNative (eventName, arg) { + jsb.bridge.sendToNative(eventName, arg); + }, + removeAllListenersForEvent (eventName) { + return this.eventMap.delete(eventName); + }, + removeNativeEventListener (eventName, listener) { + const arr = this.eventMap.get(eventName); + if (!arr) { + return false; + } + for (let i = 0, l = arr.length; i < l; i++) { + if (arr[i] === listener) { + arr.splice(i, 1); + return true; + } + } + return true; + }, + removeAllListeners () { + this.eventMap.clear(); + }, + triggerEvent (eventName, arg) { + const arr = this.eventMap.get(eventName); + if (!arr) { + console.error(`${eventName} does not exist`); + return; + } + arr.map((listener) => listener.call(null, arg)); + }, +}; + +Object.defineProperty(jsb, 'jsbBridgeWrapper', { + get () { + if (jsb.__JsbBridgeWrapper !== undefined) return jsb.__JsbBridgeWrapper; + + if (window.ScriptNativeBridge && cc.sys.os === cc.sys.OS.ANDROID || cc.sys.os === cc.sys.OS.IOS || cc.sys.os === cc.sys.OS.OSX || cc.sys.os === cc.sys.OS.OHOS) { + jsb.__JsbBridgeWrapper = JsbBridgeWrapper; + jsb.bridge.onNative = (methodName, arg1) => { + console.log(`Trigger event: ${methodName} with argeter: ${arg1}`); + jsb.__JsbBridgeWrapper.triggerEvent(methodName, arg1); + }; + } else { + jsb.__JsbBridgeWrapper = null; + } + return jsb.__JsbBridgeWrapper; + }, + enumerable: true, + configurable: true, + set (value) { + jsb.__JsbBridgeWrapper = value; + }, +}); diff --git a/platforms/native/engine/jsb-bridge.js b/platforms/native/engine/jsb-bridge.js new file mode 100644 index 0000000000..2f9643ad52 --- /dev/null +++ b/platforms/native/engine/jsb-bridge.js @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + +// JS to Native bridges +// set to lazy +Object.defineProperty(jsb, 'bridge', { + get () { + if (jsb.__ccbridge !== undefined) return jsb.__ccbridge; + if (window.ScriptNativeBridge && cc.sys.os === cc.sys.OS.ANDROID || cc.sys.os === cc.sys.OS.IOS || cc.sys.os === cc.sys.OS.OSX || cc.sys.os === cc.sys.OS.OHOS) { + jsb.__ccbridge = new ScriptNativeBridge(); + } else { + jsb.__ccbridge = null; + } + return jsb.__ccbridge; + }, + enumerable: true, + configurable: true, + set (value) { + jsb.__ccbridge = value; + }, +}); diff --git a/platforms/native/engine/jsb-reflection.js b/platforms/native/engine/jsb-reflection.js new file mode 100644 index 0000000000..c68a3940cd --- /dev/null +++ b/platforms/native/engine/jsb-reflection.js @@ -0,0 +1,45 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + https://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. + ****************************************************************************/ + +// JS to Native bridges +// set to lazy +Object.defineProperty(jsb, 'reflection', { + get () { + if (jsb.__bridge !== undefined) return jsb.__bridge; + if (window.JavascriptJavaBridge && (cc.sys.os === cc.sys.OS.ANDROID || cc.sys.os === cc.sys.OS.OHOS)) { + jsb.__bridge = new JavascriptJavaBridge(); + } else if (window.JavaScriptObjCBridge && (cc.sys.os === cc.sys.OS.IOS || cc.sys.os === cc.sys.OS.OSX)) { + jsb.__bridge = new JavaScriptObjCBridge(); + } else { + jsb.__bridge = null; + } + return jsb.__bridge; + }, + enumerable: true, + configurable: true, + set (value) { + jsb.__bridge = value; + }, +}); From 197f0db3da5a8a49d02c28da9a6a40be4e6e3175 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=87=AF=E9=B9=8F?= <609075410@qq.com> Date: Wed, 20 Jul 2022 17:35:59 +0800 Subject: [PATCH 038/111] enable bullet instantiate in Editor (#12106) --- cocos/physics/bullet/instantiated.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/cocos/physics/bullet/instantiated.ts b/cocos/physics/bullet/instantiated.ts index 133297500f..b638e265d7 100644 --- a/cocos/physics/bullet/instantiated.ts +++ b/cocos/physics/bullet/instantiated.ts @@ -37,8 +37,6 @@ if (globalThis.BULLET) { bulletLibs = globalThis.BULLET; } -if (!physics.selector.runInEditor) bulletLibs = () => ({}); - interface instanceExt extends Bullet.instance { CACHE: any, BODY_CACHE_NAME: string, From b67bf824833d3043463ea47a8e3fb565d8c86a52 Mon Sep 17 00:00:00 2001 From: yangchao <1162485779@qq.com> Date: Wed, 20 Jul 2022 18:26:00 +0800 Subject: [PATCH 039/111] on server mode, use unix executeble file (#12103) Co-authored-by: bravetwo --- templates/cmake/apple.cmake | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/templates/cmake/apple.cmake b/templates/cmake/apple.cmake index a5f8aef4ad..966fb38845 100644 --- a/templates/cmake/apple.cmake +++ b/templates/cmake/apple.cmake @@ -112,6 +112,19 @@ macro(cc_mac_after_target target_name) target_include_directories(${target_name} PRIVATE ${CC_PROJECT_DIR}/../common/Classes ) +if(USE_SERVER_MODE) + if(EXISTS ${RES_DIR}/data/jsb-adapter) + set(bin_dir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}) + add_custom_target(copy_resource ALL + COMMAND ${CMAKE_COMMAND} -E echo "Copying resources to ${bin_dir}" + COMMAND ${CMAKE_COMMAND} -E make_directory ${bin_dir}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory "${RES_DIR}/data/" "${bin_dir}/Resources/" + COMMAND ${CMAKE_COMMAND} -E echo "Copying resources done!" + ) + add_dependencies(${target_name} copy_resource) + set_target_properties(copy_resource PROPERTIES FOLDER Utils) + endif() +else() set_target_properties(${target_name} PROPERTIES OSX_ARCHITECTURES "x86_64;arm64" XCODE_ATTRIBUTE_MACOS_DEPLOYMENT_TARGET "${TARGET_OSX_VERSION}" @@ -130,6 +143,7 @@ macro(cc_mac_after_target target_name) XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS "${CC_PROJECT_DIR}/entitlements.plist" ) endif() +endif() cc_common_after_target(${target_name}) endmacro() \ No newline at end of file From e7eeab93402822bf70b221644a707f9ef435a1c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Wed, 20 Jul 2022 19:02:41 +0800 Subject: [PATCH 040/111] 3.6 remove Mat4::transformVector for Vec3 (#12088) * use Vec3::transformMat4 to replace Mat4::transformVector --- native/cocos/math/Mat4.cpp | 15 ---- native/cocos/math/Mat4.h | 77 ------------------- native/cocos/math/Mat4.inl | 13 ---- native/cocos/math/Vec3.h | 10 ++- .../renderer/pipeline/GeometryRenderer.cpp | 72 ++++++++--------- native/tests/unit-test/src/math_mat4_test.cpp | 7 -- 6 files changed, 45 insertions(+), 149 deletions(-) diff --git a/native/cocos/math/Mat4.cpp b/native/cocos/math/Mat4.cpp index 7b4b0d3443..21040457ff 100644 --- a/native/cocos/math/Mat4.cpp +++ b/native/cocos/math/Mat4.cpp @@ -1003,21 +1003,6 @@ void Mat4::subtract(const Mat4 &m1, const Mat4 &m2, Mat4 *dst) { #endif } -void Mat4::transformVector(Vec3 *vector) const { - CC_ASSERT(vector); - transformVector(vector->x, vector->y, vector->z, 0.0F, vector); -} - -void Mat4::transformVector(const Vec3 &vector, Vec3 *dst) const { - transformVector(vector.x, vector.y, vector.z, 0.0F, dst); -} - -void Mat4::transformVector(float x, float y, float z, float w, Vec3 *dst) const { - CC_ASSERT(dst); - - MathUtil::transformVec4(m, x, y, z, w, reinterpret_cast(dst)); -} - void Mat4::transformVector(Vec4 *vector) const { CC_ASSERT(vector); transformVector(*vector, vector); diff --git a/native/cocos/math/Mat4.h b/native/cocos/math/Mat4.h index d42daa0334..474aac67b4 100644 --- a/native/cocos/math/Mat4.h +++ b/native/cocos/math/Mat4.h @@ -786,61 +786,6 @@ public: */ static void subtract(const Mat4 &m1, const Mat4 &m2, Mat4 *dst); - /** - * Transforms the specified point by this matrix. - * - * The result of the transformation is stored directly into point. - * - * @param point The point to transform and also a vector to hold the result in. - */ - inline void transformPoint(Vec3 *point) const { - CC_ASSERT(point); - transformVector(point->x, point->y, point->z, 1.0F, point); - } - - /** - * Transforms the specified point by this matrix, and stores - * the result in dst. - * - * @param point The point to transform. - * @param dst A vector to store the transformed point in. - */ - inline void transformPoint(const Vec3 &point, Vec3 *dst) const { - CC_ASSERT(dst); - transformVector(point.x, point.y, point.z, 1.0F, dst); - } - - /** - * Transforms the specified vector by this matrix by - * treating the fourth (w) coordinate as zero. - * - * The result of the transformation is stored directly into vector. - * - * @param vector The vector to transform and also a vector to hold the result in. - */ - void transformVector(Vec3 *vector) const; - - /** - * Transforms the specified vector by this matrix by - * treating the fourth (w) coordinate as zero, and stores the - * result in dst. - * - * @param vector The vector to transform. - * @param dst A vector to store the transformed vector in. - */ - void transformVector(const Vec3 &vector, Vec3 *dst) const; - - /** - * Transforms the specified vector by this matrix. - * - * @param x The vector x-coordinate to transform by. - * @param y The vector y-coordinate to transform by. - * @param z The vector z-coordinate to transform by. - * @param w The vector w-coordinate to transform by. - * @param dst A vector to store the transformed point in. - */ - void transformVector(float x, float y, float z, float w, Vec3 *dst) const; - /** * Transforms the specified vector by this matrix. * @@ -984,28 +929,6 @@ private: Mat4 *dst); }; -/** - * Transforms the given vector by the given matrix. - * - * Note: this treats the given vector as a vector and not as a point. - * - * @param v The vector to transform. - * @param m The matrix to transform by. - * @return This vector, after the transformation occurs. - */ -inline Vec3 &operator*=(Vec3 &v, const Mat4 &m); - -/** - * Transforms the given vector by the given matrix. - * - * Note: this treats the given vector as a vector and not as a point. - * - * @param m The matrix to transform by. - * @param v The vector to transform. - * @return The resulting transformed vector. - */ -inline const Vec3 operator*(const Mat4 &m, const Vec3 &v); - /** * Transforms the given vector by the given matrix. * diff --git a/native/cocos/math/Mat4.inl b/native/cocos/math/Mat4.inl index ca01271d7c..edfb8e18d6 100644 --- a/native/cocos/math/Mat4.inl +++ b/native/cocos/math/Mat4.inl @@ -68,19 +68,6 @@ inline Mat4& Mat4::operator*=(const Mat4& mat) return *this; } -inline Vec3& operator*=(Vec3& v, const Mat4& m) -{ - m.transformVector(&v); - return v; -} - -inline const Vec3 operator*(const Mat4& m, const Vec3& v) -{ - Vec3 x; - m.transformVector(v, &x); - return x; -} - inline Vec4& operator*=(Vec4& v, const Mat4& m) { m.transformVector(&v); diff --git a/native/cocos/math/Vec3.h b/native/cocos/math/Vec3.h index 7d58f94a41..1591c9f814 100644 --- a/native/cocos/math/Vec3.h +++ b/native/cocos/math/Vec3.h @@ -236,13 +236,21 @@ public: void transformMat3(const Vec3 &v, const Mat3 &m); /** - * Transforms this vector by the specified Mat4 and stores the result in this vector. + * Transforms the input vector by the specified Mat4 and stores the result in this vector. * * @param v The Vec3 to transform. * @param m The matrix. */ void transformMat4(const Vec3 &v, const Mat4 &m); + /** + * Transforms this vector by the specified Mat4 and stores the result in this vector. + * @param m The matrix. + */ + inline void transformMat4(const Mat4 &m) { + transformMat4(*this, m); + } + /** * Transforms vector v by the specified Mat4 and stores the result in dst vector. * @zh 向量与四维矩阵乘法,默认向量第四位为 1。 diff --git a/native/cocos/renderer/pipeline/GeometryRenderer.cpp b/native/cocos/renderer/pipeline/GeometryRenderer.cpp index f8cbc5a77e..2c1dffd882 100644 --- a/native/cocos/renderer/pipeline/GeometryRenderer.cpp +++ b/native/cocos/renderer/pipeline/GeometryRenderer.cpp @@ -373,14 +373,14 @@ void GeometryRenderer::addBoundingBox(const geometry::AABB &aabb, gfx::Color col Vec3 v7{max.x, max.y, max.z}; if (useTransform) { - transform.transformPoint(&v0); - transform.transformPoint(&v1); - transform.transformPoint(&v2); - transform.transformPoint(&v3); - transform.transformPoint(&v4); - transform.transformPoint(&v5); - transform.transformPoint(&v6); - transform.transformPoint(&v7); + v0.transformMat4(transform); + v1.transformMat4(transform); + v2.transformMat4(transform); + v3.transformMat4(transform); + v4.transformMat4(transform); + v5.transformMat4(transform); + v6.transformMat4(transform); + v7.transformMat4(transform); } if (wireframe) { @@ -470,8 +470,8 @@ void GeometryRenderer::addCapsule(const Vec3 ¢er, float radius, float height if (useTransform) { for (auto i = 0U; i < hemiSegmentsV + 1; i++) { for (auto j = 0U; j < segmentsU + 1; j++) { - transform.transformPoint(&bottomPoints[i][j]); - transform.transformPoint(&topPoints[i][j]); + bottomPoints[i][j].transformMat4(transform); + topPoints[i][j].transformMat4(transform); } } } @@ -509,12 +509,12 @@ void GeometryRenderer::addCylinder(const Vec3 ¢er, float radius, float heigh } if (useTransform) { - transform.transformPoint(&bottomCenter); - transform.transformPoint(&topCenter); + bottomCenter.transformMat4(transform); + topCenter.transformMat4(transform); for (auto i = 0U; i < segments + 1; i++) { - transform.transformPoint(&bottomPoints[i]); - transform.transformPoint(&topPoints[i]); + bottomPoints[i].transformMat4(transform); + topPoints[i].transformMat4(transform); } } @@ -539,11 +539,11 @@ void GeometryRenderer::addCone(const Vec3 ¢er, float radius, float height, g } if (useTransform) { - transform.transformPoint(&bottomCenter); - transform.transformPoint(&topCenter); + bottomCenter.transformMat4(transform); + topCenter.transformMat4(transform); for (auto i = 0U; i < segments + 1; i++) { - transform.transformPoint(&bottomPoints[i]); + bottomPoints[i].transformMat4(transform); } } @@ -564,7 +564,7 @@ void GeometryRenderer::addCircle(const Vec3 ¢er, float radius, gfx::Color co if (useTransform) { for (auto i = 0U; i < segments + 1; i++) { - transform.transformPoint(&points[i]); + points[i].transformMat4(transform); } } @@ -586,7 +586,7 @@ void GeometryRenderer::addArc(const Vec3 ¢er, float radius, gfx::Color color if (useTransform) { for (auto i = 0U; i < segments + 1; i++) { - transform.transformPoint(&points[i]); + points[i].transformMat4(transform); } } @@ -614,10 +614,10 @@ void GeometryRenderer::addDisc(const Vec3 ¢er, float radius, gfx::Color colo } if (useTransform) { - transform.transformPoint(&newCenter); + newCenter.transformMat4(transform); for (auto i = 0U; i < segments + 1; i++) { - transform.transformPoint(&points[i]); + points[i].transformMat4(transform); } } @@ -646,10 +646,10 @@ void GeometryRenderer::addSector(const Vec3 ¢er, float radius, gfx::Color co } if (useTransform) { - transform.transformPoint(&newCenter); + newCenter.transformMat4(transform); for (auto i = 0U; i < segments + 1; i++) { - transform.transformPoint(&points[i]); + points[i].transformMat4(transform); } } @@ -693,7 +693,7 @@ void GeometryRenderer::addSphere(const Vec3 ¢er, float radius, gfx::Color co if (useTransform) { for (auto i = 0U; i < segmentsV + 1; i++) { for (auto j = 0U; j < segmentsU + 1; j++) { - transform.transformPoint(&points[i][j]); + points[i][j].transformMat4(transform); } } } @@ -734,7 +734,7 @@ void GeometryRenderer::addTorus(const Vec3 ¢er, float bigRadius, float radiu if (useTransform) { for (auto i = 0U; i < segmentsU + 1; i++) { for (auto j = 0U; j < segmentsV + 1; j++) { - transform.transformPoint(&points[i][j]); + points[i][j].transformMat4(transform); } } } @@ -759,7 +759,7 @@ void GeometryRenderer::addOctahedron(const Vec3 ¢er, float radius, gfx::Colo if (useTransform) { for (auto &point : points) { - transform.transformPoint(&point); + point.transformMat4(transform); } } @@ -800,10 +800,10 @@ void GeometryRenderer::addBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, Vec3 newV3 = v3; if (useTransform) { - transform.transformPoint(&newV0); - transform.transformPoint(&newV1); - transform.transformPoint(&newV2); - transform.transformPoint(&newV3); + newV0.transformMat4(transform); + newV1.transformMat4(transform); + newV2.transformMat4(transform); + newV3.transformMat4(transform); } for (auto i = 0U; i < segments + 1; i++) { @@ -847,9 +847,9 @@ void GeometryRenderer::addMesh(const Vec3 ¢er, const ccstd::vector &ve Vec3 v2 = center + vertices[i + 2]; if (useTransform) { - transform.transformPoint(&v0); - transform.transformPoint(&v1); - transform.transformPoint(&v2); + v0.transformMat4(transform); + v1.transformMat4(transform); + v2.transformMat4(transform); } addLine(v0, v1, color, depthTest); @@ -865,9 +865,9 @@ void GeometryRenderer::addIndexedMesh(const Vec3 ¢er, const ccstd::vector Date: Wed, 20 Jul 2022 22:58:25 +0800 Subject: [PATCH 041/111] [optimization] Split csm ubo v3.6.0 (#12072) * split csm ubo v3.6.0 * update * Modify *.meta file to ignore material upgrade * update * update * update 2 * use better struct padding and save memory * update mate * fix ci error * memory alignment * update * update 2 * chenge func name * update --- cocos/core/pipeline/custom/ubos.ts | 52 ++++++---- cocos/core/pipeline/define.ts | 54 +++++++---- cocos/core/pipeline/pipeline-scene-data.ts | 8 ++ cocos/core/pipeline/pipeline-ubo.ts | 52 ++++++---- cocos/core/pipeline/shadow/csm-layers.ts | 11 ++- cocos/core/pipeline/shadow/shadow-flow.ts | 12 ++- cocos/core/pipeline/shadow/shadow-stage.ts | 2 +- .../builtin/functionalities/shadow-map.chunk | 96 +++++++++++-------- .../functionalities/shadow-map.chunk.meta | 2 +- .../chunks/builtin/uniforms/cc-csm.chunk | 13 +++ .../chunks/builtin/uniforms/cc-csm.chunk.meta | 9 ++ .../builtin/uniforms/cc-diffusemap.chunk | 2 +- .../builtin/uniforms/cc-environment.chunk | 2 +- .../builtin/uniforms/cc-shadow-map.chunk | 4 +- .../chunks/builtin/uniforms/cc-shadow.chunk | 7 -- .../chunks/legacy/shadow-map-vs.chunk.meta | 2 +- .../chunks/surfaces/includes/common-fs.chunk | 3 + .../surfaces/includes/common-fs.chunk.meta | 2 +- .../surfaces/includes/common-vs.chunk.meta | 2 +- .../effects/builtin-standard.effect.meta | 2 +- .../effects/builtin-terrain.effect.meta | 2 +- .../assets/effects/builtin-toon.effect.meta | 2 +- .../imported-metallic-roughness.effect.meta | 2 +- .../imported-specular-glossiness.effect.meta | 2 +- .../pipeline/planar-shadow.effect.meta | 2 +- native/cocos/renderer/pipeline/Define.cpp | 27 +++++- native/cocos/renderer/pipeline/Define.h | 28 ++++-- .../pipeline/GlobalDescriptorSetManager.cpp | 2 + .../renderer/pipeline/PipelineSceneData.h | 32 ++++--- .../cocos/renderer/pipeline/PipelineUBO.cpp | 39 +++++--- native/cocos/renderer/pipeline/PipelineUBO.h | 16 ++-- .../renderer/pipeline/shadow/CSMLayers.cpp | 20 +++- .../renderer/pipeline/shadow/ShadowFlow.cpp | 9 +- .../renderer/pipeline/shadow/ShadowFlow.h | 4 + .../renderer/pipeline/shadow/ShadowStage.cpp | 2 +- native/tools/tojs/pipeline.ini | 2 +- 36 files changed, 345 insertions(+), 183 deletions(-) create mode 100644 editor/assets/chunks/builtin/uniforms/cc-csm.chunk create mode 100644 editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta diff --git a/cocos/core/pipeline/custom/ubos.ts b/cocos/core/pipeline/custom/ubos.ts index 840a2cb698..3c32267d4b 100644 --- a/cocos/core/pipeline/custom/ubos.ts +++ b/cocos/core/pipeline/custom/ubos.ts @@ -24,7 +24,7 @@ */ import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, - supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from '../define'; + supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UBOCSM } from '../define'; import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../../gfx'; import { Camera } from '../../renderer/scene/camera'; import { Mat4, Vec3, Vec4, Color } from '../../math'; @@ -199,19 +199,22 @@ export class PipelineUBO { return 0.0; } - public static updateShadowUBOView (pipeline: WebPipeline, shadowBufferView: Float32Array, camera: Camera) { + public static updateShadowUBOView (pipeline: WebPipeline, shadowBufferView: Float32Array, + csmBufferView: Float32Array, camera: Camera) { const device = pipeline.device; const mainLight = camera.scene!.mainLight; const sceneData = pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; const csmLayers = sceneData.csmLayers; const sv = shadowBufferView; + const cv = csmBufferView; + const csmSupported = sceneData.csmSupported; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; if (shadowInfo.enabled && mainLight) { if (shadowInfo.type === ShadowType.ShadowMap) { if (mainLight.shadowEnabled) { - if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) { const matShadowView = csmLayers.specialLayer.matShadowView; const matShadowProj = csmLayers.specialLayer.matShadowProj; const matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; @@ -239,33 +242,33 @@ export class PipelineUBO { Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); } else { for (let i = 0; i < mainLight.csmLevel; i++) { - sv[UBOShadow.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; + cv[UBOCSM.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; const matShadowView = csmLayers.layers[i].matShadowView; - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_CSM_VIEW_OFFSET + 16 * i); + Mat4.toArray(cv, matShadowView, UBOCSM.MAT_CSM_VIEW_OFFSET + 16 * i); const matShadowViewProj = csmLayers.layers[i].matShadowViewProj; - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); + Mat4.toArray(cv, matShadowViewProj, UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); const matShadowViewProjAtlas = csmLayers.layers[i].matShadowViewProjAtlas; - Mat4.toArray(sv, matShadowViewProjAtlas, UBOShadow.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * i); + Mat4.toArray(cv, matShadowViewProjAtlas, UBOCSM.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * i); const matShadowProj = csmLayers.layers[i].matShadowProj; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; } - sv[UBOShadow.CSM_INFO_OFFSET + 0] = 0; - sv[UBOShadow.CSM_INFO_OFFSET + 1] = this.getPCFRadius(shadowInfo, mainLight); - sv[UBOShadow.CSM_INFO_OFFSET + 2] = 0; - sv[UBOShadow.CSM_INFO_OFFSET + 3] = 0; + cv[UBOCSM.CSM_INFO_OFFSET + 0] = 0; + cv[UBOCSM.CSM_INFO_OFFSET + 1] = this.getPCFRadius(shadowInfo, mainLight); + cv[UBOCSM.CSM_INFO_OFFSET + 2] = 0; + cv[UBOCSM.CSM_INFO_OFFSET + 3] = 0; _vec4ShadowInfo.set(0, 0, 0, 1.0 - mainLight.shadowSaturation); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); @@ -384,6 +387,7 @@ export class PipelineUBO { protected _globalUBO = new Float32Array(UBOGlobal.COUNT); protected _cameraUBO = new Float32Array(UBOCamera.COUNT); protected _shadowUBO = new Float32Array(UBOShadow.COUNT); + protected _csmUBO = new Float32Array(UBOCSM.COUNT); static _combineSignY = 0; protected declare _device: Device; protected declare _pipeline: WebPipeline; @@ -433,6 +437,13 @@ export class PipelineUBO { UBOShadow.SIZE, )); ds.bindBuffer(UBOShadow.BINDING, shadowUBO); + const csmUBO = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, + UBOCSM.SIZE, + UBOCSM.SIZE, + )); + ds.bindBuffer(UBOCSM.BINDING, csmUBO); } /** @@ -474,9 +485,10 @@ export class PipelineUBO { if (mainLight && shadowFrameBufferMap.has(mainLight)) { ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); } - PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, camera); + PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, this._csmUBO, camera); ds.update(); cmdBuffer.updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO); + cmdBuffer.updateBuffer(ds.getBuffer(UBOCSM.BINDING), this._csmUBO); } public updateShadowUBOLight (globalDS: DescriptorSet, light: Light, level = 0) { diff --git a/cocos/core/pipeline/define.ts b/cocos/core/pipeline/define.ts index d78b7b2b85..7ca29cd926 100644 --- a/cocos/core/pipeline/define.ts +++ b/cocos/core/pipeline/define.ts @@ -114,6 +114,7 @@ export enum PipelineGlobalBindings { UBO_GLOBAL, UBO_CAMERA, UBO_SHADOW, + UBO_CSM, // should reserve slot for this optional ubo SAMPLER_SHADOWMAP, SAMPLER_ENVIRONMENT, // don't put this as the first sampler binding due to Mac GL driver issues: cubemap at texture unit 0 causes rendering issues @@ -256,11 +257,10 @@ globalDescriptorSetLayout.layouts[UBOCamera.NAME] = UBOCamera.LAYOUT; globalDescriptorSetLayout.bindings[UBOCamera.BINDING] = UBOCamera.DESCRIPTOR; /** - * @en The uniform buffer object for shadow - * @zh 给阴影对象使用的 UBO + * @en The uniform buffer object for 'cast shadow(fixed || csm)' && 'dir fixed area shadow' && 'spot shadow' && 'sphere shadow' && 'planar shadow' + * @zh 这个 UBO 仅仅只给 'cast shadow(fixed || csm)' && 'dir fixed area shadow' && 'spot shadow' && 'sphere shadow' && 'planar shadow' 使用 */ export class UBOShadow { - public static readonly CSM_LEVEL_COUNT = 4; public static readonly MAT_LIGHT_PLANE_PROJ_OFFSET = 0; public static readonly MAT_LIGHT_VIEW_OFFSET = UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET + 16; public static readonly MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadow.MAT_LIGHT_VIEW_OFFSET + 16; @@ -272,14 +272,7 @@ export class UBOShadow { public static readonly SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4; public static readonly SHADOW_COLOR_OFFSET = UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4; public static readonly PLANAR_NORMAL_DISTANCE_INFO_OFFSET = UBOShadow.SHADOW_COLOR_OFFSET + 4; - public static readonly MAT_CSM_VIEW_OFFSET = UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4; - public static readonly MAT_CSM_VIEW_PROJ_OFFSET = UBOShadow.MAT_CSM_VIEW_OFFSET + 16 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly MAT_CSM_VIEW_PROJ_ATLAS_OFFSET = UBOShadow.MAT_CSM_VIEW_PROJ_OFFSET + 16 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly CSM_PROJ_DEPTH_INFO_OFFSET = UBOShadow.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly CSM_PROJ_INFO_OFFSET = UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 4 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly CSM_SPLITS_INFO_OFFSET = UBOShadow.CSM_PROJ_INFO_OFFSET + 4 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly CSM_INFO_OFFSET = UBOShadow.CSM_SPLITS_INFO_OFFSET + 4; - public static readonly COUNT: number = UBOShadow.CSM_INFO_OFFSET + 4; + public static readonly COUNT: number = UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4; public static readonly SIZE = UBOShadow.COUNT * 4; public static readonly NAME = 'CCShadow'; public static readonly BINDING = PipelineGlobalBindings.UBO_SHADOW; @@ -296,18 +289,43 @@ export class UBOShadow { new Uniform('cc_shadowLPNNInfo', Type.FLOAT4, 1), new Uniform('cc_shadowColor', Type.FLOAT4, 1), new Uniform('cc_planarNDInfo', Type.FLOAT4, 1), - new Uniform('cc_matCSMView', Type.MAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_matCSMViewProj', Type.MAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_matCSMViewProjAtlas', Type.MAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_csmProjDepthInfo', Type.FLOAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_csmProjInfo', Type.FLOAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_csmSplitsInfo', Type.FLOAT4, 1), - new Uniform('cc_csmInfo', Type.FLOAT4, 1), ], 1); } globalDescriptorSetLayout.layouts[UBOShadow.NAME] = UBOShadow.LAYOUT; globalDescriptorSetLayout.bindings[UBOShadow.BINDING] = UBOShadow.DESCRIPTOR; +/** + * @en The uniform buffer object only for dir csm shadow(level: 1 ~ 4) + * @zh 级联阴影使用的UBO + */ +export class UBOCSM { + public static readonly CSM_LEVEL_COUNT = 4; + public static readonly MAT_CSM_VIEW_OFFSET = 0; + public static readonly MAT_CSM_VIEW_PROJ_OFFSET = UBOCSM.MAT_CSM_VIEW_OFFSET + 16 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly MAT_CSM_VIEW_PROJ_ATLAS_OFFSET = UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_PROJ_DEPTH_INFO_OFFSET = UBOCSM.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_PROJ_INFO_OFFSET = UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_SPLITS_INFO_OFFSET = UBOCSM.CSM_PROJ_INFO_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_INFO_OFFSET = UBOCSM.CSM_SPLITS_INFO_OFFSET + 4; + public static readonly COUNT: number = UBOCSM.CSM_INFO_OFFSET + 4; + public static readonly SIZE = UBOCSM.COUNT * 4; + + public static readonly NAME = 'CCCSM'; + public static readonly BINDING = PipelineGlobalBindings.UBO_CSM; + public static readonly DESCRIPTOR = new DescriptorSetLayoutBinding(UBOCSM.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL); + public static readonly LAYOUT = new UniformBlock(SetIndex.GLOBAL, UBOCSM.BINDING, UBOCSM.NAME, [ + new Uniform('cc_matCSMView', Type.MAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_matCSMViewProj', Type.MAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_matCSMViewProjAtlas', Type.MAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmProjDepthInfo', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmProjInfo', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmSplitsInfo', Type.FLOAT4, 1), + new Uniform('cc_csmInfo', Type.FLOAT4, 1), + ], 1); +} +globalDescriptorSetLayout.layouts[UBOCSM.NAME] = UBOCSM.LAYOUT; +globalDescriptorSetLayout.bindings[UBOCSM.BINDING] = UBOCSM.DESCRIPTOR; + /* eslint-disable max-len */ /** diff --git a/cocos/core/pipeline/pipeline-scene-data.ts b/cocos/core/pipeline/pipeline-scene-data.ts index bc7a8f549f..27c3556410 100644 --- a/cocos/core/pipeline/pipeline-scene-data.ts +++ b/cocos/core/pipeline/pipeline-scene-data.ts @@ -55,6 +55,13 @@ export class PipelineSceneData { this._shadingScale = val; } + public get csmSupported () { + return this._csmSupported; + } + public set csmSupported (val: boolean) { + this._csmSupported = val; + } + public fog: Fog = new Fog(); public ambient: Ambient = new Ambient(); public skybox: Skybox = new Skybox(); @@ -85,6 +92,7 @@ export class PipelineSceneData { protected _occlusionQueryShader: Shader | null = null; protected _isHDR = true; protected _shadingScale = 1.0; + protected _csmSupported = true; constructor () { this._shadingScale = 1.0; diff --git a/cocos/core/pipeline/pipeline-ubo.ts b/cocos/core/pipeline/pipeline-ubo.ts index 45e8a117e5..0ba29bda3d 100644 --- a/cocos/core/pipeline/pipeline-ubo.ts +++ b/cocos/core/pipeline/pipeline-ubo.ts @@ -24,7 +24,7 @@ */ import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, - supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from './define'; + supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UBOCSM } from './define'; import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, API } from '../gfx'; import { Camera } from '../renderer/scene/camera'; import { Mat4, Vec3, Vec4, Color } from '../math'; @@ -201,19 +201,22 @@ export class PipelineUBO { return 0.0; } - public static updateShadowUBOView (pipeline: RenderPipeline, shadowBufferView: Float32Array, camera: Camera) { + public static updateShadowUBOView (pipeline: RenderPipeline, shadowBufferView: Float32Array, + csmBufferView: Float32Array, camera: Camera) { const device = pipeline.device; const mainLight = camera.scene!.mainLight; const sceneData = pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; const csmLayers = sceneData.csmLayers; const sv = shadowBufferView; + const cv = csmBufferView; + const csmSupported = sceneData.csmSupported; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; if (mainLight && shadowInfo.enabled) { if (shadowInfo.type === ShadowType.ShadowMap) { if (mainLight.shadowEnabled) { - if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) { const matShadowView = csmLayers.specialLayer.matShadowView; const matShadowProj = csmLayers.specialLayer.matShadowProj; const matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; @@ -241,33 +244,33 @@ export class PipelineUBO { Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); } else { for (let i = 0; i < mainLight.csmLevel; i++) { - sv[UBOShadow.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; + cv[UBOCSM.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; const matShadowView = csmLayers.layers[i].matShadowView; - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_CSM_VIEW_OFFSET + 16 * i); + Mat4.toArray(cv, matShadowView, UBOCSM.MAT_CSM_VIEW_OFFSET + 16 * i); const matShadowViewProj = csmLayers.layers[i].matShadowViewProj; - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); + Mat4.toArray(cv, matShadowViewProj, UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); const matShadowViewProjAtlas = csmLayers.layers[i].matShadowViewProjAtlas; - Mat4.toArray(sv, matShadowViewProjAtlas, UBOShadow.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * i); + Mat4.toArray(cv, matShadowViewProjAtlas, UBOCSM.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * i); const matShadowProj = csmLayers.layers[i].matShadowProj; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; } - sv[UBOShadow.CSM_INFO_OFFSET + 0] = 0; - sv[UBOShadow.CSM_INFO_OFFSET + 1] = this.getPCFRadius(shadowInfo, mainLight); - sv[UBOShadow.CSM_INFO_OFFSET + 2] = 0; - sv[UBOShadow.CSM_INFO_OFFSET + 3] = 0; + cv[UBOCSM.CSM_INFO_OFFSET + 0] = 0; + cv[UBOCSM.CSM_INFO_OFFSET + 1] = this.getPCFRadius(shadowInfo, mainLight); + cv[UBOCSM.CSM_INFO_OFFSET + 2] = 0; + cv[UBOCSM.CSM_INFO_OFFSET + 3] = 0; _vec4ShadowInfo.set(0, 0, 0, 1.0 - mainLight.shadowSaturation); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); @@ -391,6 +394,7 @@ export class PipelineUBO { protected _globalUBO = new Float32Array(UBOGlobal.COUNT); protected _cameraUBO = new Float32Array(UBOCamera.COUNT); protected _shadowUBO = new Float32Array(UBOShadow.COUNT); + protected _csmUBO = new Float32Array(UBOCSM.COUNT); static _combineSignY = 0; protected declare _device: Device; protected declare _pipeline: RenderPipeline; @@ -440,6 +444,13 @@ export class PipelineUBO { UBOShadow.SIZE, )); ds.bindBuffer(UBOShadow.BINDING, shadowUBO); + const csmUBO = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, + UBOCSM.SIZE, + UBOCSM.SIZE, + )); + ds.bindBuffer(UBOCSM.BINDING, csmUBO); } /** @@ -481,9 +492,10 @@ export class PipelineUBO { if (mainLight && shadowFrameBufferMap.has(mainLight)) { ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); } - PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, camera); + PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, this._csmUBO, camera); ds.update(); cmdBuffer[0].updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO); + cmdBuffer[0].updateBuffer(ds.getBuffer(UBOCSM.BINDING), this._csmUBO); } public updateShadowUBOLight (globalDS: DescriptorSet, light: Light, level = 0) { diff --git a/cocos/core/pipeline/shadow/csm-layers.ts b/cocos/core/pipeline/shadow/csm-layers.ts index ed024f4e10..ba0f759874 100644 --- a/cocos/core/pipeline/shadow/csm-layers.ts +++ b/cocos/core/pipeline/shadow/csm-layers.ts @@ -162,9 +162,10 @@ export class ShadowLayerVolume { orthoSizeWidth = orthoSizeHeight = Vec3.distance(this._lightViewFrustum.vertices[0], this._lightViewFrustum.vertices[6]); } - if (dirLight.csmLevel > 1 && dirLight.csmOptimizationMode + const csmLevel = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1; + if (csmLevel > 1 && dirLight.csmOptimizationMode === CSMOptimizationMode.RemoveDuplicates) { - if (this._level >= dirLight.csmLevel - 1) { + if (this._level >= csmLevel - 1) { _maxLayerFarPlane = this._castLightViewBoundingBox.halfExtents.z; _maxLayerPosz = this._castLightViewBoundingBox.center.z; } else { @@ -310,7 +311,7 @@ export class CSMLayers { if (dirLight === null) { return; } const shadowInfo = sceneData.shadows; - const levelCount = dirLight.csmLevel; + const levelCount = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1; const shadowDistance = dirLight.shadowDistance; if (!shadowInfo.enabled || !dirLight.shadowEnabled) { return; } @@ -359,7 +360,7 @@ export class CSMLayers { const nd = 0.1; const fd = dirLight.shadowDistance; const ratio = fd / nd; - const level = dirLight.csmLevel; + const level = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1; const lambda = dirLight.csmLayerLambda; this._layers[0].splitCameraNear = nd; for (let i = 1; i < level; i++) { @@ -379,7 +380,7 @@ export class CSMLayers { } private _calculateCSM (camera: Camera, dirLight: DirectionalLight, shadowInfo: Shadows) { - const level = dirLight.csmLevel; + const level = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1; const shadowMapWidth = level > 1 ? shadowInfo.size.x * 0.5 : shadowInfo.size.x; if (shadowMapWidth < 0.0) { return; } diff --git a/cocos/core/pipeline/shadow/shadow-flow.ts b/cocos/core/pipeline/shadow/shadow-flow.ts index 562b4a531c..94e63477b4 100644 --- a/cocos/core/pipeline/shadow/shadow-flow.ts +++ b/cocos/core/pipeline/shadow/shadow-flow.ts @@ -41,6 +41,10 @@ import { Camera } from '../../renderer/scene'; import { SpotLight } from '../../renderer/scene/spot-light'; const _validLights: Light[] = []; +// csm uniform used vectors count +const CSM_UNIFORM_VECTORS = 61; +// all global uniform used vectors count +const GLOBAL_UNIFORM_VECTORS = 64; /** * @en Shadow map render flow @@ -83,6 +87,11 @@ export class ShadowFlow extends RenderFlow { const isLinear = pipeline.device.gfxAPI === API.WEBGL ? 1 : 0; pipeline.macros.CC_SHADOWMAP_USE_LINEAR_DEPTH = isLinear; + // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. + pipeline.pipelineSceneData.csmSupported = pipeline.device.capabilities.maxFragmentUniformVectors + >= (CSM_UNIFORM_VECTORS + GLOBAL_UNIFORM_VECTORS); + pipeline.macros.CC_SUPPORT_CASCADED_SHADOW_MAP = pipeline.pipelineSceneData.csmSupported; + pipeline.onGlobalPipelineStateChanged(); } @@ -127,7 +136,8 @@ export class ShadowFlow extends RenderFlow { if (mainLight.shadowFixedArea) { this._renderStage(camera, mainLight, shadowFrameBuffer!, globalDS); } else { - for (let i = 0; i < mainLight.csmLevel; i++) { + const csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1; + for (let i = 0; i < csmLevel; i++) { this._renderStage(camera, mainLight, shadowFrameBuffer!, globalDS, i); } } diff --git a/cocos/core/pipeline/shadow/shadow-stage.ts b/cocos/core/pipeline/shadow/shadow-stage.ts index 65770cd4ca..f4e768a0b0 100644 --- a/cocos/core/pipeline/shadow/shadow-stage.ts +++ b/cocos/core/pipeline/shadow/shadow-stage.ts @@ -119,7 +119,7 @@ export class ShadowStage extends RenderStage { switch (this._light.type) { case LightType.DIRECTIONAL: { const mainLight = this._light as DirectionalLight; - if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !pipelineSceneData.csmSupported) { this._renderArea.x = 0; this._renderArea.y = 0; this._renderArea.width = shadowMapSize.x; diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk index 174a86c27e..10431d7a42 100644 --- a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk @@ -1,5 +1,8 @@ // used for replacing cc-shadow-map-base.chunk #include +#if CC_SUPPORT_CASCADED_SHADOW_MAP + #include +#endif #include #include @@ -211,50 +214,61 @@ float CCGetLinearDepth(vec3 worldPos) { return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); } - - int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec4 matShadowViewLine0, out vec4 matShadowViewLine1, out vec4 matShadowViewLine2, out vec4 matShadowViewLine3, vec3 worldPos) { - int layer = -1; - for (int i = 0; i < NUMCASCADES; i++) { - vec4 shadowPos = cc_matCSMViewProj[i] * vec4(worldPos.xyz, 1.0); - vec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5; - if (clipPos.x >= (0.0 + cc_csmInfo.y) && clipPos.x <= (1.0 - cc_csmInfo.y) && - clipPos.y >= (0.0 + cc_csmInfo.y) && clipPos.y <= (1.0 - cc_csmInfo.y) && - clipPos.z >= 0.0 && clipPos.z <= 1.0 && layer < 0) { - csmPos = cc_matCSMViewProjAtlas[i] * vec4(worldPos.xyz, 1.0); - shadowProjDepthInfo = cc_csmProjDepthInfo[i]; - shadowProjInfo = cc_csmProjInfo[i]; - matShadowViewLine0 = cc_matCSMView[i][0]; - matShadowViewLine1 = cc_matCSMView[i][1]; - matShadowViewLine2 = cc_matCSMView[i][2]; - matShadowViewLine3 = cc_matCSMView[i][3]; - layer = i; + #if CC_SUPPORT_CASCADED_SHADOW_MAP + int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec4 matShadowViewLine0, out vec4 matShadowViewLine1, out vec4 matShadowViewLine2, out vec4 matShadowViewLine3, vec3 worldPos) { + int layer = -1; + for (int i = 0; i < NUMCASCADES; i++) { + vec4 shadowPos = cc_matCSMViewProj[i] * vec4(worldPos.xyz, 1.0); + vec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5; + if (clipPos.x >= (0.0 + cc_csmInfo.y) && clipPos.x <= (1.0 - cc_csmInfo.y) && + clipPos.y >= (0.0 + cc_csmInfo.y) && clipPos.y <= (1.0 - cc_csmInfo.y) && + clipPos.z >= 0.0 && clipPos.z <= 1.0 && layer < 0) { + csmPos = cc_matCSMViewProjAtlas[i] * vec4(worldPos.xyz, 1.0); + shadowProjDepthInfo = cc_csmProjDepthInfo[i]; + shadowProjInfo = cc_csmProjInfo[i]; + matShadowViewLine0 = cc_matCSMView[i][0]; + matShadowViewLine1 = cc_matCSMView[i][1]; + matShadowViewLine2 = cc_matCSMView[i][2]; + matShadowViewLine3 = cc_matCSMView[i][3]; + layer = i; + } } + return layer; } - return layer; - } - float CCCSMFactorBase(vec3 worldPos, vec3 N, vec2 shadowBias) - { - vec4 csmPos = vec4(1.0); - vec4 shadowProjDepthInfo, shadowProjInfo; - mat4 matLightView; - int level = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, matLightView[0], matLightView[1], matLightView[2], matLightView[3], worldPos); - if (level < 0) { return 1.0; } - float realtimeShadow = 1.0; + float CCCSMFactorBase(vec3 worldPos, vec3 N, vec2 shadowBias) + { + vec4 csmPos = vec4(1.0); + vec4 shadowProjDepthInfo, shadowProjInfo; + mat4 matLightView; + int level = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, matLightView[0], matLightView[1], matLightView[2], matLightView[3], worldPos); + if (level < 0) { return 1.0; } + float realtimeShadow = 1.0; - vec4 pos = ApplyShadowDepthBias_FaceNormal(csmPos, N, shadowBias.y, matLightView, shadowProjInfo.xy); - pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, shadowProjDepthInfo.x, shadowProjDepthInfo.y); - - float pcf = cc_shadowWHPBInfo.z; - if (pcf > 2.9) { - realtimeShadow = CCGetDirLightShadowFactorSoft5X(pos); - } else if (pcf > 1.9) { - realtimeShadow = CCGetDirLightShadowFactorSoft3X(pos); - } else if (pcf > 0.9) { - realtimeShadow = CCGetDirLightShadowFactorSoft(pos); - }else { - realtimeShadow = CCGetDirLightShadowFactorHard(pos); + vec4 pos = ApplyShadowDepthBias_FaceNormal(csmPos, N, shadowBias.y, matLightView, shadowProjInfo.xy); + pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, shadowProjDepthInfo.x, shadowProjDepthInfo.y); + + float pcf = cc_shadowWHPBInfo.z; + if (pcf > 2.9) { + realtimeShadow = CCGetDirLightShadowFactorSoft5X(pos); + } else if (pcf > 1.9) { + realtimeShadow = CCGetDirLightShadowFactorSoft3X(pos); + } else if (pcf > 0.9) { + realtimeShadow = CCGetDirLightShadowFactorSoft(pos); + }else { + realtimeShadow = CCGetDirLightShadowFactorHard(pos); + } + return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); } - return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); - } + #else + int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec4 matShadowViewLine0, out vec4 matShadowViewLine1, out vec4 matShadowViewLine2, out vec4 matShadowViewLine3, vec3 worldPos) { + return -1; + } + + float CCCSMFactorBase(vec3 worldPos, vec3 N, vec2 shadowBias) { + vec4 shadowPos = cc_matLightViewProj * vec4(worldPos, 1.0); + return CCShadowFactorBase(shadowPos, N, shadowBias); + } + #endif + #endif diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta index b10c803341..f10cec021f 100644 --- a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "d4c26490-0a2d-4b6a-9a52-55b5741f18a4", diff --git a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk new file mode 100644 index 0000000000..88f5d43faf --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk @@ -0,0 +1,13 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +#pragma define NUMCASCADES 4 +#pragma builtin(global) +layout(set = 0, binding = 3) uniform CCCSM { + highp mat4 cc_matCSMView[NUMCASCADES]; + highp mat4 cc_matCSMViewProj[NUMCASCADES]; + highp mat4 cc_matCSMViewProjAtlas[NUMCASCADES]; + highp vec4 cc_csmProjDepthInfo[NUMCASCADES]; + highp vec4 cc_csmProjInfo[NUMCASCADES]; + highp vec4 cc_csmSplitsInfo; // x-> level_1 far, y-> level_2 far, z-> level_3 far, w-> level_4 far + highp vec4 cc_csmInfo; // y-> radius +}; diff --git a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta new file mode 100644 index 0000000000..3f38763db3 --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "c3e3500f-370c-4da1-92f9-d0d9fd806bd8", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk index 482aa2034e..4b678a409c 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk @@ -3,4 +3,4 @@ #pragma define-meta CC_USE_DIFFUSEMAP range([0, 2]) #pragma builtin(global) -layout(set = 0, binding = 6) uniform samplerCube cc_diffuseMap; \ No newline at end of file +layout(set = 0, binding = 7) uniform samplerCube cc_diffuseMap; diff --git a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk index 6e4bd55ce0..6bc653525d 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk @@ -5,4 +5,4 @@ #pragma define-meta CC_USE_IBL range([0, 2]) #pragma builtin(global) -layout(set = 0, binding = 4) uniform samplerCube cc_environment; +layout(set = 0, binding = 5) uniform samplerCube cc_environment; diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk index dc82842bec..b1ec0587ed 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk @@ -1,5 +1,5 @@ #pragma builtin(global) -layout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap; +layout(set = 0, binding = 4) uniform highp sampler2D cc_shadowMap; #pragma builtin(global) -layout(set = 0, binding = 5) uniform highp sampler2D cc_spotShadowMap; +layout(set = 0, binding = 6) uniform highp sampler2D cc_spotShadowMap; diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk index 8a5f24f3ff..fb8990efe5 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk @@ -14,11 +14,4 @@ layout(set = 0, binding = 2) uniform CCShadow { mediump vec4 cc_shadowLPNNInfo; // x -> lightType(L); y -> isPacking(P); z -> normalBias(N); w -> CSM level(N); lowp vec4 cc_shadowColor; mediump vec4 cc_planarNDInfo; // xyz -> normalized plane (N); w -> plane (D); - highp mat4 cc_matCSMView[NUMCASCADES]; - highp mat4 cc_matCSMViewProj[NUMCASCADES]; - highp mat4 cc_matCSMViewProjAtlas[NUMCASCADES]; - highp vec4 cc_csmProjDepthInfo[NUMCASCADES]; - highp vec4 cc_csmProjInfo[NUMCASCADES]; - highp vec4 cc_csmSplitsInfo; // x-> level_1 far, y-> level_2 far, z-> level_3 far, w-> level_4 far - highp vec4 cc_csmInfo; // y-> radius }; diff --git a/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta b/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta index 8ca760831c..0564fce7dc 100644 --- a/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "b2e7c003-9c9f-40ee-82c6-32d920a759e8", diff --git a/editor/assets/chunks/surfaces/includes/common-fs.chunk b/editor/assets/chunks/surfaces/includes/common-fs.chunk index 59b8fe2a88..67497a14cf 100644 --- a/editor/assets/chunks/surfaces/includes/common-fs.chunk +++ b/editor/assets/chunks/surfaces/includes/common-fs.chunk @@ -23,6 +23,9 @@ // Uniforms--Tex #include +#if CC_SUPPORT_CASCADED_SHADOW_MAP + #include +#endif #if CC_USE_IBL #include #if CC_USE_DIFFUSEMAP diff --git a/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta index 8f7f46821d..7f9cb08c46 100644 --- a/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a6451dbc-fc4c-4a10-84f5-072c6e982fa5", diff --git a/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta index 8961da1726..4507a1b1df 100644 --- a/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "c66380b2-694f-40bd-afd8-91a2e58d904d", diff --git a/editor/assets/effects/builtin-standard.effect.meta b/editor/assets/effects/builtin-standard.effect.meta index 14658ad55d..04f0c87578 100644 --- a/editor/assets/effects/builtin-standard.effect.meta +++ b/editor/assets/effects/builtin-standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "1baf0fc9-befa-459c-8bdd-af1a450a0319", diff --git a/editor/assets/effects/builtin-terrain.effect.meta b/editor/assets/effects/builtin-terrain.effect.meta index 28b87b72b6..410178cb44 100644 --- a/editor/assets/effects/builtin-terrain.effect.meta +++ b/editor/assets/effects/builtin-terrain.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "1d08ef62-a503-4ce2-8b9a-46c90873f7d3", diff --git a/editor/assets/effects/builtin-toon.effect.meta b/editor/assets/effects/builtin-toon.effect.meta index afd69e1d7f..137aaed477 100644 --- a/editor/assets/effects/builtin-toon.effect.meta +++ b/editor/assets/effects/builtin-toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "a7612b54-35e3-4238-a1a9-4a7b54635839", diff --git a/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta index b0d0358205..eaa8359626 100644 --- a/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta +++ b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "2ec11458-f855-4978-b14d-f3ed5cf697fa", diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta index a410f41320..36c2df10a9 100644 --- a/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "f648964e-8d32-41fc-9ac9-7a1e714dd17b", diff --git a/editor/assets/effects/pipeline/planar-shadow.effect.meta b/editor/assets/effects/pipeline/planar-shadow.effect.meta index 602f81fcae..b41c449ee9 100644 --- a/editor/assets/effects/pipeline/planar-shadow.effect.meta +++ b/editor/assets/effects/pipeline/planar-shadow.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "9361fd90-ba52-4f84-aa93-6e878fd576ca", diff --git a/native/cocos/renderer/pipeline/Define.cpp b/native/cocos/renderer/pipeline/Define.cpp index 4ed9b9bff2..493ace0ad0 100644 --- a/native/cocos/renderer/pipeline/Define.cpp +++ b/native/cocos/renderer/pipeline/Define.cpp @@ -158,11 +158,28 @@ const gfx::UniformBlock UBOShadow::LAYOUT = { {"cc_shadowLPNNInfo", gfx::Type::FLOAT4, 1}, {"cc_shadowColor", gfx::Type::FLOAT4, 1}, {"cc_planarNDInfo", gfx::Type::FLOAT4, 1}, - {"cc_matCSMView", gfx::Type::MAT4, UBOShadow::CSM_LEVEL_COUNT}, - {"cc_matCSMViewProj", gfx::Type::MAT4, UBOShadow::CSM_LEVEL_COUNT}, - {"cc_matCSMViewProjAtlas", gfx::Type::MAT4, UBOShadow::CSM_LEVEL_COUNT}, - {"cc_csmProjDepthInfo", gfx::Type::FLOAT4, UBOShadow::CSM_LEVEL_COUNT}, - {"cc_csmProjInfo", gfx::Type::FLOAT4, UBOShadow::CSM_LEVEL_COUNT}, + }, + 1, +}; + +const ccstd::string UBOCSM::NAME = "CCCSM"; +const gfx::DescriptorSetLayoutBinding UBOCSM::DESCRIPTOR = { + UBOCSM::BINDING, + gfx::DescriptorType::UNIFORM_BUFFER, + 1, + gfx::ShaderStageFlagBit::ALL, + {}, +}; +const gfx::UniformBlock UBOCSM::LAYOUT = { + globalSet, + UBOCSM::BINDING, + UBOCSM::NAME, + { + {"cc_matCSMView", gfx::Type::MAT4, UBOCSM::CSM_LEVEL_COUNT}, + {"cc_matCSMViewProj", gfx::Type::MAT4, UBOCSM::CSM_LEVEL_COUNT}, + {"cc_matCSMViewProjAtlas", gfx::Type::MAT4, UBOCSM::CSM_LEVEL_COUNT}, + {"cc_csmProjDepthInfo", gfx::Type::FLOAT4, UBOCSM::CSM_LEVEL_COUNT}, + {"cc_csmProjInfo", gfx::Type::FLOAT4, UBOCSM::CSM_LEVEL_COUNT}, {"cc_csmSplitsInfo", gfx::Type::FLOAT4, 1}, {"cc_csmInfo", gfx::Type::FLOAT4, 1}, }, diff --git a/native/cocos/renderer/pipeline/Define.h b/native/cocos/renderer/pipeline/Define.h index ef086b76b6..ea8e3749f0 100644 --- a/native/cocos/renderer/pipeline/Define.h +++ b/native/cocos/renderer/pipeline/Define.h @@ -224,6 +224,7 @@ enum class CC_DLL PipelineGlobalBindings { UBO_GLOBAL, UBO_CAMERA, UBO_SHADOW, + UBO_CSM, // should reserve slot for this optional ubo SAMPLER_SHADOWMAP, SAMPLER_ENVIRONMENT, @@ -459,7 +460,6 @@ struct CC_DLL UBOCamera { }; struct CC_DLL UBOShadow { - static constexpr uint32_t CSM_LEVEL_COUNT = 4; static constexpr uint32_t MAT_LIGHT_PLANE_PROJ_OFFSET = 0; static constexpr uint32_t MAT_LIGHT_VIEW_OFFSET = MAT_LIGHT_PLANE_PROJ_OFFSET + 16; static constexpr uint32_t MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadow::MAT_LIGHT_VIEW_OFFSET + 16; @@ -471,14 +471,7 @@ struct CC_DLL UBOShadow { static constexpr uint32_t SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4; static constexpr uint32_t SHADOW_COLOR_OFFSET = UBOShadow::SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4; static constexpr uint32_t PLANAR_NORMAL_DISTANCE_INFO_OFFSET = UBOShadow::SHADOW_COLOR_OFFSET + 4; - static constexpr uint32_t MAT_CSM_VIEW_LEVELS_OFFSET = UBOShadow::PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4; - static constexpr uint32_t MAT_CSM_VIEW_PROJ_LEVELS_OFFSET = UBOShadow::MAT_CSM_VIEW_LEVELS_OFFSET + 16 * UBOShadow::CSM_LEVEL_COUNT; - static constexpr uint32_t MAT_CSM_VIEW_PROJ_ATLAS_LEVELS_OFFSET = UBOShadow::MAT_CSM_VIEW_PROJ_LEVELS_OFFSET + 16 * UBOShadow::CSM_LEVEL_COUNT; - static constexpr uint32_t CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET = UBOShadow::MAT_CSM_VIEW_PROJ_ATLAS_LEVELS_OFFSET + 16 * UBOShadow::CSM_LEVEL_COUNT; - static constexpr uint32_t CSM_PROJ_INFO_LEVELS_OFFSET = UBOShadow::CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET + 4 * UBOShadow::CSM_LEVEL_COUNT; - static constexpr uint32_t CSM_SPLITS_INFO_OFFSET = UBOShadow::CSM_PROJ_INFO_LEVELS_OFFSET + 4 * UBOShadow::CSM_LEVEL_COUNT; - static constexpr uint32_t CSM_INFO_OFFSET = UBOShadow::CSM_SPLITS_INFO_OFFSET + 4; - static constexpr uint32_t COUNT = UBOShadow::CSM_INFO_OFFSET + 4; + static constexpr uint32_t COUNT = UBOShadow::PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4; static constexpr uint32_t SIZE = UBOShadow::COUNT * 4; static constexpr uint32_t BINDING = static_cast(PipelineGlobalBindings::UBO_SHADOW); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; @@ -486,6 +479,23 @@ struct CC_DLL UBOShadow { static const ccstd::string NAME; }; +struct CC_DLL UBOCSM { + static constexpr uint32_t CSM_LEVEL_COUNT = 4; + static constexpr uint32_t MAT_CSM_VIEW_LEVELS_OFFSET = 0; + static constexpr uint32_t MAT_CSM_VIEW_PROJ_LEVELS_OFFSET = UBOCSM::MAT_CSM_VIEW_LEVELS_OFFSET + 16 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t MAT_CSM_VIEW_PROJ_ATLAS_LEVELS_OFFSET = UBOCSM::MAT_CSM_VIEW_PROJ_LEVELS_OFFSET + 16 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET = UBOCSM::MAT_CSM_VIEW_PROJ_ATLAS_LEVELS_OFFSET + 16 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t CSM_PROJ_INFO_LEVELS_OFFSET = UBOCSM::CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET + 4 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t CSM_SPLITS_INFO_OFFSET = UBOCSM::CSM_PROJ_INFO_LEVELS_OFFSET + 4 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t CSM_INFO_OFFSET = UBOCSM::CSM_SPLITS_INFO_OFFSET + 4; + static constexpr uint32_t COUNT = UBOCSM::CSM_INFO_OFFSET + 4; + static constexpr uint32_t SIZE = UBOCSM::COUNT * 4; + static constexpr uint32_t BINDING = static_cast(PipelineGlobalBindings::UBO_CSM); + static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; +}; + struct CC_DLL DescriptorSetLayoutInfos { gfx::DescriptorSetLayoutBindingList bindings; ccstd::unordered_map blocks; diff --git a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp index 265a0dadda..92f8423e27 100644 --- a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp +++ b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp @@ -181,6 +181,8 @@ void GlobalDSManager::setDescriptorSetLayout() { globalDescriptorSetLayout.bindings[UBOCamera::BINDING] = UBOCamera::DESCRIPTOR; globalDescriptorSetLayout.blocks[UBOShadow::NAME] = UBOShadow::LAYOUT; globalDescriptorSetLayout.bindings[UBOShadow::BINDING] = UBOShadow::DESCRIPTOR; + globalDescriptorSetLayout.blocks[UBOCSM::NAME] = UBOCSM::LAYOUT; + globalDescriptorSetLayout.bindings[UBOCSM::BINDING] = UBOCSM::DESCRIPTOR; globalDescriptorSetLayout.samplers[SHADOWMAP::NAME] = SHADOWMAP::LAYOUT; globalDescriptorSetLayout.bindings[SHADOWMAP::BINDING] = SHADOWMAP::DESCRIPTOR; globalDescriptorSetLayout.samplers[ENVIRONMENT::NAME] = ENVIRONMENT::LAYOUT; diff --git a/native/cocos/renderer/pipeline/PipelineSceneData.h b/native/cocos/renderer/pipeline/PipelineSceneData.h index dc32c83f54..5d4f3a0911 100644 --- a/native/cocos/renderer/pipeline/PipelineSceneData.h +++ b/native/cocos/renderer/pipeline/PipelineSceneData.h @@ -83,6 +83,8 @@ public: inline void clearValidPunctualLights() { _validPunctualLights.clear(); } inline float getShadingScale() const { return _shadingScale; } inline void setShadingScale(float val) { _shadingScale = val; } + inline bool getCSMSupported() const { return _csmSupported; } + inline void setCSMSupported(bool val) { _csmSupported = val; } protected: void initOcclusionQuery(); @@ -92,26 +94,17 @@ protected: static constexpr uint32_t GEOMETRY_RENDERER_TECHNIQUE_COUNT{6}; - RenderObjectList _renderObjects; - // `scene::Light *`: weak reference - ccstd::vector _validPunctualLights; IntrusivePtr _occlusionQueryVertexBuffer; IntrusivePtr _occlusionQueryIndicesBuffer; IntrusivePtr _occlusionQueryInputAssembler; - IntrusivePtr _occlusionQueryMaterial{nullptr}; + IntrusivePtr _debugRendererMaterial{nullptr}; + gfx::Shader *_occlusionQueryShader{nullptr}; // weak reference scene::Pass *_occlusionQueryPass{nullptr}; // weak reference - - ccstd::vector> _geometryRendererMaterials; - ccstd::vector _geometryRendererPasses; // weak reference - ccstd::vector _geometryRendererShaders; // weak reference - - IntrusivePtr _debugRendererMaterial{nullptr}; - gfx::Shader *_debugRendererShader{nullptr}; // weak reference - scene::Pass *_debugRendererPass{nullptr}; // weak reference - gfx::Device *_device{nullptr}; // weak reference - + gfx::Shader *_debugRendererShader{nullptr}; // weak reference + scene::Pass *_debugRendererPass{nullptr}; // weak reference + gfx::Device *_device{nullptr}; // weak reference // manage memory manually scene::Fog *_fog{nullptr}; // manage memory manually @@ -124,9 +117,20 @@ protected: scene::Octree *_octree{nullptr}; // manage memory manually CSMLayers *_csmLayers{nullptr}; + bool _isHDR{true}; + bool _csmSupported{true}; + float _shadingScale{1.0F}; + RenderObjectList _renderObjects; + + ccstd::vector> _geometryRendererMaterials; + // `scene::Light *`: weak reference + ccstd::vector _validPunctualLights; + ccstd::vector _geometryRendererPasses; // weak reference + ccstd::vector _geometryRendererShaders; // weak reference + ccstd::unordered_map> _shadowFrameBufferMap; }; diff --git a/native/cocos/renderer/pipeline/PipelineUBO.cpp b/native/cocos/renderer/pipeline/PipelineUBO.cpp index 01216c28d1..28e0caec78 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.cpp +++ b/native/cocos/renderer/pipeline/PipelineUBO.cpp @@ -193,7 +193,7 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out } void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, ccstd::array *shadowBufferView, - const scene::Camera *camera) { + ccstd::array *csmBufferView, const scene::Camera *camera) { const scene::RenderScene *const scene = camera->getScene(); const scene::DirectionalLight *mainLight = scene->getMainLight(); gfx::Device *device = gfx::Device::getInstance(); @@ -201,13 +201,15 @@ void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, ccstd::arr const CSMLayers *csmLayers = sceneData->getCSMLayers(); scene::Shadows *const shadowInfo = sceneData->getShadows(); ccstd::array &sv = *shadowBufferView; + ccstd::array &cv = *csmBufferView; const bool hFTexture = supportsR32FloatTexture(device); const float packing = hFTexture ? 0.0F : 1.0F; + const bool csmSupported = sceneData->getCSMSupported(); if (shadowInfo->isEnabled() && mainLight) { if (shadowInfo->getType() == scene::ShadowType::SHADOW_MAP) { if (mainLight->isShadowEnabled()) { - if (mainLight->isShadowFixedArea() || mainLight->getCSMLevel() == scene::CSMLevel::LEVEL_1) { + if (mainLight->isShadowFixedArea() || mainLight->getCSMLevel() == scene::CSMLevel::LEVEL_1 || !csmSupported) { const Mat4 &matShadowView = csmLayers->getSpecialLayer()->getMatShadowView(); const Mat4 &matShadowProj = csmLayers->getSpecialLayer()->getMatShadowProj(); const Mat4 &matShadowViewProj = csmLayers->getSpecialLayer()->getMatShadowViewProj(); @@ -232,29 +234,29 @@ void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, ccstd::arr memcpy(sv.data() + UBOShadow::SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET, &shadowLPNNInfos, sizeof(shadowLPNNInfos)); } else { for (uint32_t i = 0; i < static_cast(mainLight->getCSMLevel()); ++i) { - sv[UBOShadow::CSM_SPLITS_INFO_OFFSET + i] = csmLayers->getLayers()[i]->getSplitCameraFar() / mainLight->getShadowDistance(); + cv[UBOCSM::CSM_SPLITS_INFO_OFFSET + i] = csmLayers->getLayers()[i]->getSplitCameraFar() / mainLight->getShadowDistance(); const Mat4 &matShadowView = csmLayers->getLayers()[i]->getMatShadowView(); - memcpy(sv.data() + UBOShadow::MAT_CSM_VIEW_LEVELS_OFFSET + i * 16, matShadowView.m, sizeof(matShadowView)); + memcpy(cv.data() + UBOCSM::MAT_CSM_VIEW_LEVELS_OFFSET + i * 16, matShadowView.m, sizeof(matShadowView)); const Mat4 &matShadowViewProj = csmLayers->getLayers()[i]->getMatShadowViewProj(); - memcpy(sv.data() + UBOShadow::MAT_CSM_VIEW_PROJ_LEVELS_OFFSET + i * 16, matShadowViewProj.m, sizeof(matShadowViewProj)); + memcpy(cv.data() + UBOCSM::MAT_CSM_VIEW_PROJ_LEVELS_OFFSET + i * 16, matShadowViewProj.m, sizeof(matShadowViewProj)); const Mat4 &matShadowViewProjAtlas = csmLayers->getLayers()[i]->getMatShadowViewProjAtlas(); - memcpy(sv.data() + UBOShadow::MAT_CSM_VIEW_PROJ_ATLAS_LEVELS_OFFSET + i * 16, matShadowViewProjAtlas.m, sizeof(matShadowViewProjAtlas)); + memcpy(cv.data() + UBOCSM::MAT_CSM_VIEW_PROJ_ATLAS_LEVELS_OFFSET + i * 16, matShadowViewProjAtlas.m, sizeof(matShadowViewProjAtlas)); const Mat4 &matShadowProj = csmLayers->getLayers()[i]->getMatShadowProj(); const float shadowProjDepthInfos[4] = {matShadowProj.m[10], matShadowProj.m[14], matShadowProj.m[11], matShadowProj.m[15]}; - memcpy(sv.data() + UBOShadow::CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET + i * 4, &shadowProjDepthInfos, sizeof(shadowProjDepthInfos)); + memcpy(cv.data() + UBOCSM::CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET + i * 4, &shadowProjDepthInfos, sizeof(shadowProjDepthInfos)); const float shadowProjInfos[4] = {matShadowProj.m[00], matShadowProj.m[05], 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05]}; - memcpy(sv.data() + UBOShadow::CSM_PROJ_INFO_LEVELS_OFFSET + i * 4, &shadowProjInfos, sizeof(shadowProjInfos)); + memcpy(cv.data() + UBOCSM::CSM_PROJ_INFO_LEVELS_OFFSET + i * 4, &shadowProjInfos, sizeof(shadowProjInfos)); } - sv[UBOShadow::CSM_INFO_OFFSET + 0] = 0.0F; - sv[UBOShadow::CSM_INFO_OFFSET + 1] = getPCFRadius(shadowInfo, mainLight); - sv[UBOShadow::CSM_INFO_OFFSET + 2] = 0.0F; - sv[UBOShadow::CSM_INFO_OFFSET + 3] = 0.0F; + cv[UBOCSM::CSM_INFO_OFFSET + 0] = 0.0F; + cv[UBOCSM::CSM_INFO_OFFSET + 1] = getPCFRadius(shadowInfo, mainLight); + cv[UBOCSM::CSM_INFO_OFFSET + 2] = 0.0F; + cv[UBOCSM::CSM_INFO_OFFSET + 3] = 0.0F; const float shadowNFLSInfos[4] = {0.0F, 0.0F, 0.0F, 1.0F - mainLight->getShadowSaturation()}; memcpy(sv.data() + UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET, &shadowNFLSInfos, sizeof(shadowNFLSInfos)); @@ -443,6 +445,16 @@ void PipelineUBO::activate(gfx::Device *device, RenderPipeline *pipeline) { descriptorSet->bindBuffer(UBOShadow::BINDING, shadowUBO); _ubos.push_back(shadowUBO); + auto *csmUBO = _device->createBuffer({ + gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::DEVICE, + UBOCSM::SIZE, + UBOCSM::SIZE, + gfx::BufferFlagBit::NONE, + }); + descriptorSet->bindBuffer(UBOCSM::BINDING, csmUBO); + _ubos.push_back(csmUBO); + _shadowUBOUpdated = false; } @@ -514,9 +526,10 @@ void PipelineUBO::updateShadowUBO(const scene::Camera *camera) { } } } - updateShadowUBOView(_pipeline, &_shadowUBO, camera); + updateShadowUBOView(_pipeline, &_shadowUBO, &_csmUBO, camera); ds->update(); cmdBuffer->updateBuffer(ds->getBuffer(UBOShadow::BINDING), _shadowUBO.data(), UBOShadow::SIZE); + cmdBuffer->updateBuffer(ds->getBuffer(UBOCSM::BINDING), _csmUBO.data(), UBOCSM::SIZE); } void PipelineUBO::updateShadowUBOLight(gfx::DescriptorSet *globalDS, const scene::Light *light, uint32_t level) { diff --git a/native/cocos/renderer/pipeline/PipelineUBO.h b/native/cocos/renderer/pipeline/PipelineUBO.h index 5a00697b87..87227e581f 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.h +++ b/native/cocos/renderer/pipeline/PipelineUBO.h @@ -42,7 +42,7 @@ public: static void updateGlobalUBOView(const scene::Camera *camera, ccstd::array *bufferView); static void updateCameraUBOView(const RenderPipeline *pipeline, float *output, const scene::Camera *camera); static void updateShadowUBOView(const RenderPipeline *pipeline, ccstd::array *shadowBufferView, - const scene::Camera *camera); + ccstd::array *csmBufferView, const scene::Camera *camera); static void updateShadowUBOLightView(const RenderPipeline *pipeline, ccstd::array *shadowBufferView, const scene::Light *light, uint32_t level); static uint8_t getCombineSignY(); @@ -69,19 +69,21 @@ private: RenderPipeline *_pipeline{nullptr}; // weak reference gfx::Device *_device{nullptr}; + // weak reference, it is recorded in _ubos + gfx::Buffer *_cameraBuffer{nullptr}; + + uint32_t _currentCameraUBOOffset{0}; + uint32_t _alignedCameraUBOSize{0}; + + bool _shadowUBOUpdated{false}; ccstd::array _globalUBO; ccstd::array _shadowUBO; + ccstd::array _csmUBO; // manage memory manually ccstd::vector _ubos; ccstd::vector _cameraUBOs; - - // weak reference, it is recorded in _ubos - gfx::Buffer *_cameraBuffer{nullptr}; - uint32_t _currentCameraUBOOffset{0}; - uint32_t _alignedCameraUBOSize{0}; - bool _shadowUBOUpdated{false}; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/shadow/CSMLayers.cpp b/native/cocos/renderer/pipeline/shadow/CSMLayers.cpp index 19321e8224..38ea84b649 100644 --- a/native/cocos/renderer/pipeline/shadow/CSMLayers.cpp +++ b/native/cocos/renderer/pipeline/shadow/CSMLayers.cpp @@ -20,10 +20,12 @@ ****************************************************************************/ #include "CSMLayers.h" +#include "core/Root.h" #include "gfx-base/GFXDevice.h" #include "math/Quaternion.h" #include "pipeline/PipelineSceneData.h" #include "pipeline/RenderPipeline.h" +#include "pipeline/custom/RenderInterfaceTypes.h" #include "scene/RenderScene.h" #include "scene/Shadow.h" @@ -39,6 +41,7 @@ ShadowTransformInfo::ShadowTransformInfo(uint32_t level):_level(level) { void ShadowTransformInfo::createMatrix(const geometry::Frustum &splitFrustum, const scene::DirectionalLight *dirLight, float shadowMapWidth, bool isOnlyCulling) { const float invisibleOcclusionRange = dirLight->getShadowInvisibleOcclusionRange(); const gfx::Device *device = gfx::Device::getInstance(); + const Root *root = Root::getInstance(); geometry::Frustum::copy(&_lightViewFrustum, splitFrustum); const float projectionSinY = device->getCapabilities().clipSpaceSignY; const float clipSpaceMinZ = device->getCapabilities().clipSpaceMinZ; @@ -64,9 +67,10 @@ void ShadowTransformInfo::createMatrix(const geometry::Frustum &splitFrustum, co orthoSizeWidth = orthoSizeHeight = _lightViewFrustum.vertices[0].distance(_lightViewFrustum.vertices[6]); } - if (dirLight->getCSMLevel() != scene::CSMLevel::LEVEL_1 && dirLight->getCSMOptimizationMode() == + const auto csmLevel = root->getPipeline()->getPipelineSceneData()->getCSMSupported() ? dirLight->getCSMLevel() : scene::CSMLevel::LEVEL_1; + if (csmLevel != scene::CSMLevel::LEVEL_1 && dirLight->getCSMOptimizationMode() == scene::CSMOptimizationMode::REMOVE_DUPLICATES) { - if (_level >= static_cast(dirLight->getCSMLevel()) - 1U) { + if (_level >= static_cast(csmLevel) - 1U) { _maxLayerFarPlane = _castLightViewBoundingBox.halfExtents.z; _maxLayerPosz = _castLightViewBoundingBox.center.z; } else { @@ -168,11 +172,13 @@ void CSMLayers::update(const PipelineSceneData *sceneData, const scene::Camera * const scene::Shadows *shadowInfo = sceneData->getShadows(); const scene::RenderScene *const scene = camera->getScene(); + const Root *root = Root::getInstance(); scene::DirectionalLight *dirLight = scene->getMainLight(); CC_ASSERT(dirLight); - const auto levelCount = static_cast(dirLight->getCSMLevel()); + const auto levelCount = root->getPipeline()->getPipelineSceneData()->getCSMSupported() ? + static_cast(dirLight->getCSMLevel()) : 1U; CC_ASSERT(levelCount <= static_cast(scene::CSMLevel::LEVEL_4)); const float shadowDistance = dirLight->getShadowDistance(); @@ -220,10 +226,12 @@ void CSMLayers::updateFixedArea(const scene::DirectionalLight *dirLight) const { } void CSMLayers::splitFrustumLevels(scene::DirectionalLight *dirLight) { + const Root *root = Root::getInstance(); constexpr float nd = 0.1F; const float fd = dirLight->getShadowDistance(); const float ratio = fd / nd; - const auto level = static_cast(dirLight->getCSMLevel()); + const auto level = root->getPipeline()->getPipelineSceneData()->getCSMSupported() ? + static_cast(dirLight->getCSMLevel()) : 1U; const float lambda = dirLight->getCSMLayerLambda(); _layers.at(0)->setSplitCameraNear(nd); for (uint32_t i = 1; i < level; ++i) { @@ -242,7 +250,9 @@ void CSMLayers::splitFrustumLevels(scene::DirectionalLight *dirLight) { } void CSMLayers::calculateCSM(const scene::Camera *camera, const scene::DirectionalLight *dirLight, const scene::Shadows *shadowInfo) { - const auto level = dirLight->getCSMLevel(); + const Root *root = Root::getInstance(); + const auto level = root->getPipeline()->getPipelineSceneData()->getCSMSupported() ? + dirLight->getCSMLevel() : scene::CSMLevel::LEVEL_1; const float shadowMapWidth = level != scene::CSMLevel::LEVEL_1 ? shadowInfo->getSize().x * 0.5F : shadowInfo->getSize().x; if (shadowMapWidth < 0.999F) { diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index 3b470e1eee..f9903e42f4 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -77,6 +77,12 @@ void ShadowFlow::activate(RenderPipeline *pipeline) { const int32_t isLinear = 0; pipeline->setValue("CC_SHADOWMAP_USE_LINEAR_DEPTH", isLinear); + // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. + const auto csmSupported = pipeline->getDevice()->getCapabilities().maxFragmentUniformVectors >= + CSM_UNIFORM_VECTORS + GLOBAL_UNIFORM_VECTORS; + pipeline->getPipelineSceneData()->setCSMSupported(csmSupported); + pipeline->setValue("CC_SUPPORT_CASCADED_SHADOW_MAP", csmSupported); + pipeline->onGlobalPipelineStateChanged(); } @@ -117,7 +123,8 @@ void ShadowFlow::render(scene::Camera *camera) { if (mainLight->isShadowFixedArea()) { renderStage(globalDS, camera, mainLight, shadowFrameBuffer); } else { - for (uint32_t i = 0; i < static_cast(mainLight->getCSMLevel()); ++i) { + const auto level = _pipeline->getPipelineSceneData()->getCSMSupported() ? static_cast(mainLight->getCSMLevel()) : 1U; + for (uint32_t i = 0; i < level; ++i) { renderStage(globalDS, camera, mainLight, shadowFrameBuffer, i); } } diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.h b/native/cocos/renderer/pipeline/shadow/ShadowFlow.h index e46663054c..373f279c60 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.h +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.h @@ -59,6 +59,10 @@ private: void initShadowFrameBuffer(const RenderPipeline* pipeline, const scene::Light* light); static RenderFlowInfo initInfo; + // csm uniform used vectors count. + static const uint32_t CSM_UNIFORM_VECTORS = 61U; + // all global uniform used vectors count. + static const uint32_t GLOBAL_UNIFORM_VECTORS = 64U; // weak reference gfx::RenderPass *_renderPass{nullptr}; diff --git a/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp b/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp index ed29ca3a79..1a8d85dc1a 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp @@ -93,7 +93,7 @@ void ShadowStage::render(scene::Camera *camera) { switch (_light->getType()) { case scene::LightType::DIRECTIONAL: { const auto* mainLight = static_cast(_light); - if (mainLight->isShadowFixedArea() || mainLight->getCSMLevel() == scene::CSMLevel::LEVEL_1) { + if (mainLight->isShadowFixedArea() || mainLight->getCSMLevel() == scene::CSMLevel::LEVEL_1 || !sceneData->getCSMSupported()) { _renderArea.x = 0; _renderArea.y = 0; _renderArea.width = static_cast(shadowMapSize.x); diff --git a/native/tools/tojs/pipeline.ini b/native/tools/tojs/pipeline.ini index ec1199165d..ec0d03d834 100644 --- a/native/tools/tojs/pipeline.ini +++ b/native/tools/tojs/pipeline.ini @@ -57,7 +57,7 @@ skip = ForwardPipeline::[getOrCreateRenderPass getLightsUBO getValidLights getLi PostProcessStage::[initialize activate destroy render getUIPhase getUIPhase], GlobalDSManager::[activate destroy], GeometryRenderer::[activate render destroy], - PipelineSceneData::[(g|s)etRenderObjects (g|s)etShadowObjects getShadowFramebufferMap getCSMLayers], + PipelineSceneData::[(g|s)etRenderObjects (g|s)etShadowObjects getShadowFramebufferMap getCSMLayers (g|s)etCSMSupported], CSMLayers::[update (g|s)etCastShadowObjects addCastShadowObject clearCastShadowObjects (g|s)etLayerObjects addLayerObject clearLayerObjects getLayers getSpecialLayer] rename_functions = From ca7a3e35afe109178754aa2b6ea5099866d161ca Mon Sep 17 00:00:00 2001 From: mikecoker Date: Wed, 20 Jul 2022 10:05:56 -0500 Subject: [PATCH 042/111] fix a leak with htmlcanvaselements (#11979) --- cocos/2d/assembler/label/font-utils.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/2d/assembler/label/font-utils.ts b/cocos/2d/assembler/label/font-utils.ts index cda68fea39..2208be9118 100644 --- a/cocos/2d/assembler/label/font-utils.ts +++ b/cocos/2d/assembler/label/font-utils.ts @@ -144,6 +144,7 @@ class LetterTexture { public destroy () { this.image = null; // Label._canvasPool.put(this._data); + CanvasPool.getInstance().put(this.data as ISharedLabelData); } private _updateProperties () { From 8951ed13ec91f78f8465a8b17eb9c50b1ae0c2f3 Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Thu, 21 Jul 2022 10:13:13 +0800 Subject: [PATCH 043/111] [bug] Fix planar shadow serialization problem v3.6.0 (#12086) --- cocos/core/pipeline/scene-culling.ts | 2 +- cocos/core/scene-graph/scene-globals.ts | 2 +- native/cocos/renderer/pipeline/SceneCulling.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/core/pipeline/scene-culling.ts b/cocos/core/pipeline/scene-culling.ts index b2b28f419a..2579f2b288 100644 --- a/cocos/core/pipeline/scene-culling.ts +++ b/cocos/core/pipeline/scene-culling.ts @@ -142,7 +142,7 @@ export function updatePlanarNormalAndDistance (shadowInfo: Shadows, shadowUBO: F shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3.x; shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3.y; shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 2] = _tempVec3.z; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = shadowInfo.distance; + shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = -shadowInfo.distance; } export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Camera) { diff --git a/cocos/core/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts index cfed18f5ed..0a0b30aa24 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -806,7 +806,7 @@ export class ShadowsInfo { @tooltip('i18n:shadow.planeHeight') set planeHeight (val: number) { this._distance = val; - if (this._resource) { this._resource.distance = -val; } + if (this._resource) { this._resource.distance = val; } } get planeHeight () { return this._distance; diff --git a/native/cocos/renderer/pipeline/SceneCulling.cpp b/native/cocos/renderer/pipeline/SceneCulling.cpp index 31aae24490..c4a370b0f0 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.cpp +++ b/native/cocos/renderer/pipeline/SceneCulling.cpp @@ -150,7 +150,7 @@ void updateDirLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd void updatePlanarNormalAndDistance(const scene::Shadows* shadowInfo, ccstd::array* shadowUBO) { const Vec3 normal = shadowInfo->getNormal().getNormalized(); - const float planarNDInfo[4] = {normal.x, normal.y, normal.z, shadowInfo->getDistance()}; + const float planarNDInfo[4] = {normal.x, normal.y, normal.z, -shadowInfo->getDistance()}; memcpy(shadowUBO->data() + UBOShadow::PLANAR_NORMAL_DISTANCE_INFO_OFFSET, &planarNDInfo, sizeof(planarNDInfo)); } From db97f15096b0eb60495f06913c80773aa23361a5 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Thu, 21 Jul 2022 10:27:03 +0800 Subject: [PATCH 044/111] fix wrong orientation by use vulkan at android platform (#12109) --- native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp index 5f98de50bd..3da6327b8a 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp @@ -193,7 +193,7 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { _gpuSwapchain->createInfo.imageExtent = imageExtent; _gpuSwapchain->createInfo.imageUsage = imageUsage; _gpuSwapchain->createInfo.imageArrayLayers = 1; - _gpuSwapchain->createInfo.preTransform = surfaceCapabilities.currentTransform; + _gpuSwapchain->createInfo.preTransform = VkSurfaceTransformFlagBitsKHR::VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; _gpuSwapchain->createInfo.compositeAlpha = compositeAlpha; _gpuSwapchain->createInfo.presentMode = swapchainPresentMode; _gpuSwapchain->createInfo.clipped = VK_TRUE; // Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area From 2fcd242b18acfe0776ac2f6e92cf977a793579f2 Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Thu, 21 Jul 2022 10:35:44 +0800 Subject: [PATCH 045/111] fix physx create terrain height out of range (#13252) (#12100) --- cocos/physics/physx/shapes/physx-terrain-shape.ts | 2 +- platforms/native/engine/jsb-physics.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/physics/physx/shapes/physx-terrain-shape.ts b/cocos/physics/physx/shapes/physx-terrain-shape.ts index 3a8fb9d4b4..aac0767c6a 100644 --- a/cocos/physics/physx/shapes/physx-terrain-shape.ts +++ b/cocos/physics/physx/shapes/physx-terrain-shape.ts @@ -32,7 +32,7 @@ import { PhysXInstance } from '../physx-instance'; import { EPhysXShapeType, PhysXShape } from './physx-shape'; export class PhysXTerrainShape extends PhysXShape implements ITerrainShape { - static heightScale = 1 / 5000; + static heightScale = 1 / 512; constructor () { super(EPhysXShapeType.TERRAIN); diff --git a/platforms/native/engine/jsb-physics.js b/platforms/native/engine/jsb-physics.js index 860e0b9060..a4671a7ba1 100644 --- a/platforms/native/engine/jsb-physics.js +++ b/platforms/native/engine/jsb-physics.js @@ -20,7 +20,7 @@ jsbPhy.OBJECT = { }; jsbPhy.CONFIG = { - heightScale: 1 / 5000, + heightScale: 1 / 512, }; const books = jsbPhy.OBJECT.books; From 811ed11bfa1521105a915e341f9b4a10f87264d7 Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Thu, 21 Jul 2022 10:37:15 +0800 Subject: [PATCH 046/111] =?UTF-8?q?default=20physics=20material=20useing?= =?UTF-8?q?=20internal=20asset=20:=20default-physics-mate=E2=80=A6=20(#118?= =?UTF-8?q?55)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * default physics material useing internal asset : default-physics-material.pmtl. todo: Project Setting's physics material config need to use this asset too. (#12662) * support set default physics material value from project setting panel. It will effect the packaging processing, and scene loading(todo). this value will not be saved to default-physics-material.pmtl. * fix physics-system unit test failure: physics system 's constructAndRegister() will directly init default physics material if the default physics material asset is ready * minor modification of PhysicsSystem::_updateMaterial --- cc.config.json | 12 ++-- cocos/physics/framework/physics-selector.ts | 2 - cocos/physics/framework/physics-system.ts | 68 ++++++++++++++----- editor/assets/physics.meta | 12 ++++ .../physics/default-physics-material.pmtl | 10 +++ .../default-physics-material.pmtl.meta | 11 +++ tests/fixtures/builtin-physics-material.ts | 9 +++ tests/init.ts | 5 +- 8 files changed, 106 insertions(+), 23 deletions(-) create mode 100644 editor/assets/physics.meta create mode 100644 editor/assets/physics/default-physics-material.pmtl create mode 100644 editor/assets/physics/default-physics-material.pmtl.meta create mode 100644 tests/fixtures/builtin-physics-material.ts diff --git a/cc.config.json b/cc.config.json index 0abf04065e..b7a4593140 100644 --- a/cc.config.json +++ b/cc.config.json @@ -57,10 +57,14 @@ }, "particle-2d": { "modules": [ "particle-2d" ] }, "physics-framework": { "modules": [ "physics-framework" ] }, - "physics-cannon": { "modules": [ "physics-cannon", "physics-framework" ] }, - "physics-physx": { "modules": [ "physics-physx", "physics-framework" ] }, - "physics-ammo": { "modules": [ "physics-ammo", "physics-framework", "wait-for-ammo-instantiation" ] }, - "physics-builtin": { "modules": [ "physics-builtin", "physics-framework" ] }, + "physics-cannon": { "modules": [ "physics-cannon", "physics-framework" ] , + "dependentAssets": [ "ba21476f-2866-4f81-9c4d-6e359316e448" ]}, + "physics-physx": { "modules": [ "physics-physx", "physics-framework" ] , + "dependentAssets": [ "ba21476f-2866-4f81-9c4d-6e359316e448" ]}, + "physics-ammo": { "modules": [ "physics-ammo", "physics-framework", "wait-for-ammo-instantiation" ] , + "dependentAssets": [ "ba21476f-2866-4f81-9c4d-6e359316e448" ]}, + "physics-builtin": { "modules": [ "physics-builtin", "physics-framework" ] , + "dependentAssets": [ "ba21476f-2866-4f81-9c4d-6e359316e448" ]}, "physics-2d-framework": { "modules": [ "physics-2d-framework" ] }, "physics-2d-box2d": { "modules": [ "physics-2d-box2d", "physics-2d-framework" ] }, "physics-2d-builtin": { "modules": [ "physics-2d-builtin", "physics-2d-framework" ] }, diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 284a98d27c..763c7145dc 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -156,7 +156,6 @@ function switchTo (id: IPhysicsEngineId) { const world = mutableSelector.physicsWorld; world.setGravity(worldInitData.gravity); world.setAllowSleep(worldInitData.allowSleep); - world.setDefaultMaterial(worldInitData.defaultMaterial); } } @@ -187,7 +186,6 @@ export function constructDefaultWorld (data: IWorldInitData) { const world = mutableSelector.physicsWorld = createPhysicsWorld(); world.setGravity(worldInitData.gravity); world.setAllowSleep(worldInitData.allowSleep); - world.setDefaultMaterial(worldInitData.defaultMaterial); } } diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index 1bf94dd628..595519fb00 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -24,15 +24,15 @@ */ import { EDITOR } from 'internal:constants'; -import { Vec3 } from '../../core/math'; +import { Vec3, builtinResMgr, RecyclePool, game, Enum } from '../../core'; import { IRaycastOptions } from '../spec/i-physics-world'; import { director, Director } from '../../core/director'; import { System } from '../../core/components'; import { PhysicsMaterial } from './assets/physics-material'; -import { RecyclePool, game, Enum } from '../../core'; + import { Ray } from '../../core/geometry'; import { PhysicsRayResult } from './physics-ray-result'; -import { IPhysicsConfig, ICollisionMatrix } from './physics-config'; +import { IPhysicsConfig, ICollisionMatrix, IPhysicsMaterial } from './physics-config'; import { CollisionMatrix } from './collision-matrix'; import { PhysicsGroup } from './physics-enum'; import { constructDefaultWorld, IWorldInitData, selector } from './physics-selector'; @@ -210,6 +210,25 @@ export class PhysicsSystem extends System implements IWorldInitData { return this._material; } + initDefaultMaterial () : void { + if (this._material != null) { + return; + } + + this._material = builtinResMgr.get('default-physics-material'); + if (this._material != null) { + //console.log('initDefaultMaterial'); + //console.log('this._materialConfig', this._materialConfig); + this.physicsWorld.setDefaultMaterial(this._material); + this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this); + + //set default physics material using material config + this.setDefaultMaterial(this._materialConfig); + } else { + console.error('PhysicsSystem initDefaultMaterial failed'); + } + } + /** * @en * Gets the wrappered object of the physical world through which you can access the actual underlying object. @@ -263,9 +282,9 @@ export class PhysicsSystem extends System implements IWorldInitData { private _accumulator = 0; private _sleepThreshold = 0.1; private readonly _gravity = new Vec3(0, -10, 0); - private readonly _material = new PhysicsMaterial(); + private _material!: PhysicsMaterial; //default physics material + private _materialConfig: IPhysicsMaterial = new PhysicsMaterial(); private static readonly _instance: PhysicsSystem | null = null; - private readonly raycastOptions: IRaycastOptions = { group: -1, mask: -1, @@ -277,7 +296,6 @@ export class PhysicsSystem extends System implements IWorldInitData { private constructor () { super(); - this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this); } postUpdate (deltaTime: number) { @@ -332,15 +350,10 @@ export class PhysicsSystem extends System implements IWorldInitData { const gravity = config ? config.gravity : settings.querySettings(Settings.Category.PHYSICS, 'gravity'); if (gravity) Vec3.copy(this._gravity, gravity); - const defaultMaterial = config ? config.defaultMaterial : settings.querySettings(Settings.Category.PHYSICS, 'defaultMaterial'); - if (defaultMaterial) { - this._material.setValues( - defaultMaterial.friction, - defaultMaterial.rollingFriction, - defaultMaterial.spinningFriction, - defaultMaterial.restitution, - ); - } + const defaultMaterialConfig = config ? config.defaultMaterial : settings.querySettings(Settings.Category.PHYSICS, 'defaultMaterial'); + //console.log('resetConfiguration'); + //console.log('defaultMaterialConfig', defaultMaterialConfig); + this._materialConfig = defaultMaterialConfig; const collisionMatrix = config ? config.collisionMatrix : settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix'); if (collisionMatrix) { @@ -360,10 +373,27 @@ export class PhysicsSystem extends System implements IWorldInitData { if (this.physicsWorld) { this.physicsWorld.setGravity(this._gravity); this.physicsWorld.setAllowSleep(this._allowSleep); - this.physicsWorld.setDefaultMaterial(this._material); } } + /** + * @en + * Set the default physics material to given value. + * @zh + * 设置默认物理材质到指定的值。 + */ + setDefaultMaterial (materialConfig : IPhysicsMaterial):void { + if (!this._material) return; + if (!materialConfig) return; + + this._material.setValues( + materialConfig.friction, + materialConfig.rollingFriction, + materialConfig.spinningFriction, + materialConfig.restitution, + ); + } + /** * @en * Reset the accumulator of time to given value. @@ -468,6 +498,12 @@ export class PhysicsSystem extends System implements IWorldInitData { constructDefaultWorld(sys); (PhysicsSystem._instance as unknown as PhysicsSystem) = sys; director.registerSystem(PhysicsSystem.ID, sys, sys.priority); + + if (!builtinResMgr.get('default-physics-material')) { + game.onPostProjectInitDelegate.add(sys.initDefaultMaterial.bind(sys)); + } else { + sys.initDefaultMaterial(); + } } } } diff --git a/editor/assets/physics.meta b/editor/assets/physics.meta new file mode 100644 index 0000000000..030d815e47 --- /dev/null +++ b/editor/assets/physics.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "b80a0d17-b988-4ad3-b214-25df2694b0e7", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/physics/default-physics-material.pmtl b/editor/assets/physics/default-physics-material.pmtl new file mode 100644 index 0000000000..b50ff948b4 --- /dev/null +++ b/editor/assets/physics/default-physics-material.pmtl @@ -0,0 +1,10 @@ +{ + "__type__": "cc.PhysicMaterial", + "_name": "default-physics-material", + "_objFlags": 0, + "_native": "", + "_friction": 0.8, + "_rollingFriction": 0.1, + "_spinningFriction": 0.1, + "_restitution": 0.1 +} \ No newline at end of file diff --git a/editor/assets/physics/default-physics-material.pmtl.meta b/editor/assets/physics/default-physics-material.pmtl.meta new file mode 100644 index 0000000000..b47936b3f6 --- /dev/null +++ b/editor/assets/physics/default-physics-material.pmtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.1", + "importer": "physics-material", + "imported": true, + "uuid": "ba21476f-2866-4f81-9c4d-6e359316e448", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/tests/fixtures/builtin-physics-material.ts b/tests/fixtures/builtin-physics-material.ts new file mode 100644 index 0000000000..0e2dbf9c28 --- /dev/null +++ b/tests/fixtures/builtin-physics-material.ts @@ -0,0 +1,9 @@ +import { PhysicsMaterial } from "../../cocos/physics/framework/assets/physics-material"; +import { builtinResMgr, color, game, Game } from "../../cocos/core"; + +export function initBuiltinPhysicsMaterial () { + // default physics material material + const defaultPhysicsMtl = new PhysicsMaterial(); + defaultPhysicsMtl._uuid = 'default-physics-material'; + builtinResMgr.addAsset(defaultPhysicsMtl._uuid, defaultPhysicsMtl); +} \ No newline at end of file diff --git a/tests/init.ts b/tests/init.ts index c6d399c54f..896637bcba 100644 --- a/tests/init.ts +++ b/tests/init.ts @@ -100,6 +100,7 @@ import '../cocos/core/animation'; import { effects } from './fixtures/builtin-effects'; import { glsl4 } from './fixtures/builtin-glsl4'; import { initBuiltinMaterial } from './fixtures/builtin-material'; +import { initBuiltinPhysicsMaterial } from './fixtures/builtin-physics-material'; import '../cocos/2d/utils/dynamic-atlas/atlas-manager'; const canvas = document.createElement('canvas'); @@ -126,7 +127,9 @@ globalThis.waitThis((async () => { effect.onLoaded(); }); initBuiltinMaterial() - }); + }); + + initBuiltinPhysicsMaterial(); await game.init(config); await game.run(); })()); From 81a8656bd9763f89ead078cc5753fe66c20b2882 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Thu, 21 Jul 2022 10:57:49 +0800 Subject: [PATCH 047/111] update chunk and effect meta files (#12108) --- editor/assets/chunks/builtin/functionalities/fog.chunk.meta | 2 +- .../chunks/builtin/functionalities/morph-animation.chunk.meta | 2 +- .../builtin/functionalities/skinning-animation-dqs.chunk.meta | 2 +- .../builtin/functionalities/skinning-animation-lbs.chunk.meta | 2 +- .../chunks/builtin/functionalities/world-transform.chunk.meta | 2 +- editor/assets/chunks/builtin/internal/alpha-test.chunk.meta | 2 +- editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta | 2 +- .../assets/chunks/builtin/internal/particle-common.chunk.meta | 2 +- editor/assets/chunks/builtin/internal/particle-trail.chunk.meta | 2 +- .../assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta | 2 +- .../chunks/builtin/internal/particle-vs-legacy.chunk.meta | 2 +- editor/assets/chunks/builtin/internal/sprite-common.chunk.meta | 2 +- editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta | 2 +- .../assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta | 2 +- .../assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta | 2 +- editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta | 2 +- editor/assets/chunks/common/color/aces.chunk.meta | 2 +- editor/assets/chunks/common/color/gamma.chunk.meta | 2 +- editor/assets/chunks/common/common-define.chunk.meta | 2 +- editor/assets/chunks/common/data/packing.chunk.meta | 2 +- editor/assets/chunks/common/data/unpack.chunk.meta | 2 +- editor/assets/chunks/common/debug/debug-view-define.chunk.meta | 2 +- editor/assets/chunks/common/effect/fog.chunk.meta | 2 +- editor/assets/chunks/common/lighting/attenuation.chunk.meta | 2 +- editor/assets/chunks/common/lighting/brdf.chunk.meta | 2 +- editor/assets/chunks/common/lighting/functions.chunk.meta | 2 +- editor/assets/chunks/common/lighting/light-map.chunk.meta | 2 +- editor/assets/chunks/common/lighting/rect-area-light.chunk.meta | 2 +- editor/assets/chunks/common/math/coordinates.chunk.meta | 2 +- editor/assets/chunks/common/math/number.chunk.meta | 2 +- .../assets/chunks/common/math/octahedron-transform.chunk.meta | 2 +- editor/assets/chunks/common/math/transform.chunk.meta | 2 +- editor/assets/chunks/common/mesh/material.chunk.meta | 2 +- editor/assets/chunks/common/shadow/native-pcf.chunk.meta | 2 +- editor/assets/chunks/common/texture/cubemap.chunk.meta | 2 +- editor/assets/chunks/common/texture/texture-lod.chunk.meta | 2 +- editor/assets/chunks/deprecated.chunk.meta | 2 +- editor/assets/chunks/legacy/decode-base.chunk.meta | 2 +- editor/assets/chunks/legacy/decode-standard.chunk.meta | 2 +- editor/assets/chunks/legacy/decode.chunk.meta | 2 +- editor/assets/chunks/legacy/fog-base.chunk.meta | 2 +- editor/assets/chunks/legacy/fog-fs.chunk.meta | 2 +- editor/assets/chunks/legacy/fog-vs.chunk.meta | 2 +- editor/assets/chunks/legacy/input-standard.chunk.meta | 2 +- editor/assets/chunks/legacy/input.chunk.meta | 2 +- editor/assets/chunks/legacy/lighting.chunk.meta | 2 +- editor/assets/chunks/legacy/lightingmap-fs.chunk.meta | 2 +- editor/assets/chunks/legacy/lightingmap-vs.chunk.meta | 2 +- editor/assets/chunks/legacy/local-batch.chunk.meta | 2 +- .../assets/chunks/legacy/main-functions/general-vs.chunk.meta | 2 +- .../assets/chunks/legacy/main-functions/outline-fs.chunk.meta | 2 +- .../assets/chunks/legacy/main-functions/outline-vs.chunk.meta | 2 +- editor/assets/chunks/legacy/morph.chunk.meta | 2 +- editor/assets/chunks/legacy/output-standard.chunk.meta | 2 +- editor/assets/chunks/legacy/output.chunk.meta | 2 +- editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta | 2 +- .../assets/chunks/legacy/shading-standard-additive.chunk.meta | 2 +- editor/assets/chunks/legacy/shading-standard-base.chunk.meta | 2 +- editor/assets/chunks/legacy/shading-standard.chunk.meta | 2 +- editor/assets/chunks/legacy/shading-toon.chunk.meta | 2 +- editor/assets/chunks/legacy/shadow-map-base.chunk.meta | 2 +- editor/assets/chunks/legacy/shadow-map-fs.chunk.meta | 2 +- editor/assets/chunks/legacy/skinning.chunk.meta | 2 +- editor/assets/chunks/legacy/standard-surface-entry.chunk.meta | 2 +- .../data-structures/lighting-intermediate-data.chunk.meta | 2 +- .../lighting-models/data-structures/lighting-result.chunk.meta | 2 +- .../lighting-models/default-functions/simple-skin.chunk.meta | 2 +- .../assets/chunks/lighting-models/includes/standard.chunk.meta | 2 +- editor/assets/chunks/lighting-models/includes/toon.chunk.meta | 2 +- .../chunks/lighting-models/lighting-flow/common-flow.chunk.meta | 2 +- .../chunks/lighting-models/model-functions/standard.chunk.meta | 2 +- .../chunks/lighting-models/model-functions/toon.chunk.meta | 2 +- editor/assets/chunks/post-process/anti-aliasing.chunk.meta | 2 +- editor/assets/chunks/post-process/fxaa.chunk.meta | 2 +- .../chunks/shading-entries/data-structures/fs-input.chunk.meta | 2 +- .../chunks/shading-entries/data-structures/vs-fs.chunk.meta | 2 +- .../chunks/shading-entries/data-structures/vs-input.chunk.meta | 2 +- .../shading-entries/data-structures/vs-intermediate.chunk.meta | 2 +- .../chunks/shading-entries/data-structures/vs-output.chunk.meta | 2 +- .../main-functions/misc/silhouette-edge-fs.chunk.meta | 2 +- .../main-functions/misc/silhouette-edge-vs.chunk.meta | 2 +- .../shading-entries/main-functions/misc/sky-fs.chunk.meta | 2 +- .../shading-entries/main-functions/misc/sky-vs.chunk.meta | 2 +- .../main-functions/render-to-scene/fs.chunk.meta | 2 +- .../render-to-scene/pipeline/deferred-fs.chunk.meta | 2 +- .../render-to-scene/pipeline/forward-fs.chunk.meta | 2 +- .../main-functions/render-to-scene/vs.chunk.meta | 2 +- .../main-functions/render-to-shadowmap/fs.chunk.meta | 2 +- .../main-functions/render-to-shadowmap/vs.chunk.meta | 2 +- .../assets/chunks/surfaces/data-structures/standard.chunk.meta | 2 +- editor/assets/chunks/surfaces/data-structures/toon.chunk.meta | 2 +- .../chunks/surfaces/default-functions/common-vs.chunk.meta | 2 +- .../chunks/surfaces/default-functions/standard-fs.chunk.meta | 2 +- .../assets/chunks/surfaces/default-functions/toon-fs.chunk.meta | 2 +- .../chunks/surfaces/effect-macros/common-macros.chunk.meta | 2 +- .../surfaces/effect-macros/render-to-shadowmap.chunk.meta | 2 +- .../chunks/surfaces/effect-macros/silhouette-edge.chunk.meta | 2 +- editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta | 2 +- editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta | 2 +- editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta | 2 +- editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta | 2 +- editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta | 2 +- editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta | 2 +- .../chunks/surfaces/module-functions/common-vs.chunk.meta | 2 +- .../chunks/surfaces/module-functions/debug-view.chunk.meta | 2 +- .../chunks/surfaces/module-functions/standard-fs.chunk.meta | 2 +- .../assets/chunks/surfaces/module-functions/toon-fs.chunk.meta | 2 +- editor/assets/effects/builtin-billboard.effect.meta | 2 +- editor/assets/effects/builtin-camera-texture.effect.meta | 2 +- editor/assets/effects/builtin-clear-stencil.effect.meta | 2 +- editor/assets/effects/builtin-debug-renderer.effect.meta | 2 +- editor/assets/effects/builtin-geometry-renderer.effect.meta | 2 +- editor/assets/effects/builtin-graphics.effect.meta | 2 +- editor/assets/effects/builtin-occlusion-query.effect.meta | 2 +- editor/assets/effects/builtin-particle-gpu.effect.meta | 2 +- editor/assets/effects/builtin-particle-trail.effect.meta | 2 +- editor/assets/effects/builtin-particle.effect.meta | 2 +- editor/assets/effects/builtin-reflection-deferred.effect.meta | 2 +- editor/assets/effects/builtin-spine.effect.meta | 2 +- editor/assets/effects/builtin-sprite-renderer.effect.meta | 2 +- editor/assets/effects/builtin-sprite.effect.meta | 2 +- editor/assets/effects/builtin-unlit.effect.meta | 2 +- editor/assets/effects/builtin-wireframe.effect.meta | 2 +- .../dcc/surfaces-imported-metallic-roughness.effect.meta | 2 +- .../dcc/surfaces-imported-specular-glossiness.effect.meta | 2 +- editor/assets/effects/editor/gizmo.effect.meta | 2 +- editor/assets/effects/editor/grid-2d.effect.meta | 2 +- editor/assets/effects/editor/grid-stroke.effect.meta | 2 +- editor/assets/effects/editor/grid.effect.meta | 2 +- editor/assets/effects/editor/light.effect.meta | 2 +- editor/assets/effects/editor/terrain-circle-brush.effect.meta | 2 +- editor/assets/effects/editor/terrain-image-brush.effect.meta | 2 +- editor/assets/effects/editor/terrain-select-brush.effect.meta | 2 +- editor/assets/effects/pipeline/bloom.effect.meta | 2 +- editor/assets/effects/pipeline/deferred-lighting.effect.meta | 2 +- editor/assets/effects/pipeline/post-process.effect.meta | 2 +- editor/assets/effects/pipeline/skybox.effect.meta | 2 +- editor/assets/effects/pipeline/smaa.effect.meta | 2 +- editor/assets/effects/pipeline/tonemap.effect.meta | 2 +- editor/assets/effects/surfaces/sky.effect.meta | 2 +- editor/assets/effects/surfaces/standard.effect.meta | 2 +- editor/assets/effects/surfaces/toon.effect.meta | 2 +- editor/assets/effects/util/batched-unlit.effect.meta | 2 +- editor/assets/effects/util/profiler.effect.meta | 2 +- editor/assets/effects/util/sequence-anim.effect.meta | 2 +- editor/assets/effects/util/splash-screen.effect.meta | 2 +- 156 files changed, 156 insertions(+), 156 deletions(-) diff --git a/editor/assets/chunks/builtin/functionalities/fog.chunk.meta b/editor/assets/chunks/builtin/functionalities/fog.chunk.meta index 58cb06b250..760dfe7d31 100644 --- a/editor/assets/chunks/builtin/functionalities/fog.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/fog.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "02a04bf3-4c27-4596-81fd-dfc35224f1d1", diff --git a/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta index 354b4ae4f8..3bc483a242 100644 --- a/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3adaa06a-e674-487c-9d49-42bc398c255b", diff --git a/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta index 4daae2933a..b2af9f5561 100644 --- a/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "80908463-4566-4fdf-9744-775605cd7ab7", diff --git a/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta index fb212ed6dd..f0740c7d8e 100644 --- a/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "258a17ce-6c50-4e8a-92aa-8ecec1a6af24", diff --git a/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta b/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta index 6d7ea1fe6b..88f1d9961d 100644 --- a/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "c2885f54-4ff2-4284-8bbc-b77bc71965b4", diff --git a/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta b/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta index 575c886b84..bac2e2d260 100644 --- a/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta +++ b/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "2c3da5b6-0202-470a-a915-59f1e2968853", diff --git a/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta index 10ddc4f29f..fb3ba3d851 100644 --- a/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta +++ b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "ef4fb7de-9b39-4eeb-9ae8-d292ff94a452", diff --git a/editor/assets/chunks/builtin/internal/particle-common.chunk.meta b/editor/assets/chunks/builtin/internal/particle-common.chunk.meta index d1117e8fa3..452f0a8667 100644 --- a/editor/assets/chunks/builtin/internal/particle-common.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-common.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7a49db3a-930e-4ffc-8659-a82141dabebb", diff --git a/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta b/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta index c299ebfbca..90b911d7c9 100644 --- a/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "df7d02d8-559a-4c02-9aac-3732cfc83d7a", diff --git a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta index 814eb46b72..07624b6cb8 100644 --- a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "b4b00c01-eca8-4ae4-a04d-e00bbeb6d0e0", diff --git a/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta index 3654188849..f2fc3d2483 100644 --- a/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "6e1b48cb-69c8-448c-8055-69ab9793fbab", diff --git a/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta b/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta index 1b9639a9a5..19ab4b6952 100644 --- a/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta +++ b/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "35822e78-bb35-405f-87bd-d42af6ac9ede", diff --git a/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta b/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta index b99baf3b52..79d2474698 100644 --- a/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta +++ b/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4b48672e-e044-4035-9029-13afb50c1aee", diff --git a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta index 3f38763db3..6511219a49 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "c3e3500f-370c-4da1-92f9-d0d9fd806bd8", diff --git a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta index 785b080d44..8a554d4208 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "17e8e047-4c5e-412c-85c8-a76a98742f2a", diff --git a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta index af73e27c3c..9d0d0fad91 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "cd94308c-6959-4671-9dcb-6c58342273e2", diff --git a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta index c20ac85e4e..53dd5b0098 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5e0f5e6e-5008-497f-b223-4e5f1801d8fd", diff --git a/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta index 78b4e93f32..73ede74a6f 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1ea907a3-a36e-432a-ae38-af712c77aaad", diff --git a/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta index 42d24030dc..4f9e7f7efc 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "fa1c0cd1-03c6-45dd-8294-bf7a1e21aad4", diff --git a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta index 50f2d38f86..853ddc200a 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "21b24bc9-a158-488e-b27c-b98a461fb438", diff --git a/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta index b30beab87f..0686dc98f4 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e835c2d5-a377-4197-bdb8-382037573494", diff --git a/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta index 003376ce0a..5ea9bba5c4 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "94d19070-32c6-4900-a288-2258fda37f29", diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta index b8d0fb62b5..e20bf64968 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e8411010-e411-43ab-8f2e-4f4865dca4cf", diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta index a148f8d4bd..295624e6ff 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "69f8ecd8-cdc9-4655-a6ec-d39dacdffc2f", diff --git a/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta index a23d9b8235..d657b6681b 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "99488fd6-220b-4d13-9a41-8b9439cd3944", diff --git a/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta index f60c1335b6..cdb49e8e32 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "669458fe-c428-40cd-8575-51607aa8edbc", diff --git a/editor/assets/chunks/common/color/aces.chunk.meta b/editor/assets/chunks/common/color/aces.chunk.meta index ed401b322f..faba7c9f8b 100644 --- a/editor/assets/chunks/common/color/aces.chunk.meta +++ b/editor/assets/chunks/common/color/aces.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7efbe295-0202-4979-8cda-6cfe35e086cf", diff --git a/editor/assets/chunks/common/color/gamma.chunk.meta b/editor/assets/chunks/common/color/gamma.chunk.meta index 00ea376a9e..09cb52dbeb 100644 --- a/editor/assets/chunks/common/color/gamma.chunk.meta +++ b/editor/assets/chunks/common/color/gamma.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "bb213412-2e68-43b3-9de5-73ca332acace", diff --git a/editor/assets/chunks/common/common-define.chunk.meta b/editor/assets/chunks/common/common-define.chunk.meta index bcaeda1c0f..bc5f8672cc 100644 --- a/editor/assets/chunks/common/common-define.chunk.meta +++ b/editor/assets/chunks/common/common-define.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9d86a3e4-ec06-4e51-ba68-45f2b7739fbb", diff --git a/editor/assets/chunks/common/data/packing.chunk.meta b/editor/assets/chunks/common/data/packing.chunk.meta index 5e7417f776..8c0ac60eb4 100644 --- a/editor/assets/chunks/common/data/packing.chunk.meta +++ b/editor/assets/chunks/common/data/packing.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "73866dd2-eaf5-40af-a061-1b9d38782204", diff --git a/editor/assets/chunks/common/data/unpack.chunk.meta b/editor/assets/chunks/common/data/unpack.chunk.meta index d22d3257f1..bcb9a88365 100644 --- a/editor/assets/chunks/common/data/unpack.chunk.meta +++ b/editor/assets/chunks/common/data/unpack.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e3e5d086-acc9-4dd8-98e8-24ac02f547d5", diff --git a/editor/assets/chunks/common/debug/debug-view-define.chunk.meta b/editor/assets/chunks/common/debug/debug-view-define.chunk.meta index 81ea67f60a..ca074c5fbf 100644 --- a/editor/assets/chunks/common/debug/debug-view-define.chunk.meta +++ b/editor/assets/chunks/common/debug/debug-view-define.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9c973ee8-952a-4ee3-a617-ba6397db6bac", diff --git a/editor/assets/chunks/common/effect/fog.chunk.meta b/editor/assets/chunks/common/effect/fog.chunk.meta index 9291399821..2e3a0ef339 100644 --- a/editor/assets/chunks/common/effect/fog.chunk.meta +++ b/editor/assets/chunks/common/effect/fog.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "399f5890-dde1-40de-9751-a7aa91a56b93", diff --git a/editor/assets/chunks/common/lighting/attenuation.chunk.meta b/editor/assets/chunks/common/lighting/attenuation.chunk.meta index 75f253af0f..6e0822a887 100644 --- a/editor/assets/chunks/common/lighting/attenuation.chunk.meta +++ b/editor/assets/chunks/common/lighting/attenuation.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "077cca29-6f66-4aad-a3a7-4f0a7ecd523f", diff --git a/editor/assets/chunks/common/lighting/brdf.chunk.meta b/editor/assets/chunks/common/lighting/brdf.chunk.meta index 14002851f1..27adcff968 100644 --- a/editor/assets/chunks/common/lighting/brdf.chunk.meta +++ b/editor/assets/chunks/common/lighting/brdf.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3a85eafd-0fd0-468f-8a2e-0c81493230c7", diff --git a/editor/assets/chunks/common/lighting/functions.chunk.meta b/editor/assets/chunks/common/lighting/functions.chunk.meta index 650ec89532..0007383998 100644 --- a/editor/assets/chunks/common/lighting/functions.chunk.meta +++ b/editor/assets/chunks/common/lighting/functions.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "d360c347-a546-4967-bdd3-30cae323f123", diff --git a/editor/assets/chunks/common/lighting/light-map.chunk.meta b/editor/assets/chunks/common/lighting/light-map.chunk.meta index 6ba97ff7df..c408be98e3 100644 --- a/editor/assets/chunks/common/lighting/light-map.chunk.meta +++ b/editor/assets/chunks/common/lighting/light-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "00e591cd-469d-4611-adb9-a5ca965a0552", diff --git a/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta b/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta index 2960457ec7..414e0f636a 100644 --- a/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta +++ b/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a24fb7a1-f7a5-430c-a8b2-e4c516131086", diff --git a/editor/assets/chunks/common/math/coordinates.chunk.meta b/editor/assets/chunks/common/math/coordinates.chunk.meta index 673d9ae7b7..356a11304d 100644 --- a/editor/assets/chunks/common/math/coordinates.chunk.meta +++ b/editor/assets/chunks/common/math/coordinates.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e9d8b3bb-03e4-46b2-be29-ea58fac18c18", diff --git a/editor/assets/chunks/common/math/number.chunk.meta b/editor/assets/chunks/common/math/number.chunk.meta index 000a1f2345..8327256642 100644 --- a/editor/assets/chunks/common/math/number.chunk.meta +++ b/editor/assets/chunks/common/math/number.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9f84c121-c61b-499f-b400-81a5448d6078", diff --git a/editor/assets/chunks/common/math/octahedron-transform.chunk.meta b/editor/assets/chunks/common/math/octahedron-transform.chunk.meta index db4b5cf3dc..e990809fa2 100644 --- a/editor/assets/chunks/common/math/octahedron-transform.chunk.meta +++ b/editor/assets/chunks/common/math/octahedron-transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "41f91fc1-5aec-45dd-91ca-39ab964f8054", diff --git a/editor/assets/chunks/common/math/transform.chunk.meta b/editor/assets/chunks/common/math/transform.chunk.meta index d3270470d9..1bd281d564 100644 --- a/editor/assets/chunks/common/math/transform.chunk.meta +++ b/editor/assets/chunks/common/math/transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "0de81d5f-2a3e-467e-bcf5-84f7828edab6", diff --git a/editor/assets/chunks/common/mesh/material.chunk.meta b/editor/assets/chunks/common/mesh/material.chunk.meta index 58551fa823..5186e23dab 100644 --- a/editor/assets/chunks/common/mesh/material.chunk.meta +++ b/editor/assets/chunks/common/mesh/material.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f992af76-5145-4f8e-beae-6d88be403e8e", diff --git a/editor/assets/chunks/common/shadow/native-pcf.chunk.meta b/editor/assets/chunks/common/shadow/native-pcf.chunk.meta index 95779e1cc1..5e1e511993 100644 --- a/editor/assets/chunks/common/shadow/native-pcf.chunk.meta +++ b/editor/assets/chunks/common/shadow/native-pcf.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "cac4ba94-f412-4899-83b1-ce035b0c09e0", diff --git a/editor/assets/chunks/common/texture/cubemap.chunk.meta b/editor/assets/chunks/common/texture/cubemap.chunk.meta index 824fdc2036..a26916f2eb 100644 --- a/editor/assets/chunks/common/texture/cubemap.chunk.meta +++ b/editor/assets/chunks/common/texture/cubemap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3931bd87-0a7b-4d2d-a5f1-9544227343a8", diff --git a/editor/assets/chunks/common/texture/texture-lod.chunk.meta b/editor/assets/chunks/common/texture/texture-lod.chunk.meta index 6f3bad78d9..794063d21a 100644 --- a/editor/assets/chunks/common/texture/texture-lod.chunk.meta +++ b/editor/assets/chunks/common/texture/texture-lod.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "d26f7be9-ac7f-4dfd-88ee-6657dfe3426e", diff --git a/editor/assets/chunks/deprecated.chunk.meta b/editor/assets/chunks/deprecated.chunk.meta index 4c57b9fe65..8eab61fa91 100644 --- a/editor/assets/chunks/deprecated.chunk.meta +++ b/editor/assets/chunks/deprecated.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "355259fc-3a13-4fed-b553-a5e2caeb2e75", diff --git a/editor/assets/chunks/legacy/decode-base.chunk.meta b/editor/assets/chunks/legacy/decode-base.chunk.meta index badd50fc3d..5987d28c61 100644 --- a/editor/assets/chunks/legacy/decode-base.chunk.meta +++ b/editor/assets/chunks/legacy/decode-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e05f440c-0ba5-4c83-a039-5644d248bb87", diff --git a/editor/assets/chunks/legacy/decode-standard.chunk.meta b/editor/assets/chunks/legacy/decode-standard.chunk.meta index 5f72be4425..76fa7d87af 100644 --- a/editor/assets/chunks/legacy/decode-standard.chunk.meta +++ b/editor/assets/chunks/legacy/decode-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "8daa33da-9438-4294-aace-2a58d1b183ab", diff --git a/editor/assets/chunks/legacy/decode.chunk.meta b/editor/assets/chunks/legacy/decode.chunk.meta index c9784e1a4f..815fe18760 100644 --- a/editor/assets/chunks/legacy/decode.chunk.meta +++ b/editor/assets/chunks/legacy/decode.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "385a7ca1-9421-475c-aa02-38d52ef3ba7f", diff --git a/editor/assets/chunks/legacy/fog-base.chunk.meta b/editor/assets/chunks/legacy/fog-base.chunk.meta index 6a0164cf37..621bc94080 100644 --- a/editor/assets/chunks/legacy/fog-base.chunk.meta +++ b/editor/assets/chunks/legacy/fog-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "84b6c1d8-edf3-4d07-9151-8f7ec568fd69", diff --git a/editor/assets/chunks/legacy/fog-fs.chunk.meta b/editor/assets/chunks/legacy/fog-fs.chunk.meta index 254c62b66d..c63910a58e 100644 --- a/editor/assets/chunks/legacy/fog-fs.chunk.meta +++ b/editor/assets/chunks/legacy/fog-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5915ee07-9b06-4383-9b98-5b292bd116e9", diff --git a/editor/assets/chunks/legacy/fog-vs.chunk.meta b/editor/assets/chunks/legacy/fog-vs.chunk.meta index 927934a2bc..cd31a3c843 100644 --- a/editor/assets/chunks/legacy/fog-vs.chunk.meta +++ b/editor/assets/chunks/legacy/fog-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "0bc1a9f5-9282-4192-a0d4-4818568f2b16", diff --git a/editor/assets/chunks/legacy/input-standard.chunk.meta b/editor/assets/chunks/legacy/input-standard.chunk.meta index e207992247..5251175db1 100644 --- a/editor/assets/chunks/legacy/input-standard.chunk.meta +++ b/editor/assets/chunks/legacy/input-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f957d7e0-a3eb-480c-b3c6-43a1a5273b71", diff --git a/editor/assets/chunks/legacy/input.chunk.meta b/editor/assets/chunks/legacy/input.chunk.meta index c42482bae0..27b99aeb1c 100644 --- a/editor/assets/chunks/legacy/input.chunk.meta +++ b/editor/assets/chunks/legacy/input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3b9a2995-9fa1-4862-9bcf-9b6fa2c64bd4", diff --git a/editor/assets/chunks/legacy/lighting.chunk.meta b/editor/assets/chunks/legacy/lighting.chunk.meta index 9441cbaf19..b7b414e28a 100644 --- a/editor/assets/chunks/legacy/lighting.chunk.meta +++ b/editor/assets/chunks/legacy/lighting.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4b078b9b-ae79-4653-bc9d-d70e69b49f4b", diff --git a/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta b/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta index 1339518218..6e33014baa 100644 --- a/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta +++ b/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1cd3229a-63b6-438b-88e9-98afa7f1c69e", diff --git a/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta b/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta index ac4b38351c..da17d515ec 100644 --- a/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta +++ b/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "d22a3ca1-78fe-442c-a604-0349f5c873f7", diff --git a/editor/assets/chunks/legacy/local-batch.chunk.meta b/editor/assets/chunks/legacy/local-batch.chunk.meta index cd7932b447..8556ca2c67 100644 --- a/editor/assets/chunks/legacy/local-batch.chunk.meta +++ b/editor/assets/chunks/legacy/local-batch.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "bcff50e8-1d1f-4aea-bd0c-6868a4f2a45b", diff --git a/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta b/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta index 522b83410b..874741a555 100644 --- a/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "2cdcf2a6-42f3-4142-a340-eabfe530ccbf", diff --git a/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta index 31abf0e7b0..5c736f4ad9 100644 --- a/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4864e2f6-3eb5-4f08-a87a-5c98141cdef4", diff --git a/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta index 282d26c222..0984a95f92 100644 --- a/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f71444cb-cecf-4692-a310-2a5fdb96b469", diff --git a/editor/assets/chunks/legacy/morph.chunk.meta b/editor/assets/chunks/legacy/morph.chunk.meta index 0cf4637e72..7c900ae6a5 100644 --- a/editor/assets/chunks/legacy/morph.chunk.meta +++ b/editor/assets/chunks/legacy/morph.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "48359533-f5f1-4346-b242-66597abd9838", diff --git a/editor/assets/chunks/legacy/output-standard.chunk.meta b/editor/assets/chunks/legacy/output-standard.chunk.meta index 963d8ad8c4..4e7271e7d8 100644 --- a/editor/assets/chunks/legacy/output-standard.chunk.meta +++ b/editor/assets/chunks/legacy/output-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a3c0cc1c-64de-4e52-9698-5f73f8db488e", diff --git a/editor/assets/chunks/legacy/output.chunk.meta b/editor/assets/chunks/legacy/output.chunk.meta index b8bc4f3744..3d594a4524 100644 --- a/editor/assets/chunks/legacy/output.chunk.meta +++ b/editor/assets/chunks/legacy/output.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "713f0582-5c82-484f-81f7-5006e5a4f48f", diff --git a/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta b/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta index 456dad04bc..f40e8cf466 100644 --- a/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta +++ b/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "b2d386c6-615b-4375-accd-574405611e35", diff --git a/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta b/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta index adb70f1e55..73c4783751 100644 --- a/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a70c48b7-cf69-4c97-a857-21149cd71200", diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk.meta b/editor/assets/chunks/legacy/shading-standard-base.chunk.meta index e2532ae168..adef3c3f57 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9ae7cfaf-c5cc-4899-95a5-d6e1215c8964", diff --git a/editor/assets/chunks/legacy/shading-standard.chunk.meta b/editor/assets/chunks/legacy/shading-standard.chunk.meta index 872b5824cc..2753b8f39a 100644 --- a/editor/assets/chunks/legacy/shading-standard.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f9ba1729-bacf-4e62-8c97-0103d940c464", diff --git a/editor/assets/chunks/legacy/shading-toon.chunk.meta b/editor/assets/chunks/legacy/shading-toon.chunk.meta index ae89c4d64e..0a067a7499 100644 --- a/editor/assets/chunks/legacy/shading-toon.chunk.meta +++ b/editor/assets/chunks/legacy/shading-toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "bbfd1dfb-8f99-4b68-9aa6-817d5b67096d", diff --git a/editor/assets/chunks/legacy/shadow-map-base.chunk.meta b/editor/assets/chunks/legacy/shadow-map-base.chunk.meta index a076463160..48cb2d8d89 100644 --- a/editor/assets/chunks/legacy/shadow-map-base.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1d68b1b7-2f78-4c24-9f35-b215dc980207", diff --git a/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta b/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta index dac386137d..7737ba3c7c 100644 --- a/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5716d893-2ecc-4110-9291-88b7e939d37d", diff --git a/editor/assets/chunks/legacy/skinning.chunk.meta b/editor/assets/chunks/legacy/skinning.chunk.meta index b2122b52e9..7c45a21b0c 100644 --- a/editor/assets/chunks/legacy/skinning.chunk.meta +++ b/editor/assets/chunks/legacy/skinning.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f1e9de44-ca95-48c8-9233-d1b5406ab544", diff --git a/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta b/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta index 7aa2c5a7a1..4952255b79 100644 --- a/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta +++ b/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "31d0a199-05e2-422c-a019-8139a855841c", diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta index a34b2330e0..47c4149611 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "be2dc7d9-db45-4d0b-957b-aee1cb81bde0", diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta index fdcb215751..ec12eb8e50 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7646cc74-5fcc-47c4-970b-5958505c17e5", diff --git a/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta b/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta index 2b899695c8..1c6eaafd8e 100644 --- a/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta +++ b/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9ada82f2-4c4e-433f-8090-e8bfad31fcf2", diff --git a/editor/assets/chunks/lighting-models/includes/standard.chunk.meta b/editor/assets/chunks/lighting-models/includes/standard.chunk.meta index ad70678752..aed47b8c7d 100644 --- a/editor/assets/chunks/lighting-models/includes/standard.chunk.meta +++ b/editor/assets/chunks/lighting-models/includes/standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "cc12f5ac-3dcf-4455-aea9-b9be2dd9071e", diff --git a/editor/assets/chunks/lighting-models/includes/toon.chunk.meta b/editor/assets/chunks/lighting-models/includes/toon.chunk.meta index b8099d0120..e50c36cac6 100644 --- a/editor/assets/chunks/lighting-models/includes/toon.chunk.meta +++ b/editor/assets/chunks/lighting-models/includes/toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "2710ad01-b6c3-4048-b5d9-b3b69cec3e94", diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta index 19fc3e1827..55ceff5cac 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "41c84281-f2e7-43e2-88bd-6ffcaf1daf5a", diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta b/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta index cf93dfd88f..07695ab1b5 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4c24618b-1e1d-40e4-883a-cd3fd2304233", diff --git a/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta b/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta index afbfaec417..f7999c03d4 100644 --- a/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta +++ b/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9276cd2c-6001-4f89-b024-f53f63628527", diff --git a/editor/assets/chunks/post-process/anti-aliasing.chunk.meta b/editor/assets/chunks/post-process/anti-aliasing.chunk.meta index e75d0351e9..52e21fdbbe 100644 --- a/editor/assets/chunks/post-process/anti-aliasing.chunk.meta +++ b/editor/assets/chunks/post-process/anti-aliasing.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "60bb7684-4cd7-4d19-96c4-262e12e0b025", diff --git a/editor/assets/chunks/post-process/fxaa.chunk.meta b/editor/assets/chunks/post-process/fxaa.chunk.meta index c1801612d6..63f3a4284f 100644 --- a/editor/assets/chunks/post-process/fxaa.chunk.meta +++ b/editor/assets/chunks/post-process/fxaa.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "0afb4a28-945f-48ac-91e5-6f483345f8ab", diff --git a/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta index 42a257d04c..dfaf28401b 100644 --- a/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "ec870cfb-9c88-4f70-929a-ae540a33075b", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta index 0397a96d5e..ae509452e5 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f3454fd7-28d9-48dd-a761-ebc8e26834ed", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta index 05258f96b8..1c0c4c3b8b 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "65084d4a-ae7c-4ca9-8448-f4cd405144b7", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta index e8eca09b32..3429e4df33 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "45e6b403-a354-48de-a1e1-e59238bd30b1", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta index bf692bfc58..bea46aabc9 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "513eb9a6-0193-4ab1-a7da-2ab087936caa", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta index 0af09667a2..ffdd36b88d 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1d7d5670-83c4-4dab-acf3-edb7ae758881", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta index 1d6a31a520..786eff84ec 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e25e8368-0f16-4322-981e-8b7eebc97afb", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta index ddc4b7b01d..ad13a831b1 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "6a27185f-415d-419c-95b0-85337e21eff9", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta index ff1eeaeabb..8231fd5cdb 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "070d960d-b2b5-437c-99da-0aeb502f7273", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta index 416f4df722..a2a0e6dd05 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "52b875e1-87c0-4dc5-a3f7-ce32cb4d93c6", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta index 282eca1aa7..2e7803fb24 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1101cf65-cc90-486b-b6a5-29ae060e01c7", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta index 01e57b893a..2184c1ffd7 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "349a2be0-c8d3-420c-9dd1-bf86e01a7055", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta index cfe1d49566..8a665f9597 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4306c0df-b6d6-4733-8a45-c85907f94d29", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta index fa25ea61ea..2597a07791 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a734c67a-3ce2-4978-bf57-080d1dfbbb43", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta index 942f03f737..9817d7fc3b 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7a668e36-d75e-488d-b47a-52591e07151d", diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta b/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta index 4c83acc676..59fc003fdb 100644 --- a/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "29b8aed8-f4da-471e-a036-4fffc28868f3", diff --git a/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta b/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta index 4940e02b61..8c506a3bb1 100644 --- a/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta +++ b/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7ac0dc35-81bc-4b7c-9701-a401747deccf", diff --git a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta index 68e84b64df..8de04a9d76 100644 --- a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "b3d7cc71-db0a-4f76-a2e1-c145c679180f", diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta index e2a4ec4208..406d413813 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "57b9c877-9855-47c0-bb6f-da3a2c19414e", diff --git a/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta index bf7c495dba..d5675a8111 100644 --- a/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3804c73c-5c8d-42cf-8382-6b64ab2ea7bc", diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta index 5fb3edc435..5a1200e89a 100644 --- a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5fb14bc4-12ef-4b8f-b2d2-e0a7df233e31", diff --git a/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta index 2f27574999..f19174c1cc 100644 --- a/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f66020b7-1a8a-424a-abf4-a8cbe80e410f", diff --git a/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta index 3886390638..71dd84019e 100644 --- a/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "2f746ff4-a6d3-41ec-bcd7-52c8283f3a57", diff --git a/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta index 48e61c6e3f..1e06271390 100644 --- a/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "dc6e17a4-b3b4-4316-8f1e-c925b6fab67c", diff --git a/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta index 1511825d54..a49c4e71ac 100644 --- a/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1de87047-07ab-491a-b418-588ff145eaec", diff --git a/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta index db736e4f9a..82c32350c4 100644 --- a/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "0d0afa06-80d6-45b8-9fa6-6f6ad947c00b", diff --git a/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta index ae8aeba766..abd2cec726 100644 --- a/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "698b9da6-3f0e-4113-8b1c-5ebc82e3ab3d", diff --git a/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta index 9e64e66c52..15d9e0d196 100644 --- a/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5a2c165c-7d8d-4ed5-9142-52f895dee13c", diff --git a/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta index c8212a7459..8df6b5aeac 100644 --- a/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "ef0e1f2a-454f-4613-959c-3d9da0cae4f8", diff --git a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta index a949abc4ad..a3e2ec1a71 100644 --- a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e1feba3c-c7a2-4208-9c1f-732b7e46abd4", diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta index 49ff1d145f..8d793ce426 100644 --- a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "30961f82-b8ef-4d3b-a9e5-944bb5e103f1", diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta index dcd7687993..eb9b75fcb7 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "6853f548-fd1c-4a96-94f3-ba6981fbefd4", diff --git a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta index e73d37d4cd..436be700d3 100644 --- a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "218130cc-7167-4535-b6b8-99807138bb39", diff --git a/editor/assets/effects/builtin-billboard.effect.meta b/editor/assets/effects/builtin-billboard.effect.meta index 0330371d48..b99edfc9ce 100644 --- a/editor/assets/effects/builtin-billboard.effect.meta +++ b/editor/assets/effects/builtin-billboard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "711ebe11-f673-4cd9-9a83-63c60ba54c5b", diff --git a/editor/assets/effects/builtin-camera-texture.effect.meta b/editor/assets/effects/builtin-camera-texture.effect.meta index c1306a4724..963bb6e224 100644 --- a/editor/assets/effects/builtin-camera-texture.effect.meta +++ b/editor/assets/effects/builtin-camera-texture.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "bf4078d6-d2d7-4073-83bb-cd6f1802e880", diff --git a/editor/assets/effects/builtin-clear-stencil.effect.meta b/editor/assets/effects/builtin-clear-stencil.effect.meta index 3bad34afcb..7d8f0c60b4 100644 --- a/editor/assets/effects/builtin-clear-stencil.effect.meta +++ b/editor/assets/effects/builtin-clear-stencil.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "810e96e4-e456-4468-9b59-f4e8f39732c0", diff --git a/editor/assets/effects/builtin-debug-renderer.effect.meta b/editor/assets/effects/builtin-debug-renderer.effect.meta index 100aa99380..5716841b4d 100644 --- a/editor/assets/effects/builtin-debug-renderer.effect.meta +++ b/editor/assets/effects/builtin-debug-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "ff9be190-20a4-4e48-b68c-76e3c7cff085", diff --git a/editor/assets/effects/builtin-geometry-renderer.effect.meta b/editor/assets/effects/builtin-geometry-renderer.effect.meta index 229c4ccaec..003d482453 100644 --- a/editor/assets/effects/builtin-geometry-renderer.effect.meta +++ b/editor/assets/effects/builtin-geometry-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "4bb480dd-8384-4bc9-987f-de67cc53052a", diff --git a/editor/assets/effects/builtin-graphics.effect.meta b/editor/assets/effects/builtin-graphics.effect.meta index 7a96ca66ad..4359b7a619 100644 --- a/editor/assets/effects/builtin-graphics.effect.meta +++ b/editor/assets/effects/builtin-graphics.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "1c02ae6f-4492-4915-b8f8-7492a3b1e4cd", diff --git a/editor/assets/effects/builtin-occlusion-query.effect.meta b/editor/assets/effects/builtin-occlusion-query.effect.meta index ab0239f48d..9df4581862 100644 --- a/editor/assets/effects/builtin-occlusion-query.effect.meta +++ b/editor/assets/effects/builtin-occlusion-query.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "d9937e59-61fe-4ec6-92ab-7ac5a19c89b0", diff --git a/editor/assets/effects/builtin-particle-gpu.effect.meta b/editor/assets/effects/builtin-particle-gpu.effect.meta index 2c6c603fed..a2520b7436 100644 --- a/editor/assets/effects/builtin-particle-gpu.effect.meta +++ b/editor/assets/effects/builtin-particle-gpu.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "971bdb23-3ff6-43eb-b422-1c30165a3663", diff --git a/editor/assets/effects/builtin-particle-trail.effect.meta b/editor/assets/effects/builtin-particle-trail.effect.meta index a924478f5c..2229e8dadf 100644 --- a/editor/assets/effects/builtin-particle-trail.effect.meta +++ b/editor/assets/effects/builtin-particle-trail.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "17debcc3-0a6b-4b8a-b00b-dc58b885581e", diff --git a/editor/assets/effects/builtin-particle.effect.meta b/editor/assets/effects/builtin-particle.effect.meta index 9f33a7edef..c03b1229ae 100644 --- a/editor/assets/effects/builtin-particle.effect.meta +++ b/editor/assets/effects/builtin-particle.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "d1346436-ac96-4271-b863-1f4fdead95b0", diff --git a/editor/assets/effects/builtin-reflection-deferred.effect.meta b/editor/assets/effects/builtin-reflection-deferred.effect.meta index 372ca1464d..ca823d592a 100644 --- a/editor/assets/effects/builtin-reflection-deferred.effect.meta +++ b/editor/assets/effects/builtin-reflection-deferred.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "99498f84-efe6-43a6-a9a7-e6e93eb845c1", diff --git a/editor/assets/effects/builtin-spine.effect.meta b/editor/assets/effects/builtin-spine.effect.meta index 9af7395abb..0fe556b993 100644 --- a/editor/assets/effects/builtin-spine.effect.meta +++ b/editor/assets/effects/builtin-spine.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "c27215d8-6835-4b68-bfbb-bdeac6100c04", diff --git a/editor/assets/effects/builtin-sprite-renderer.effect.meta b/editor/assets/effects/builtin-sprite-renderer.effect.meta index b0163d210a..02784a96f0 100644 --- a/editor/assets/effects/builtin-sprite-renderer.effect.meta +++ b/editor/assets/effects/builtin-sprite-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "6ef1defe-7997-477a-9b35-c18859ff8066", diff --git a/editor/assets/effects/builtin-sprite.effect.meta b/editor/assets/effects/builtin-sprite.effect.meta index 29f28e1cc8..2d830603b1 100644 --- a/editor/assets/effects/builtin-sprite.effect.meta +++ b/editor/assets/effects/builtin-sprite.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", diff --git a/editor/assets/effects/builtin-unlit.effect.meta b/editor/assets/effects/builtin-unlit.effect.meta index 460184af4a..a66c3e0920 100644 --- a/editor/assets/effects/builtin-unlit.effect.meta +++ b/editor/assets/effects/builtin-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "a3cd009f-0ab0-420d-9278-b9fdab939bbc", diff --git a/editor/assets/effects/builtin-wireframe.effect.meta b/editor/assets/effects/builtin-wireframe.effect.meta index 4dc7a7aa5a..8bc31eefbc 100644 --- a/editor/assets/effects/builtin-wireframe.effect.meta +++ b/editor/assets/effects/builtin-wireframe.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "81127eb0-7556-453c-b147-670782dd5e53", diff --git a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta index 78dc909476..05e963698b 100644 --- a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta +++ b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "994bae8e-8bfc-4bc4-a32d-ad924f9917d0", diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta index 29279dae5d..36d84ac32b 100644 --- a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "5b7d6814-90a6-4d9f-b7fd-410dca9de957", diff --git a/editor/assets/effects/editor/gizmo.effect.meta b/editor/assets/effects/editor/gizmo.effect.meta index d04dd02b1f..da110fe4b9 100644 --- a/editor/assets/effects/editor/gizmo.effect.meta +++ b/editor/assets/effects/editor/gizmo.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "9d6c6bde-2fe2-44ee-883b-909608948b04", diff --git a/editor/assets/effects/editor/grid-2d.effect.meta b/editor/assets/effects/editor/grid-2d.effect.meta index 0de78e4d9a..435d55ae85 100644 --- a/editor/assets/effects/editor/grid-2d.effect.meta +++ b/editor/assets/effects/editor/grid-2d.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "cb2c332a-fa5e-4235-a129-f011634bb7ad", diff --git a/editor/assets/effects/editor/grid-stroke.effect.meta b/editor/assets/effects/editor/grid-stroke.effect.meta index 29685ea2bb..a1571f491e 100644 --- a/editor/assets/effects/editor/grid-stroke.effect.meta +++ b/editor/assets/effects/editor/grid-stroke.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "4736e978-c8fa-449f-9cf6-fe0158ded9d7", diff --git a/editor/assets/effects/editor/grid.effect.meta b/editor/assets/effects/editor/grid.effect.meta index 78d9c604ea..ce5401dd4c 100644 --- a/editor/assets/effects/editor/grid.effect.meta +++ b/editor/assets/effects/editor/grid.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "ba35f02e-a81c-464c-bfc5-c788328da667", diff --git a/editor/assets/effects/editor/light.effect.meta b/editor/assets/effects/editor/light.effect.meta index 6d7e64d869..9a8c7639de 100644 --- a/editor/assets/effects/editor/light.effect.meta +++ b/editor/assets/effects/editor/light.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "e4e4cb19-8dd2-450d-ad20-1a818263b8d3", diff --git a/editor/assets/effects/editor/terrain-circle-brush.effect.meta b/editor/assets/effects/editor/terrain-circle-brush.effect.meta index 02be42bc8f..a777d57d97 100644 --- a/editor/assets/effects/editor/terrain-circle-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-circle-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "a3e72674-c38f-4336-a285-1826b1799cd7", diff --git a/editor/assets/effects/editor/terrain-image-brush.effect.meta b/editor/assets/effects/editor/terrain-image-brush.effect.meta index bdf635471b..5e5f19b091 100644 --- a/editor/assets/effects/editor/terrain-image-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-image-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "7a115de7-2d94-4620-8b89-766d7f8cbff9", diff --git a/editor/assets/effects/editor/terrain-select-brush.effect.meta b/editor/assets/effects/editor/terrain-select-brush.effect.meta index 63be517a0b..3509cb6b08 100644 --- a/editor/assets/effects/editor/terrain-select-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-select-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "9b4d3fa5-89bf-4715-b69a-dbbd1efaf6a5", diff --git a/editor/assets/effects/pipeline/bloom.effect.meta b/editor/assets/effects/pipeline/bloom.effect.meta index 4c2ea4ad1f..31ef120dd6 100644 --- a/editor/assets/effects/pipeline/bloom.effect.meta +++ b/editor/assets/effects/pipeline/bloom.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "28d6d6b8-3f66-4a73-9795-17a0852ba2d4", diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect.meta b/editor/assets/effects/pipeline/deferred-lighting.effect.meta index 9b7398987d..d473a6e17d 100644 --- a/editor/assets/effects/pipeline/deferred-lighting.effect.meta +++ b/editor/assets/effects/pipeline/deferred-lighting.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "5d45aa00-e064-4938-b314-4265f0c2258c", diff --git a/editor/assets/effects/pipeline/post-process.effect.meta b/editor/assets/effects/pipeline/post-process.effect.meta index 22332aa354..00fc08ae12 100644 --- a/editor/assets/effects/pipeline/post-process.effect.meta +++ b/editor/assets/effects/pipeline/post-process.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "ec8106fe-05bf-4e94-943c-e0d3b7bb5e45", diff --git a/editor/assets/effects/pipeline/skybox.effect.meta b/editor/assets/effects/pipeline/skybox.effect.meta index 8772f85d25..bcfe4cc866 100644 --- a/editor/assets/effects/pipeline/skybox.effect.meta +++ b/editor/assets/effects/pipeline/skybox.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "511d2633-09a7-4bdd-ac42-f778032124b3", diff --git a/editor/assets/effects/pipeline/smaa.effect.meta b/editor/assets/effects/pipeline/smaa.effect.meta index 77044b5679..76f2381c99 100644 --- a/editor/assets/effects/pipeline/smaa.effect.meta +++ b/editor/assets/effects/pipeline/smaa.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "6624c63c-0e3d-4d5f-bd15-a7805b71c521", diff --git a/editor/assets/effects/pipeline/tonemap.effect.meta b/editor/assets/effects/pipeline/tonemap.effect.meta index 20ffa1b2d1..04ff4a614a 100644 --- a/editor/assets/effects/pipeline/tonemap.effect.meta +++ b/editor/assets/effects/pipeline/tonemap.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "31b152ff-f689-4082-a292-3eb5a0b33014", diff --git a/editor/assets/effects/surfaces/sky.effect.meta b/editor/assets/effects/surfaces/sky.effect.meta index e2aa6109bf..0178ca6f69 100644 --- a/editor/assets/effects/surfaces/sky.effect.meta +++ b/editor/assets/effects/surfaces/sky.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "6308c013-7d49-4160-9516-562dd205b480", diff --git a/editor/assets/effects/surfaces/standard.effect.meta b/editor/assets/effects/surfaces/standard.effect.meta index 466869b12f..d79f6cf3a5 100644 --- a/editor/assets/effects/surfaces/standard.effect.meta +++ b/editor/assets/effects/surfaces/standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "c8f66d17-351a-48da-a12c-0212d28575c4", diff --git a/editor/assets/effects/surfaces/toon.effect.meta b/editor/assets/effects/surfaces/toon.effect.meta index 1bdd20b5af..a40ba7fcb4 100644 --- a/editor/assets/effects/surfaces/toon.effect.meta +++ b/editor/assets/effects/surfaces/toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "9b20a514-6cc3-49de-b216-b6b863046249", diff --git a/editor/assets/effects/util/batched-unlit.effect.meta b/editor/assets/effects/util/batched-unlit.effect.meta index f6dbbb069e..5f0fe9590c 100644 --- a/editor/assets/effects/util/batched-unlit.effect.meta +++ b/editor/assets/effects/util/batched-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "f1556893-88b6-4c65-8c16-a5256ef3ad25", diff --git a/editor/assets/effects/util/profiler.effect.meta b/editor/assets/effects/util/profiler.effect.meta index 3673052970..a0bd1c8fd4 100644 --- a/editor/assets/effects/util/profiler.effect.meta +++ b/editor/assets/effects/util/profiler.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "871c3b6c-7379-419d-bda3-794b239ab90d", diff --git a/editor/assets/effects/util/sequence-anim.effect.meta b/editor/assets/effects/util/sequence-anim.effect.meta index 6c878d5975..2c4ed14748 100644 --- a/editor/assets/effects/util/sequence-anim.effect.meta +++ b/editor/assets/effects/util/sequence-anim.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "27cc5a0b-ec0b-4a67-98cf-b42d4fa971de", diff --git a/editor/assets/effects/util/splash-screen.effect.meta b/editor/assets/effects/util/splash-screen.effect.meta index 2b1b7c4e7d..02692371d7 100644 --- a/editor/assets/effects/util/splash-screen.effect.meta +++ b/editor/assets/effects/util/splash-screen.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "970b0598-bcb0-4714-91fb-2e81440dccd8", From 914170632557270f76a0d7b2e6e827790b947a47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Thu, 21 Jul 2022 11:35:29 +0800 Subject: [PATCH 048/111] update cmake list (#12107) --- native/CMakeLists.txt | 62 ++++------------------------ native/cmake/scripts/effects_gzip.js | 34 --------------- native/cmake/scripts/glsl_gzip.js | 55 ------------------------ 3 files changed, 8 insertions(+), 143 deletions(-) delete mode 100644 native/cmake/scripts/effects_gzip.js delete mode 100644 native/cmake/scripts/glsl_gzip.js diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index fb87d0fb4a..d42d87fc2b 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -29,7 +29,6 @@ cc_set_if_undefined(USE_JOB_SYSTEM_TBB OFF) cc_set_if_undefined(USE_PHYSICS_PHYSX OFF) cc_set_if_undefined(USE_MODULES OFF) cc_set_if_undefined(USE_SERVER_MODE OFF) -cc_set_if_undefined(USE_CCACHE OFF) cc_set_if_undefined(USE_PLUGINS ON) cc_set_if_undefined(USE_OCCLUSION_QUERY ON) cc_set_if_undefined(USE_DEBUG_RENDERER ON) @@ -39,7 +38,14 @@ cc_set_if_undefined(NET_MODE 0) # 0 is client cc_set_if_undefined(USE_REMOTE_LOG OFF) -add_definitions() +if(ANDROID AND NOT DEFINED USE_CCACHE) + if("$ENV{COCOS_USE_CCACHE}" STREQUAL "1") + message(STATUS "Enable ccache by env CC_USE_CACHE=1") + set(USE_CCACHE ON) + else() + set(USE_CCACHE OFF) + endif() +endif() if(NX) cc_set_if_undefined(CC_USE_VULKAN ON) @@ -2671,70 +2677,18 @@ list(APPEND COCOS_SOURCE_LIST ${CC_EXTERNAL_SOURCES}) ### generate source files - -function(compile_ts input_file_ts output_file) - get_filename_component(outdir ${output_file} DIRECTORY) - get_filename_component(from_ts ${input_file_ts} NAME) - add_custom_command( - OUTPUT ${output_file} - COMMAND ${CMAKE_COMMAND} -E echo " transform ${from_ts} file ${output_file}" - COMMAND ${TSC_EXECUTABLE} --module commonjs ${input_file_ts} --outDir ${outdir} - DEPENDS ${input_file_ts} - VERBATIM USES_TERMINAL - ) -endfunction() - -# compile_ts(${CWD}/../cocos/core/builtin/effects.ts ${CWD}/cocos/core/builtin/effects.js) -# compile_ts(${CWD}/../cocos/core/builtin/shader-sources/glsl1.ts ${CWD}/cocos/core/builtin/shader-sources/glsl1.js) -# compile_ts(${CWD}/../cocos/core/builtin/shader-sources/glsl3.ts ${CWD}/cocos/core/builtin/shader-sources/glsl3.js) -# compile_ts(${CWD}/../cocos/core/builtin/shader-sources/glsl4.ts ${CWD}/cocos/core/builtin/shader-sources/glsl4.js) - set(CC_GENERATED_FILES - # ${CWD}/cocos/core/builtin/Effects.cpp ${CWD}/cocos/core/builtin/DebugInfos.cpp - # ${CWD}/cocos/core/builtin/shader-sources/glsl1.cpp - # ${CWD}/cocos/core/builtin/shader-sources/glsl3.cpp - # ${CWD}/cocos/core/builtin/shader-sources/glsl4.cpp ) add_custom_target(builtin-res COMMAND ${CMAKE_COMMAND} -E echo "Generate builtin resources ..." - # COMMAND ${NODE_EXECUTABLE} ${CWD}/cmake/scripts/glsl_gzip.js - # ${CWD}/cocos/core/builtin/shader-sources/glsl1.js - # glsl1 - # ${CWD}/cocos/core/builtin/shader-sources/glsl1.cpp.in - # ${CWD}/cocos/core/builtin/shader-sources/glsl1.cpp - # COMMAND ${NODE_EXECUTABLE} ${CWD}/cmake/scripts/glsl_gzip.js - # ${CWD}/cocos/core/builtin/shader-sources/glsl3.js - # glsl3 - # ${CWD}/cocos/core/builtin/shader-sources/glsl3.cpp.in - # ${CWD}/cocos/core/builtin/shader-sources/glsl3.cpp - # COMMAND ${NODE_EXECUTABLE} ${CWD}/cmake/scripts/glsl_gzip.js - # ${CWD}/cocos/core/builtin/shader-sources/glsl4.js - # glsl4 - # ${CWD}/cocos/core/builtin/shader-sources/glsl4.cpp.in - # ${CWD}/cocos/core/builtin/shader-sources/glsl4.cpp - # COMMAND ${NODE_EXECUTABLE} ${CWD}/cmake/scripts/effects_gzip.js - # ${CWD}/cocos/core/builtin/effects.js - # effects - # ${CWD}/cocos/core/builtin/Effects.cpp.in - # ${CWD}/cocos/core/builtin/Effects.cpp COMMAND ${NODE_EXECUTABLE} ${CWD}/cmake/scripts/gen_debugInfos.js ${CWD}/../EngineErrorMap.md ${CWD}/cocos/core/builtin/DebugInfos.cpp.in ${CWD}/cocos/core/builtin/DebugInfos.cpp DEPENDS - # ${CWD}/cocos/core/builtin/shader-sources/glsl1.js - # ${CWD}/cocos/core/builtin/shader-sources/glsl3.js - # ${CWD}/cocos/core/builtin/shader-sources/glsl4.js - # ${CWD}/cocos/core/builtin/shader-sources/glsl1.cpp.in - # ${CWD}/cocos/core/builtin/shader-sources/glsl3.cpp.in - # ${CWD}/cocos/core/builtin/shader-sources/glsl4.cpp.in - # ${CWD}/cocos/core/builtin/effects.js - # ${CWD}/cocos/core/builtin/Effects.cpp.in ${CWD}/cocos/core/builtin/DebugInfos.cpp.in - # ${CWD}/cmake/scripts/glsl_gzip.js - # ${CWD}/cmake/scripts/effects_gzip.js VERBATIM USES_TERMINAL ) set_target_properties(builtin-res PROPERTIES FOLDER Utils) diff --git a/native/cmake/scripts/effects_gzip.js b/native/cmake/scripts/effects_gzip.js deleted file mode 100644 index 3b00c01cd6..0000000000 --- a/native/cmake/scripts/effects_gzip.js +++ /dev/null @@ -1,34 +0,0 @@ -const zlib = require('zlib'); -const fs = require('fs'); -const process = require('process'); -const writeIfDifferent = require('./utils').writeIfDifferent; - -if (process.argv.length !== 6) { - console.error('bad argument'); - console.error(' - input file'); - console.error(' - export var'); - console.error(' - template file'); - console.error(' - output file'); - process.exit(-1); -} - -const inputFile = process.argv[2]; -const exportVar = process.argv[3]; -const template = process.argv[4]; -const outputFile = process.argv[5]; - -let data = require(inputFile)[exportVar]; - -let encoded = zlib.gzipSync(JSON.stringify(data, null, 2)).toString("base64"); -let array = []; -let start = 0, last = encoded.length; -const charPerRow = 118; -while (start < last) { - array.push(`"${encoded.substr(start, charPerRow)}"`); - start += charPerRow; -} -encoded = array.join("\n"); -let replaceData = fs.readFileSync(template).toString('utf-8').replace("${PLACE_HOLDER}", encoded); -writeIfDifferent(outputFile, replaceData, { encoding: 'utf-8' }); - -process.exit(0); \ No newline at end of file diff --git a/native/cmake/scripts/glsl_gzip.js b/native/cmake/scripts/glsl_gzip.js deleted file mode 100644 index e97a045acd..0000000000 --- a/native/cmake/scripts/glsl_gzip.js +++ /dev/null @@ -1,55 +0,0 @@ -const zlib = require('zlib'); -const fs = require('fs'); -const process = require('process'); -const writeIfDifferent = require('./utils').writeIfDifferent; - -const VERBOSE = false; - -if (process.argv.length !== 6) { - console.error('bad argument'); - console.error(' - input file'); - console.error(' - export var'); - console.error(' - template file'); - console.error(' - output file'); - process.exit(-1); -} - -const inputFile = process.argv[2]; -const exportVar = process.argv[3]; -const template = process.argv[4]; -const outputFile = process.argv[5]; - -if(VERBOSE) { - console.log(`--processing ${inputFile} : ${exportVar}`); -} - -const shaders = require(inputFile)[exportVar]; - -let newShaders = shaders.map((eff)=> '{' + eff.map(s => { - let o = {...s}; - let arr = ['{\n']; - let shaders = []; - for(let i in o) { - let gziped = zlib.gzipSync(o[i]).toString("base64"); - shaders.push(` {"${i}", GzipedString("${gziped}")}`); - } - arr.push(shaders.join(",\n")); - arr.push('\n}'); - return arr.join(""); -}).join("\n,") + '}'); - -let encoded = newShaders.join(',\n'); - - -if(VERBOSE) { - console.log(`--gen ${outputFile} : ${exportVar}`); -} - -let replaceData = fs.readFileSync(template).toString('utf-8').replace("${PLACE_HOLDER}", encoded); -writeIfDifferent(outputFile, replaceData, {encoding: 'utf-8'}); - -if(VERBOSE) { - console.log(`--done ${outputFile} : ${exportVar}`); -} - -process.exit(0); \ No newline at end of file From 8ecfdeaf669b10e2715ac0072c7f2a97b2df0111 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Thu, 21 Jul 2022 11:41:44 +0800 Subject: [PATCH 049/111] Correct the logic to obtain the batching scheme. (#12094) --- native/cocos/scene/Pass.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/native/cocos/scene/Pass.cpp b/native/cocos/scene/Pass.cpp index eb94073fa7..b672e6dbfa 100644 --- a/native/cocos/scene/Pass.cpp +++ b/native/cocos/scene/Pass.cpp @@ -613,7 +613,7 @@ void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */) void Pass::syncBatchingScheme() { auto iter = _defines.find("USE_INSTANCING"); if (iter != _defines.end()) { - if (_device->hasFeature(gfx::Feature::INSTANCED_ARRAYS)) { + if (_device->hasFeature(gfx::Feature::INSTANCED_ARRAYS) && ccstd::get(iter->second)) { _batchingScheme = BatchingSchemes::INSTANCING; } else { iter->second = false; @@ -621,7 +621,7 @@ void Pass::syncBatchingScheme() { } } else { auto iter = _defines.find("USE_BATCHING"); - if (iter != _defines.end()) { + if (iter != _defines.end() && ccstd::get(iter->second)) { _batchingScheme = BatchingSchemes::VB_MERGING; } else { _batchingScheme = BatchingSchemes::NONE; From 2ae2d94b93109f9fb633403e11d153973ac7f308 Mon Sep 17 00:00:00 2001 From: Santy-Wang Date: Thu, 21 Jul 2022 11:50:43 +0800 Subject: [PATCH 050/111] optimize performance (#12080) * optimize performance * fix binding * fix bugs * fix bugs * fix crash * remove useless func * fix ci * fix ci * fix ci --- cocos/2d/assembler/mask/mask-assembler.ts | 3 +- cocos/2d/framework/ui-renderer.ts | 5 +- cocos/2d/renderer/native-2d.ts | 37 +-- cocos/2d/renderer/render-data.ts | 7 +- cocos/2d/renderer/render-draw-info.ts | 134 ++++++----- native/cocos/2d/renderer/Batcher2d.cpp | 85 ++++--- native/cocos/2d/renderer/Batcher2d.h | 9 +- native/cocos/2d/renderer/RenderDrawInfo.cpp | 141 +++-------- native/cocos/2d/renderer/RenderDrawInfo.h | 253 +++++++++++++------- native/cocos/2d/renderer/RenderEntity.cpp | 2 +- native/tools/tojs/2d.ini | 4 +- 11 files changed, 335 insertions(+), 345 deletions(-) diff --git a/cocos/2d/assembler/mask/mask-assembler.ts b/cocos/2d/assembler/mask/mask-assembler.ts index 77eb48e9d8..a564f0bd99 100644 --- a/cocos/2d/assembler/mask/mask-assembler.ts +++ b/cocos/2d/assembler/mask/mask-assembler.ts @@ -27,6 +27,7 @@ import { IBatcher } from '../../renderer/i-batcher'; import { Mask, MaskType } from '../../components/mask'; import { IAssembler, IAssemblerManager } from '../../renderer/base'; import { StencilManager } from '../../renderer/stencil-manager'; +import { RenderDrawInfoType } from '../../renderer/render-draw-info'; const _stencilManager = StencilManager.sharedManager!; @@ -45,7 +46,7 @@ function applyAreaMask (mask: Mask, renderer: IBatcher) { export const maskAssembler: IAssembler = { createData (mask: Mask) { - const renderData = mask.requestRenderData(); + const renderData = mask.requestRenderData(RenderDrawInfoType.MODEL); return renderData; }, diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index 74ed58e0de..99cb72f8d6 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -46,6 +46,7 @@ import { Renderer } from '../../core/components/renderer'; import { RenderEntity, RenderEntityType } from '../renderer/render-entity'; import { uiRendererManager } from './ui-renderer-manager'; import { assert, director } from '../../core'; +import { RenderDrawInfoType } from '../renderer/render-draw-info'; // hack ccenum(BlendFactor); @@ -382,9 +383,9 @@ export class UIRenderer extends Renderer { * @zh 请求新的渲染数据对象。 * @return The new render data */ - public requestRenderData () { + public requestRenderData (drawInfoType = RenderDrawInfoType.COMP) { const data = RenderData.add(); - data.initRenderDrawInfo(this); + data.initRenderDrawInfo(this, drawInfoType); this._renderData = data; return data; } diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index 8d76283afc..b1091cc197 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -6,18 +6,6 @@ import { Model } from '../../core/renderer/scene'; export declare class NativeRenderDrawInfo { constructor(); - get accId(): number; - set accId(accId: number); - - get bufferId(): number; - set bufferId(bufferId: number); - - get vertexOffset(): number; - set vertexOffset(vertexOffset: number); - - get indexOffset(): number; - set indexOffset(indexOffset: number); - get vbBuffer(): ArrayBufferLike; set vbBuffer(vbBuffer: ArrayBufferLike); @@ -30,44 +18,25 @@ export declare class NativeRenderDrawInfo { get iDataBuffer(): ArrayBufferLike; set iDataBuffer(iDataBuffer: ArrayBufferLike); - get vbCount(): number; - set vbCount(vbCount: number); - - get ibCount(): number; - set ibCount(ibCount: number); - - get vertDirty(): boolean; - set vertDirty(val: boolean); - - get dataHash(): number; - set dataHash(dataHash: number); - - get isMeshBuffer(): boolean; - set isMeshBuffer(isMeshBuffer: boolean); - get material(): Material | null; set material(material: Material | null); get texture(): Texture | null; set texture(texture: Texture | null); - get textureHash(): number; - set textureHash(textureHash: number); - get sampler(): Sampler | null; set sampler(sampler: Sampler | null); get model(): Model | null; set model(model: Model | null); - get drawInfoType(): number; - set drawInfoType(drawInfoType: number); - get subNode(): Node; set subNode(node: Node); - setRender2dBufferToNative(data: TypedArray, stride: number, size: number); + changeMeshBuffer(); + setRender2dBufferToNative(data: TypedArray); syncSharedBufferToNative(data: TypedArray); + getAttrSharedBufferForJS(): ArrayBufferLike; } export declare class NativeRenderEntity { diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index c9344004fc..5be1a829d5 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -178,8 +178,8 @@ export class BaseRenderData { } } - this.setRenderDrawInfoAttributes(); this.drawInfoType = drawInfoType; + this.setRenderDrawInfoAttributes(); } } @@ -415,8 +415,9 @@ export class RenderData extends BaseRenderData { if (!this._renderDrawInfo) { return; } - this.renderDrawInfo.initRender2dBuffer(this.dataLength, this.floatStride); - this.renderDrawInfo.setRender2dBufferToNative(); + this.renderDrawInfo.setStride(this.floatStride); + this.renderDrawInfo.setVBCount(this.dataLength); + this.renderDrawInfo.initRender2dBuffer(); } } diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts index 343c466f18..e8904d3917 100644 --- a/cocos/2d/renderer/render-draw-info.ts +++ b/cocos/2d/renderer/render-draw-info.ts @@ -6,9 +6,28 @@ import { director, Material, Node } from '../../core'; import { Sampler, Texture } from '../../core/gfx'; import { Model } from '../../core/renderer/scene'; -export enum RenderDrawInfoSharedBufferView { - enabled, - count, +export enum AttrUInt8ArrayView { + DrawInfoType, + VertDirty, + IsMeshBuffer, + Stride, + Count +} + +export enum AttrUInt16ArrayView { + BufferID, + AccessorID, + Count +} + +export enum AttrUInt32ArrayView { + VertexOffset, + IndexOffset, + VBCount, + IBCount, + TextureHash, + DataHash, + Count } export enum RenderDrawInfoType { @@ -18,50 +37,51 @@ export enum RenderDrawInfoType { } export class RenderDrawInfo { - public stencilStage: Stage = Stage.DISABLED; - protected _accId: number | undefined; - protected _bufferId: number | undefined; - protected _vertexOffset: number | undefined; - protected _indexOffset: number | undefined; - protected _vb: Float32Array | undefined; - protected _ib: Uint16Array | undefined; - protected _vData: Float32Array | undefined; - protected _iData: Uint16Array | undefined; - protected _vertDirty: boolean | undefined; - protected _vbCount: number | undefined; - protected _ibCount: number | undefined; - protected _dataHash: number | undefined; - protected _isMeshBuffer: boolean | undefined; - protected _material: Material | undefined; + protected _accId = -1; + protected _bufferId = -1; + protected _vertexOffset = 0; + protected _indexOffset = 0; + protected _vb: Float32Array | null = null; + protected _ib: Uint16Array | null = null; + protected _vData: Float32Array | null = null; + protected _iData: Uint16Array | null = null; + protected _vertDirty = false; + protected _vbCount = 0; + protected _ibCount = 0; + protected _dataHash = 0; + protected _isMeshBuffer = false; + protected _textureHash = 0; + protected _material: Material | null = null; protected _texture: Texture | null = null; - protected _textureHash: number | undefined; protected _sampler: Sampler | null = null; - //protected _blendHash: number | undefined; - - protected _model: Model | undefined; + protected _stride = 0; + protected _model: Model | null = null; protected _drawInfoType :RenderDrawInfoType = RenderDrawInfoType.COMP; - protected _subNode: Node | null = null; protected declare _nativeObj: NativeRenderDrawInfo; + protected _uint8SharedBuffer: Uint8Array; + protected _uint16SharedBuffer: Uint16Array; + protected _uint32SharedBuffer: Uint32Array; // SharedBuffer of pos/uv/color protected declare _render2dBuffer: Float32Array; - protected _vertexCount = 0; - protected _stride = 0; - constructor (nativeDrawInfo?: NativeRenderDrawInfo) { this.init(nativeDrawInfo); + const attrSharedBuffer = this._nativeObj.getAttrSharedBufferForJS(); + let offset = 0; + this._uint8SharedBuffer = new Uint8Array(attrSharedBuffer, offset, AttrUInt8ArrayView.Count); + offset += AttrUInt8ArrayView.Count * Uint8Array.BYTES_PER_ELEMENT; + this._uint16SharedBuffer = new Uint16Array(attrSharedBuffer, offset, AttrUInt16ArrayView.Count); + offset += AttrUInt16ArrayView.Count * Uint16Array.BYTES_PER_ELEMENT; + this._uint32SharedBuffer = new Uint32Array(attrSharedBuffer, offset, AttrUInt32ArrayView.Count); } get nativeObj () { return this._nativeObj; } - // set nativeObj (val:NativeRenderDrawInfo) { - // this._nativeObj = val; - // } get render2dBuffer () { return this._render2dBuffer; @@ -88,28 +108,31 @@ export class RenderDrawInfo { public setAccId (accId) { this._accId = accId; if (JSB) { - this._nativeObj.accId = accId; + this._uint16SharedBuffer[AttrUInt16ArrayView.AccessorID] = accId; } } public setBufferId (bufferId) { - this._bufferId = bufferId; if (JSB) { - this._nativeObj.bufferId = bufferId; + if (this._bufferId !== bufferId) { + this._uint16SharedBuffer[AttrUInt16ArrayView.BufferID] = bufferId; + this._nativeObj.changeMeshBuffer(); + } } + this._bufferId = bufferId; } public setVertexOffset (vertexOffset) { this._vertexOffset = vertexOffset; if (JSB) { - this._nativeObj.vertexOffset = vertexOffset; + this._uint32SharedBuffer[AttrUInt32ArrayView.VertexOffset] = vertexOffset; } } public setIndexOffset (indexOffset) { this._indexOffset = indexOffset; if (JSB) { - this._nativeObj.indexOffset = indexOffset; + this._uint32SharedBuffer[AttrUInt32ArrayView.IndexOffset] = indexOffset; } } @@ -139,37 +162,34 @@ export class RenderDrawInfo { public setVBCount (vbCount) { if (JSB) { - this._nativeObj.vbCount = vbCount; + this._uint32SharedBuffer[AttrUInt32ArrayView.VBCount] = vbCount; } + this._vbCount = vbCount; } public setIBCount (ibCount) { if (JSB) { - this._nativeObj.ibCount = ibCount; + this._uint32SharedBuffer[AttrUInt32ArrayView.IBCount] = ibCount; } } public setVertDirty (val: boolean) { if (JSB) { - this._nativeObj.vertDirty = val; + this._uint8SharedBuffer[AttrUInt8ArrayView.VertDirty] = val ? 1 : 0; } this._vertDirty = val; } public setDataHash (dataHash: number) { if (JSB) { - if (this._dataHash !== dataHash) { - this._nativeObj.dataHash = dataHash; - } + this._uint32SharedBuffer[AttrUInt32ArrayView.DataHash] = dataHash; } this._dataHash = dataHash; } public setIsMeshBuffer (isMeshBuffer: boolean) { if (JSB) { - if (this._isMeshBuffer !== isMeshBuffer) { - this._nativeObj.isMeshBuffer = isMeshBuffer; - } + this._uint8SharedBuffer[AttrUInt8ArrayView.IsMeshBuffer] = isMeshBuffer ? 1 : 0; } this._isMeshBuffer = isMeshBuffer; } @@ -194,9 +214,7 @@ export class RenderDrawInfo { public setTextureHash (textureHash: number) { if (JSB) { - if (this._textureHash !== textureHash) { - this._nativeObj.textureHash = textureHash; - } + this._uint32SharedBuffer[AttrUInt32ArrayView.TextureHash] = textureHash; } this._textureHash = textureHash; } @@ -221,7 +239,7 @@ export class RenderDrawInfo { public setDrawInfoType (drawInfoType: RenderDrawInfoType) { if (JSB) { if (this._drawInfoType !== drawInfoType) { - this._nativeObj.drawInfoType = drawInfoType; + this._uint8SharedBuffer[AttrUInt8ArrayView.DrawInfoType] = drawInfoType; } } this._drawInfoType = drawInfoType; @@ -236,17 +254,23 @@ export class RenderDrawInfo { this._subNode = node; } - public initRender2dBuffer (vertexCount: number, stride: number) { + public setStride (stride: number) { if (JSB) { - this._stride = stride; - this._vertexCount = vertexCount; - this._render2dBuffer = new Float32Array(vertexCount * stride); + this._uint8SharedBuffer[AttrUInt8ArrayView.Stride] = stride; + } + this._stride = stride; + } + + public initRender2dBuffer () { + if (JSB) { + this._render2dBuffer = new Float32Array(this._vbCount * this._stride); + this._nativeObj.setRender2dBufferToNative(this._render2dBuffer); } } public fillRender2dBuffer (vertexDataArr: IRenderData[]) { if (JSB) { - const fillLength = Math.min(this._vertexCount, vertexDataArr.length); + const fillLength = Math.min(this._vbCount, vertexDataArr.length); let bufferOffset = 0; for (let i = 0; i < fillLength; i++) { this.updateVertexBuffer(bufferOffset, vertexDataArr[i]); @@ -272,10 +296,4 @@ export class RenderDrawInfo { this._render2dBuffer[bufferOffset++] = temp.color.a; } } - - public setRender2dBufferToNative () { - if (JSB) { - this._nativeObj.setRender2dBufferToNative(this._render2dBuffer, this._stride, this._vertexCount * this._stride); - } - } } diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index ab32a02397..37deafa0f5 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -57,11 +57,11 @@ Batcher2d::~Batcher2d() { // NOLINT _attributes.clear(); } -void Batcher2d::syncMeshBuffersToNative(uint32_t accId, ccstd::vector&& buffers) { +void Batcher2d::syncMeshBuffersToNative(uint16_t accId, ccstd::vector&& buffers) { _meshBuffersMap[accId] = std::move(buffers); } -UIMeshBuffer* Batcher2d::getMeshBuffer(uint32_t accId, uint32_t bufferId) { // NOLINT(bugprone-easily-swappable-parameters) +UIMeshBuffer* Batcher2d::getMeshBuffer(uint16_t accId, uint16_t bufferId) { // NOLINT(bugprone-easily-swappable-parameters) const auto& map = _meshBuffersMap[accId]; return map[bufferId]; } @@ -93,39 +93,47 @@ void Batcher2d::walk(Node* node, float parentOpacity) { // NOLINT(misc-no-recurs } bool breakWalk = false; auto* entity = static_cast(node->getUserData()); - if (entity && entity->isEnabled()) { - RenderEntityType entityType = entity->getRenderEntityType(); - - // when filling buffers, we should distinguish common components and other complex components like middleware - if (entityType == RenderEntityType::STATIC) { - std::array& drawInfos = entity->getStaticRenderDrawInfos(); - for (uint32_t i = 0; i < entity->getStaticDrawInfoSize(); i++) { - handleDrawInfo(entity, &(drawInfos[i]), node, parentOpacity); - } - } else if (entityType == RenderEntityType::DYNAMIC) { - ccstd::vector& drawInfos = entity->getDynamicRenderDrawInfos(); - for (auto* drawInfo : drawInfos) { - handleDrawInfo(entity, drawInfo, node, parentOpacity); - } - } else if (entityType == RenderEntityType::CROSSED) { - //for tiledmap - ccstd::vector& drawInfos = entity->getDynamicRenderDrawInfos(); - for (auto* drawInfo : drawInfos) { - if (drawInfo->getSubNode()) { - walk(drawInfo->getSubNode(), entity->getOpacity()); - } else { - handleDrawInfo(entity, drawInfo, node, parentOpacity); - } - - } - breakWalk = true; + if (entity) { + if (entity->getColorDirty()) { + float localOpacity = entity->getLocalOpacity(); + float localColorAlpha = entity->getColorAlpha(); + entity->setOpacity(parentOpacity * localOpacity * localColorAlpha); } + if (entity->isEnabled()) { + RenderEntityType entityType = entity->getRenderEntityType(); + + // when filling buffers, we should distinguish common components and other complex components like middleware + if (entityType == RenderEntityType::STATIC) { + std::array& drawInfos = entity->getStaticRenderDrawInfos(); + for (uint32_t i = 0; i < entity->getStaticDrawInfoSize(); i++) { + handleDrawInfo(entity, &(drawInfos[i]), node); + } + } else if (entityType == RenderEntityType::DYNAMIC) { + ccstd::vector& drawInfos = entity->getDynamicRenderDrawInfos(); + for (auto* drawInfo : drawInfos) { + handleDrawInfo(entity, drawInfo, node); + } + } else if (entityType == RenderEntityType::CROSSED) { + //for tiledmap + ccstd::vector& drawInfos = entity->getDynamicRenderDrawInfos(); + for (auto* drawInfo : drawInfos) { + if (drawInfo->getSubNode()) { + walk(drawInfo->getSubNode(), entity->getOpacity()); + } else { + handleDrawInfo(entity, drawInfo, node); + } + } + breakWalk = true; + } + } + entity->setColorDirty(false); } + if (!breakWalk) { const auto& children = node->getChildren(); + float thisOpacity = entity ? entity->getOpacity() : parentOpacity; for (const auto& child : children) { // we should find parent opacity recursively upwards if it doesn't have an entity. - float thisOpacity = entity ? entity->getOpacity() : parentOpacity; walk(child, thisOpacity); } } @@ -150,7 +158,7 @@ void Batcher2d::handlePostRender(RenderEntity* entity) { } } -CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node, float parentOpacity) { +CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node) { CC_ASSERT(entity); CC_ASSERT(drawInfo); RenderDrawInfoType drawInfoType = drawInfo->getEnumDrawInfoType(); @@ -203,7 +211,10 @@ CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawI fillVertexBuffers(entity, drawInfo); drawInfo->setVertDirty(false); } - handleColor(entity, drawInfo, parentOpacity); + if (entity->getColorDirty()) { + fillColors(entity, drawInfo); + } + fillIndexBuffers(drawInfo); } @@ -223,8 +234,6 @@ CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawI _stencilManager->pushMask(); _stencilManager->clear(entity); - handleColor(entity, drawInfo, parentOpacity); - } else if (isSubMask) { //Mask Comp _stencilManager->enterLevel(entity); @@ -304,16 +313,6 @@ CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawI } } -void Batcher2d::handleColor(RenderEntity* entity, RenderDrawInfo* drawInfo, float parentOpacity) { - if (entity->getColorDirty()) { - float localOpacity = entity->getLocalOpacity(); - float localColorAlpha = entity->getColorAlpha(); - entity->setOpacity(parentOpacity * localOpacity * localColorAlpha); - fillColors(entity, drawInfo); - entity->setColorDirty(false); - } -} - void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) { if (drawInfo == nullptr || _currMaterial == nullptr) { return; diff --git a/native/cocos/2d/renderer/Batcher2d.h b/native/cocos/2d/renderer/Batcher2d.h index 3047f2f2fd..b1cf582882 100644 --- a/native/cocos/2d/renderer/Batcher2d.h +++ b/native/cocos/2d/renderer/Batcher2d.h @@ -39,7 +39,7 @@ namespace cc { class Root; using UIMeshBufferArray = ccstd::vector; -using UIMeshBufferMap = ccstd::unordered_map; +using UIMeshBufferMap = ccstd::unordered_map; class Batcher2d final { public: @@ -47,7 +47,7 @@ public: explicit Batcher2d(Root* root); ~Batcher2d(); - void syncMeshBuffersToNative(uint32_t accId, ccstd::vector&& buffers); + void syncMeshBuffersToNative(uint16_t accId, ccstd::vector&& buffers); bool initialize(); void update(); @@ -57,7 +57,7 @@ public: void syncRootNodesToNative(ccstd::vector&& rootNodes); void releaseDescriptorSetCache(gfx::Texture* texture, gfx::Sampler* sampler); - UIMeshBuffer* getMeshBuffer(uint32_t accId, uint32_t bufferId); + UIMeshBuffer* getMeshBuffer(uint16_t accId, uint16_t bufferId); gfx::Device* getDevice(); inline ccstd::vector* getDefaultAttribute() { return &_attributes; } @@ -66,8 +66,7 @@ public: void fillBuffersAndMergeBatches(); void walk(Node* node, float parentOpacity); void handlePostRender(RenderEntity* entity); - void handleColor(RenderEntity* entity, RenderDrawInfo* drawInfo, float parentOpacity); - void handleDrawInfo(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node, float parentOpacity); + void handleDrawInfo(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node); void generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo); void resetRenderStates(); diff --git a/native/cocos/2d/renderer/RenderDrawInfo.cpp b/native/cocos/2d/renderer/RenderDrawInfo.cpp index 97ec1af8a3..7f945cd0bd 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.cpp +++ b/native/cocos/2d/renderer/RenderDrawInfo.cpp @@ -31,137 +31,54 @@ namespace cc { -RenderDrawInfo::RenderDrawInfo(index_t bufferId, uint32_t vertexOffset, uint32_t indexOffset) { // NOLINT(bugprone-easily-swappable-parameters) - _bufferId = bufferId; - _vertexOffset = vertexOffset; - _indexOffset = indexOffset; - _stride = 0; - _size = 0; +RenderDrawInfo::RenderDrawInfo() { + _attrSharedBufferActor.initialize(&_drawInfoAttrs, sizeof(_drawInfoAttrs)); } RenderDrawInfo::~RenderDrawInfo() { destroy(); } -void RenderDrawInfo::setAccId(index_t id) { - _accId = id; -} - -void RenderDrawInfo::setBufferId(index_t bufferId) { +void RenderDrawInfo::changeMeshBuffer() { CC_ASSERT(Root::getInstance()->getBatcher2D()); - _bufferId = bufferId; - _meshBuffer = Root::getInstance()->getBatcher2D()->getMeshBuffer(_accId, _bufferId); -} - -void RenderDrawInfo::setVertexOffset(uint32_t vertexOffset) { - _vertexOffset = vertexOffset; -} - -void RenderDrawInfo::setIndexOffset(uint32_t indexOffset) { - _indexOffset = indexOffset; -} - -void RenderDrawInfo::setVbBuffer(float* vbBuffer) { - _vbBuffer = vbBuffer; -} - -void RenderDrawInfo::setIbBuffer(uint16_t* ibBuffer) { - _ibBuffer = ibBuffer; -} - -void RenderDrawInfo::setVDataBuffer(float* vDataBuffer) { - _vDataBuffer = vDataBuffer; -} - -void RenderDrawInfo::setIDataBuffer(uint16_t* iDataBuffer) { - _iDataBuffer = iDataBuffer; -} - -void RenderDrawInfo::setVbCount(uint32_t vbCount) { - _vbCount = vbCount; -} - -void RenderDrawInfo::setIbCount(uint32_t ibCount) { - _ibCount = ibCount; -} - -void RenderDrawInfo::setVertDirty(bool val) { - _vertDirty = val; -} - -void RenderDrawInfo::setDataHash(ccstd::hash_t dataHash) { - _dataHash = dataHash; -} - -void RenderDrawInfo::setIsMeshBuffer(bool isMeshBuffer) { - _isMeshBuffer = isMeshBuffer; -} - -void RenderDrawInfo::setMaterial(Material* material) { - _material = material; -} - -void RenderDrawInfo::setTexture(gfx::Texture* texture) { - _texture = texture; -} - -void RenderDrawInfo::setTextureHash(uint32_t textureHash) { - _textureHash = textureHash; -} - -void RenderDrawInfo::setSampler(gfx::Sampler* sampler) { - _sampler = sampler; -} - -void RenderDrawInfo::setModel(scene::Model* model) { - _model = model; -} - -void RenderDrawInfo::setDrawInfoType(uint32_t type) { - _drawInfoType = static_cast(type); -} - -void RenderDrawInfo::setSubNode(Node *node) { - _subNode = node; -} - -void RenderDrawInfo::setRender2dBufferToNative(uint8_t* buffer, uint8_t stride, uint32_t size) { // NOLINT(bugprone-easily-swappable-parameters) - _stride = stride; - _size = size; - _sharedBuffer = buffer; + _meshBuffer = Root::getInstance()->getBatcher2D()->getMeshBuffer(_drawInfoAttrs._accId, _drawInfoAttrs._bufferId); } gfx::InputAssembler* RenderDrawInfo::requestIA(gfx::Device* device) { - if (_nextFreeIAHandle >= _iaPool.size()) { + CC_ASSERT(_drawInfoAttrs._isMeshBuffer && _drawInfoAttrs._drawInfoType == RenderDrawInfoType::COMP); + if (!_iaPool) { + _iaPool = ccnew ccstd::vector; + } + if (_nextFreeIAHandle >= _iaPool -> size()) { initIAInfo(device); } - auto* ia = _iaPool[_nextFreeIAHandle++]; // 需要 reset + auto* ia = (*_iaPool)[_nextFreeIAHandle++]; ia->setFirstIndex(getIndexOffset()); ia->setIndexCount(getIbCount()); return ia; } void RenderDrawInfo::uploadBuffers() { - if (_vbCount == 0 || _ibCount == 0) return; - uint32_t size = _vbCount * 9 * sizeof(float);// magic Number - gfx::Buffer* vBuffer = _vbGFXBuffer; + CC_ASSERT(_drawInfoAttrs._isMeshBuffer && _drawInfoAttrs._drawInfoType == RenderDrawInfoType::COMP); + if (_drawInfoAttrs._vbCount == 0 || _drawInfoAttrs._ibCount == 0) return; + uint32_t size = _drawInfoAttrs._vbCount * 9 * sizeof(float); // magic Number + gfx::Buffer* vBuffer = _iaInfo->vertexBuffers[0]; vBuffer->resize(size); vBuffer->update(_vDataBuffer); - gfx::Buffer* iBuffer = _ibGFXBuffer; - uint32_t iSize = _ibCount * 2; + gfx::Buffer* iBuffer = _iaInfo->indexBuffer; + uint32_t iSize = _drawInfoAttrs._ibCount * 2; iBuffer->resize(iSize); iBuffer->update(_iDataBuffer); } void RenderDrawInfo::resetMeshIA() { + CC_ASSERT(_drawInfoAttrs._isMeshBuffer && _drawInfoAttrs._drawInfoType == RenderDrawInfoType::COMP); _nextFreeIAHandle = 0; } void RenderDrawInfo::destroy() { _nextFreeIAHandle = 0; - - //TODO(): Should use _iaPool to delete vb, ib. - if (_iaInfo != nullptr) { + if (_iaInfo) { CC_SAFE_DELETE(_iaInfo->indexBuffer); if (!_iaInfo->vertexBuffers.empty()) { // only one vb @@ -171,19 +88,18 @@ void RenderDrawInfo::destroy() { CC_SAFE_DELETE(_iaInfo); } - for (auto* ia : _iaPool) { - //TODO(): should use these codes to delete all ib, vb. - // delete ia->getIndexBuffer(); - // // only one vertex buffer - // delete ia->getVertexBuffers()[0]; - CC_SAFE_DELETE(ia); + if (_iaPool) { + for (auto* ia : *_iaPool) { + CC_SAFE_DELETE(ia); + } + _iaPool->clear(); + CC_SAFE_DELETE(_iaPool); } - _iaPool.clear(); } gfx::InputAssembler* RenderDrawInfo::initIAInfo(gfx::Device* device) { - if (_iaPool.empty()) { - _iaInfo = new gfx::InputAssemblerInfo(); + if (_iaPool->empty()) { + _iaInfo = ccnew gfx::InputAssemblerInfo(); uint32_t vbStride = 9 * sizeof(float);// magic Number uint32_t ibStride = sizeof(uint16_t); auto* vertexBuffer = device->createBuffer({ @@ -199,15 +115,12 @@ gfx::InputAssembler* RenderDrawInfo::initIAInfo(gfx::Device* device) { ibStride, }); - _vbGFXBuffer = vertexBuffer; - _ibGFXBuffer = indexBuffer; - _iaInfo->attributes = *(Root::getInstance()->getBatcher2D()->getDefaultAttribute()); _iaInfo->vertexBuffers.emplace_back(vertexBuffer); _iaInfo->indexBuffer = indexBuffer; } auto* ia = device->createInputAssembler(*_iaInfo); - _iaPool.emplace_back(ia); + _iaPool->emplace_back(ia); return ia; } diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index 6a40bebcd1..5bc6b2841d 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -52,64 +52,162 @@ enum class RenderDrawInfoType: uint8_t { }; class Batcher2d; + class RenderDrawInfo final { public: - RenderDrawInfo() = default; - RenderDrawInfo(index_t bufferId, uint32_t vertexOffset, uint32_t indexOffset); + RenderDrawInfo(); ~RenderDrawInfo(); - inline index_t getAccId() const { return _accId; } - void setAccId(index_t id); - inline index_t getBufferId() const { return _bufferId; } - void setBufferId(index_t bufferId); - inline uint32_t getVertexOffset() const { return _vertexOffset; } - void setVertexOffset(uint32_t vertexOffset); - inline uint32_t getIndexOffset() const { return _indexOffset; } - void setIndexOffset(uint32_t indexOffset); - inline UIMeshBuffer* getMeshBuffer() const { return _meshBuffer; }; - inline float* getVbBuffer() const { return _vbBuffer; } - void setVbBuffer(float* vbBuffer); - inline uint16_t* getIbBuffer() const { return _ibBuffer; } - void setIbBuffer(uint16_t* ibBuffer); - inline float* getVDataBuffer() const { return _vDataBuffer; } - void setVDataBuffer(float* vDataBuffer); - inline uint16_t* getIDataBuffer() const { return _iDataBuffer; } - void setIDataBuffer(uint16_t* iDataBuffer); - inline uint32_t getVbCount() const { return _vbCount; } - void setVbCount(uint32_t vbCount); - inline uint32_t getIbCount() const { return _ibCount; } - void setIbCount(uint32_t ibCount); - inline bool getVertDirty() const { return _vertDirty; } - void setVertDirty(bool val); - inline ccstd::hash_t getDataHash() const { return _dataHash; } - void setDataHash(ccstd::hash_t dataHash); - inline bool getIsMeshBuffer() const { return _isMeshBuffer; } - void setIsMeshBuffer(bool isMeshBuffer); + inline uint32_t getDrawInfoType() const { return static_cast(_drawInfoAttrs._drawInfoType); } + inline void setDrawInfoType(uint32_t type) { + _drawInfoAttrs._drawInfoType = static_cast(type); + } + + inline uint16_t getAccId() const { return _drawInfoAttrs._accId; } + inline void setAccId(uint16_t id) { + _drawInfoAttrs._accId = id; + } + + inline uint16_t getBufferId() const { return _drawInfoAttrs._bufferId; } + inline void setBufferId(uint16_t bufferId) { + _drawInfoAttrs._bufferId = bufferId; + } + + inline uint32_t getVertexOffset() const { return _drawInfoAttrs._vertexOffset; } + inline void setVertexOffset(uint32_t vertexOffset) { + _drawInfoAttrs._vertexOffset = vertexOffset; + } + + inline uint32_t getIndexOffset() const { return _drawInfoAttrs._indexOffset; } + inline void setIndexOffset(uint32_t indexOffset) { + _drawInfoAttrs._indexOffset = indexOffset; + } + + inline uint32_t getVbCount() const { return _drawInfoAttrs._vbCount; } + inline void setVbCount(uint32_t vbCount) { + _drawInfoAttrs._vbCount = vbCount; + } + + inline uint32_t getIbCount() const { return _drawInfoAttrs._ibCount; } + inline void setIbCount(uint32_t ibCount) { + _drawInfoAttrs._ibCount = ibCount; + } + + inline bool getVertDirty() const { return _drawInfoAttrs._vertDirty; } + inline void setVertDirty(bool val) { + _drawInfoAttrs._vertDirty = val; + } + + inline ccstd::hash_t getDataHash() const { return _drawInfoAttrs._dataHash; } + inline void setDataHash(ccstd::hash_t dataHash) { + _drawInfoAttrs._dataHash = dataHash; + } + + inline bool getIsMeshBuffer() const { return _drawInfoAttrs._isMeshBuffer; } + inline void setIsMeshBuffer(bool isMeshBuffer) { + _drawInfoAttrs._isMeshBuffer = isMeshBuffer; + } + + inline uint8_t getStride() const { return _drawInfoAttrs._stride; } + inline void setStride(uint8_t stride) { + _drawInfoAttrs._stride = stride; + } + inline Material* getMaterial() const { return _material; } - void setMaterial(Material* material); - inline gfx::Texture* getTexture() const { return _texture; } - void setTexture(gfx::Texture* texture); - inline uint32_t getTextureHash() const { return _textureHash; } - void setTextureHash(uint32_t textureHash); - inline gfx::Sampler* getSampler() const { return _sampler; } - void setSampler(gfx::Sampler* sampler); - inline scene::Model* getModel() const { return _model; } - void setModel(scene::Model* model); - inline uint32_t getDrawInfoType() const { return static_cast(_drawInfoType); } - void setDrawInfoType(uint32_t type); + inline void setMaterial(Material* material) { + _material = material; + } + + inline UIMeshBuffer* getMeshBuffer() const { + return _meshBuffer; + } + + inline float* getVDataBuffer() const { + return _vDataBuffer; + } + inline void setVDataBuffer(float* vDataBuffer) { + _vDataBuffer = vDataBuffer; + } + inline uint16_t* getIDataBuffer() const { + return _iDataBuffer; + } + + inline void setIDataBuffer(uint16_t* iDataBuffer) { + _iDataBuffer = iDataBuffer; + } + + inline gfx::Texture* getTexture() const { + return _texture; + } + + inline void setTexture(gfx::Texture* texture) { + _texture = texture; + } + + inline uint32_t getTextureHash() const { + return _drawInfoAttrs._textureHash; + } + + inline void setTextureHash(uint32_t textureHash) { + _drawInfoAttrs._textureHash = textureHash; + } + + inline gfx::Sampler* getSampler() const { + return _sampler; + } + + inline void setSampler(gfx::Sampler* sampler) { + _sampler = sampler; + } + + inline float* getVbBuffer() const { + return _vbBuffer; + } + + inline void setVbBuffer(float* vbBuffer) { + _vbBuffer = vbBuffer; + } + + inline uint16_t* getIbBuffer() const { + return _ibBuffer; + } + + inline void setIbBuffer(uint16_t* ibBuffer) { + _ibBuffer = ibBuffer; + } + + inline scene::Model* getModel() const { + CC_ASSERT(_drawInfoAttrs._drawInfoType == RenderDrawInfoType::MODEL); + return _model; + } + + inline void setModel(scene::Model* model) { + CC_ASSERT(_drawInfoAttrs._drawInfoType == RenderDrawInfoType::MODEL); + if (_drawInfoAttrs._drawInfoType == RenderDrawInfoType::MODEL) { + _model = model; + } + } + inline Node* getSubNode() const { return _subNode; } - void setSubNode(Node *node); + inline void setSubNode(Node* node) { + _subNode = node; + } - inline RenderDrawInfoType getEnumDrawInfoType() const { return _drawInfoType; } + void changeMeshBuffer(); - void setRender2dBufferToNative(uint8_t* buffer, uint8_t stride, uint32_t size); + inline RenderDrawInfoType getEnumDrawInfoType() const { return _drawInfoAttrs._drawInfoType; } - inline Render2dLayout* getRender2dLayout(uint32_t dataOffset) { + inline void setRender2dBufferToNative(uint8_t* buffer) { // NOLINT(bugprone-easily-swappable-parameters) + CC_ASSERT(_drawInfoAttrs._drawInfoType == RenderDrawInfoType::COMP && !_drawInfoAttrs._isMeshBuffer); + _sharedBuffer = buffer; + } + + inline Render2dLayout* getRender2dLayout(uint32_t dataOffset) const { + CC_ASSERT(_drawInfoAttrs._drawInfoType == RenderDrawInfoType::COMP && !_drawInfoAttrs._isMeshBuffer); return reinterpret_cast(_sharedBuffer + dataOffset * sizeof(float)); } - inline uint8_t getStride() const { return _stride; } - inline uint32_t getSize() const { return _size; } + inline se::Object* getAttrSharedBufferForJS() const { return _attrSharedBufferActor.getSharedArrayBufferObject(); } gfx::InputAssembler* requestIA(gfx::Device* device); void uploadBuffers(); @@ -120,57 +218,48 @@ private: void destroy(); gfx::InputAssembler* initIAInfo(gfx::Device* device); - // weak reference - uint8_t* _sharedBuffer{nullptr}; - uint32_t _size{0}; - index_t _bufferId{0}; - index_t _accId{0}; - uint32_t _vertexOffset{0}; - - uint32_t _indexOffset{0}; + struct DrawInfoAttrs { + RenderDrawInfoType _drawInfoType{RenderDrawInfoType::COMP}; + bool _vertDirty{false}; + bool _isMeshBuffer{false}; + uint8_t _stride{0}; + uint16_t _bufferId{0}; + uint16_t _accId{0}; + uint32_t _vertexOffset{0}; + uint32_t _indexOffset{0}; + uint32_t _vbCount{0}; + uint32_t _ibCount{0}; + uint32_t _textureHash{0}; + ccstd::hash_t _dataHash{0}; + } _drawInfoAttrs{}; + bindings::NativeMemorySharedToScriptActor _attrSharedBufferActor; // weak reference - float* _vbBuffer{nullptr}; - // weak reference - uint16_t* _ibBuffer{nullptr}; + Material* _material{nullptr}; // weak reference float* _vDataBuffer{nullptr}; // weak reference uint16_t* _iDataBuffer{nullptr}; // weak reference UIMeshBuffer* _meshBuffer{nullptr}; - - uint32_t _vbCount{0}; - uint32_t _ibCount{0}; - - uint8_t _stride{0}; - bool _vertDirty{false}; - bool _isMeshBuffer{false}; - RenderDrawInfoType _drawInfoType{RenderDrawInfoType::COMP}; - - // weak reference - scene::Model* _model{nullptr}; - - ccstd::hash_t _dataHash{0}; - // weak reference - Material* _material{nullptr}; // weak reference gfx::Texture* _texture{nullptr}; - uint32_t _textureHash{0}; // weak reference gfx::Sampler* _sampler{nullptr}; - Node* _subNode{nullptr}; + // weak reference + float* _vbBuffer{nullptr}; + // weak reference + uint16_t* _ibBuffer{nullptr}; - uint32_t _nextFreeIAHandle{0}; - // weak reference - gfx::Buffer* _vbGFXBuffer{nullptr}; - // weak reference - gfx::Buffer* _ibGFXBuffer{nullptr}; + union { + Node* _subNode{nullptr}; + scene::Model* _model; + uint8_t* _sharedBuffer; + }; gfx::InputAssemblerInfo* _iaInfo{nullptr}; - //TODO(): it is not a good way to cache IA here. - // manage memory manually - ccstd::vector _iaPool; + ccstd::vector* _iaPool{nullptr}; + uint16_t _nextFreeIAHandle{0}; }; } // namespace cc diff --git a/native/cocos/2d/renderer/RenderEntity.cpp b/native/cocos/2d/renderer/RenderEntity.cpp index cbdc1e9fc9..5ec3922f94 100644 --- a/native/cocos/2d/renderer/RenderEntity.cpp +++ b/native/cocos/2d/renderer/RenderEntity.cpp @@ -89,7 +89,7 @@ ccstd::vector& RenderEntity::getDynamicRenderDrawInfos() { return _dynamicDrawInfos; } void RenderEntity::setStaticDrawInfoSize(uint32_t size) { - CC_ASSERT(size < RenderEntity::STATIC_DRAW_INFO_CAPACITY); + CC_ASSERT(size <= RenderEntity::STATIC_DRAW_INFO_CAPACITY); _staticDrawInfoSize = size; } RenderDrawInfo* RenderEntity::getStaticRenderDrawInfo(uint32_t index) { diff --git a/native/tools/tojs/2d.ini b/native/tools/tojs/2d.ini index 92fd0d4e76..13b258273e 100644 --- a/native/tools/tojs/2d.ini +++ b/native/tools/tojs/2d.ini @@ -46,14 +46,14 @@ classes = RenderDrawInfo UIMeshBuffer Batcher2d RenderEntity UIModelProxy # add a single "*" as functions. See bellow for several examples. A special class name is "*", which # will apply to all class names. This is a convenience wildcard to be able to skip similar named # functions from all classes. -skip = RenderDrawInfo::[getBatcher setBatcher parseAttrLayout getRender2dLayout getStride getSize getEnumDrawInfoType], +skip = RenderDrawInfo::[getBatcher setBatcher parseAttrLayout getRender2dLayout getEnumDrawInfoType], Batcher2d::[addVertDirtyRenderer getMeshBuffer getDevice updateDescriptorSet fillBuffersAndMergeBatches walk generateBatch resetRenderStates handleDrawInfo], UIMeshBuffer::[requireFreeIA createNewIA recycleIA resetIA parseLayout getByteOffset setByteOffset getVertexOffset setVertexOffset getIndexOffset setIndexOffset getDirty setDirty getFloatsPerVertex setFloatsPerVertex], RenderEntity::[getDynamicRenderDrawInfo getDynamicRenderDrawInfos getRenderEntityType getColorDirty getColor isEnabled getEnumStencilStage setEnumStencilStage] rename_functions = -getter_setter = RenderDrawInfo::[bufferId accId vertexOffset indexOffset vbBuffer ibBuffer vDataBuffer iDataBuffer vbCount ibCount vertDirty dataHash isMeshBuffer material texture textureHash sampler model drawInfoType subNode], +getter_setter = RenderDrawInfo::[bufferId accId vertexOffset indexOffset vbBuffer ibBuffer vDataBuffer iDataBuffer vbCount ibCount vertDirty dataHash isMeshBuffer material texture textureHash sampler model drawInfoType subNode stride], UIMeshBuffer::[vData iData], RenderEntity::[node staticDrawInfoSize stencilStage isMask isSubMask isMaskInverted] From 3261ab1930914d723de63402f2828db7b03c1c60 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 21 Jul 2022 11:54:47 +0800 Subject: [PATCH 051/111] Check passes length in Shadow.getPlanarShader & getPlanarInstanceShader. (#12105) --- cocos/core/renderer/scene/shadows.ts | 14 ++++++++++++-- native/cocos/scene/Shadow.cpp | 14 ++++++++------ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/cocos/core/renderer/scene/shadows.ts b/cocos/core/renderer/scene/shadows.ts index ec37aedbb4..7673f65793 100644 --- a/cocos/core/renderer/scene/shadows.ts +++ b/cocos/core/renderer/scene/shadows.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ +import { DEBUG } from 'internal:constants'; import { Material } from '../../assets/material'; import { Sphere } from '../../geometry'; import { Color, Mat4, Vec3, Vec2 } from '../../math'; @@ -31,6 +32,7 @@ import { Enum } from '../../value-types'; import type { ShadowsInfo } from '../../scene-graph/scene-globals'; import { IMacroPatch } from '../core/pass'; import { Shader } from '../../gfx'; +import { assert } from '../../platform/debug'; /** * @zh 阴影贴图分辨率。 @@ -346,7 +348,11 @@ export class Shadows { this._material.initialize({ effectName: 'pipeline/planar-shadow' }); } - return this._material.passes[0].getShaderVariant(patches); + const passes = this._material.passes; + if (DEBUG) { + assert(passes.length > 0, 'passes should not be empty!'); + } + return passes.length > 0 ? passes[0].getShaderVariant(patches) : null; } /** @@ -361,7 +367,11 @@ export class Shadows { this._instancingMaterial.initialize({ effectName: 'pipeline/planar-shadow', defines: { USE_INSTANCING: true } }); } - return this._instancingMaterial.passes[0].getShaderVariant(patches); + const passes = this._instancingMaterial.passes; + if (DEBUG) { + assert(passes.length > 0, 'passes should not be empty!'); + } + return passes.length > 0 ? passes[0].getShaderVariant(patches) : null; } public initialize (shadowsInfo: ShadowsInfo) { diff --git a/native/cocos/scene/Shadow.cpp b/native/cocos/scene/Shadow.cpp index fb61fe5bfe..571f24b039 100644 --- a/native/cocos/scene/Shadow.cpp +++ b/native/cocos/scene/Shadow.cpp @@ -91,7 +91,7 @@ void ShadowsInfo::setShadowMapSize(float value) { } } -void ShadowsInfo::setPlaneFromNode(const Node* node) { +void ShadowsInfo::setPlaneFromNode(const Node *node) { const auto &qt = node->getWorldRotation(); _normal = Vec3::UNIT_Y; _normal.transformQuat(qt); @@ -117,7 +117,7 @@ void Shadows::initialize(const ShadowsInfo &shadowsInfo) { setSize(Vec2(shadowsInfo.getShadowMapSize(), shadowsInfo.getShadowMapSize())); _shadowMapDirty = true; } - + setShadowColor(shadowsInfo.getShadowColor()); } @@ -138,8 +138,9 @@ gfx::Shader *Shadows::getPlanarShader(const ccstd::vector &patches) createMaterial(); } - const auto &passes = *_material->getPasses(); - return passes[0]->getShaderVariant(patches); + const auto &passes = _material->getPasses(); + CC_ASSERT(passes && !passes->empty()); + return (passes && !passes->empty()) ? passes->at(0)->getShaderVariant(patches) : nullptr; } gfx::Shader *Shadows::getPlanarInstanceShader(const ccstd::vector &patches) { @@ -147,8 +148,9 @@ gfx::Shader *Shadows::getPlanarInstanceShader(const ccstd::vector & createInstanceMaterial(); } - const auto &passes = *_instancingMaterial->getPasses(); - return passes[0]->getShaderVariant(patches); + const auto &passes = _instancingMaterial->getPasses(); + CC_ASSERT(passes && !passes->empty()); + return (passes && !passes->empty()) ? passes->at(0)->getShaderVariant(patches) : nullptr; } void Shadows::activate() { From 24f259ecfb4736e2b678d8715eebb969e52db89e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A2=81=E7=82=9C=E6=B5=B7?= <35713518+dogodo-cc@users.noreply.github.com> Date: Thu, 21 Jul 2022 11:57:23 +0800 Subject: [PATCH 052/111] fix: Modify the judgment condition (#12050) * fix: Modify the judgment condition * fix: Modify the judgment condition --- editor/inspector/contributions/node.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index 31b0adf90e..7b4e38758d 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -1473,7 +1473,7 @@ exports.methods = { const lastIndex = length - 1; const lastComp = nodeDump.__comps__[lastIndex]; - if (lastComp && lastComp.type === clipboardComponentInfo.type) { + if (lastComp?.cid === clipboardComponentInfo.cid) { await Editor.Message.request('scene', 'set-property', { uuid, path: `__comps__.${lastIndex}`, @@ -1596,7 +1596,7 @@ exports.methods = { const lastIndex = length - 1; const lastComp = nodeDump.__comps__[lastIndex]; - if (lastComp && lastComp.type === clipboardComponentInfo.type) { + if (lastComp?.cid === clipboardComponentInfo.cid) { await Editor.Message.request('scene', 'set-property', { uuid, path: `__comps__.${lastIndex}`, From 7117ba4dd4473ee7f40f3ffb33666155963df780 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AA=9B=E5=AA=9B?= Date: Thu, 21 Jul 2022 11:58:42 +0800 Subject: [PATCH 053/111] update native pack tool (#12113) --- scripts/native-pack-tool/readme.md | 7 ++++--- scripts/native-pack-tool/source/base/default.ts | 12 +++++++----- scripts/native-pack-tool/source/base/manager.ts | 12 +++++++++++- scripts/native-pack-tool/source/platforms/ios.ts | 2 -- scripts/native-pack-tool/source/platforms/mac.ts | 2 -- scripts/native-pack-tool/source/platforms/windows.ts | 1 - 6 files changed, 22 insertions(+), 14 deletions(-) diff --git a/scripts/native-pack-tool/readme.md b/scripts/native-pack-tool/readme.md index c13c599f4c..45cf60fc8d 100644 --- a/scripts/native-pack-tool/readme.md +++ b/scripts/native-pack-tool/readme.md @@ -23,11 +23,12 @@ ## 支持的命令 ```bash -npm run pack [projectBuildPath] create // 根据原始构建后的目录资源生成基础的原生资源工程 +npm run pack [projectBuildPath] create // 根据原始构建后的目录资源生成基础的原生模板 +npm run pack [projectBuildPath] generate // 根据基础原生模板,调用 cmake 生成完整工程 npm run pack [projectBuildPath] make // 编译/生成指定的原生工程 npm run pack [projectBuildPath] run // 运行已经编译好的原生导出软件 -npm run pack [projectBuildPath] init,make,run +npm run pack [projectBuildPath] create,generate,make,run ``` > [projectBuildPath] 指代 `build/[platform]` 路径 @@ -47,7 +48,7 @@ import { WindowsPackTool } from './platforms/windows'; nativePackToolMg.register('windows', new WindowsPackTool()); ``` -(3) 保障新的类里,`create, make, run` 的逻辑都正常,直接使用命令行测试即可。 +(3) 保障新的类里,`create, generate, make, run` 的逻辑都正常,直接使用命令行测试即可。 (4) 构建的内置平台是直接调用的命令行执行的生成、编译逻辑,所有如果有其他闭源插件想要添加新平台的定制打包逻辑,可以在 `hooks` 脚本的 `load` 或者 `beforeBuild` 之类的钩子里加载 `nativePackToolMg` 后执行注册逻辑即可,通过命令行和直接加载脚本的差异主要在于脚本加载有缓存,通过这种方式可能会取到被多个不同插件加工过的原生平台打包逻辑。 diff --git a/scripts/native-pack-tool/source/base/default.ts b/scripts/native-pack-tool/source/base/default.ts index a5ca1d9c90..0456e5b2a8 100644 --- a/scripts/native-pack-tool/source/base/default.ts +++ b/scripts/native-pack-tool/source/base/default.ts @@ -61,10 +61,11 @@ const ErrorCodeIncompatible = 15004; export interface INativePlatformOptions { extends?: InternaleNativePlatform, //传入继承的平台,将会继承已有平台注册的一些代码 overwrite?: InternaleNativePlatform, //传入继承但如果有同名的方法等会复写平台,将会继承已有平台注册的一些代码 - create?: () => Promise; - compile?: () => Promise; + create: () => Promise; + genrate: () => Promise; + make?: () => Promise; run?: () => Promise; - init?: (params: CocosParams) => void; + init: (params: CocosParams) => void; } export abstract class NativePackTool { @@ -432,7 +433,7 @@ export abstract class NativePackTool { } /** - * 加密脚本,加密后,会修改 cmake 参数,因而要在 cmake 命令执行之前 + * 加密脚本,加密后,会修改 cmake 参数,因而需要再次执行 cmake 配置文件的生成 * @returns */ protected async encrypteScripts() { @@ -492,7 +493,8 @@ export abstract class NativePackTool { } } - create?(): Promise; + abstract create(): Promise; + generate?(): Promise; make?(): Promise; run?(): Promise; } diff --git a/scripts/native-pack-tool/source/base/manager.ts b/scripts/native-pack-tool/source/base/manager.ts index 50f5c23fd4..f325cb8f11 100644 --- a/scripts/native-pack-tool/source/base/manager.ts +++ b/scripts/native-pack-tool/source/base/manager.ts @@ -32,12 +32,22 @@ export class NativePackToolManager { throw new Error(`No pack tool for platform ${platform}}`); } if (!tool.create) { - // TODO Error return false; } await tool.create(); } + async generate(platform: string) { + const tool = this.getPackTool(platform); + if (!tool) { + throw new Error(`No pack tool for platform ${platform}}`); + } + if (!tool.generate) { + return false; + } + await tool.generate(); + } + async make(platform: string) { const tool = this.getPackTool(platform); if (!tool.make) { diff --git a/scripts/native-pack-tool/source/platforms/ios.ts b/scripts/native-pack-tool/source/platforms/ios.ts index 82d25ab9cb..517937016e 100644 --- a/scripts/native-pack-tool/source/platforms/ios.ts +++ b/scripts/native-pack-tool/source/platforms/ios.ts @@ -33,9 +33,7 @@ export class IOSPackTool extends MacOSPackTool { await this.excuteCocosTemplateTask(); await this.setOrientation(); - await this.encrypteScripts(); - await this.generate(); return true; } diff --git a/scripts/native-pack-tool/source/platforms/mac.ts b/scripts/native-pack-tool/source/platforms/mac.ts index b946ee59a1..bedde32cbf 100644 --- a/scripts/native-pack-tool/source/platforms/mac.ts +++ b/scripts/native-pack-tool/source/platforms/mac.ts @@ -16,9 +16,7 @@ export class MacPackTool extends MacOSPackTool { async create(): Promise { await super.create(); - await this.encrypteScripts(); - await this.generate(); return true; } diff --git a/scripts/native-pack-tool/source/platforms/windows.ts b/scripts/native-pack-tool/source/platforms/windows.ts index 8d25886651..ba32427aea 100644 --- a/scripts/native-pack-tool/source/platforms/windows.ts +++ b/scripts/native-pack-tool/source/platforms/windows.ts @@ -20,7 +20,6 @@ export class WindowsPackTool extends NativePackTool { await this.excuteCocosTemplateTask(); await this.encrypteScripts(); - await this.generate(); return true; } From 0c82b143fc66704dc1eb7724a88c59308889fa64 Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Thu, 21 Jul 2022 12:40:13 +0800 Subject: [PATCH 054/111] [V3.6.0 pipeline] added web forward and deferred pipelines (#11646) * added custom web forward and deferred pipelines --- cocos/core/index.ts | 2 + .../core/pipeline/custom/builtin-pipelines.ts | 448 +++++++++ cocos/core/pipeline/custom/compiler.ts | 49 +- cocos/core/pipeline/custom/debug.ts | 200 ++++ cocos/core/pipeline/custom/effect.ts | 268 +++++- cocos/core/pipeline/custom/executor.ts | 851 +++++++++++++++--- cocos/core/pipeline/custom/graph.ts | 260 ++++++ cocos/core/pipeline/custom/index.jsb.ts | 20 +- cocos/core/pipeline/custom/index.ts | 22 +- cocos/core/pipeline/custom/layout-graph.ts | 21 +- cocos/core/pipeline/custom/pipeline.ts | 53 +- cocos/core/pipeline/custom/render-graph.ts | 196 ++-- cocos/core/pipeline/custom/types.ts | 132 ++- cocos/core/pipeline/custom/ubos.ts | 512 ----------- cocos/core/pipeline/custom/utils.ts | 39 + .../custom/web-descriptor-hierarchy.ts | 256 +++++- .../core/pipeline/custom/web-layout-graph.ts | 361 +++++--- cocos/core/pipeline/custom/web-pipeline.ts | 408 +++++---- cocos/core/pipeline/custom/web-scene.ts | 106 +-- cocos/core/pipeline/pipeline-ubo.ts | 12 +- cocos/core/pipeline/planar-shadow-queue.ts | 7 +- .../pipeline/render-additive-light-queue.ts | 6 +- cocos/core/pipeline/render-pipeline.ts | 24 + .../render-shadow-map-batched-queue.ts | 6 +- cocos/core/renderer/core/program-lib.ts | 25 +- cocos/core/root.jsb.ts | 14 +- cocos/core/root.ts | 3 +- editor/engine-features/render-config.json | 6 + native/cocos/core/Root.cpp | 34 + .../renderer/pipeline/custom/LayoutGraphFwd.h | 1 - .../pipeline/custom/LayoutGraphTypes.h | 9 +- .../pipeline/custom/NativeLayoutGraphImpl.cpp | 23 + .../pipeline/custom/NativePipelineImpl.cpp | 63 +- .../pipeline/custom/NativePipelineTypes.h | 93 +- .../custom/NativeRenderGraphSetup.cpp | 221 +++-- .../pipeline/custom/RenderCommonFwd.h | 11 + .../pipeline/custom/RenderCommonJsb.cpp | 154 ++++ .../pipeline/custom/RenderCommonJsb.h | 16 + .../pipeline/custom/RenderCommonNames.h | 33 + .../pipeline/custom/RenderCommonTypes.cpp | 55 ++ .../pipeline/custom/RenderCommonTypes.h | 105 ++- .../renderer/pipeline/custom/RenderGraphFwd.h | 13 +- .../pipeline/custom/RenderGraphGraphs.h | 246 +++++ .../pipeline/custom/RenderGraphJsb.cpp | 150 +-- .../renderer/pipeline/custom/RenderGraphJsb.h | 15 +- .../pipeline/custom/RenderGraphNames.h | 27 +- .../pipeline/custom/RenderGraphTypes.cpp | 92 +- .../pipeline/custom/RenderGraphTypes.h | 155 ++-- .../pipeline/custom/RenderInterfaceFwd.h | 1 + .../pipeline/custom/RenderInterfaceTypes.h | 95 +- native/tools/tojs/render.ini | 8 +- 51 files changed, 4114 insertions(+), 1813 deletions(-) create mode 100644 cocos/core/pipeline/custom/builtin-pipelines.ts create mode 100644 cocos/core/pipeline/custom/debug.ts delete mode 100644 cocos/core/pipeline/custom/ubos.ts create mode 100644 cocos/core/pipeline/custom/utils.ts diff --git a/cocos/core/index.ts b/cocos/core/index.ts index 308a71d09f..11604930e2 100644 --- a/cocos/core/index.ts +++ b/cocos/core/index.ts @@ -60,3 +60,5 @@ export * from './components'; export * from './builtin'; export * from './curves'; export * from './settings'; + +export * from './pipeline/custom/builtin-pipelines'; diff --git a/cocos/core/pipeline/custom/builtin-pipelines.ts b/cocos/core/pipeline/custom/builtin-pipelines.ts new file mode 100644 index 0000000000..35fc3a7a6e --- /dev/null +++ b/cocos/core/pipeline/custom/builtin-pipelines.ts @@ -0,0 +1,448 @@ +import { Material } from '../../assets'; +import { intersect, Sphere } from '../../geometry'; +import { ClearFlagBit, Color, Format, LoadOp, Rect, StoreOp, Viewport } from '../../gfx'; +import { macro } from '../../platform'; +import { Camera, CSMLevel, DirectionalLight, Light, LightType, ShadowType, SKYBOX_FLAG, SpotLight } from '../../renderer/scene'; +import { supportsR32FloatTexture } from '../define'; +import { SRGBToLinear } from '../pipeline-funcs'; +import { AccessType, AttachmentType, ComputeView, LightInfo, QueueHint, RasterView, ResourceResidency, SceneFlags } from './types'; +import { Pipeline, PipelineBuilder } from './pipeline'; + +export function getRenderArea (camera: Camera, width: number, height: number, light: Light | null = null, level = 0): Rect { + const out = new Rect(); + const vp = camera.viewport; + const w = width; + const h = height; + out.x = vp.x * w; + out.y = vp.y * h; + out.width = vp.width * w; + out.height = vp.height * h; + if (light) { + switch (light.type) { + case LightType.DIRECTIONAL: { + const mainLight = light as DirectionalLight; + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + out.x = 0; + out.y = 0; + out.width = w; + out.height = h; + } else { + out.x = level % 2 * 0.5 * w; + out.y = (1 - Math.floor(level / 2)) * 0.5 * h; + out.width = 0.5 * w; + out.height = 0.5 * h; + } + break; + } + case LightType.SPOT: { + out.x = 0; + out.y = 0; + out.width = w; + out.height = h; + break; + } + default: + } + } + return out; +} + +export function buildShadowPass (passName: Readonly, + ppl: Pipeline, + camera: Camera, light: Light, level: number, + width: Readonly, height: Readonly) { + const device = ppl.device; + const shadowMapName = passName; + if (!ppl.containsResource(shadowMapName)) { + const format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8; + ppl.addRenderTarget(shadowMapName, format, width, height, ResourceResidency.MANAGED); + ppl.addDepthStencil(`${shadowMapName}Depth`, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + const pass = ppl.addRasterPass(width, height, 'default', passName); + pass.addRasterView(shadowMapName, new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + ClearFlagBit.COLOR, + new Color(1, 1, 1, camera.clearColor.w))); + pass.addRasterView(`${shadowMapName}Depth`, new RasterView('_', + AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + LoadOp.CLEAR, StoreOp.DISCARD, + ClearFlagBit.DEPTH_STENCIL, + new Color(camera.clearDepth, camera.clearStencil, 0, 0))); + const rect = getRenderArea(camera, width, height, light, level); + pass.setViewport(new Viewport(rect.x, rect.y, rect.width, rect.height)); + const queue = pass.addQueue(QueueHint.RENDER_OPAQUE); + queue.addSceneOfCamera(camera, new LightInfo(light, level), + SceneFlags.SHADOW_CASTER); +} + +class CameraInfo { + shadowEnabled = false; + mainLightShadowNames = new Array(); + spotLightShadowNames = new Array(); +} + +export function buildShadowPasses (cameraName: string, camera: Camera, ppl: Pipeline): CameraInfo { + const pipeline = ppl; + const shadowInfo = pipeline.pipelineSceneData.shadows; + const validPunctualLights = ppl.pipelineSceneData.validPunctualLights; + const cameraInfo = new CameraInfo(); + const shadows = ppl.pipelineSceneData.shadows; + if (!shadowInfo.enabled || shadowInfo.type !== ShadowType.ShadowMap) { return cameraInfo; } + cameraInfo.shadowEnabled = true; + const _validLights: Light[] = []; + let n = 0; + let m = 0; + for (;n < shadowInfo.maxReceived && m < validPunctualLights.length;) { + const light = validPunctualLights[m]; + if (light.type === LightType.SPOT) { + const spotLight = light as SpotLight; + if (spotLight.shadowEnabled) { + _validLights.push(light); + n++; + } + } + m++; + } + + const { mainLight } = camera.scene!; + // build shadow map + const mapWidth = shadows.size.x; + const mapHeight = shadows.size.y; + if (mainLight && mainLight.shadowEnabled) { + cameraInfo.mainLightShadowNames[0] = `MainLightShadow${cameraName}`; + if (mainLight.shadowFixedArea) { + buildShadowPass(cameraInfo.mainLightShadowNames[0], ppl, + camera, mainLight, 0, mapWidth, mapHeight); + } else { + for (let i = 0; i < mainLight.csmLevel; i++) { + cameraInfo.mainLightShadowNames[i] = `MainLightShadow${cameraName}`; + buildShadowPass(cameraInfo.mainLightShadowNames[i], ppl, + camera, mainLight, i, mapWidth, mapHeight); + } + } + } + + for (let l = 0; l < _validLights.length; l++) { + const light = _validLights[l]; + const passName = `SpotLightShadow${l.toString()}${cameraName}`; + cameraInfo.spotLightShadowNames[l] = passName; + buildShadowPass(passName, ppl, + camera, light, 0, mapWidth, mapHeight); + } + return cameraInfo; +} + +const _cameras: Camera[] = []; + +export function getCameraUniqueID (camera: Camera) { + if (!_cameras.includes(camera)) { + _cameras.push(camera); + } + return _cameras.indexOf(camera); +} + +export function getLoadOpOfClearFlag (clearFlag: ClearFlagBit, attachment: AttachmentType): LoadOp { + let loadOp = LoadOp.CLEAR; + if (!(clearFlag & ClearFlagBit.COLOR) + && attachment === AttachmentType.RENDER_TARGET) { + if (clearFlag & SKYBOX_FLAG) { + loadOp = LoadOp.DISCARD; + } else { + loadOp = LoadOp.LOAD; + } + } + if ((clearFlag & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL + && attachment === AttachmentType.DEPTH_STENCIL) { + if (!(clearFlag & ClearFlagBit.DEPTH)) loadOp = LoadOp.LOAD; + if (!(clearFlag & ClearFlagBit.STENCIL)) loadOp = LoadOp.LOAD; + } + return loadOp; +} + +export class ForwardPipelineBuilder extends PipelineBuilder { + public setup (cameras: Camera[], ppl: Pipeline): void { + for (let i = 0; i < cameras.length; i++) { + const camera = cameras[i]; + if (camera.scene === null) { + continue; + } + validPunctualLightsCulling(ppl, camera); + const cameraID = getCameraUniqueID(camera); + const cameraName = `Camera${cameraID}`; + const cameraInfo = buildShadowPasses(cameraName, camera, ppl); + const width = camera.window.width; + const height = camera.window.height; + + const forwardPassRTName = `dsForwardPassColor${cameraName}`; + const forwardPassDSName = `dsForwardPassDS${cameraName}`; + if (!ppl.containsResource(forwardPassRTName)) { + ppl.addRenderTexture(forwardPassRTName, Format.RGBA8, width, height, camera.window); + ppl.addDepthStencil(forwardPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + const forwardPass = ppl.addRasterPass(width, height, 'default', `CameraForwardPass${cameraID}`); + for (const dirShadowName of cameraInfo.mainLightShadowNames) { + if (ppl.containsResource(dirShadowName)) { + const computeView = new ComputeView(); + forwardPass.addComputeView(dirShadowName, computeView); + } + } + for (const spotShadowName of cameraInfo.spotLightShadowNames) { + if (ppl.containsResource(spotShadowName)) { + const computeView = new ComputeView(); + forwardPass.addComputeView(spotShadowName, computeView); + } + } + const passView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), + StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); + const passDSView = new RasterView('_', + AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), + StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearDepth, camera.clearStencil, 0, 0)); + forwardPass.addRasterView(forwardPassRTName, passView); + forwardPass.addRasterView(forwardPassDSName, passDSView); + forwardPass + .addQueue(QueueHint.RENDER_OPAQUE) + .addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT | SceneFlags.DEFAULT_LIGHTING); + forwardPass + .addQueue(QueueHint.RENDER_TRANSPARENT) + .addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.UI); + } + } +} + +// Anti-aliasing type, other types will be gradually added in the future +export enum AntiAliasing { + NONE, + FXAA, +} + +class DeferredData { + constructor () { + this._deferredLightingMaterial = new Material(); + this._deferredLightingMaterial.name = 'builtin-deferred-material'; + this._deferredLightingMaterial.initialize({ + effectName: 'pipeline/deferred-lighting', + defines: { CC_RECEIVE_SHADOW: 1 }, + }); + for (let i = 0; i < this._deferredLightingMaterial.passes.length; ++i) { + this._deferredLightingMaterial.passes[i].tryCompile(); + } + + this._deferredPostMaterial = new Material(); + this._deferredPostMaterial.name = 'builtin-post-process-material'; + if (macro.ENABLE_ANTIALIAS_FXAA) { + this._antiAliasing = AntiAliasing.FXAA; + } + this._deferredPostMaterial.initialize({ + effectName: 'pipeline/post-process', + defines: { + // Anti-aliasing type, currently only fxaa, so 1 means fxaa + ANTIALIAS_TYPE: this._antiAliasing, + }, + }); + for (let i = 0; i < this._deferredPostMaterial.passes.length; ++i) { + this._deferredPostMaterial.passes[i].tryCompile(); + } + } + readonly _deferredLightingMaterial: Material; + readonly _deferredPostMaterial: Material; + _antiAliasing: AntiAliasing = AntiAliasing.NONE; +} + +export function validPunctualLightsCulling (pipeline: Pipeline, camera: Camera) { + const sceneData = pipeline.pipelineSceneData; + const validPunctualLights = sceneData.validPunctualLights; + validPunctualLights.length = 0; + const _sphere = Sphere.create(0, 0, 0, 1); + const { spotLights } = camera.scene!; + for (let i = 0; i < spotLights.length; i++) { + const light = spotLights[i]; + if (light.baked) { + continue; + } + + Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphereFrustum(_sphere, camera.frustum)) { + validPunctualLights.push(light); + } + } + + const { sphereLights } = camera.scene!; + for (let i = 0; i < sphereLights.length; i++) { + const light = sphereLights[i]; + if (light.baked) { + continue; + } + Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphereFrustum(_sphere, camera.frustum)) { + validPunctualLights.push(light); + } + } +} + +export class DeferredPipelineBuilder extends PipelineBuilder { + public setup (cameras: Camera[], ppl: Pipeline): void { + for (let i = 0; i < cameras.length; ++i) { + const camera = cameras[i]; + if (!camera.scene) { + continue; + } + validPunctualLightsCulling(ppl, camera); + const cameraID = getCameraUniqueID(camera); + const cameraName = `Camera${cameraID}`; + const cameraInfo = buildShadowPasses(cameraName, camera, ppl); + const width = camera.window.width; + const height = camera.window.height; + + const deferredGbufferPassRTName = `dsDeferredPassColorCamera`; + const deferredGbufferPassNormal = `deferredGbufferPassNormal`; + const deferredGbufferPassEmissive = `deferredGbufferPassEmissive`; + const deferredGbufferPassDSName = `dsDeferredPassDSCamera`; + if (!ppl.containsResource(deferredGbufferPassRTName)) { + const colFormat = Format.RGBA16F; + ppl.addRenderTarget(deferredGbufferPassRTName, colFormat, width, height, ResourceResidency.MANAGED); + ppl.addRenderTarget(deferredGbufferPassNormal, colFormat, width, height, ResourceResidency.MANAGED); + ppl.addRenderTarget(deferredGbufferPassEmissive, colFormat, width, height, ResourceResidency.MANAGED); + ppl.addDepthStencil(deferredGbufferPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + // gbuffer pass + const gbufferPass = ppl.addRasterPass(width, height, 'Geometry', `CameraGbufferPass${cameraID}`); + + const rtColor = new Color(0, 0, 0, 0); + if (camera.clearFlag & ClearFlagBit.COLOR) { + if (ppl.pipelineSceneData.isHDR) { + SRGBToLinear(rtColor, camera.clearColor); + } else { + rtColor.x = camera.clearColor.x; + rtColor.y = camera.clearColor.y; + rtColor.z = camera.clearColor.z; + } + } + const passColorView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + rtColor); + const passNormalView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + new Color(0, 0, 0, 0)); + const passEmissiveView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + new Color(0, 0, 0, 0)); + const passDSView = new RasterView('_', + AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearDepth, camera.clearStencil, 0, 0)); + gbufferPass.addRasterView(deferredGbufferPassRTName, passColorView); + gbufferPass.addRasterView(deferredGbufferPassNormal, passNormalView); + gbufferPass.addRasterView(deferredGbufferPassEmissive, passEmissiveView); + gbufferPass.addRasterView(deferredGbufferPassDSName, passDSView); + gbufferPass + .addQueue(QueueHint.RENDER_OPAQUE) + .addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT); + const deferredLightingPassRTName = `deferredLightingPassRTName`; + const deferredLightingPassDS = `deferredLightingPassDS`; + if (!ppl.containsResource(deferredLightingPassRTName)) { + ppl.addRenderTarget(deferredLightingPassRTName, Format.RGBA8, width, height, ResourceResidency.MANAGED); + ppl.addDepthStencil(deferredLightingPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + // lighting pass + const lightingPass = ppl.addRasterPass(width, height, 'Lighting', `CameraLightingPass${cameraID}`); + for (const dirShadowName of cameraInfo.mainLightShadowNames) { + if (ppl.containsResource(dirShadowName)) { + const computeView = new ComputeView(); + lightingPass.addComputeView(dirShadowName, computeView); + } + } + for (const spotShadowName of cameraInfo.spotLightShadowNames) { + if (ppl.containsResource(spotShadowName)) { + const computeView = new ComputeView(); + lightingPass.addComputeView(spotShadowName, computeView); + } + } + if (ppl.containsResource(deferredGbufferPassRTName)) { + const computeView = new ComputeView(); + computeView.name = 'gbuffer_albedoMap'; + lightingPass.addComputeView(deferredGbufferPassRTName, computeView); + + const computeNormalView = new ComputeView(); + computeNormalView.name = 'gbuffer_normalMap'; + lightingPass.addComputeView(deferredGbufferPassNormal, computeNormalView); + + const computeEmissiveView = new ComputeView(); + computeEmissiveView.name = 'gbuffer_emissiveMap'; + lightingPass.addComputeView(deferredGbufferPassEmissive, computeEmissiveView); + + const computeDepthView = new ComputeView(); + computeDepthView.name = 'depth_stencil'; + lightingPass.addComputeView(deferredGbufferPassDSName, computeDepthView); + } + const lightingClearColor = new Color(0, 0, 0, 0); + if (camera.clearFlag & ClearFlagBit.COLOR) { + lightingClearColor.x = camera.clearColor.x; + lightingClearColor.y = camera.clearColor.y; + lightingClearColor.z = camera.clearColor.z; + } + lightingClearColor.w = 0; + const lightingPassView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + lightingClearColor); + lightingPass.addRasterView(deferredLightingPassRTName, lightingPassView); + lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( + camera, this._deferredData._deferredLightingMaterial, + SceneFlags.VOLUMETRIC_LIGHTING, + ); + lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT); + // Postprocess + const postprocessPassRTName = `postprocessPassRTName${cameraID}`; + const postprocessPassDS = `postprocessPassDS${cameraID}`; + if (!ppl.containsResource(postprocessPassRTName)) { + ppl.addRenderTexture(postprocessPassRTName, Format.RGBA8, width, height, camera.window); + ppl.addDepthStencil(postprocessPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + const postprocessPass = ppl.addRasterPass(width, height, 'Postprocess', `CameraPostprocessPass${cameraID}`); + if (ppl.containsResource(deferredLightingPassRTName)) { + const computeView = new ComputeView(); + computeView.name = 'outputResultMap'; + postprocessPass.addComputeView(deferredLightingPassRTName, computeView); + } + const postClearColor = new Color(0, 0, 0, camera.clearColor.w); + if (camera.clearFlag & ClearFlagBit.COLOR) { + postClearColor.x = camera.clearColor.x; + postClearColor.y = camera.clearColor.y; + postClearColor.z = camera.clearColor.z; + } + const postprocessPassView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), + StoreOp.STORE, + camera.clearFlag, + postClearColor); + const postprocessPassDSView = new RasterView('_', + AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), + StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearDepth, camera.clearStencil, 0, 0)); + postprocessPass.addRasterView(postprocessPassRTName, postprocessPassView); + postprocessPass.addRasterView(postprocessPassDS, postprocessPassDSView); + postprocessPass.addQueue(QueueHint.NONE).addFullscreenQuad(this._deferredData._deferredPostMaterial, SceneFlags.NONE); + postprocessPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), SceneFlags.UI); + } + } + readonly _deferredData = new DeferredData(); +} diff --git a/cocos/core/pipeline/custom/compiler.ts b/cocos/core/pipeline/custom/compiler.ts index 57c2a8b161..56e533f383 100644 --- a/cocos/core/pipeline/custom/compiler.ts +++ b/cocos/core/pipeline/custom/compiler.ts @@ -22,14 +22,14 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -import { Buffer, Framebuffer, Texture } from '../../gfx'; +import { Buffer, Framebuffer, Texture, Viewport } from '../../gfx'; import { assert } from '../../platform/debug'; import { LayoutGraphData } from './layout-graph'; import { Pipeline } from './pipeline'; -import { AccessType, Blit, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, - PresentPass, RasterPass, RasterView, RaytracePass, RenderGraph, RenderGraphValue, RenderGraphVisitor, +import { Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, + PresentPass, RasterPass, RaytracePass, RenderGraph, RenderGraphValue, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResourceGraph, ResourceGraphVisitor, SceneData } from './render-graph'; -import { ResourceResidency } from './types'; +import { AccessType, RasterView, ResourceResidency } from './types'; class PassVisitor implements RenderGraphVisitor { public passID = 0xFFFFFFFF; @@ -42,6 +42,12 @@ class PassVisitor implements RenderGraphVisitor { constructor (context: CompilerContext) { this._context = context; } + clear (value: ClearView[]): unknown { + throw new Error('Method not implemented.'); + } + viewport (value: Viewport): unknown { + throw new Error('Method not implemented.'); + } raster (pass: RasterPass) { // Since the pass is valid, there is no need to continue traversing. if (pass.isValid) { @@ -82,7 +88,7 @@ class PassVisitor implements RenderGraphVisitor { rg.visitVertex(this, sceneID); } } - scene (value: SceneData) { + private _fetchValidPass () { if (this._currPass!.isValid) { return; } @@ -90,31 +96,48 @@ class PassVisitor implements RenderGraphVisitor { const outputName = this._context.resourceGraph.vertexName(outputId); const readViews: Map = new Map(); const pass = this._currPass!; - for (const [name, raster] of pass.rasterViews) { + + for (const [readName, raster] of pass.rasterViews) { // find the pass - if (name === outputName + if (readName === outputName && raster.accessType !== AccessType.READ) { assert(!pass.isValid, 'The same pass cannot output multiple resources with the same name at the same time'); pass.isValid = true; continue; } if (raster.accessType !== AccessType.WRITE) { - readViews.set(name, raster); + readViews.set(readName, raster); } } if (pass.isValid) { - for (const [name, raster] of readViews) { - const resVisitor = new ResourceVisitor(this._context); - const resourceGraph = this._context.resourceGraph; - const vertID = resourceGraph.vertex(name); - if (vertID) { + let resVisitor; + let resourceGraph; + let vertID; + for (const [rasterName, raster] of readViews) { + resVisitor = new ResourceVisitor(this._context); + resourceGraph = this._context.resourceGraph; + vertID = resourceGraph.find(rasterName); + if (vertID !== 0xFFFFFFFF) { + resVisitor.resID = vertID; + resourceGraph.visitVertex(resVisitor, vertID); + } + } + for (const [computeName, cViews] of pass.computeViews) { + resVisitor = new ResourceVisitor(this._context); + resourceGraph = this._context.resourceGraph; + vertID = resourceGraph.find(computeName); + if (vertID !== 0xFFFFFFFF) { resVisitor.resID = vertID; resourceGraph.visitVertex(resVisitor, vertID); } } } } + scene (value: SceneData) { + this._fetchValidPass(); + } blit (value: Blit) { + this._fetchValidPass(); } dispatch (value: Dispatch) { } diff --git a/cocos/core/pipeline/custom/debug.ts b/cocos/core/pipeline/custom/debug.ts new file mode 100644 index 0000000000..0ee76dd397 --- /dev/null +++ b/cocos/core/pipeline/custom/debug.ts @@ -0,0 +1,200 @@ +/* eslint-disable max-len */ +import { Viewport } from '../../gfx'; +import { assert } from '../../platform'; +import { DefaultVisitor, ReferenceGraphView, ED, edge_descriptor, IncidenceGraph } from './graph'; +import { Blit, ClearView, ComputePass, CopyPass, Dispatch, getRenderGraphValueName, MovePass, PresentPass, RasterPass, RaytracePass, RenderGraph, RenderGraphValue, RenderGraphVisitor, RenderQueue, SceneData } from './render-graph'; +import { getQueueHintName } from './types'; + +export const enableDebug = true; + +let oss = ''; +let space = ''; + +class PrePrintVisitor implements RenderGraphVisitor { + constructor (g: RenderGraph) { + this.g = g; + } + clear (value: ClearView[]) { + // do nothing + } + viewport (value: Viewport) { + // do nothing + } + raster (value: RasterPass) { + oss += `${space}width = ${value.width}\n`; + oss += `${space}height = ${value.height}\n`; + for (const rasterView of value.rasterViews) { + oss += `${space}"${rasterView[0]}": RasterView\n`; + } + for (const computeView of value.computeViews) { + oss += `${space}"${computeView[0]}": ComputeView[]\n`; + } + } + compute (value: ComputePass) { + for (const computeView of value.computeViews) { + oss += `${space}"${computeView[0]}": ComputeView[]\n`; + } + } + copy (value: CopyPass) { + if (value.copyPairs.length === 1) { + const pair = value.copyPairs[0]; + oss += `${space}source = "${pair.source}"\n`; + oss += `${space}target = "${pair.target}"\n`; + } else { + let i = 0; + oss += `${space}sources = [`; + for (const pair of value.copyPairs) { + if (i++) { + oss += ', '; + } + oss += `"${pair.source}"`; + } + oss += ']\n'; + + oss += `${space}targets = [`; + for (const pair of value.copyPairs) { + if (i++) { + oss += ', '; + } + oss += `"${pair.target}"`; + } + oss += ']\n'; + } + } + move (value: MovePass) { + if (value.movePairs.length === 1) { + const pair = value.movePairs[0]; + oss += `${space}source = "${pair.source}"\n`; + oss += `${space}target = "${pair.target}"\n`; + } else { + let i = 0; + oss += `${space}sources = [`; + for (const pair of value.movePairs) { + if (i++) { + oss += ', '; + } + oss += `"${pair.source}"`; + } + oss += ']\n'; + + oss += `${space}targets = [`; + for (const pair of value.movePairs) { + if (i++) { + oss += ', '; + } + oss += `"${pair.target}"`; + } + oss += ']\n'; + } + } + present (value: PresentPass) { + for (const present of value.presents) { + oss += `${space}"${present[0]}": Present{ interval = ${present[1].syncInterval} }\n`; + } + } + raytrace (value: RaytracePass) { + for (const computeView of value.computeViews) { + oss += `${space}"${computeView[0]}": ComputeView[]\n`; + } + } + queue (value: RenderQueue) { + oss += `${space}hint = ${getQueueHintName(value.hint)}\n`; + } + scene (value: SceneData) { + oss += `${space}scenes = [`; + let i = 0; + for (const scene of value.scenes) { + if (i++) { + oss += ', '; + } + oss += `"${scene}"`; + } + oss += ']\n'; + } + blit (value: Blit) {} + dispatch (value: Dispatch) { + oss += `${space}shader = "${value.shader}"\n`; + oss += `${space}groupX = ${value.threadGroupCountX}\n`; + oss += `${space}groupY = ${value.threadGroupCountY}\n`; + oss += `${space}groupZ = ${value.threadGroupCountZ}\n`; + } + g: RenderGraph; +} + +class PostPrintVisitor implements RenderGraphVisitor { + constructor (g: RenderGraph) { + this.g = g; + } + clear (value: ClearView[]) { + // do nothing + } + viewport (value: Viewport) { + // do nothing + } + raster (value: RasterPass) { + // post raster pass + } + compute (value: ComputePass) {} + copy (value: CopyPass) {} + move (value: MovePass) {} + present (value: PresentPass) {} + raytrace (value: RaytracePass) {} + queue (value: RenderQueue) { + // collect scene results + } + scene (value: SceneData) { + // scene command list finished + } + blit (value: Blit) {} + dispatch (value: Dispatch) {} + g: RenderGraph; +} + +export class RenderGraphPrintVisitor extends DefaultVisitor { + constructor (g: RenderGraph) { + super(); + this.preVertexVisitor = new PrePrintVisitor(g); + this.postVertexVisitor = new PostPrintVisitor(g); + } + initializeVertex (v: number, gv: ReferenceGraphView): void { + // initialization + } + startVertex (v: number, gv: ReferenceGraphView): void { + const g = gv.g; + // passes begin + // assert(g.holds(RenderGraphValue.Raster, v) + // || g.holds(RenderGraphValue.Compute, v) + // || g.holds(RenderGraphValue.Copy, v) + // || g.holds(RenderGraphValue.Move, v) + // || g.holds(RenderGraphValue.Present, v) + // || g.holds(RenderGraphValue.Raytrace, v)); + } + discoverVertex (v: number, gv: ReferenceGraphView): void { + const g = gv.g; + oss += `${space}"${g.getName(v)}": ${getRenderGraphValueName(g.id(v))} {\n`; + space += ' '; + + g.visitVertex(this.preVertexVisitor, v); + } + backEdge (e: ED, gv: ReferenceGraphView): void { + assert(false); + } + forwardOrCrossEdge (e: ED, gv: ReferenceGraphView): void { + assert(false); + } + finishEdge (e: ED, gv: ReferenceGraphView): void { + const g = gv.g; + } + finishVertex (v: number, gv: ReferenceGraphView): void { + const g = gv.g; + g.visitVertex(this.postVertexVisitor, v); + + space = space.substring(0, space.length - 4); + oss += `${space}}\n`; + } + print (): string { + return oss; + } + readonly preVertexVisitor; + readonly postVertexVisitor; +} diff --git a/cocos/core/pipeline/custom/effect.ts b/cocos/core/pipeline/custom/effect.ts index d9d56a830d..bd0c748ae0 100644 --- a/cocos/core/pipeline/custom/effect.ts +++ b/cocos/core/pipeline/custom/effect.ts @@ -1,10 +1,12 @@ import { legacyCC } from '../../global-exports'; import { EffectAsset } from '../../assets'; -import { WebDescriptorHierarchy } from './web-descriptor-hierarchy'; +import { CollectVisitor, WebDescriptorHierarchy } from './web-descriptor-hierarchy'; // eslint-disable-next-line max-len -import { Descriptor, DescriptorBlock, DescriptorBlockFlattened, DescriptorBlockIndex, DescriptorDB, LayoutGraph, LayoutGraphValue } from './layout-graph'; -import { Pipeline } from './pipeline'; -import { UniformBlock } from '../../gfx'; +import { Descriptor, DescriptorBlock, DescriptorBlockFlattened, DescriptorBlockIndex, DescriptorDB, DescriptorTypeOrder, LayoutGraph, LayoutGraphData, LayoutGraphValue, RenderPhase } from './layout-graph'; +import { LayoutGraphBuilder, Pipeline } from './pipeline'; +import { DescriptorType, ShaderStageFlagBit, Type, UniformBlock } from '../../gfx'; +import { ParameterType, UpdateFrequency } from './types'; +import { depthFirstSearch, GraphColor, MutableVertexPropertyMap } from './graph'; function descriptorBlock2Flattened (block: DescriptorBlock, flattened: DescriptorBlockFlattened): void { block.descriptors.forEach((value, key) => { @@ -23,30 +25,7 @@ function descriptorBlock2Flattened (block: DescriptorBlock, flattened: Descripto flattened.capacity = block.capacity; } -export function rebuildLayoutGraph (): void { - const root = legacyCC.director.root; - if (!root.usesCustomPipeline) { - return; - } - if (EffectAsset.isLayoutValid()) { - return; - } - console.log('rebuildLayoutGraph begin'); - const ppl: Pipeline = root.customPipeline; - const effects = EffectAsset.getAll(); - const lg = new WebDescriptorHierarchy(); - const lgData = ppl.layoutGraphBuilder; - lgData.clear(); - - const defaultStage: number = lg.addGlobal('default', true, true, true, true, true, true, true); - - for (const n in effects) { - const e: EffectAsset = effects[n]; - lg.addEffect(e, defaultStage); - } - - const graph: LayoutGraph = lg.layoutGraph; - +export function buildLayoutGraphDataImpl (graph: LayoutGraph, lgData: LayoutGraphBuilder) { for (const v of graph.vertices()) { const db: DescriptorDB = graph.getDescriptors(v); let vid = 0; @@ -64,17 +43,242 @@ export function rebuildLayoutGraph (): void { db.blocks.forEach((value, key) => { const index: DescriptorBlockIndex = JSON.parse(key) as DescriptorBlockIndex; const block: DescriptorBlock = value; + const flattened = new DescriptorBlockFlattened(); + descriptorBlock2Flattened(block, flattened); if (block.capacity > 0) { - const flattened = new DescriptorBlockFlattened(); - descriptorBlock2Flattened(block, flattened); lgData.addDescriptorBlock(vid, index, flattened); } + for (let i = 0; i < flattened.uniformBlockNames.length; ++i) { + lgData.addUniformBlock(vid, index, flattened.uniformBlockNames[i], flattened.uniformBlocks[i]); + } }); } +} - lgData.compile(); - console.log(lgData.print()); +function rebuildLayoutGraph (): void { + const root = legacyCC.director.root; + if (!root.usesCustomPipeline) { + return; + } + if (EffectAsset.isLayoutValid()) { + return; + } + console.log('rebuildLayoutGraph begin'); + const ppl: Pipeline = root.customPipeline; + const effects = EffectAsset.getAll(); + const lg: WebDescriptorHierarchy = new WebDescriptorHierarchy(); + const lgData = ppl.layoutGraphBuilder; + lgData.clear(); + + const defaultStage: number = lg.addGlobal('default', true, true, true, true, true, true, true); + + for (const n in effects) { + const e: EffectAsset = effects[n]; + lg.addEffect(e, defaultStage); + } + + lg.mergeDescriptors(defaultStage); + + buildLayoutGraphDataImpl(lg.layoutGraph, lgData); EffectAsset.setLayoutValid(); console.log('rebuildLayoutGraph end'); } + +function buildForwardLayoutFromGlobal (ppl: Pipeline, lg: WebDescriptorHierarchy) { + const src = ppl.globalDSManager.descriptorSetLayout; + const passDB: DescriptorDB = new DescriptorDB(); + let count = 0; + for (const b of src.bindings) { + switch (b.descriptorType) { + case DescriptorType.UNIFORM_BUFFER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.UNIFORM_BUFFER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.DYNAMIC_UNIFORM_BUFFER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.STORAGE_BUFFER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.STORAGE_BUFFER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.DYNAMIC_STORAGE_BUFFER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.DYNAMIC_STORAGE_BUFFER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.SAMPLER_TEXTURE: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.SAMPLER_TEXTURE, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.SAMPLER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.SAMPLER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.TEXTURE: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.TEXTURE, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.STORAGE_IMAGE: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.STORAGE_IMAGE, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.INPUT_ATTACHMENT: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.INPUT_ATTACHMENT, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.UNKNOWN: + default: + break; + } + ++count; + } + const defaultID = lg._layoutGraph.addVertex( + LayoutGraphValue.RenderStage, + LayoutGraphValue.RenderStage, + 'default', passDB, + ); + + lg.mergeDescriptors(defaultID); +} + +export function buildForwardLayout (ppl: Pipeline) { + const lg = new WebDescriptorHierarchy(); + const bFromGlobalDescriptorSet = false; + + if (bFromGlobalDescriptorSet) { + buildForwardLayoutFromGlobal(ppl, lg); + } else { + const defaultID = lg.addGlobal('default', true, true, true, true, true, true, true); + lg.mergeDescriptors(defaultID); + } + + const builder = ppl.layoutGraphBuilder; + builder.clear(); + buildLayoutGraphDataImpl(lg.layoutGraph, builder); +} + +enum DeferredStage { + GEOMETRY, + LIGHTING, + POST +} + +export class VectorGraphColorMap implements MutableVertexPropertyMap { + constructor (sz: number) { + this.colors = new Array(sz); + } + get (u: number): GraphColor { + return this.colors[u]; + } + put (u: number, value: GraphColor): void { + this.colors[u] = value; + } + readonly colors: Array; +} + +export function buildDeferredLayout (ppl: Pipeline) { + const lg = new WebDescriptorHierarchy(); + const defaultID = lg.addGlobal('default', true, true, true, true, true, true, true); + lg.mergeDescriptors(defaultID); + const geometryPassID = lg.addRenderStage('Geometry', DeferredStage.GEOMETRY); + const lightingPassID = lg.addRenderStage('Lighting', DeferredStage.LIGHTING); + const postPassID = lg.addRenderStage('Postprocess', DeferredStage.POST); + + const geometryQueueID = lg.addRenderPhase('Queue', geometryPassID); + const lightingQueueID = lg.addRenderPhase('Queue', lightingPassID); + const postQueueID = lg.addRenderPhase('Queue', postPassID); + + const lightingDescriptors = lg.layoutGraph.getDescriptors(lightingQueueID); + + const lightingPassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.SAMPLER_TEXTURE, + ShaderStageFlagBit.FRAGMENT, + lightingDescriptors); + + lg.setDescriptor(lightingPassBlock, 'gbuffer_albedoMap', Type.FLOAT4); + lg.setDescriptor(lightingPassBlock, 'gbuffer_normalMap', Type.FLOAT4); + lg.setDescriptor(lightingPassBlock, 'gbuffer_emissiveMap', Type.FLOAT4); + lg.setDescriptor(lightingPassBlock, 'depth_stencil', Type.FLOAT4); + + const visitor = new CollectVisitor(); + const colorMap = new VectorGraphColorMap(lg.layoutGraph.numVertices()); + depthFirstSearch(lg.layoutGraph, visitor, colorMap); + + lg.mergeDescriptors(lightingPassID); + // Postprocess + const postDescriptors = lg.layoutGraph.getDescriptors(postPassID); + + const postPassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.SAMPLER_TEXTURE, + ShaderStageFlagBit.FRAGMENT, + postDescriptors); + + lg.setDescriptor(postPassBlock, 'outputResultMap', Type.FLOAT4); + lg.merge(postDescriptors); + + lg.mergeDescriptors(postPassID); + if (visitor.error) { + console.log(visitor.error); + } + + const builder = ppl.layoutGraphBuilder; + builder.clear(); + buildLayoutGraphDataImpl(lg.layoutGraph, builder); +} diff --git a/cocos/core/pipeline/custom/executor.ts b/cocos/core/pipeline/custom/executor.ts index 57730554de..05d0e1bc58 100644 --- a/cocos/core/pipeline/custom/executor.ts +++ b/cocos/core/pipeline/custom/executor.ts @@ -30,24 +30,42 @@ */ /* eslint-disable max-len */ import { getPhaseID, InstancedBuffer, PipelineStateManager } from '..'; -import { AccessFlagBit, Buffer, ClearFlagBit, Color, ColorAttachment, CommandBuffer, DepthStencilAttachment, Device, deviceManager, Format, Framebuffer, - FramebufferInfo, GeneralBarrierInfo, LoadOp, PipelineState, Rect, RenderPass, RenderPassInfo, StoreOp, Swapchain, Texture, TextureInfo, +import { assert } from '../..'; +import { AABB } from '../../geometry/aabb'; +import intersect from '../../geometry/intersect'; +import { Sphere } from '../../geometry/sphere'; +import { AccessFlagBit, Attribute, Buffer, BufferInfo, BufferUsageBit, BufferViewInfo, ClearFlagBit, Color, ColorAttachment, CommandBuffer, DepthStencilAttachment, DescriptorSet, DescriptorSetInfo, Device, deviceManager, Format, Framebuffer, + FramebufferInfo, GeneralBarrierInfo, InputAssemblerInfo, LoadOp, MemoryUsageBit, PipelineState, Rect, RenderPass, RenderPassInfo, SamplerInfo, Shader, StoreOp, SurfaceTransform, Swapchain, Texture, TextureInfo, TextureType, TextureUsageBit, Viewport } from '../../gfx'; import { legacyCC } from '../../global-exports'; -import { BatchingSchemes } from '../../renderer'; +import { Mat4 } from '../../math/mat4'; +import { Vec3 } from '../../math/vec3'; +import { Vec4 } from '../../math/vec4'; +import { BatchingSchemes, Pass } from '../../renderer'; +import { DirectionalLight, SpotLight } from '../../renderer/scene'; import { Camera, SKYBOX_FLAG } from '../../renderer/scene/camera'; +import { Light, LightType } from '../../renderer/scene/light'; +import { Model } from '../../renderer/scene/model'; +import { CSMLevel, CSMOptimizationMode, ShadowType } from '../../renderer/scene/shadows'; +import { SubModel } from '../../renderer/scene/submodel'; import { Root } from '../../root'; import { BatchedBuffer } from '../batched-buffer'; -import { SetIndex } from '../define'; +import { RenderPassStage, SetIndex, UBODeferredLight, UBOForwardLight, UBOLocal } from '../define'; import { PipelineSceneData } from '../pipeline-scene-data'; +import { PipelineInputAssemblerData } from '../render-pipeline'; +import { ShadowLayerVolume } from '../shadow/csm-layers'; +import { LayoutGraph, LayoutGraphData, LayoutGraphDataVisitor, LayoutGraphVisitor, PipelineLayoutData, RenderPhase, RenderPhaseData, RenderStageData } from './layout-graph'; import { Pipeline, SceneVisitor } from './pipeline'; -import { AccessType, AttachmentType, Blit, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, PresentPass, - RasterPass, RaytracePass, RenderGraph, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResourceDesc, +import { Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, PresentPass, + RasterPass, RaytracePass, RenderGraph, RenderGraphValue, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphVisitor, ResourceTraits, SceneData } from './render-graph'; -import { QueueHint, ResourceDimension, ResourceFlags } from './types'; -import { PipelineUBO } from './ubos'; +import { AttachmentType, ComputeView, QueueHint, ResourceDimension, ResourceFlags, SceneFlags, UpdateFrequency } from './types'; +import { PipelineUBO } from '../pipeline-ubo'; import { RenderInfo, RenderObject, WebSceneTask, WebSceneTransversal } from './web-scene'; import { WebSceneVisitor } from './web-scene-visitor'; +import { stringify, parse } from './utils'; +import { RenderAdditiveLightQueue } from '../render-additive-light-queue'; +import { RenderShadowMapBatchedQueue } from '../render-shadow-map-batched-queue'; class DeviceResource { protected _context: ExecutorContext; @@ -119,6 +137,17 @@ class DeviceTexture extends DeviceResource { info.height, )); } + + release () { + if (this.framebuffer) { + this.framebuffer.destroy(); + this._framebuffer = null; + } + if (this.texture) { + this.texture.destroy(); + this._texture = null; + } + } } class DeviceBuffer extends DeviceResource { @@ -126,6 +155,230 @@ class DeviceBuffer extends DeviceResource { super(name, context); } } + +class BlitDesc { + private _blit: Blit; + private _screenQuad: PipelineInputAssemblerData | null = null; + private _queue: DeviceRenderQueue | null = null; + private _stageDesc: DescriptorSet | null = null; + // If VOLUMETRIC_LIGHTING is turned on, it needs to be assigned + private _lightVolumeBuffer: Buffer | null = null; + private _lightMeterScale = 10000.0; + private _lightBufferData!: Float32Array; + get screenQuad () { return this._screenQuad; } + get blit () { return this._blit; } + set blit (blit: Blit) { this._blit = blit; } + get stageDesc () { return this._stageDesc; } + constructor (blit: Blit, queue: DeviceRenderQueue) { + this._blit = blit; + this._queue = queue; + } + /** + * @zh + * 创建四边形输入汇集器。 + */ + protected _createQuadInputAssembler (): PipelineInputAssemblerData { + // create vertex buffer + const inputAssemblerData = new PipelineInputAssemblerData(); + + const vbStride = Float32Array.BYTES_PER_ELEMENT * 4; + const vbSize = vbStride * 4; + const device = this._queue!.devicePass.context.device; + const quadVB = device.createBuffer(new BufferInfo( + BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE | MemoryUsageBit.HOST, + vbSize, + vbStride, + )); + + if (!quadVB) { + return inputAssemblerData; + } + + // create index buffer + const ibStride = Uint8Array.BYTES_PER_ELEMENT; + const ibSize = ibStride * 6; + + const quadIB = device.createBuffer(new BufferInfo( + BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + ibSize, + ibStride, + )); + + if (!quadIB) { + return inputAssemblerData; + } + + const indices = new Uint8Array(6); + indices[0] = 0; indices[1] = 1; indices[2] = 2; + indices[3] = 1; indices[4] = 3; indices[5] = 2; + + quadIB.update(indices); + + // create input assembler + + const attributes = new Array(2); + attributes[0] = new Attribute('a_position', Format.RG32F); + attributes[1] = new Attribute('a_texCoord', Format.RG32F); + + const quadIA = device.createInputAssembler(new InputAssemblerInfo( + attributes, + [quadVB], + quadIB, + )); + + inputAssemblerData.quadIB = quadIB; + inputAssemblerData.quadVB = quadVB; + inputAssemblerData.quadIA = quadIA; + return inputAssemblerData; + } + createSreenQuad () { + if (!this._screenQuad) { + this._screenQuad = this._createQuadInputAssembler(); + } + } + private _updateScreenVB () { + const devicePass = this._queue!.devicePass; + const width = devicePass.context.width; + const height = devicePass.context.height; + const vb = devicePass.genQuadVertexData(SurfaceTransform.IDENTITY, new Rect(0, 0, width, height)); + this._screenQuad!.quadVB!.update(vb); + } + private _gatherVolumeLights (camera: Camera) { + if (!camera.scene) { return; } + const context = this._queue!.devicePass.context; + const pipeline = context.pipeline; + const cmdBuff = context.commandBuffer; + + const sphereLights = camera.scene.sphereLights; + const spotLights = camera.scene.spotLights; + const _sphere = Sphere.create(0, 0, 0, 1); + const _vec4Array = new Float32Array(4); + const exposure = camera.exposure; + + let idx = 0; + const maxLights = UBODeferredLight.LIGHTS_PER_PASS; + const elementLen = Vec4.length; // sizeof(vec4) / sizeof(float32) + const fieldLen = elementLen * maxLights; + + for (let i = 0; i < sphereLights.length && idx < maxLights; i++, ++idx) { + const light = sphereLights[i]; + Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphereFrustum(_sphere, camera.frustum)) { + // cc_lightPos + Vec3.toArray(_vec4Array, light.position); + _vec4Array[3] = 0; + this._lightBufferData.set(_vec4Array, idx * elementLen); + + // cc_lightColor + Vec3.toArray(_vec4Array, light.color); + if (light.useColorTemperature) { + const tempRGB = light.colorTemperatureRGB; + _vec4Array[0] *= tempRGB.x; + _vec4Array[1] *= tempRGB.y; + _vec4Array[2] *= tempRGB.z; + } + + if (pipeline.pipelineSceneData.isHDR) { + _vec4Array[3] = light.luminance * exposure * this._lightMeterScale; + } else { + _vec4Array[3] = light.luminance; + } + + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1); + + // cc_lightSizeRangeAngle + _vec4Array[0] = light.size; + _vec4Array[1] = light.range; + _vec4Array[2] = 0.0; + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2); + } + } + + for (let i = 0; i < spotLights.length && idx < maxLights; i++, ++idx) { + const light = spotLights[i]; + Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphereFrustum(_sphere, camera.frustum)) { + // cc_lightPos + Vec3.toArray(_vec4Array, light.position); + _vec4Array[3] = 1; + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 0); + + // cc_lightColor + Vec3.toArray(_vec4Array, light.color); + if (light.useColorTemperature) { + const tempRGB = light.colorTemperatureRGB; + _vec4Array[0] *= tempRGB.x; + _vec4Array[1] *= tempRGB.y; + _vec4Array[2] *= tempRGB.z; + } + if (pipeline.pipelineSceneData.isHDR) { + _vec4Array[3] = light.luminance * exposure * this._lightMeterScale; + } else { + _vec4Array[3] = light.luminance; + } + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1); + + // cc_lightSizeRangeAngle + _vec4Array[0] = light.size; + _vec4Array[1] = light.range; + _vec4Array[2] = light.spotAngle; + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2); + + // cc_lightDir + Vec3.toArray(_vec4Array, light.direction); + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 3); + } + } + + // the count of lights is set to cc_lightDir[0].w + const offset = fieldLen * 3 + 3; + this._lightBufferData.set([idx], offset); + + cmdBuff.updateBuffer(this._lightVolumeBuffer!, this._lightBufferData); + } + update () { + this._updateScreenVB(); + if (this.blit.sceneFlags & SceneFlags.VOLUMETRIC_LIGHTING + && this.blit.camera) { + this._gatherVolumeLights(this.blit.camera); + } + this._stageDesc!.update(); + } + + createStageDescriptor () { + if (this._stageDesc) { + return; + } + const pass = this.blit.material!.passes[0]; + const device = this._queue!.devicePass.context.device; + this._stageDesc = device.createDescriptorSet(new DescriptorSetInfo(pass.localSetLayout)); + if (this.blit.sceneFlags & SceneFlags.VOLUMETRIC_LIGHTING) { + let totalSize = Float32Array.BYTES_PER_ELEMENT * 4 * 4 * UBODeferredLight.LIGHTS_PER_PASS; + totalSize = Math.ceil(totalSize / device.capabilities.uboOffsetAlignment) * device.capabilities.uboOffsetAlignment; + + this._lightVolumeBuffer = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, + totalSize, + device.capabilities.uboOffsetAlignment, + )); + + const deferredLitsBufView = device.createBuffer(new BufferViewInfo(this._lightVolumeBuffer, 0, totalSize)); + this._lightBufferData = new Float32Array(totalSize / Float32Array.BYTES_PER_ELEMENT); + this._stageDesc.bindBuffer(UBOForwardLight.BINDING, deferredLitsBufView); + } + const _localUBO = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + UBOLocal.SIZE, + UBOLocal.SIZE, + )); + this._stageDesc.bindBuffer(UBOLocal.BINDING, _localUBO); + } +} + class DeviceRenderQueue { private _preSceneTasks: DevicePreSceneTask[] = []; private _sceneTasks: DeviceSceneTask[] = []; @@ -133,18 +386,29 @@ class DeviceRenderQueue { private _devicePass: DeviceRenderPass; private _hint: QueueHint = QueueHint.NONE; private _phaseID = getPhaseID('default'); + private _renderPhase: RenderPhaseData | null = null; protected _transversal: DeviceSceneTransversal | null = null; get phaseID (): number { return this._phaseID; } - + get renderPhase (): RenderPhaseData | null { return this._renderPhase; } + set renderPhase (val) { this._renderPhase = val; } private _sceneVisitor: WebSceneVisitor; + private _blitDesc: BlitDesc | null = null; constructor (devicePass: DeviceRenderPass) { this._devicePass = devicePass; this._sceneVisitor = new WebSceneVisitor(this._devicePass.context.commandBuffer, this._devicePass.context.pipeline.pipelineSceneData); } - addSceneTask (scene: SceneData) { + createBlitDesc (blit: Blit) { + if (this._blitDesc) { + return; + } + this._blitDesc = new BlitDesc(blit, this); + this._blitDesc.createSreenQuad(); + this._blitDesc.createStageDescriptor(); + } + addSceneTask (scene: GraphScene): void { if (!this._transversal) { - this._transversal = new DeviceSceneTransversal(this, this.devicePass.context.pipelineSceneData, scene.camera!); + this._transversal = new DeviceSceneTransversal(this, this.devicePass.context.pipelineSceneData, scene); } this._preSceneTasks.push(this._transversal.preRenderPass(this._sceneVisitor)); this._sceneTasks.push(this._transversal.transverse(this._sceneVisitor)); @@ -152,6 +416,7 @@ class DeviceRenderQueue { clearTasks () { this._sceneTasks.length = 0; } + get blitDesc () { return this._blitDesc; } get sceneTasks () { return this._sceneTasks; } set queueHint (value: QueueHint) { this._hint = value; } get queueHint () { return this._hint; } @@ -186,6 +451,68 @@ class SubmitInfo { public batches = new Set(); public opaqueList: RenderInfo[] = []; public transparentList: RenderInfo[] = []; + public shadowMap: RenderShadowMapBatchedQueue | null = null; + public additiveLight: RenderAdditiveLightQueue | null = null; +} + +class RenderPassLayoutInfo { + protected _layoutID = 0; + protected _stage: RenderStageData | null = null; + protected _layout: PipelineLayoutData; + protected _context: ExecutorContext; + protected _inputName: string; + protected _descriptorSet: DescriptorSet | null = null; + constructor (layoutId, input: [string, ComputeView[]], context: ExecutorContext) { + this._inputName = input[0]; + this._layoutID = layoutId; + const lg = context.layoutGraph; + this._stage = lg.getRenderStage(layoutId); + this._context = context; + this._layout = lg.getLayout(layoutId); + const layoutData = this._layout.descriptorSets.get(UpdateFrequency.PER_PASS); + if (layoutData) { + // find resource + const deviceTex = context.deviceTextures.get(this._inputName); + const gfxTex = deviceTex?.texture; + if (!gfxTex) { + throw Error(`Could not find texture with resource name ${this._inputName}`); + } + // bind descriptors + for (const descriptor of input[1]) { + const descriptorName = descriptor.name; + const descriptorID = lg.attributeIndex.get(descriptorName); + // find descriptor binding + for (const block of layoutData.descriptorSetLayoutData.descriptorBlocks) { + for (let i = 0; i !== block.descriptors.length; ++i) { + if (descriptorID === block.descriptors[i].descriptorID) { + layoutData.descriptorSet!.bindTexture(block.offset + i, gfxTex); + layoutData.descriptorSet!.bindSampler(block.offset + i, context.device.getSampler(new SamplerInfo())); + if (!this._descriptorSet) this._descriptorSet = layoutData.descriptorSet; + } + } + } + } + } + } + get descriptorSet () { return this._descriptorSet; } + get layoutID () { return this._layoutID; } + get stage () { return this._stage; } + get layout () { return this._layout; } +} + +class RasterPassInfo { + protected _id: number; + protected _pass: RasterPass; + constructor (id, pass) { + this._id = id; + this._pass = pass; + } + get id () { return this._id; } + get pass () { return this._pass; } + applyInfo (id: number, pass: RasterPass) { + this._id = id; + this._pass = pass; + } } class DeviceRenderPass { @@ -196,35 +523,42 @@ class DeviceRenderPass { protected _clearDepth = 1; protected _clearStencil = 0; protected _context: ExecutorContext; - private _rasterPass: RasterPass; + protected _viewport: Viewport | null = null; + private _rasterInfo: RasterPassInfo; + private _layout: RenderPassLayoutInfo | null = null; public submitMap: Map = new Map(); - constructor (context: ExecutorContext, rasterPass: RasterPass) { + constructor (context: ExecutorContext, passInfo: RasterPassInfo) { this._context = context; - this._rasterPass = rasterPass; + this._rasterInfo = passInfo; const device = context.device; const depthStencilAttachment = new DepthStencilAttachment(); depthStencilAttachment.format = Format.DEPTH_STENCIL; + depthStencilAttachment.depthLoadOp = LoadOp.DISCARD; + depthStencilAttachment.stencilLoadOp = LoadOp.DISCARD; depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD; depthStencilAttachment.depthStoreOp = StoreOp.DISCARD; - depthStencilAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo( - AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE, - AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE, - )); + const colors: ColorAttachment[] = []; const colorTexs: Texture[] = []; let depthTex: Texture | null = null; let swapchain: Swapchain | null = null; let framebuffer: Framebuffer | null = null; - for (const [resName, rasterV] of rasterPass.rasterViews) { + for (const cv of passInfo.pass.computeViews) { + this._applyRenderLayout(cv); + } + // update the layout descriptorSet + if (this.renderLayout && this.renderLayout.descriptorSet) { + this.renderLayout.descriptorSet.update(); + } + for (const [resName, rasterV] of passInfo.pass.rasterViews) { let resTex = context.deviceTextures.get(resName); - if (rasterV.accessType === AccessType.READ || resTex) { - continue; + if (!resTex) { + const resourceGraph = context.resourceGraph; + const vertId = resourceGraph.vertex(resName); + const resourceVisitor = new ResourceVisitor(resName, context); + resourceGraph.visitVertex(resourceVisitor, vertId); + resTex = context.deviceTextures.get(resName)!; } - const resourceGraph = context.resourceGraph; - const vertId = resourceGraph.vertex(resName); - const resourceVisitor = new ResourceVisitor(resName, context); - resourceGraph.visitVertex(resourceVisitor, vertId); - resTex = context.deviceTextures.get(resName)!; if (!swapchain) swapchain = resTex.swapchain; if (!framebuffer) framebuffer = resTex.framebuffer; const clearFlag = rasterV.clearFlags & 0xffffffff; @@ -235,31 +569,26 @@ class DeviceRenderPass { const colorAttachment = new ColorAttachment(); colorAttachment.format = resTex.description!.format; colorAttachment.sampleCount = resTex.description!.sampleCount; - if (!(clearFlag & ClearFlagBit.COLOR)) { - rasterV.clearColor.x = 0; - rasterV.clearColor.y = 0; - rasterV.clearColor.z = 0; - rasterV.clearColor.w = 1; - if (clearFlag & SKYBOX_FLAG) { - colorAttachment.loadOp = LoadOp.DISCARD; - } else { - colorAttachment.loadOp = LoadOp.LOAD; - colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo( - AccessFlagBit.COLOR_ATTACHMENT_WRITE, - AccessFlagBit.COLOR_ATTACHMENT_WRITE, - )); - } - } + colorAttachment.loadOp = rasterV.loadOp; + colorAttachment.storeOp = rasterV.storeOp; + colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo( + rasterV.loadOp === LoadOp.LOAD ? AccessFlagBit.COLOR_ATTACHMENT_WRITE : AccessFlagBit.NONE, + rasterV.storeOp === StoreOp.STORE ? AccessFlagBit.COLOR_ATTACHMENT_WRITE : AccessFlagBit.NONE, + )); this._clearColor.push(rasterV.clearColor); colors.push(colorAttachment); } break; case AttachmentType.DEPTH_STENCIL: + depthStencilAttachment.depthStoreOp = rasterV.storeOp; + depthStencilAttachment.stencilStoreOp = rasterV.storeOp; + depthStencilAttachment.depthLoadOp = rasterV.loadOp; + depthStencilAttachment.stencilLoadOp = rasterV.loadOp; + depthStencilAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo( + rasterV.loadOp === LoadOp.LOAD ? AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE : AccessFlagBit.NONE, + rasterV.storeOp === StoreOp.STORE ? AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE : AccessFlagBit.NONE, + )); if (!resTex.swapchain && !resTex.framebuffer) depthTex = resTex.texture!; - if ((clearFlag & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL) { - if (!(clearFlag & ClearFlagBit.DEPTH)) depthStencilAttachment.depthLoadOp = LoadOp.LOAD; - if (!(clearFlag & ClearFlagBit.STENCIL)) depthStencilAttachment.stencilLoadOp = LoadOp.LOAD; - } this._clearDepth = rasterV.clearColor.x; this._clearStencil = rasterV.clearColor.y; break; @@ -274,20 +603,21 @@ class DeviceRenderPass { const currTex = device.createTexture(new TextureInfo()); colorTexs.push(currTex); } - if (!depthTex && !swapchain && !framebuffer) { - depthTex = device.createTexture(new TextureInfo( - TextureType.TEX2D, - TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, - Format.DEPTH_STENCIL, - colorTexs[0].width, - colorTexs[0].height, - )); - } + // if (!depthTex && !swapchain && !framebuffer) { + // depthTex = device.createTexture(new TextureInfo( + // TextureType.TEX2D, + // TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, + // Format.DEPTH_STENCIL, + // colorTexs[0].width, + // colorTexs[0].height, + // )); + // } this._renderPass = device.createRenderPass(new RenderPassInfo(colors, depthStencilAttachment)); this._framebuffer = framebuffer || device.createFramebuffer(new FramebufferInfo(this._renderPass, swapchain ? [swapchain.colorTexture] : colorTexs, swapchain ? swapchain.depthStencilTexture : depthTex)); } + get renderLayout () { return this._layout; } get context () { return this._context; } get renderPass () { return this._renderPass; } get framebuffer () { return this._framebuffer; } @@ -295,18 +625,90 @@ class DeviceRenderPass { get clearDepth () { return this._clearDepth; } get clearStencil () { return this._clearStencil; } get deviceQueues () { return this._deviceQueues; } - get rasterPass () { return this._rasterPass; } + get rasterPassInfo () { return this._rasterInfo; } + get viewport () { return this._viewport; } addQueue (queue: DeviceRenderQueue) { this._deviceQueues.push(queue); } prePass () { for (const queue of this._deviceQueues) { queue.preRecord(); } } + protected _applyRenderLayout (input: [string, ComputeView[]]) { + const stageName = this._context.renderGraph.getLayout(this.rasterPassInfo.id); + if (stageName) { + const layoutGraph = this._context.layoutGraph; + const stageId = layoutGraph.locateChild(layoutGraph.nullVertex(), stageName); + if (stageId !== 0xFFFFFFFF) { + this._layout = new RenderPassLayoutInfo(stageId, input, this._context); + } + } + } + genQuadVertexData (surfaceTransform: SurfaceTransform, renderArea: Rect) : Float32Array { + const vbData = new Float32Array(4 * 4); + + const minX = renderArea.x / this._context.width; + const maxX = (renderArea.x + renderArea.width) / this._context.width; + let minY = renderArea.y / this._context.height; + let maxY = (renderArea.y + renderArea.height) / this._context.height; + if (this._context.root.device.capabilities.screenSpaceSignY > 0) { + const temp = maxY; + maxY = minY; + minY = temp; + } + let n = 0; + switch (surfaceTransform) { + case (SurfaceTransform.IDENTITY): + n = 0; + vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = maxY; + vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = maxY; + vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = minY; + vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = minY; + break; + case (SurfaceTransform.ROTATE_90): + n = 0; + vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = maxY; + vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = minY; + vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = maxY; + vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = minY; + break; + case (SurfaceTransform.ROTATE_180): + n = 0; + vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = minY; + vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = minY; + vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = maxY; + vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = maxY; + break; + case (SurfaceTransform.ROTATE_270): + n = 0; + vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = minY; + vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = maxY; + vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = minY; + vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = maxY; + break; + default: + break; + } + + return vbData; + } + + protected _applyViewport (frameTex: Texture) { + this._viewport = null; + const viewport = this._rasterInfo.pass.viewport; + if (viewport.left !== 0 || viewport.top !== 0 + || viewport.width !== frameTex.width + || viewport.height !== frameTex.height) { + this._viewport = viewport; + } + } // record common buffer record () { - const cmdBuff = this._context.commandBuffer; const tex = this.framebuffer.colorTextures[0]!; - cmdBuff.beginRenderPass(this.renderPass, this.framebuffer, new Rect(0, 0, tex.width, tex.height), + this._applyViewport(tex); + const cmdBuff = this._context.commandBuffer; + const renderArea = this._viewport ? new Rect(this._viewport.left, this._viewport.top, this._viewport.width, this._viewport.height) + : new Rect(0, 0, tex.width, tex.height); + cmdBuff.beginRenderPass(this.renderPass, this.framebuffer, renderArea, this.clearColor, this.clearDepth, this.clearStencil); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, this._context.pipeline.globalDSManager.globalDescriptorSet); @@ -321,46 +723,79 @@ class DeviceRenderPass { queue.postRecord(); } } + resetQueues (id: number, pass: RasterPass) { + this._rasterInfo.applyInfo(id, pass); + this._deviceQueues.length = 0; + } } class DeviceSceneTransversal extends WebSceneTransversal { protected _currentQueue: DeviceRenderQueue; - constructor (quque: DeviceRenderQueue, sceneData: PipelineSceneData, camera: Camera) { - super(camera, sceneData); + protected _graphScene: GraphScene; + constructor (quque: DeviceRenderQueue, sceneData: PipelineSceneData, graphSceneData: GraphScene) { + const camera = graphSceneData.scene ? graphSceneData.scene.camera : null; + super(camera, sceneData, quque.devicePass.context.ubo); this._currentQueue = quque; + this._graphScene = graphSceneData; } + get graphScene () { return this._graphScene; } public preRenderPass (visitor: WebSceneVisitor): DevicePreSceneTask { - return new DevicePreSceneTask(this._currentQueue, this._camera, visitor); + return new DevicePreSceneTask(this._currentQueue, this._graphScene, visitor); } public transverse (visitor: WebSceneVisitor): DeviceSceneTask { - return new DeviceSceneTask(this._currentQueue, this._camera, visitor); + return new DeviceSceneTask(this._currentQueue, this._graphScene, visitor); } public postRenderPass (visitor: WebSceneVisitor): DevicePostSceneTask { - return new DevicePostSceneTask(this._sceneData, this._camera, visitor); + return new DevicePostSceneTask(this._sceneData, this._currentQueue.devicePass.context.ubo, this._camera, visitor); } } - +class GraphScene { + scene: SceneData | null = null; + blit: Blit | null = null; + dispatch: Dispatch | null = null; +} class DevicePreSceneTask extends WebSceneTask { protected _currentQueue: DeviceRenderQueue; protected _renderPass: RenderPass; protected _submitInfo: SubmitInfo | null = null; + protected _graphScene: GraphScene; private _cmdBuff: CommandBuffer; - constructor (queue: DeviceRenderQueue, camera: Camera, visitor: SceneVisitor) { - super(queue.devicePass.context.pipelineSceneData, camera, visitor); + constructor (queue: DeviceRenderQueue, graphScene: GraphScene, visitor: SceneVisitor) { + super(queue.devicePass.context.pipelineSceneData, queue.devicePass.context.ubo, + graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, visitor); this._currentQueue = queue; + this._graphScene = graphScene; this._renderPass = this._currentQueue.devicePass.renderPass; - this._cmdBuff = this._currentQueue.devicePass.context.commandBuffer; + this._cmdBuff = queue.devicePass.context.commandBuffer; } + get graphScene () { return this._graphScene; } public start () { + if (this.graphScene.blit) { + this._currentQueue.createBlitDesc(this.graphScene.blit); + return; + } + if (!this.camera) { + return; + } const submitMap = this._currentQueue.devicePass.submitMap; if (submitMap.has(this.camera)) { this._submitInfo = submitMap.get(this.camera)!; } else { // culling - super.start(); + if (!this._isShadowMap() || (this._isShadowMap() && this.graphScene.scene!.light.level === 0)) super.start(); this._submitInfo = new SubmitInfo(); + submitMap.set(this.camera, this._submitInfo); } + // shadowmap + if (this._isShadowMap() && !this._submitInfo.shadowMap) { + assert(this.graphScene.scene!.light.light); + this._submitInfo.shadowMap = new RenderShadowMapBatchedQueue(this._currentQueue.devicePass.context.pipeline); + this._submitInfo.shadowMap.gatherLightPasses(this.camera, this.graphScene.scene!.light.light, this._cmdBuff, this.graphScene.scene!.light.level); + this.sceneData.shadowFrameBufferMap.set(this.graphScene.scene!.light.light, this._currentQueue.devicePass.framebuffer); + return; + } + const sceneFlag = this._graphScene.scene!.flags; for (const ro of this.sceneData.renderObjects) { const subModels = ro.model.subModels; for (const submodel of subModels) { @@ -379,29 +814,25 @@ class DevicePreSceneTask extends WebSceneTask { const batchedBuffer = p.getBatchedBuffer(); batchedBuffer.merge(submodel, passes.indexOf(p), ro.model); this._submitInfo.batches.add(batchedBuffer); - } else { - switch (this._currentQueue.queueHint) { - case QueueHint.NONE: - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); - break; - case QueueHint.RENDER_CUTOUT: - case QueueHint.RENDER_OPAQUE: - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); - break; - case QueueHint.RENDER_TRANSPARENT: - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); - break; - default: - } + } else if ((sceneFlag & SceneFlags.TRANSPARENT_OBJECT) + && (sceneFlag & SceneFlags.OPAQUE_OBJECT || sceneFlag & SceneFlags.OPAQUE_OBJECT)) { + this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); + this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); + } else if ((sceneFlag & SceneFlags.CUTOUT_OBJECT) || (sceneFlag & SceneFlags.OPAQUE_OBJECT)) { + this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); + } else if (sceneFlag & SceneFlags.TRANSPARENT_OBJECT) { + this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); } } } } - + if (sceneFlag & SceneFlags.DEFAULT_LIGHTING) { + const pipeline = this._currentQueue.devicePass.context.pipeline; + this._submitInfo.additiveLight = new RenderAdditiveLightQueue(pipeline); + this._submitInfo.additiveLight.gatherLightPasses(this.camera, this._cmdBuff); + } this._submitInfo.opaqueList.sort(this._opaqueCompareFn); this._submitInfo.transparentList.sort(this._transparentCompareFn); - if (!submitMap.has(this.camera)) submitMap.set(this.camera, this._submitInfo); } protected _insertRenderList (ro: RenderObject, subModelIdx: number, passIdx: number, isTransparent = false) { const subModel = ro.model.subModels[subModelIdx]; @@ -463,11 +894,34 @@ class DevicePreSceneTask extends WebSceneTask { } } - public submit () { + private _isShadowMap () { + return this.sceneData.shadows.enabled + && this.sceneData.shadows.type === ShadowType.ShadowMap + && this.graphScene.scene!.flags & SceneFlags.SHADOW_CASTER; + } + + protected _updateUbo (camera: Camera) { const ubo = this._currentQueue.devicePass.context.ubo; - ubo.updateGlobalUBO(this.camera.window); - ubo.updateCameraUBO(this.camera); - ubo.updateShadowUBO(this.camera); + ubo.updateGlobalUBO(camera.window); + ubo.updateCameraUBO(camera); + ubo.updateShadowUBO(camera); + } + + public submit () { + const context = this._currentQueue.devicePass.context; + const ubo = context.ubo; + if (this.graphScene.blit) { + const blitCam = this.graphScene.blit.camera; + if (blitCam) this._updateUbo(blitCam); + this._currentQueue.blitDesc!.update(); + return; + } + if (this._isShadowMap()) { + ubo.updateShadowUBOLight(context.pipeline.descriptorSet, + this.graphScene.scene!.light.light!, this.graphScene.scene!.light.level); + return; + } + this._updateUbo(this.camera!); this._uploadInstanceBuffers(); this._uploadBatchedBuffers(); @@ -477,15 +931,19 @@ class DevicePreSceneTask extends WebSceneTask { class DeviceSceneTask extends WebSceneTask { protected _currentQueue: DeviceRenderQueue; protected _renderPass: RenderPass; - constructor (queue: DeviceRenderQueue, camera: Camera, visitor: SceneVisitor) { - super(queue.devicePass.context.pipelineSceneData, camera, visitor); + protected _graphScene: GraphScene; + constructor (queue: DeviceRenderQueue, graphScene: GraphScene, visitor: SceneVisitor) { + super(queue.devicePass.context.pipelineSceneData, queue.devicePass.context.ubo, + graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, visitor); this._currentQueue = queue; this._renderPass = this._currentQueue.devicePass.renderPass; + this._graphScene = graphScene; } + get graphScene () { return this._graphScene; } public start () {} protected _recordRenderList (isTransparent: boolean) { const submitMap = this._currentQueue.devicePass.submitMap; - const renderList = isTransparent ? submitMap.get(this.camera)!.transparentList : submitMap.get(this.camera)!.opaqueList; + const renderList = isTransparent ? submitMap.get(this.camera!)!.transparentList : submitMap.get(this.camera!)!.opaqueList; for (let i = 0; i < renderList.length; ++i) { const { subModel, passIdx } = renderList[i]; const { inputAssembler } = subModel; @@ -505,7 +963,7 @@ class DeviceSceneTask extends WebSceneTask { } protected _recordInstences () { const submitMap = this._currentQueue.devicePass.submitMap; - const it = submitMap.get(this.camera)!.instances.values(); let res = it.next(); + const it = submitMap.get(this.camera!)!.instances.values(); let res = it.next(); while (!res.done) { const { instances, pass, hasPendingModels } = res.value; if (hasPendingModels) { @@ -532,7 +990,7 @@ class DeviceSceneTask extends WebSceneTask { } protected _recordBatches () { const submitMap = this._currentQueue.devicePass.submitMap; - const it = submitMap.get(this.camera)!.batches.values(); let res = it.next(); + const it = submitMap.get(this.camera!)!.batches.values(); let res = it.next(); while (!res.done) { let boundPSO = false; for (let b = 0; b < res.value.batches.length; ++b) { @@ -555,11 +1013,11 @@ class DeviceSceneTask extends WebSceneTask { } } protected _recordUI () { - const batches = this.camera.scene!.batches; + const batches = this.camera!.scene!.batches; for (let i = 0; i < batches.length; i++) { const batch = batches[i]; let visible = false; - if (this.camera.visibility & batch.visFlags) { + if (this.camera!.visibility & batch.visFlags) { visible = true; } @@ -584,26 +1042,112 @@ class DeviceSceneTask extends WebSceneTask { protected _recordTransparentList () { this._recordRenderList(true); } + protected _recordShadowMap () { + const context = this._currentQueue.devicePass.context; + const submitMap = this._currentQueue.devicePass.submitMap; + submitMap.get(this.camera!)?.shadowMap?.recordCommandBuffer(context.device, + this._renderPass, context.commandBuffer); + } protected _generateRenderArea (): Rect { const out = new Rect(); - const vp = this.camera.viewport; - const w = this.camera.window.width; - const h = this.camera.window.height; + const vp = this.camera ? this.camera.viewport : new Rect(0, 0, 1, 1); + const texture = this._currentQueue.devicePass.framebuffer.colorTextures[0]!; + const w = texture.width; + const h = texture.height; out.x = vp.x * w; out.y = vp.y * h; out.width = vp.width * w; out.height = vp.height * h; + if (this._isShadowMap() && this.graphScene.scene!.light.light) { + const light = this.graphScene.scene!.light.light; + const level = this.graphScene.scene!.light.level; + switch (light.type) { + case LightType.DIRECTIONAL: { + const mainLight = light as DirectionalLight; + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + out.x = 0; + out.y = 0; + out.width = w; + out.height = h; + } else { + out.x = level % 2 * 0.5 * w; + out.y = (1 - Math.floor(level / 2)) * 0.5 * h; + out.width = 0.5 * w; + out.height = 0.5 * h; + } + break; + } + case LightType.SPOT: { + out.x = 0; + out.y = 0; + out.width = w; + out.height = h; + break; + } + default: + } + } return out; } + private _isShadowMap () { + return this.sceneData.shadows.enabled + && this.sceneData.shadows.type === ShadowType.ShadowMap + && this.graphScene.scene + && this.graphScene.scene.flags & SceneFlags.SHADOW_CASTER; + } + private _recordBlit () { + if (!this.graphScene.blit) { return; } + const currMat = this.graphScene.blit.material; + const pass = currMat!.passes[0]; + const shader = pass.getShaderVariant(); + const devicePass = this._currentQueue.devicePass; + const screenIa: any = this._currentQueue.blitDesc!.screenQuad!.quadIA; + let pso; + if (pass !== null && shader !== null && screenIa !== null) { + pso = PipelineStateManager.getOrCreatePipelineState(devicePass.context.device, pass, shader, + devicePass.renderPass, screenIa); + } + if (pso) { + this.visitor.bindPipelineState(pso); + const layoutStage = devicePass.renderLayout; + // TODO: It will be changed to global later + this.visitor.bindDescriptorSet(SetIndex.MATERIAL, layoutStage!.descriptorSet!); + this.visitor.bindDescriptorSet(SetIndex.LOCAL, this._currentQueue.blitDesc!.stageDesc!); + this.visitor.bindInputAssembler(screenIa); + this.visitor.draw(screenIa); + } + } + private _recordAdditiveLights () { + const devicePass = this._currentQueue.devicePass; + const submitMap = devicePass.submitMap; + const context = devicePass.context; + submitMap.get(this.camera!)?.additiveLight?.recordCommandBuffer(context.device, + this._renderPass, + devicePass.context.commandBuffer); + } public submit () { const area = this._generateRenderArea(); - this.visitor.setViewport(new Viewport(area.x, area.y, area.width, area.height)); - this.visitor.setScissor(area); + if (!this._currentQueue.devicePass.viewport) { + this.visitor.setViewport(new Viewport(area.x, area.y, area.width, area.height)); + this.visitor.setScissor(area); + } + // Currently processing blit and camera first + if (this.graphScene.blit) { + this._recordBlit(); + return; + } + if (this._isShadowMap()) { + this._recordShadowMap(); + return; + } this._recordOpaqueList(); this._recordInstences(); this._recordBatches(); + this._recordAdditiveLights(); this._recordTransparentList(); - this._recordUI(); + if (this.graphScene.scene!.flags & SceneFlags.UI) { + this._recordUI(); + } } } @@ -614,7 +1158,10 @@ class ExecutorContext { ubo: PipelineUBO, device: Device, resourceGraph: ResourceGraph, - renderGraph: RenderGraph) { + renderGraph: RenderGraph, + layoutGraph: LayoutGraphData, + width: number, + height: number) { this.pipeline = pipeline; this.device = device; this.commandBuffer = device.commandBuffer; @@ -623,19 +1170,24 @@ class ExecutorContext { this.renderGraph = renderGraph; this.root = legacyCC.director.root; this.ubo = ubo; + this.layoutGraph = layoutGraph; + this.width = width; + this.height = height; } readonly device: Device; readonly pipeline: Pipeline; readonly commandBuffer: CommandBuffer; readonly pipelineSceneData: PipelineSceneData; readonly resourceGraph: ResourceGraph; - readonly devicePasses: Map = new Map(); + readonly devicePasses: Map = new Map(); readonly deviceTextures: Map = new Map(); - readonly renderGraph: RenderGraph; + readonly layoutGraph: LayoutGraphData; readonly root: Root; readonly ubo: PipelineUBO; + readonly width: number; + readonly height: number; + renderGraph: RenderGraph; } - class ResourceVisitor implements ResourceGraphVisitor { private _context: ExecutorContext; name: string; @@ -662,6 +1214,7 @@ class ResourceVisitor implements ResourceGraphVisitor { this.createDeviceTex(value); } } + class PassVisitor implements RenderGraphVisitor { public passID = 0xFFFFFFFF; private _queueID = 0xFFFFFFFF; @@ -672,21 +1225,31 @@ class PassVisitor implements RenderGraphVisitor { constructor (context: ExecutorContext) { this._context = context; } + clear (value: ClearView[]): unknown { + throw new Error('Method not implemented.'); + } + viewport (value: Viewport): unknown { + throw new Error('Method not implemented.'); + } raster (pass: RasterPass) { if (!pass.isValid) { return; } const rg = this._context.renderGraph; const devicePasses = this._context.devicePasses; - this._currPass = devicePasses.get(this.passID); + const layout = this._context.layoutGraph; + const passHash = stringify(pass); + this._currPass = devicePasses.get(passHash); if (!this._currPass) { - this._currPass = new DeviceRenderPass(this._context, pass); - devicePasses.set(this.passID, this._currPass); - for (const q of rg.children(this.passID)) { - const queueID = q.target as number; - this._queueID = queueID; - rg.visitVertex(this, queueID); - } + this._currPass = new DeviceRenderPass(this._context, new RasterPassInfo(this.passID, pass)); + devicePasses.set(passHash, this._currPass); + } else { + this._currPass.resetQueues(this.passID, pass); + } + for (const q of rg.children(this.passID)) { + const queueID = q.target as number; + this._queueID = queueID; + rg.visitVertex(this, queueID); } this._currPass.prePass(); this._currPass.record(); @@ -713,6 +1276,14 @@ class PassVisitor implements RenderGraphVisitor { this._currQueue = deviceQueue; this._currPass!.addQueue(deviceQueue); const rg = this._context.renderGraph; + const layoutName = this._context.renderGraph.getLayout(this._queueID); + if (layoutName) { + const layoutGraph = this._context.layoutGraph; + if (this._currPass!.renderLayout) { + const layoutId = layoutGraph.locateChild(this._currPass!.renderLayout.layoutID, layoutName); + deviceQueue.renderPhase = layoutGraph.tryGetRenderPhase(layoutId); + } + } for (const s of rg.children(this._queueID)) { const sceneID = s.target as number; this._sceneID = sceneID; @@ -720,9 +1291,14 @@ class PassVisitor implements RenderGraphVisitor { } } scene (value: SceneData) { - this._currQueue!.addSceneTask(value); + const graphScene = new GraphScene(); + graphScene.scene = value; + this._currQueue!.addSceneTask(graphScene); } blit (value: Blit) { + const graphScene = new GraphScene(); + graphScene.blit = value; + this._currQueue!.addSceneTask(graphScene); } dispatch (value: Dispatch) { } @@ -732,25 +1308,26 @@ export class Executor { constructor (pipeline: Pipeline, ubo: PipelineUBO, device: Device, - resourceGraph: ResourceGraph) { - this._pipeline = pipeline; - this._device = device; - this._ubo = ubo; - this._commandBuffer = device.commandBuffer; - this._resourceGraph = resourceGraph; + resourceGraph: ResourceGraph, + layoutGraph: LayoutGraphData, + width: number, height: number) { + this._context = new ExecutorContext( + pipeline, + ubo, + device, + resourceGraph, + new RenderGraph(), + layoutGraph, + width, + height, + ); } execute (rg: RenderGraph) { - const context = new ExecutorContext( - this._pipeline, - this._ubo, - this._device, - this._resourceGraph, - rg, - ); - const cmdBuff = context.commandBuffer; + this._context.renderGraph = rg; + const cmdBuff = this._context.commandBuffer; cmdBuff.begin(); - const passVisitor = new PassVisitor(context); + const passVisitor = new PassVisitor(this._context); for (const vertID of rg.vertices()) { if (rg.numParents(vertID) === 0) { // vertex has no parents, must be pass @@ -759,11 +1336,15 @@ export class Executor { } } cmdBuff.end(); - context.device.queue.submit([cmdBuff]); + this._context.device.queue.submit([cmdBuff]); } - private readonly _pipeline: Pipeline; - private readonly _device: Device; - private readonly _commandBuffer: CommandBuffer; - private readonly _resourceGraph: ResourceGraph; - private readonly _ubo: PipelineUBO; + + release () { + this._context.devicePasses.clear(); + for (const [k, v] of this._context.deviceTextures) { + v.release(); + } + this._context.deviceTextures.clear(); + } + private readonly _context: ExecutorContext; } diff --git a/cocos/core/pipeline/custom/graph.ts b/cocos/core/pipeline/custom/graph.ts index 89c9e7f28b..650d89d4e3 100644 --- a/cocos/core/pipeline/custom/graph.ts +++ b/cocos/core/pipeline/custom/graph.ts @@ -343,6 +343,10 @@ export interface PropertyMap { get (x: vertex_descriptor | edge_descriptor): unknown; } +export interface MutableVertexPropertyMap extends PropertyMap { + put (x: vertex_descriptor, value: T): void; +} + //-------------------------------------------------------------------------- // PropertyGraph //-------------------------------------------------------------------------- @@ -519,3 +523,259 @@ export function findRelative (g: ParentGraph, v: vertex_descriptor | null, path: } return curr; } + +//======================================================================= +// DFS +// Based on boost/graph/depth_first_search.hpp +//======================================================================= + +//======================================================================= +// Copyright 1997, 1998, 1999, 2000 University of Notre Dame. +// Copyright 2003 Bruce Barr +// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +//======================================================================= + +export interface TerminatorFunc { + terminate (v: vertex_descriptor, g: IncidenceGraph): boolean; +} + +class NoTermination implements TerminatorFunc { + terminate (v: vertex_descriptor, g: IncidenceGraph): boolean { + return false; + } +} + +function getDefaultStartingVertex (g: IncidenceGraph & VertexListGraph): vertex_descriptor | null { + const iter = g.vertices(); + const v = iter.next(); + if (v.done) { + return g.nullVertex(); + } else { + return v.value; + } +} + +export interface GraphVisitor { + // 0. before dfs + initializeVertex (v: vertex_descriptor, g: IncidenceGraph): void; + // 1. dfs starting vertex (usually the root) + startVertex (v: vertex_descriptor, g: IncidenceGraph): void; + // 2. vertex discovered + discoverVertex (v: vertex_descriptor, g: IncidenceGraph): void; + // 3. edge discovered + examineEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 4(a). is tree edge + treeEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 4(b). is back edge + backEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 4(c). is forward or cross edge + forwardOrCrossEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 5. edge finished + finishEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 6. vertex finished + finishVertex (v: vertex_descriptor, g: IncidenceGraph): void; +} + +export enum GraphColor { + WHITE, + GRAY, + GREEN, + RED, + BLACK, +} + +class VertexInfo { + constructor ( + v: vertex_descriptor, + e: edge_descriptor | null, + iter: out_edge_iterator | null, + ) { + this.v = v; + this.e = e; + this.iter = iter; + } + v: vertex_descriptor; + e: edge_descriptor | null; + iter: out_edge_iterator | null; +} + +function depthFirstVisitImpl ( + g: IncidenceGraph, + u: vertex_descriptor, + visitor: GraphVisitor, + color: MutableVertexPropertyMap, + func: TerminatorFunc, +): void { + let srcE: edge_descriptor | null = null; + let ei: out_edge_iterator | null = null; + const stack = new Array(); + + color.put(u, GraphColor.GRAY); + visitor.discoverVertex(u, g); + + ei = g.outEdges(u); + if (func.terminate(u, g)) { + // If this vertex terminates the search, we push empty range + stack.push(new VertexInfo(u, null, null)); + } else { + stack.push(new VertexInfo(u, null, ei)); + } + + while (stack.length) { + const back = stack.pop()!; + u = back.v; + srcE = back.e; + ei = back.iter; + // finish_edge has to be called here, not after the + // loop. Think of the pop as the return from a recursive call. + if (srcE !== null) { + visitor.finishEdge(srcE, g); + } + if (ei) { // has out edges + for (let ev = ei.next(); !ev.done; ev = ei.next()) { + const e = ev.value; + const v = e.target; + visitor.examineEdge(e, g); + const vColor = color.get(v); + if (vColor === GraphColor.WHITE) { + visitor.treeEdge(e, g); + srcE = e; + stack.push(new VertexInfo(u, srcE, ei)); + u = v; + color.put(u, GraphColor.GRAY); + visitor.discoverVertex(u, g); + ei = g.outEdges(u); + if (func.terminate(u, g)) { + break; + } + } else { + if (vColor === GraphColor.GRAY) { + visitor.backEdge(e, g); + } else { + visitor.forwardOrCrossEdge(e, g); + } + visitor.finishEdge(e, g); + } + } + } + color.put(u, GraphColor.BLACK); + visitor.finishVertex(u, g); + } +} + +export function depthFirstSearch ( + g: IncidenceGraph & VertexListGraph, + visitor: GraphVisitor, + color: MutableVertexPropertyMap, + startVertex: vertex_descriptor | null = null, +): void { + // get start vertex + startVertex = startVertex || getDefaultStartingVertex(g); + // graph is empty, do nothing + if (startVertex === null || g.numVertices() === 0) { + return; + } + // initialize vertex and color map + for (const u of g.vertices()) { + color.put(u, GraphColor.WHITE); + visitor.initializeVertex(u, g); + } + // start DFS + const terminator = new NoTermination(); + // try starting from startVertex + if (startVertex !== getDefaultStartingVertex(g)) { + visitor.startVertex(startVertex, g); + depthFirstVisitImpl(g, startVertex, visitor, color, terminator); + } + // try starting from each vertex + for (const u of g.vertices()) { + // if vertex is not visited, start DFS + if (color.get(u) === GraphColor.WHITE) { + visitor.startVertex(u, g); + depthFirstVisitImpl(g, u, visitor, color, terminator); + } + } +} + +export function depthFirstVisit ( + g: IncidenceGraph, + u: vertex_descriptor, + visitor: GraphVisitor, + color: MutableVertexPropertyMap, + func: TerminatorFunc = new NoTermination(), +): void { + visitor.startVertex(u, g); + depthFirstVisitImpl(g, u, visitor, color, func); +} + +export class DefaultVisitor implements GraphVisitor { + initializeVertex (v: vertex_descriptor, g: IncidenceGraph): void { + // do nothing + } + startVertex (v: vertex_descriptor, g: IncidenceGraph): void { + // do nothing + } + discoverVertex (v: vertex_descriptor, g: IncidenceGraph): void { + // do nothing + } + examineEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + treeEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + backEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + forwardOrCrossEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + finishEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + finishVertex (v: vertex_descriptor, g: IncidenceGraph): void { + // do nothing + } +} + +export class ReferenceGraphView +implements IncidenceGraph, VertexListGraph { + constructor (g: BaseGraph) { + this.g = g; + this.directed_category = directional.directed; + this.edge_parallel_category = parallel.allow; + this.traversal_category = traversal.incidence | traversal.vertex_list; + } + nullVertex () { + return this.g.nullVertex(); + } + edge (u: vertex_descriptor, v: vertex_descriptor): boolean { + return this.g.reference(u, v); + } + source (e: edge_descriptor): vertex_descriptor { + return this.g.parent(e); + } + target (e: edge_descriptor): vertex_descriptor { + return this.g.child(e); + } + outEdges (v: vertex_descriptor): out_edge_iterator { + return this.g.children(v); + } + outDegree (v: vertex_descriptor): number { + return this.g.numChildren(v); + } + vertices (): IterableIterator { + return this.g.vertices(); + } + numVertices (): number { + return this.g.numVertices(); + } + readonly directed_category: directional; + readonly edge_parallel_category: parallel; + readonly traversal_category: traversal; + g: BaseGraph; +} diff --git a/cocos/core/pipeline/custom/index.jsb.ts b/cocos/core/pipeline/custom/index.jsb.ts index 7d82f809fc..3d7115c0ea 100644 --- a/cocos/core/pipeline/custom/index.jsb.ts +++ b/cocos/core/pipeline/custom/index.jsb.ts @@ -25,17 +25,21 @@ declare const render: any; -import { Pipeline } from './pipeline'; -import { rebuildLayoutGraph } from './effect'; import { legacyCC } from '../../global-exports'; +import { Pipeline, PipelineBuilder } from './pipeline'; +import { buildDeferredLayout, buildForwardLayout } from './effect'; export function createCustomPipeline (): Pipeline { - return render.Factory.createPipeline(); + const root = legacyCC.director.root; + const ppl = render.Factory.createPipeline(); + if (root.useDeferredPipeline) { + buildDeferredLayout(ppl); + } else { + buildForwardLayout(ppl); + } + return ppl; } -export function registerRebuildLayoutGraph() { - const director = legacyCC.director; - if (director.root.usesCustomPipeline) { - director.on(legacyCC.Director.EVENT_BEFORE_DRAW, rebuildLayoutGraph); - } +export function setCustomPipelineBuilder (builder: PipelineBuilder) { + // not implemented yet } diff --git a/cocos/core/pipeline/custom/index.ts b/cocos/core/pipeline/custom/index.ts index 26d09084e4..0f77ca67f7 100644 --- a/cocos/core/pipeline/custom/index.ts +++ b/cocos/core/pipeline/custom/index.ts @@ -23,9 +23,27 @@ THE SOFTWARE. */ -import { Pipeline } from './pipeline'; +import { legacyCC } from '../../global-exports'; +import { Pipeline, PipelineBuilder } from './pipeline'; import { WebPipeline } from './web-pipeline'; +import { buildDeferredLayout, buildForwardLayout } from './effect'; + +let _pipeline: WebPipeline | null = null; export function createCustomPipeline (): Pipeline { - return new WebPipeline(); + const root = legacyCC.director.root; + const ppl = new WebPipeline(); + if (root.useDeferredPipeline) { + buildDeferredLayout(ppl); + } else { + buildForwardLayout(ppl); + } + _pipeline = ppl; + return ppl; +} + +export function setCustomPipelineBuilder (builder: PipelineBuilder) { + if (_pipeline) { + _pipeline.builder = builder; + } } diff --git a/cocos/core/pipeline/custom/layout-graph.ts b/cocos/core/pipeline/custom/layout-graph.ts index e354b2f0c8..2f708b4924 100644 --- a/cocos/core/pipeline/custom/layout-graph.ts +++ b/cocos/core/pipeline/custom/layout-graph.ts @@ -124,6 +124,14 @@ export const enum LayoutGraphValue { RenderPhase, } +export function getLayoutGraphValueName (e: LayoutGraphValue): string { + switch (e) { + case LayoutGraphValue.RenderStage: return 'RenderStage'; + case LayoutGraphValue.RenderPhase: return 'RenderPhase'; + default: return ''; + } +} + interface LayoutGraphValueType { [LayoutGraphValue.RenderStage]: number [LayoutGraphValue.RenderPhase]: RenderPhase @@ -662,7 +670,7 @@ export class DescriptorSetLayoutData { slot: number; capacity: number; readonly descriptorBlocks: DescriptorBlockData[] = []; - readonly uniformBlocks: Map = new Map(); + readonly uniformBlocks: Map = new Map(); } export class DescriptorSetData { @@ -703,6 +711,14 @@ export const enum LayoutGraphDataValue { RenderPhase, } +export function getLayoutGraphDataValueName (e: LayoutGraphDataValue): string { + switch (e) { + case LayoutGraphDataValue.RenderStage: return 'RenderStage'; + case LayoutGraphDataValue.RenderPhase: return 'RenderPhase'; + default: return ''; + } +} + interface LayoutGraphDataValueType { [LayoutGraphDataValue.RenderStage]: RenderStageData [LayoutGraphDataValue.RenderPhase]: RenderPhaseData @@ -1043,6 +1059,9 @@ export class LayoutGraphData implements impl.BidirectionalGraph getUpdate (v: number): UpdateFrequency { return this._updateFrequencies[v]; } + setUpdate (v: number, value: UpdateFrequency) { + this._updateFrequencies[v] = value; + } getLayout (v: number): PipelineLayoutData { return this._layouts[v]; } diff --git a/cocos/core/pipeline/custom/pipeline.ts b/cocos/core/pipeline/custom/pipeline.ts index 09e6c7bf19..09800827c6 100644 --- a/cocos/core/pipeline/custom/pipeline.ts +++ b/cocos/core/pipeline/custom/pipeline.ts @@ -29,26 +29,30 @@ * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ /* eslint-disable max-len */ +import { Material } from '../../assets'; import { Camera } from '../../renderer/scene/camera'; import { GeometryRenderer } from '../geometry-renderer'; -import { Buffer, Color, DescriptorSet, DescriptorSetLayout, DrawInfo, Format, InputAssembler, PipelineState, Rect, Sampler, Swapchain, Texture, Viewport } from '../../gfx'; +import { Buffer, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, DrawInfo, Format, InputAssembler, PipelineState, Rect, Sampler, Swapchain, Texture, UniformBlock, Viewport } from '../../gfx'; import { GlobalDSManager } from '../global-descriptor-set-manager'; import { DescriptorBlockFlattened, DescriptorBlockIndex } from './layout-graph'; import { Mat4, Quat, Vec2, Vec4 } from '../../math'; import { MacroRecord } from '../../renderer/core/pass-utils'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { QueueHint, ResourceResidency, SceneFlags, TaskType, UpdateFrequency } from './types'; -import { ComputeView, CopyPair, MovePair, RasterView } from './render-graph'; +import { ComputeView, LightInfo, QueueHint, RasterView, ResourceResidency, SceneFlags, TaskType, UpdateFrequency } from './types'; +import { CopyPair, MovePair } from './render-graph'; import { RenderScene } from '../../renderer/core/render-scene'; import { RenderWindow } from '../../renderer/core/render-window'; -import { Light, Model } from '../../renderer/scene'; +import { Model } from '../../renderer/scene'; export abstract class PipelineRuntime { public abstract activate(swapchain: Swapchain): boolean; public abstract destroy(): boolean; public abstract render(cameras: Camera[]): void; + public abstract get device(): Device; public abstract get globalDSManager(): GlobalDSManager; public abstract get descriptorSetLayout(): DescriptorSetLayout; + public abstract get descriptorSet(): DescriptorSet; + public abstract get commandBuffers(): CommandBuffer[]; public abstract get pipelineSceneData(): PipelineSceneData; public abstract get constantMacros(): string; public abstract get profiler(): Model | null; @@ -56,6 +60,9 @@ export abstract class PipelineRuntime { public abstract get geometryRenderer(): GeometryRenderer | null; public abstract get shadingScale(): number; public abstract set shadingScale(scale: number); + public abstract getMacroString(name: string): string; + public abstract getMacroInt(name: string): number; + public abstract getMacroBool(name: string): boolean; public abstract setMacroString(name: string, value: string): void; public abstract setMacroInt(name: string, value: number): void; public abstract setMacroBool(name: string, value: boolean): void; @@ -79,37 +86,39 @@ export abstract class Setter { } export abstract class RasterQueueBuilder extends Setter { - public abstract addSceneOfCamera(camera: Camera, light: Light | null, sceneFlags: SceneFlags, name: string): void; - public abstract addSceneOfCamera(camera: Camera, light: Light | null, sceneFlags: SceneFlags): void; + public abstract addSceneOfCamera(camera: Camera, light: LightInfo, sceneFlags: SceneFlags, name: string): void; + public abstract addSceneOfCamera(camera: Camera, light: LightInfo, sceneFlags: SceneFlags): void; public abstract addScene(name: string, sceneFlags: SceneFlags): void; - public abstract addFullscreenQuad(shader: string, name: string): void; - public abstract addFullscreenQuad(shader: string): void; + public abstract addFullscreenQuad(material: Material, sceneFlags: SceneFlags, name: string): void; + public abstract addFullscreenQuad(material: Material, sceneFlags: SceneFlags): void; + public abstract addCameraQuad(camera: Camera, material: Material, sceneFlags: SceneFlags, name: string): void; + public abstract addCameraQuad(camera: Camera, material: Material, sceneFlags: SceneFlags): void; + public abstract clearRenderTarget(name: string, color: Color): void; + public abstract setViewport(viewport: Viewport): void; } export abstract class RasterPassBuilder extends Setter { public abstract addRasterView(name: string, view: RasterView): void; public abstract addComputeView(name: string, view: ComputeView): void; - public abstract addQueue(hint: QueueHint, layoutName: string, name: string): RasterQueueBuilder; - public abstract addQueue(hint: QueueHint, layoutName: string): RasterQueueBuilder; + public abstract addQueue(hint: QueueHint, name: string): RasterQueueBuilder; public abstract addQueue(hint: QueueHint): RasterQueueBuilder; - public abstract addFullscreenQuad(shader: string, layoutName: string, name: string): void; - public abstract addFullscreenQuad(shader: string, layoutName: string): void; - public abstract addFullscreenQuad(shader: string): void; + public abstract addFullscreenQuad(material: Material, sceneFlags: SceneFlags, name: string): void; + public abstract addFullscreenQuad(material: Material, sceneFlags: SceneFlags): void; + public abstract addCameraQuad(camera: Camera, material: Material, sceneFlags: SceneFlags, name: string): void; + public abstract addCameraQuad(camera: Camera, material: Material, sceneFlags: SceneFlags): void; + public abstract setViewport(viewport: Viewport): void; } export abstract class ComputeQueueBuilder extends Setter { - public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, layoutName: string, name: string): void; - public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, layoutName: string): void; + public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, name: string): void; public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number): void; } export abstract class ComputePassBuilder extends Setter { public abstract addComputeView(name: string, view: ComputeView): void; - public abstract addQueue(layoutName: string, name: string): ComputeQueueBuilder; - public abstract addQueue(layoutName: string): ComputeQueueBuilder; + public abstract addQueue(name: string): ComputeQueueBuilder; public abstract addQueue(): ComputeQueueBuilder; - public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, layoutName: string, name: string): void; - public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, layoutName: string): void; + public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, name: string): void; public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number): void; } @@ -150,12 +159,14 @@ export abstract class LayoutGraphBuilder { public abstract addRenderPhase(name: string, parentID: number): number; public abstract addShader(name: string, parentPhaseID: number): void; public abstract addDescriptorBlock(nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void; + public abstract addUniformBlock(nodeID: number, index: DescriptorBlockIndex, name: string, uniformBlock: UniformBlock): void; public abstract reserveDescriptorBlock(nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void; public abstract compile(): number; public abstract print(): string; } export abstract class Pipeline extends PipelineRuntime { + public abstract containsResource(name: string): boolean; public abstract addRenderTexture(name: string, format: Format, width: number, height: number, renderWindow: RenderWindow): number; public abstract addRenderTarget(name: string, format: Format, width: number, height: number, residency: ResourceResidency): number; public abstract addDepthStencil(name: string, format: Format, width: number, height: number, residency: ResourceResidency): number; @@ -173,5 +184,9 @@ export abstract class Pipeline extends PipelineRuntime { public abstract getDescriptorSetLayout(shaderName: string, freq: UpdateFrequency): DescriptorSetLayout | null; } +export abstract class PipelineBuilder { + public abstract setup(cameras: Camera[], pipeline: Pipeline): void; +} + export class Factory { } diff --git a/cocos/core/pipeline/custom/render-graph.ts b/cocos/core/pipeline/custom/render-graph.ts index b7e5a3dcaf..1f7a4146f2 100644 --- a/cocos/core/pipeline/custom/render-graph.ts +++ b/cocos/core/pipeline/custom/render-graph.ts @@ -30,10 +30,10 @@ */ /* eslint-disable max-len */ import * as impl from './graph'; +import { Material } from '../../assets'; import { Camera } from '../../renderer/scene/camera'; -import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, LoadOp, SampleCount, Sampler, StoreOp, Swapchain, Texture, TextureFlagBit } from '../../gfx'; -import { QueueHint, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags } from './types'; -import { Light } from '../../renderer/scene'; +import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, SampleCount, Sampler, Swapchain, Texture, TextureFlagBit, Viewport } from '../../gfx'; +import { ComputeView, LightInfo, QueueHint, RasterView, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags } from './types'; export class ResourceDesc { dimension: ResourceDimension = ResourceDimension.BUFFER; @@ -84,6 +84,17 @@ export const enum ResourceGraphValue { Swapchain, } +export function getResourceGraphValueName (e: ResourceGraphValue): string { + switch (e) { + case ResourceGraphValue.Managed: return 'Managed'; + case ResourceGraphValue.PersistentBuffer: return 'PersistentBuffer'; + case ResourceGraphValue.PersistentTexture: return 'PersistentTexture'; + case ResourceGraphValue.Framebuffer: return 'Framebuffer'; + case ResourceGraphValue.Swapchain: return 'Swapchain'; + default: return ''; + } +} + interface ResourceGraphValueType { [ResourceGraphValue.Managed]: ManagedResource [ResourceGraphValue.PersistentBuffer]: Buffer @@ -594,92 +605,6 @@ export class ResourceGraph implements impl.BidirectionalGraph readonly _valueIndex: Map = new Map(); } -export const enum AttachmentType { - RENDER_TARGET, - DEPTH_STENCIL, -} - -export function getAttachmentTypeName (e: AttachmentType): string { - switch (e) { - case AttachmentType.RENDER_TARGET: - return 'RENDER_TARGET'; - case AttachmentType.DEPTH_STENCIL: - return 'DEPTH_STENCIL'; - default: - return ''; - } -} - -export const enum AccessType { - READ, - READ_WRITE, - WRITE, -} - -export function getAccessTypeName (e: AccessType): string { - switch (e) { - case AccessType.READ: - return 'READ'; - case AccessType.READ_WRITE: - return 'READ_WRITE'; - case AccessType.WRITE: - return 'WRITE'; - default: - return ''; - } -} - -export class RasterView { - constructor ( - slotName = '', - accessType: AccessType = AccessType.WRITE, - attachmentType: AttachmentType = AttachmentType.RENDER_TARGET, - loadOp: LoadOp = LoadOp.LOAD, - storeOp: StoreOp = StoreOp.STORE, - clearFlags: ClearFlagBit = ClearFlagBit.ALL, - clearColor: Color = new Color(), - ) { - this.slotName = slotName; - this.accessType = accessType; - this.attachmentType = attachmentType; - this.loadOp = loadOp; - this.storeOp = storeOp; - this.clearFlags = clearFlags; - this.clearColor = clearColor; - } - slotName: string; - accessType: AccessType; - attachmentType: AttachmentType; - loadOp: LoadOp; - storeOp: StoreOp; - clearFlags: ClearFlagBit; - readonly clearColor: Color; -} - -export const enum ClearValueType { - FLOAT_TYPE, - INT_TYPE, -} - -export function getClearValueTypeName (e: ClearValueType): string { - switch (e) { - case ClearValueType.FLOAT_TYPE: - return 'FLOAT_TYPE'; - case ClearValueType.INT_TYPE: - return 'INT_TYPE'; - default: - return ''; - } -} - -export class ComputeView { - name = ''; - accessType: AccessType = AccessType.READ; - clearFlags: ClearFlagBit = ClearFlagBit.NONE; - readonly clearColor: Color = new Color(); - clearValueType: ClearValueType = ClearValueType.FLOAT_TYPE; -} - export class RasterSubpass { readonly rasterViews: Map = new Map(); readonly computeViews: Map = new Map(); @@ -980,6 +905,7 @@ export class RasterPass { readonly subpassGraph: SubpassGraph = new SubpassGraph(); width = 0; height = 0; + readonly viewport: Viewport = new Viewport(); } export class ComputePass { @@ -1061,6 +987,17 @@ export class RaytracePass { readonly computeViews: Map = new Map(); } +export class ClearView { + constructor (slotName = '', clearFlags: ClearFlagBit = gfx.ClearFlagBit.ALL, clearColor: Color = new Color()) { + this.slotName = slotName; + this.clearFlags = clearFlags; + this.clearColor = clearColor; + } + slotName: string; + clearFlags: ClearFlagBit; + readonly clearColor: Color; +} + export class RenderQueue { constructor (hint: QueueHint = QueueHint.RENDER_OPAQUE) { this.hint = hint; @@ -1069,13 +1006,14 @@ export class RenderQueue { } export class SceneData { - constructor (name = '', flags: SceneFlags = SceneFlags.NONE) { + constructor (name = '', flags: SceneFlags = SceneFlags.NONE, light: LightInfo = new LightInfo()) { this.name = name; + this.light = light; this.flags = flags; } name: string; camera: Camera | null = null; - light: Light | null = null; + readonly light: LightInfo; flags: SceneFlags; readonly scenes: string[] = []; } @@ -1094,10 +1032,14 @@ export class Dispatch { } export class Blit { - constructor (shader = '') { - this.shader = shader; + constructor (material: Material | null, sceneFlags: SceneFlags, camera: Camera | null) { + this.material = material; + this.sceneFlags = sceneFlags; + this.camera = camera; } - shader: string; + /*object*/ material: Material | null; + sceneFlags: SceneFlags; + camera: Camera | null; } export class Present { @@ -1135,6 +1077,26 @@ export const enum RenderGraphValue { Scene, Blit, Dispatch, + Clear, + Viewport, +} + +export function getRenderGraphValueName (e: RenderGraphValue): string { + switch (e) { + case RenderGraphValue.Raster: return 'Raster'; + case RenderGraphValue.Compute: return 'Compute'; + case RenderGraphValue.Copy: return 'Copy'; + case RenderGraphValue.Move: return 'Move'; + case RenderGraphValue.Present: return 'Present'; + case RenderGraphValue.Raytrace: return 'Raytrace'; + case RenderGraphValue.Queue: return 'Queue'; + case RenderGraphValue.Scene: return 'Scene'; + case RenderGraphValue.Blit: return 'Blit'; + case RenderGraphValue.Dispatch: return 'Dispatch'; + case RenderGraphValue.Clear: return 'Clear'; + case RenderGraphValue.Viewport: return 'Viewport'; + default: return ''; + } } interface RenderGraphValueType { @@ -1148,6 +1110,8 @@ interface RenderGraphValueType { [RenderGraphValue.Scene]: SceneData [RenderGraphValue.Blit]: Blit [RenderGraphValue.Dispatch]: Dispatch + [RenderGraphValue.Clear]: ClearView[] + [RenderGraphValue.Viewport]: Viewport } export interface RenderGraphVisitor { @@ -1161,6 +1125,8 @@ export interface RenderGraphVisitor { scene(value: SceneData): unknown; blit(value: Blit): unknown; dispatch(value: Dispatch): unknown; + clear(value: ClearView[]): unknown; + viewport(value: Viewport): unknown; } type RenderGraphObject = RasterPass @@ -1172,7 +1138,9 @@ type RenderGraphObject = RasterPass | RenderQueue | SceneData | Blit -| Dispatch; +| Dispatch +| ClearView[] +| Viewport; //----------------------------------------------------------------- // Graph Concept @@ -1553,12 +1521,18 @@ export class RenderGraph implements impl.BidirectionalGraph getLayout (v: number): string { return this._layoutNodes[v]; } + setLayout (v: number, value: string) { + this._layoutNodes[v] = value; + } getData (v: number): RenderData { return this._data[v]; } getValid (v: number): boolean { return this._valid[v]; } + setValid (v: number, value: boolean) { + this._valid[v] = value; + } //----------------------------------------------------------------- // PolymorphicGraph holds (id: RenderGraphValue, v: number): boolean { @@ -1607,6 +1581,10 @@ export class RenderGraph implements impl.BidirectionalGraph return visitor.blit(vert._object as Blit); case RenderGraphValue.Dispatch: return visitor.dispatch(vert._object as Dispatch); + case RenderGraphValue.Clear: + return visitor.clear(vert._object as ClearView[]); + case RenderGraphValue.Viewport: + return visitor.viewport(vert._object as Viewport); default: throw Error('polymorphic type not found'); } @@ -1681,6 +1659,20 @@ export class RenderGraph implements impl.BidirectionalGraph throw Error('value id not match'); } } + getClear (v: number): ClearView[] { + if (this._vertices[v]._id === RenderGraphValue.Clear) { + return this._vertices[v]._object as ClearView[]; + } else { + throw Error('value id not match'); + } + } + getViewport (v: number): Viewport { + if (this._vertices[v]._id === RenderGraphValue.Viewport) { + return this._vertices[v]._object as Viewport; + } else { + throw Error('value id not match'); + } + } tryGetRaster (v: number): RasterPass | null { if (this._vertices[v]._id === RenderGraphValue.Raster) { return this._vertices[v]._object as RasterPass; @@ -1751,6 +1743,20 @@ export class RenderGraph implements impl.BidirectionalGraph return null; } } + tryGetClear (v: number): ClearView[] | null { + if (this._vertices[v]._id === RenderGraphValue.Clear) { + return this._vertices[v]._object as ClearView[]; + } else { + return null; + } + } + tryGetViewport (v: number): Viewport | null { + if (this._vertices[v]._id === RenderGraphValue.Viewport) { + return this._vertices[v]._object as Viewport; + } else { + return null; + } + } //----------------------------------------------------------------- // ReferenceGraph // type reference_descriptor = impl.ED; diff --git a/cocos/core/pipeline/custom/types.ts b/cocos/core/pipeline/custom/types.ts index 571136effb..f891839276 100644 --- a/cocos/core/pipeline/custom/types.ts +++ b/cocos/core/pipeline/custom/types.ts @@ -29,6 +29,9 @@ * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ /* eslint-disable max-len */ +import { ClearFlagBit, Color, LoadOp, StoreOp } from '../../gfx'; +import { Light } from '../../renderer/scene'; + export const enum UpdateFrequency { PER_INSTANCE, PER_BATCH, @@ -180,9 +183,130 @@ export function getTaskTypeName (e: TaskType): string { export const enum SceneFlags { NONE = 0, - OPAQUE_OBJECT = 0x1, - CUTOUT_OBJECT = 0x2, - TRANSPARENT_OBJECT = 0x4, - SHADOW_CASTER = 0x8, + OPAQUE_OBJECT = 1, + CUTOUT_OBJECT = 2, + TRANSPARENT_OBJECT = 4, + SHADOW_CASTER = 8, + UI = 16, + DEFAULT_LIGHTING = 32, + VOLUMETRIC_LIGHTING = 64, + CLUSTERED_LIGHTING = 128, + PLANAR_SHADOW = 256, + GEOMETRY = 512, + PROFILER = 1024, ALL = 0xFFFFFFFF, } + +export const enum LightingMode { + NONE, + DEFAULT, + CLUSTERED, +} + +export function getLightingModeName (e: LightingMode): string { + switch (e) { + case LightingMode.NONE: + return 'NONE'; + case LightingMode.DEFAULT: + return 'DEFAULT'; + case LightingMode.CLUSTERED: + return 'CLUSTERED'; + default: + return ''; + } +} + +export const enum AttachmentType { + RENDER_TARGET, + DEPTH_STENCIL, +} + +export function getAttachmentTypeName (e: AttachmentType): string { + switch (e) { + case AttachmentType.RENDER_TARGET: + return 'RENDER_TARGET'; + case AttachmentType.DEPTH_STENCIL: + return 'DEPTH_STENCIL'; + default: + return ''; + } +} + +export const enum AccessType { + READ, + READ_WRITE, + WRITE, +} + +export function getAccessTypeName (e: AccessType): string { + switch (e) { + case AccessType.READ: + return 'READ'; + case AccessType.READ_WRITE: + return 'READ_WRITE'; + case AccessType.WRITE: + return 'WRITE'; + default: + return ''; + } +} + +export class RasterView { + constructor ( + slotName = '', + accessType: AccessType = AccessType.WRITE, + attachmentType: AttachmentType = AttachmentType.RENDER_TARGET, + loadOp: LoadOp = LoadOp.LOAD, + storeOp: StoreOp = StoreOp.STORE, + clearFlags: ClearFlagBit = ClearFlagBit.ALL, + clearColor: Color = new Color(), + ) { + this.slotName = slotName; + this.accessType = accessType; + this.attachmentType = attachmentType; + this.loadOp = loadOp; + this.storeOp = storeOp; + this.clearFlags = clearFlags; + this.clearColor = clearColor; + } + slotName: string; + accessType: AccessType; + attachmentType: AttachmentType; + loadOp: LoadOp; + storeOp: StoreOp; + clearFlags: ClearFlagBit; + readonly clearColor: Color; +} + +export const enum ClearValueType { + FLOAT_TYPE, + INT_TYPE, +} + +export function getClearValueTypeName (e: ClearValueType): string { + switch (e) { + case ClearValueType.FLOAT_TYPE: + return 'FLOAT_TYPE'; + case ClearValueType.INT_TYPE: + return 'INT_TYPE'; + default: + return ''; + } +} + +export class ComputeView { + name = ''; + accessType: AccessType = AccessType.READ; + clearFlags: ClearFlagBit = ClearFlagBit.NONE; + readonly clearColor: Color = new Color(); + clearValueType: ClearValueType = ClearValueType.FLOAT_TYPE; +} + +export class LightInfo { + constructor (light: Light | null = null, level = 0) { + this.light = light; + this.level = level; + } + /*object*/ light: Light | null; + level: number; +} diff --git a/cocos/core/pipeline/custom/ubos.ts b/cocos/core/pipeline/custom/ubos.ts deleted file mode 100644 index 3c32267d4b..0000000000 --- a/cocos/core/pipeline/custom/ubos.ts +++ /dev/null @@ -1,512 +0,0 @@ -/* - Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. - - https://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 { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, - supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UBOCSM } from '../define'; -import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../../gfx'; -import { Camera } from '../../renderer/scene/camera'; -import { Mat4, Vec3, Vec4, Color } from '../../math'; -import { WebPipeline } from './web-pipeline'; -import { legacyCC } from '../../global-exports'; -import { CSMLevel, PCFType, Shadows, ShadowType } from '../../renderer/scene/shadows'; -import { updatePlanarNormalAndDistance, updatePlanarPROJ } from '../scene-culling'; -import { Light, LightType } from '../../renderer/scene/light'; -import { DirectionalLight, SpotLight } from '../../renderer/scene'; -import { RenderWindow } from '../../renderer/core/render-window'; -import { builtinResMgr } from '../../builtin/builtin-res-mgr'; -import { Texture2D } from '../../assets'; -import { DebugView, DebugViewCompositeType } from '../debug-view'; - -const _matShadowView = new Mat4(); -const _matShadowProj = new Mat4(); -const _matShadowViewProj = new Mat4(); -const _vec4ShadowInfo = new Vec4(); -const _lightDir = new Vec4(0.0, 0.0, 1.0, 0.0); - -export class PipelineUBO { - public static updateGlobalUBOView (window: RenderWindow, bufferView: Float32Array) { - const director = legacyCC.director; - const root = director.root; - const fv = bufferView; - - const shadingWidth = Math.floor(window.width); - const shadingHeight = Math.floor(window.height); - - // update UBOGlobal - fv[UBOGlobal.TIME_OFFSET] = root.cumulativeTime; - fv[UBOGlobal.TIME_OFFSET + 1] = root.frameTime; - fv[UBOGlobal.TIME_OFFSET + 2] = director.getTotalFrames(); - - fv[UBOGlobal.SCREEN_SIZE_OFFSET] = shadingWidth; - fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = shadingHeight; - fv[UBOGlobal.SCREEN_SIZE_OFFSET + 2] = 1.0 / shadingWidth; - fv[UBOGlobal.SCREEN_SIZE_OFFSET + 3] = 1.0 / shadingHeight; - - fv[UBOGlobal.NATIVE_SIZE_OFFSET] = shadingWidth; - fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1] = shadingHeight; - fv[UBOGlobal.NATIVE_SIZE_OFFSET + 2] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET]; - fv[UBOGlobal.NATIVE_SIZE_OFFSET + 3] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1]; - - const debugView = root.debugView; - if (debugView) { - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = debugView.singleMode as number; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1] = debugView.lightingWithAlbedo ? 1.0 : 0.0; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 2] = debugView.csmLayerColoration ? 1.0 : 0.0; - for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { - fv[UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + i] = debugView.isCompositeModeEnabled(i) ? 1.0 : 0.0; - } - } else { - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = 0.0; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1] = 1.0; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 2] = 0.0; - for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { - fv[UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + i] = 1.0; - } - } - } - - public static updateCameraUBOView (pipeline: WebPipeline, bufferView: Float32Array, - camera: Camera) { - const scene = camera.scene ? camera.scene : legacyCC.director.getScene().renderScene; - const mainLight = scene.mainLight; - const sceneData = pipeline.pipelineSceneData; - const ambient = sceneData.ambient; - const fog = sceneData.fog; - const shadowInfo = sceneData.shadows; - const cv = bufferView; - const exposure = camera.exposure; - const isHDR = sceneData.isHDR; - - // update camera ubo - cv[UBOCamera.SCREEN_SCALE_OFFSET] = sceneData.shadingScale; - cv[UBOCamera.SCREEN_SCALE_OFFSET + 1] = sceneData.shadingScale; - cv[UBOCamera.SCREEN_SCALE_OFFSET + 2] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET]; - cv[UBOCamera.SCREEN_SCALE_OFFSET + 3] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET + 1]; - - cv[UBOCamera.EXPOSURE_OFFSET] = exposure; - cv[UBOCamera.EXPOSURE_OFFSET + 1] = 1.0 / exposure; - cv[UBOCamera.EXPOSURE_OFFSET + 2] = isHDR ? 1.0 : 0.0; - cv[UBOCamera.EXPOSURE_OFFSET + 3] = 0.0; - - if (mainLight) { - const shadowEnable = (mainLight.shadowEnabled && shadowInfo.type === ShadowType.ShadowMap) ? 1.0 : 0.0; - const mainLightDir = mainLight.direction; - _lightDir.set(mainLightDir.x, mainLightDir.y, mainLightDir.z, shadowEnable); - Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET); - Vec3.toArray(cv, mainLight.color, UBOCamera.MAIN_LIT_COLOR_OFFSET); - if (mainLight.useColorTemperature) { - const colorTempRGB = mainLight.colorTemperatureRGB; - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET] *= colorTempRGB.x; - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 1] *= colorTempRGB.y; - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 2] *= colorTempRGB.z; - } - - if (isHDR) { - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure; - } else { - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance; - } - } else { - _lightDir.set(0, 0, 1, 0); - Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET); - Vec4.toArray(cv, Vec4.ZERO, UBOCamera.MAIN_LIT_COLOR_OFFSET); - } - - const skyColor = ambient.skyColor; - if (isHDR) { - skyColor.w = ambient.skyIllum * exposure; - } else { - skyColor.w = ambient.skyIllum; - } - cv[UBOCamera.AMBIENT_SKY_OFFSET + 0] = skyColor.x; - cv[UBOCamera.AMBIENT_SKY_OFFSET + 1] = skyColor.y; - cv[UBOCamera.AMBIENT_SKY_OFFSET + 2] = skyColor.z; - cv[UBOCamera.AMBIENT_SKY_OFFSET + 3] = skyColor.w; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 0] = ambient.groundAlbedo.x; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 1] = ambient.groundAlbedo.y; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 2] = ambient.groundAlbedo.z; - const skybox = pipeline.pipelineSceneData.skybox; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 3] = skybox.envmap ? skybox.envmap?.mipmapLevel : 1.0; - - Mat4.toArray(cv, camera.matView, UBOCamera.MAT_VIEW_OFFSET); - Mat4.toArray(cv, camera.node.worldMatrix, UBOCamera.MAT_VIEW_INV_OFFSET); - Vec3.toArray(cv, camera.position, UBOCamera.CAMERA_POS_OFFSET); - - Mat4.toArray(cv, camera.matProj, UBOCamera.MAT_PROJ_OFFSET); - Mat4.toArray(cv, camera.matProjInv, UBOCamera.MAT_PROJ_INV_OFFSET); - Mat4.toArray(cv, camera.matViewProj, UBOCamera.MAT_VIEW_PROJ_OFFSET); - Mat4.toArray(cv, camera.matViewProjInv, UBOCamera.MAT_VIEW_PROJ_INV_OFFSET); - cv[UBOCamera.CAMERA_POS_OFFSET + 3] = this.getCombineSignY(); - - const colorTempRGB = fog.colorArray; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET] = colorTempRGB.x; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 1] = colorTempRGB.y; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 2] = colorTempRGB.z; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 3] = colorTempRGB.z; - - cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET] = fog.fogStart; - cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 1] = fog.fogEnd; - cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 2] = fog.fogDensity; - - cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET] = fog.fogTop; - cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 1] = fog.fogRange; - cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 2] = fog.fogAtten; - - cv[UBOCamera.NEAR_FAR_OFFSET] = camera.nearClip; - cv[UBOCamera.NEAR_FAR_OFFSET + 1] = camera.farClip; - - cv[UBOCamera.VIEW_PORT_OFFSET] = sceneData.shadingScale * camera.window.width * camera.viewport.x; - cv[UBOCamera.VIEW_PORT_OFFSET + 1] = sceneData.shadingScale * camera.window.height * camera.viewport.y; - cv[UBOCamera.VIEW_PORT_OFFSET + 2] = sceneData.shadingScale * camera.window.width * camera.viewport.z; - cv[UBOCamera.VIEW_PORT_OFFSET + 3] = sceneData.shadingScale * camera.window.height * camera.viewport.w; - } - - public static getPCFRadius (shadowInfo: Shadows, mainLight: DirectionalLight): number { - const shadowMapSize = shadowInfo.size.x; - switch (mainLight.shadowPcf) { - case PCFType.HARD: - return 0.0; - case PCFType.SOFT: - return 1.0 / (shadowMapSize * 0.5); - case PCFType.SOFT_2X: - return 2.0 / (shadowMapSize * 0.5); - case PCFType.SOFT_4X: - return 3.0 / (shadowMapSize * 0.5); - default: - } - return 0.0; - } - - public static updateShadowUBOView (pipeline: WebPipeline, shadowBufferView: Float32Array, - csmBufferView: Float32Array, camera: Camera) { - const device = pipeline.device; - const mainLight = camera.scene!.mainLight; - const sceneData = pipeline.pipelineSceneData; - const shadowInfo = sceneData.shadows; - const csmLayers = sceneData.csmLayers; - const sv = shadowBufferView; - const cv = csmBufferView; - const csmSupported = sceneData.csmSupported; - const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - - if (shadowInfo.enabled && mainLight) { - if (shadowInfo.type === ShadowType.ShadowMap) { - if (mainLight.shadowEnabled) { - if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) { - const matShadowView = csmLayers.specialLayer.matShadowView; - const matShadowProj = csmLayers.specialLayer.matShadowProj; - const matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; - const near = mainLight.shadowNear; - const far = mainLight.shadowFar; - - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; - - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; - - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(0, packing, mainLight.shadowNormalBias, 0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - } else { - for (let i = 0; i < mainLight.csmLevel; i++) { - cv[UBOCSM.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; - - const matShadowView = csmLayers.layers[i].matShadowView; - Mat4.toArray(cv, matShadowView, UBOCSM.MAT_CSM_VIEW_OFFSET + 16 * i); - - const matShadowViewProj = csmLayers.layers[i].matShadowViewProj; - Mat4.toArray(cv, matShadowViewProj, UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); - - const matShadowViewProjAtlas = csmLayers.layers[i].matShadowViewProjAtlas; - Mat4.toArray(cv, matShadowViewProjAtlas, UBOCSM.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * i); - - const matShadowProj = csmLayers.layers[i].matShadowProj; - cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; - cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; - cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; - cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; - - cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; - cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; - cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; - cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; - } - - cv[UBOCSM.CSM_INFO_OFFSET + 0] = 0; - cv[UBOCSM.CSM_INFO_OFFSET + 1] = this.getPCFRadius(shadowInfo, mainLight); - cv[UBOCSM.CSM_INFO_OFFSET + 2] = 0; - cv[UBOCSM.CSM_INFO_OFFSET + 3] = 0; - - _vec4ShadowInfo.set(0, 0, 0, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, mainLight.csmLevel); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - } - _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); - } - } else { - updatePlanarPROJ(shadowInfo, mainLight, sv); - updatePlanarNormalAndDistance(shadowInfo, sv); - } - - Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); - } - } - - public static updateShadowUBOLightView (pipeline: WebPipeline, shadowBufferView: Float32Array, light: Light, level: number) { - const device = pipeline.device; - const sceneData = pipeline.pipelineSceneData; - const shadowInfo = sceneData.shadows; - const csmLayers = sceneData.csmLayers; - const sv = shadowBufferView; - const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - switch (light.type) { - case LightType.DIRECTIONAL: { - const mainLight = light as DirectionalLight; - if (shadowInfo.enabled && mainLight && mainLight.shadowEnabled) { - if (shadowInfo.type === ShadowType.ShadowMap) { - let near = 0.1; - let far = 0; - let matShadowView; - let matShadowProj; - let matShadowViewProj; - let levelCount = 0; - if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { - matShadowView = csmLayers.specialLayer.matShadowView; - matShadowProj = csmLayers.specialLayer.matShadowProj; - matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; - if (mainLight.shadowFixedArea) { - near = mainLight.shadowNear; - far = mainLight.shadowFar; - levelCount = 0; - } else { - near = 0.1; - far = csmLayers.specialLayer.shadowCameraFar; - levelCount = 1; - } - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, 0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - } else { - const layer = csmLayers.layers[level]; - matShadowView = layer.matShadowView; - matShadowProj = layer.matShadowProj; - matShadowViewProj = layer.matShadowViewProj; - - near = layer.splitCameraNear; - far = layer.splitCameraFar; - levelCount = mainLight.csmLevel; - } - - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; - - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; - - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, levelCount); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - - _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); - } - } - break; - } - case LightType.SPOT: { - const spotLight = light as SpotLight; - Mat4.invert(_matShadowView, (light as any).node.getWorldMatrix()); - Mat4.toArray(sv, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - - Mat4.perspective(_matShadowProj, (light as any).angle, 1.0, 0.001, (light as any).range); - - Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); - Mat4.toArray(sv, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - _vec4ShadowInfo.set(0.01, (light as SpotLight).range, 0.0, 0.0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, spotLight.shadowPcf, spotLight.shadowBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); - - _vec4ShadowInfo.set(1.0, packing, spotLight.shadowNormalBias, 0.0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - break; - } - default: - } - - Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); - } - - protected _globalUBO = new Float32Array(UBOGlobal.COUNT); - protected _cameraUBO = new Float32Array(UBOCamera.COUNT); - protected _shadowUBO = new Float32Array(UBOShadow.COUNT); - protected _csmUBO = new Float32Array(UBOCSM.COUNT); - static _combineSignY = 0; - protected declare _device: Device; - protected declare _pipeline: WebPipeline; - - /** - *|combinedSignY|clipSpaceSignY|screenSpaceSignY| Backends | - *| :--: | :--: | :--: | :--: | - *| 0 | -1 | -1 | Vulkan | - *| 1 | 1 | -1 | Metal | - *| 2 | -1 | 1 | | - *| 3 | 1 | 1 | GL-like | - */ - public static getCombineSignY () { - return PipelineUBO._combineSignY; - } - - private _initCombineSignY () { - const device = this._device; - PipelineUBO._combineSignY = (device.capabilities.screenSpaceSignY * 0.5 + 0.5) << 1 | (device.capabilities.clipSpaceSignY * 0.5 + 0.5); - } - - public activate (device: Device, pipeline: WebPipeline) { - this._device = device; - this._pipeline = pipeline; - const ds = this._pipeline.globalDSManager.globalDescriptorSet; - this._initCombineSignY(); - - const globalUBO = device.createBuffer(new BufferInfo( - BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOGlobal.SIZE, - UBOGlobal.SIZE, - )); - ds.bindBuffer(UBOGlobal.BINDING, globalUBO); - - const cameraUBO = device.createBuffer(new BufferInfo( - BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOCamera.SIZE, - UBOCamera.SIZE, - )); - ds.bindBuffer(UBOCamera.BINDING, cameraUBO); - const shadowUBO = device.createBuffer(new BufferInfo( - BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOShadow.SIZE, - UBOShadow.SIZE, - )); - ds.bindBuffer(UBOShadow.BINDING, shadowUBO); - const csmUBO = device.createBuffer(new BufferInfo( - BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOCSM.SIZE, - UBOCSM.SIZE, - )); - ds.bindBuffer(UBOCSM.BINDING, csmUBO); - } - - /** - * @en Update all UBOs - * @zh 更新全部 UBO。 - */ - public updateGlobalUBO (window: RenderWindow) { - const globalDSManager = this._pipeline.globalDSManager; - const ds = this._pipeline.globalDSManager.globalDescriptorSet; - const cmdBuffer = this._pipeline.device.commandBuffer; - ds.update(); - PipelineUBO.updateGlobalUBOView(window, this._globalUBO); - cmdBuffer.updateBuffer(ds.getBuffer(UBOGlobal.BINDING), this._globalUBO); - - globalDSManager.bindBuffer(UBOGlobal.BINDING, ds.getBuffer(UBOGlobal.BINDING)); - globalDSManager.update(); - } - - public updateCameraUBO (camera: Camera) { - const globalDSManager = this._pipeline.globalDSManager; - const ds = this._pipeline.globalDSManager.globalDescriptorSet; - const cmdBuffer = this._pipeline.device.commandBuffer; - PipelineUBO.updateCameraUBOView(this._pipeline, this._cameraUBO, camera); - cmdBuffer.updateBuffer(ds.getBuffer(UBOCamera.BINDING), this._cameraUBO); - - globalDSManager.bindBuffer(UBOCamera.BINDING, ds.getBuffer(UBOCamera.BINDING)); - globalDSManager.update(); - } - - public updateShadowUBO (camera: Camera) { - const sceneData = this._pipeline.pipelineSceneData; - const shadowInfo = sceneData.shadows; - if (!shadowInfo.enabled) return; - - const ds = this._pipeline.globalDSManager.globalDescriptorSet; - const cmdBuffer = this._pipeline.device.commandBuffer; - const shadowFrameBufferMap = sceneData.shadowFrameBufferMap; - const mainLight = camera.scene!.mainLight; - if (mainLight && shadowFrameBufferMap.has(mainLight)) { - ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); - } - PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, this._csmUBO, camera); - ds.update(); - cmdBuffer.updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO); - cmdBuffer.updateBuffer(ds.getBuffer(UBOCSM.BINDING), this._csmUBO); - } - - public updateShadowUBOLight (globalDS: DescriptorSet, light: Light, level = 0) { - PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light, level); - globalDS.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); - globalDS.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); - globalDS.update(); - globalDS.getBuffer(UBOShadow.BINDING).update(this._shadowUBO); - } - - public updateShadowUBORange (offset: number, data: Mat4 | Color) { - if (data instanceof Mat4) { - Mat4.toArray(this._shadowUBO, data, offset); - } else if (data instanceof Color) { - Color.toArray(this._shadowUBO, data, offset); - } - } - - public destroy () { - } -} diff --git a/cocos/core/pipeline/custom/utils.ts b/cocos/core/pipeline/custom/utils.ts new file mode 100644 index 0000000000..ee00bad60a --- /dev/null +++ b/cocos/core/pipeline/custom/utils.ts @@ -0,0 +1,39 @@ +// https://stackoverflow.com/questions/56714318/how-to-disable-multiple-rules-for-eslint-nextline?msclkid=5d4c2298ba7911eca34d0ab30591752e + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function replacer (key: unknown, value: unknown) { + if (value instanceof Map) { + return { + meta_t: 'Map', + value: Array.from(value.entries()).sort((a, b) => String(a[0]).localeCompare(b[0])), + }; + } else if (value instanceof Set) { + return { + meta_t: 'Set', + value: Array.from(value).sort(), + }; + } + return value; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars +export function reviver (key: unknown, value: any) { + if (typeof value === 'object' && value !== null) { + if (value.meta_t === 'Map') { + return new Map(value.value); + } else if (value.meta_t === 'Set') { + return new Set(value.value); + } + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return value; +} + +export function stringify (data: unknown, space?: string | number | undefined) { + return JSON.stringify(data, replacer, space); +} + +export function parse (text: string) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return JSON.parse(text, reviver); +} diff --git a/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts b/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts index b587f56664..9273cf8671 100644 --- a/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts +++ b/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts @@ -25,58 +25,67 @@ ****************************************************************************/ import { EffectAsset } from '../../assets'; -import { Descriptor, DescriptorBlock, DescriptorBlockIndex, DescriptorDB, DescriptorTypeOrder, LayoutGraph, LayoutGraphValue, RenderPhase } from './layout-graph'; +import { Descriptor, DescriptorBlock, DescriptorBlockIndex, DescriptorDB, DescriptorTypeOrder, LayoutGraph, LayoutGraphValue, LayoutGraphVisitor, RenderPhase } from './layout-graph'; import { ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx'; import { ParameterType, UpdateFrequency } from './types'; -import { JOINT_UNIFORM_CAPACITY, UBOForwardLight, UBOLocalBatched, UBOMorph } from '../define'; +import { JOINT_UNIFORM_CAPACITY, RenderPassStage, SetIndex, UBOCamera, UBOForwardLight, UBOGlobal, UBOLocal, UBOLocalBatched, UBOMorph, UBOShadow, UBOSkinning, UBOSkinningAnimation, UBOSkinningTexture, UBOUILocal, UBOWorldBound } from '../define'; +import { DefaultVisitor, edge_descriptor, IncidenceGraph, vertex_descriptor } from './graph'; +import { assert } from '../../platform'; export class WebDescriptorHierarchy { + public uniformBlockIndex: Map; + public blockMerged: Map>; + public dbsToMerge: Map; + constructor () { this._layoutGraph = new LayoutGraph(); + this.uniformBlockIndex = new Map(); + this.blockMerged = new Map>(); + this.dbsToMerge = new Map(); } - private getLayoutBlock (freq: UpdateFrequency, paraType: ParameterType, descType: DescriptorTypeOrder, vis: ShaderStageFlagBit, descriptorDB: DescriptorDB): DescriptorBlock { + public getLayoutBlock (freq: UpdateFrequency, paraType: ParameterType, descType: DescriptorTypeOrder, vis: ShaderStageFlagBit, descriptorDB: DescriptorDB): DescriptorBlock { const blockIndex: DescriptorBlockIndex = new DescriptorBlockIndex(freq, paraType, descType, vis); const key = JSON.stringify(blockIndex); if (descriptorDB.blocks.get(key) === undefined) { const uniformBlock: DescriptorBlock = new DescriptorBlock(); descriptorDB.blocks.set(key, uniformBlock); - // uniformBlock['blockIndex'] = blockIndex; + this.uniformBlockIndex.set(uniformBlock, blockIndex); } return descriptorDB.blocks.get(key) as DescriptorBlock; } - private getLayoutBlockByKey (key: string, descriptorDB: DescriptorDB): DescriptorBlock { + public getLayoutBlockByKey (key: string, descriptorDB: DescriptorDB): DescriptorBlock { if (descriptorDB.blocks.get(key) === undefined) { const uniformBlock: DescriptorBlock = new DescriptorBlock(); descriptorDB.blocks.set(key, uniformBlock); - // const blockIndedx: DescriptorBlockIndex = JSON.parse(key) as DescriptorBlockIndex; - // uniformBlock['blockIndex'] = blockIndedx; + const blockIndedx: DescriptorBlockIndex = JSON.parse(key) as DescriptorBlockIndex; + this.uniformBlockIndex.set(uniformBlock, blockIndedx); } return descriptorDB.blocks.get(key) as DescriptorBlock; } - private getUniformBlock (blockName: string, targetBlock: DescriptorBlock): UniformBlock { + public getUniformBlock (set: number, binding: number, blockName: string, targetBlock: DescriptorBlock): UniformBlock { if (targetBlock.uniformBlocks.get(blockName) === undefined) { - const uniformDB: UniformBlock = new UniformBlock(); + const uniformDB: UniformBlock = new UniformBlock(set, binding, blockName, [], 1); targetBlock.uniformBlocks.set(blockName, uniformDB); } return targetBlock.uniformBlocks.get(blockName) as UniformBlock; } - private setUniform (uniformDB: UniformBlock, name: string, type: Type, count: number) { + public setUniform (uniformDB: UniformBlock, name: string, type: Type, count: number) { const uniform: Uniform = new Uniform(name, type, count); - // uniformDB.values.set(uniform.name, uniform); + uniformDB.members.push(uniform); } - private setDescriptor (targetBlock: DescriptorBlock, name: string, type: Type) { + public setDescriptor (targetBlock: DescriptorBlock, name: string, type: Type) { const descriptor: Descriptor = new Descriptor(type); targetBlock.descriptors.set(name, descriptor); } - private merge (descriptorDB: DescriptorDB) { + public merge (descriptorDB: DescriptorDB) { for (const entry of descriptorDB.blocks) { const block: DescriptorBlock = entry[1]; const typeMap: Map = new Map(); @@ -97,31 +106,49 @@ export class WebDescriptorHierarchy { if (count > 0) { const mergedDescriptor: Descriptor = new Descriptor(type); mergedDescriptor.count = count; - // block.merged.set(type, mergedDescriptor); + let merged: Map; + if (this.blockMerged.get(block) === undefined) { + merged = new Map(); + this.blockMerged.set(block, merged); + } + this.blockMerged.get(block)?.set(type, mergedDescriptor); } } } } - private mergeDBs (descriptorDBs: DescriptorDB[], target: DescriptorDB) { - /* + public mergeDBs (descriptorDBs: DescriptorDB[], target: DescriptorDB) { for (let i = 0; i < descriptorDBs.length; ++i) { const db: DescriptorDB = descriptorDBs[i]; for (const e of db.blocks) { const key: string = e[0]; const block: DescriptorBlock = e[1]; - if (block.merged.size > 0) { + let merged: Map; + if (this.blockMerged.get(block) === undefined) { + merged = new Map(); + this.blockMerged.set(block, merged); + } else { + merged = this.blockMerged.get(block) as Map; + } + if (merged.size > 0) { const targetBlock: DescriptorBlock = this.getLayoutBlockByKey(key, target); - for (const ee of block.merged) { + let targetMerged: Map; + if (this.blockMerged.get(targetBlock) === undefined) { + targetMerged = new Map(); + this.blockMerged.set(targetBlock, targetMerged); + } else { + targetMerged = this.blockMerged.get(targetBlock) as Map; + } + for (const ee of merged) { const type: Type = ee[0]; const descriptor: Descriptor = ee[1]; - if (!targetBlock.merged.has(type)) { + if (!targetMerged.has(type)) { const ds: Descriptor = new Descriptor(descriptor.type); ds.count = descriptor.count; - targetBlock.merged.set(type, ds); + targetMerged.set(type, ds); } else { - const ds: Descriptor | undefined = targetBlock.merged.get(type); + const ds: Descriptor | undefined = targetMerged.get(type); if (ds !== undefined) { ds.count = ds.count > descriptor.count ? ds.count : descriptor.count; } @@ -131,10 +158,9 @@ export class WebDescriptorHierarchy { } } } - */ } - private sort (descriptorDB: DescriptorDB) { + public sort (descriptorDB: DescriptorDB) { const sortedMap: Map = new Map(Array.from(descriptorDB.blocks).sort((a, b) => String(a[0]).localeCompare(b[0]))); descriptorDB.blocks.clear(); for (const e of sortedMap) { @@ -145,8 +171,6 @@ export class WebDescriptorHierarchy { public addEffect (asset: EffectAsset, parent: number): void { const sz = asset.shaders.length; - const dbsToMerge: DescriptorDB[] = []; - for (let i = 0; i !== sz; ++i) { const shader: EffectAsset.IShaderInfo = asset.shaders[i]; @@ -156,10 +180,10 @@ export class WebDescriptorHierarchy { const blockInfo: EffectAsset.IBlockInfo = shader.blocks[k]; const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, blockInfo.stageFlags, queueDB); - const uniformDB: UniformBlock = this.getUniformBlock(blockInfo.name, targetBlock); + const uniformDB: UniformBlock = this.getUniformBlock(SetIndex.MATERIAL, blockInfo.binding, blockInfo.name, targetBlock); for (let kk = 0; kk < blockInfo.members.length; ++kk) { const uniform: Uniform = blockInfo.members[kk]; - // uniformDB.values.set(uniform.name, uniform); + uniformDB.members.push(uniform); } } @@ -200,7 +224,7 @@ export class WebDescriptorHierarchy { for (let k = 0; k < shader.subpassInputs.length; ++k) { const subpassInfo: EffectAsset.IInputAttachmentInfo = shader.subpassInputs[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_QUEUE, + const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, ParameterType.TABLE, DescriptorTypeOrder.INPUT_ATTACHMENT, subpassInfo.stageFlags, queueDB); this.setDescriptor(targetBlock, subpassInfo.name, Type.SUBPASS_INPUT); } @@ -224,37 +248,37 @@ export class WebDescriptorHierarchy { for (let k = 0; k < shader.builtins.locals.blocks.length; ++k) { const blockName: string = shader.builtins.locals.blocks[k].name; if (blockName === 'CCMorph') { - const morphDB: UniformBlock = this.getUniformBlock('CCMorph', localUniformTarget); + const morphDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOMorph.BINDING, 'CCMorph', localUniformTarget); this.setUniform(morphDB, 'cc_displacementWeights', Type.FLOAT4, UBOMorph.MAX_MORPH_TARGET_COUNT / 4); this.setUniform(morphDB, 'cc_displacementTextureInfo', Type.FLOAT4, 1); } else if (blockName === 'CCSkinningTexture') { - const skinningTexDB: UniformBlock = this.getUniformBlock('CCSkinningTexture', localUniformTarget); + const skinningTexDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOSkinningTexture.BINDING, 'CCSkinningTexture', localUniformTarget); this.setUniform(skinningTexDB, 'cc_jointTextureInfo', Type.FLOAT4, 1); } else if (blockName === 'CCSkinningAnimation') { - const skinningAnimDB: UniformBlock = this.getUniformBlock('CCSkinningAnimation', localUniformTarget); + const skinningAnimDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOSkinningAnimation.BINDING, 'CCSkinningAnimation', localUniformTarget); this.setUniform(skinningAnimDB, 'cc_jointAnimInfo', Type.FLOAT4, 1); } else if (blockName === 'CCSkinning') { - const skinningDB: UniformBlock = this.getUniformBlock('CCSkinning', localUniformTarget); + const skinningDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOSkinning.BINDING, 'CCSkinning', localUniformTarget); this.setUniform(skinningDB, 'cc_joints', Type.FLOAT4, JOINT_UNIFORM_CAPACITY * 3); } else if (blockName === 'CCUILocal') { - const uiDB: UniformBlock = this.getUniformBlock('CCUILocal', localUITarget); + const uiDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOUILocal.BINDING, 'CCUILocal', localUITarget); this.setUniform(uiDB, 'cc_local_data', Type.FLOAT4, 1); } else if (blockName === 'CCForwardLight') { - const lightDB: UniformBlock = this.getUniformBlock('CCForwardLight', localLightTarget); + const lightDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOForwardLight.BINDING, 'CCForwardLight', localLightTarget); this.setUniform(lightDB, 'cc_lightPos', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); this.setUniform(lightDB, 'cc_lightColor', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); this.setUniform(lightDB, 'cc_lightSizeRangeAngle', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); this.setUniform(lightDB, 'cc_lightDir', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); } else if (blockName === 'CCLocal') { - const localDB: UniformBlock = this.getUniformBlock('CCLocal', localModelTarget); + const localDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOLocal.BINDING, 'CCLocal', localModelTarget); this.setUniform(localDB, 'cc_matWorld', Type.MAT4, 1); this.setUniform(localDB, 'cc_matWorldIT', Type.MAT4, 1); this.setUniform(localDB, 'cc_lightingMapUVParam', Type.FLOAT4, 1); } else if (blockName === 'CCLocalBatched') { - const batchDB: UniformBlock = this.getUniformBlock('CCLocalBatched', localModelTarget); + const batchDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOLocalBatched.BINDING, 'CCLocalBatched', localModelTarget); this.setUniform(batchDB, 'cc_matWorlds', Type.MAT4, UBOLocalBatched.BATCHING_COUNT); } else if (blockName === 'CCWorldBound') { - const boundDB: UniformBlock = this.getUniformBlock('CCWorldBound', localModelTarget); + const boundDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOWorldBound.BINDING, 'CCWorldBound', localModelTarget); this.setUniform(boundDB, 'cc_worldBoundCenter', Type.FLOAT4, 1); this.setUniform(boundDB, 'cc_worldBoundHalfExtents', Type.FLOAT4, 1); } @@ -292,13 +316,16 @@ export class WebDescriptorHierarchy { this.merge(queueDB); this.sort(queueDB); - dbsToMerge.push(queueDB); + + const parentDB: DescriptorDB = this._layoutGraph.getDescriptors(parent); + if (this.dbsToMerge.get(parentDB) === undefined) { + this.dbsToMerge.set(parentDB, []); + } + this.dbsToMerge.get(parentDB)?.push(queueDB); } } public addGlobal (vName: string, hasCCGlobal, hasCCCamera, hasCCShadow, hasShadowmap, hasEnv, hasDiffuse, hasSpot): number { - const dbsToMerge: DescriptorDB[] = []; - const passDB: DescriptorDB = new DescriptorDB(); // Add pass layout from define.ts const globalUniformTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_PASS, @@ -307,14 +334,18 @@ export class WebDescriptorHierarchy { ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.FRAGMENT, passDB); if (hasCCGlobal) { - const globalDB: UniformBlock = this.getUniformBlock('CCGlobal', globalUniformTarget); + const globalDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, + UBOGlobal.BINDING, 'CCGlobal', globalUniformTarget); this.setUniform(globalDB, 'cc_time', Type.FLOAT4, 1); this.setUniform(globalDB, 'cc_screenSize', Type.FLOAT4, 1); this.setUniform(globalDB, 'cc_nativeSize', Type.FLOAT4, 1); + + this.setDescriptor(globalUniformTarget, 'CCGlobal', Type.UNKNOWN); } if (hasCCCamera) { - const cameraDB: UniformBlock = this.getUniformBlock('CCCamera', globalUniformTarget); + const cameraDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, + UBOCamera.BINDING, 'CCCamera', globalUniformTarget); this.setUniform(cameraDB, 'cc_matView', Type.MAT4, 1); this.setUniform(cameraDB, 'cc_matViewInv', Type.MAT4, 1); this.setUniform(cameraDB, 'cc_matProj', Type.MAT4, 1); @@ -334,10 +365,13 @@ export class WebDescriptorHierarchy { this.setUniform(cameraDB, 'cc_fogAdd', Type.FLOAT4, 1); this.setUniform(cameraDB, 'cc_nearFar', Type.FLOAT4, 1); this.setUniform(cameraDB, 'cc_viewPort', Type.FLOAT4, 1); + + this.setDescriptor(globalUniformTarget, 'CCCamera', Type.UNKNOWN); } if (hasCCShadow) { - const shadowDB: UniformBlock = this.getUniformBlock('CCShadow', globalUniformTarget); + const shadowDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, + UBOShadow.BINDING, 'CCShadow', globalUniformTarget); this.setUniform(shadowDB, 'cc_matLightPlaneProj', Type.MAT4, 1); this.setUniform(shadowDB, 'cc_matLightView', Type.MAT4, 1); this.setUniform(shadowDB, 'cc_matLightViewProj', Type.MAT4, 1); @@ -348,6 +382,8 @@ export class WebDescriptorHierarchy { this.setUniform(shadowDB, 'cc_shadowWHPBInfo', Type.FLOAT4, 1); this.setUniform(shadowDB, 'cc_shadowLPNNInfo', Type.FLOAT4, 1); this.setUniform(shadowDB, 'cc_shadowColor', Type.FLOAT4, 1); + + this.setDescriptor(globalUniformTarget, 'CCShadow', Type.UNKNOWN); } if (hasShadowmap) { @@ -363,18 +399,142 @@ export class WebDescriptorHierarchy { this.setDescriptor(globalSamplerTexTarget, 'cc_spotShadowMap', Type.SAMPLER2D); } - const vid = this._layoutGraph.addVertex(LayoutGraphValue.RenderStage, LayoutGraphValue.RenderStage, vName, passDB); - - //this.mergeDBs(dbsToMerge, passDB); this.merge(passDB); - this.sort(passDB); + + const vid = this._layoutGraph.addVertex( + LayoutGraphValue.RenderStage, RenderPassStage.DEFAULT, vName, passDB, + ); return vid; } - private _layoutGraph: LayoutGraph; + public mergeDescriptors (vid: number) { + const target: DescriptorDB = this._layoutGraph.getDescriptors(vid); + const toMerge = this.dbsToMerge.get(target); + if (toMerge !== undefined) { + this.mergeDBs(toMerge, target); + this.sort(target); + } + } + + public addRenderStage (name: string, stageID: number): number { + const passDB: DescriptorDB = new DescriptorDB(); + return this._layoutGraph.addVertex(LayoutGraphValue.RenderStage, + stageID, name, passDB); + } + + public addRenderPhase (name: string, parentStageID: number): number { + const passDB: DescriptorDB = new DescriptorDB(); + return this._layoutGraph.addVertex(LayoutGraphValue.RenderPhase, + new RenderPhase(), name, passDB, parentStageID); + } + + public _layoutGraph: LayoutGraph; public get layoutGraph () { return this._layoutGraph; } } + +function getNumDescriptors (block: DescriptorBlock): number { + let count = 0; + for (const [, d] of block.descriptors) { + count += d.count; + } + return count; +} + +function checkDescriptorConsistency (lhs: Descriptor, rhs: Descriptor): boolean { + if (lhs.type !== rhs.type) { + return false; + } + if (lhs.count !== rhs.count) { + return false; + } + return true; +} + +export class CollectVisitor extends DefaultVisitor { + getFrequency (g: LayoutGraph, v: number): UpdateFrequency { + let freq: UpdateFrequency; + if (g.holds(LayoutGraphValue.RenderStage, v)) { + freq = UpdateFrequency.PER_PASS; + } else { + assert(g.holds(LayoutGraphValue.RenderPhase, v)); + freq = UpdateFrequency.PER_QUEUE; + } + return freq; + } + + mergeDescriptors (srcBlock: DescriptorBlock, dstBlock: DescriptorBlock): string { + for (const [name, src] of srcBlock.descriptors) { + const dst = dstBlock.descriptors.get(name); + if (dst !== undefined) { + if (!checkDescriptorConsistency(src, dst)) { + return `Descriptor ${name} is inconsistent`; + } + } else { + dstBlock.descriptors.set(name, src); + } + } + return ''; + } + + mergeParent (freq: UpdateFrequency, src: DescriptorDB, dst: DescriptorDB): string { + for (const [key, srcBlock] of src.blocks) { + let dstBlock = dst.blocks.get(key); + if (dstBlock === undefined) { + dstBlock = new DescriptorBlock(); + dst.blocks.set(key, dstBlock); + } + const index = JSON.parse(key) as DescriptorBlockIndex; + if (index.updateFrequency > freq) { + const error = this.mergeDescriptors(srcBlock, dstBlock); + if (error) { + return error; + } + } + } + return ''; + } + + updateInfo (freq: UpdateFrequency, db: DescriptorDB) { + db.blocks.forEach((block: DescriptorBlock, key: string) => { + const index = JSON.parse(key) as DescriptorBlockIndex; + if (index.updateFrequency >= freq) { + block.count = getNumDescriptors(block); + block.capacity = block.count; + } + }); + } + + backEdge (e: edge_descriptor, g: LayoutGraph): void { + this._error = 'Cycle detected in graph'; + } + + finishEdge (e: edge_descriptor, g: LayoutGraph): void { + if (this._error !== '') { + return; + } + const parentID = g.source(e); + const v = g.target(e); + const dst = g.getDescriptors(parentID); + const src = g.getDescriptors(v); + const freq = this.getFrequency(g, v); + this.mergeParent(freq, src, dst); + } + + finishVertex (v: number, g: LayoutGraph): void { + if (this._error !== '') { + return; + } + const freq = this.getFrequency(g, v); + const db = g.getDescriptors(v); + this.updateInfo(freq, db); + } + + get error (): string { + return this._error; + } + private _error = ''; +} diff --git a/cocos/core/pipeline/custom/web-layout-graph.ts b/cocos/core/pipeline/custom/web-layout-graph.ts index 2c98b15234..7dc864e8b4 100644 --- a/cocos/core/pipeline/custom/web-layout-graph.ts +++ b/cocos/core/pipeline/custom/web-layout-graph.ts @@ -1,10 +1,188 @@ +import { DEBUG } from 'internal:constants'; // eslint-disable-next-line max-len -import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, ShaderStageFlagBit } from '../../gfx'; +import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx'; +import { VectorGraphColorMap } from './effect'; +import { DefaultVisitor, depthFirstSearch, GraphColor, MutableVertexPropertyMap } from './graph'; // eslint-disable-next-line max-len -import { DescriptorBlock, DescriptorBlockIndex, LayoutGraphData, PipelineLayoutData, LayoutGraphDataValue, RenderStageData, RenderPhaseData, DescriptorTypeOrder, DescriptorSetLayoutData, DescriptorSetData, DescriptorBlockData, Descriptor, DescriptorData, getDescriptorTypeOrderName, DescriptorBlockFlattened } from './layout-graph'; +import { DescriptorBlockIndex, LayoutGraphData, PipelineLayoutData, LayoutGraphDataValue, RenderStageData, RenderPhaseData, DescriptorTypeOrder, DescriptorSetLayoutData, DescriptorSetData, DescriptorBlockData, Descriptor, DescriptorData, getDescriptorTypeOrderName, DescriptorBlockFlattened } from './layout-graph'; import { LayoutGraphBuilder } from './pipeline'; import { getUpdateFrequencyName, UpdateFrequency } from './types'; +function getName (type: Type): string { + switch (type) { + case Type.UNKNOWN: return 'Unknown'; + case Type.BOOL: return 'Bool'; + case Type.BOOL2: return 'Bool2'; + case Type.BOOL3: return 'Bool3'; + case Type.BOOL4: return 'Bool4'; + case Type.INT: return 'Int'; + case Type.INT2: return 'Int2'; + case Type.INT3: return 'Int3'; + case Type.INT4: return 'Int4'; + case Type.UINT: return 'Uint'; + case Type.UINT2: return 'Uint2'; + case Type.UINT3: return 'Uint3'; + case Type.UINT4: return 'Uint4'; + case Type.FLOAT: return 'Float'; + case Type.FLOAT2: return 'Float2'; + case Type.FLOAT3: return 'Float3'; + case Type.FLOAT4: return 'Float4'; + case Type.MAT2: return 'Mat2'; + case Type.MAT2X3: return 'Mat2x3'; + case Type.MAT2X4: return 'Mat2x4'; + case Type.MAT3X2: return 'Mat3x2'; + case Type.MAT3: return 'Mat3'; + case Type.MAT3X4: return 'Mat3x4'; + case Type.MAT4X2: return 'Mat4x2'; + case Type.MAT4X3: return 'Mat4x3'; + case Type.MAT4: return 'Mat4'; + case Type.SAMPLER1D: return 'Sampler1D'; + case Type.SAMPLER1D_ARRAY: return 'Sampler1DArray'; + case Type.SAMPLER2D: return 'Sampler2D'; + case Type.SAMPLER2D_ARRAY: return 'Sampler2DArray'; + case Type.SAMPLER3D: return 'Sampler3D'; + case Type.SAMPLER_CUBE: return 'SamplerCube'; + case Type.SAMPLER: return 'Sampler'; + case Type.TEXTURE1D: return 'Texture1D'; + case Type.TEXTURE1D_ARRAY: return 'Texture1DArray'; + case Type.TEXTURE2D: return 'Texture2D'; + case Type.TEXTURE2D_ARRAY: return 'Texture2DArray'; + case Type.TEXTURE3D: return 'Texture3D'; + case Type.TEXTURE_CUBE: return 'TextureCube'; + case Type.IMAGE1D: return 'Image1D'; + case Type.IMAGE1D_ARRAY: return 'Image1DArray'; + case Type.IMAGE2D: return 'Image2D'; + case Type.IMAGE2D_ARRAY: return 'Image2DArray'; + case Type.IMAGE3D: return 'Image3D'; + case Type.IMAGE_CUBE: return 'ImageCube'; + case Type.SUBPASS_INPUT: return 'SubpassInput'; + case Type.COUNT: return 'Count'; + default: return 'Unknown'; + } +} + +function hasFlag (flags: ShaderStageFlagBit, flagToTest: ShaderStageFlagBit): boolean { + return (flags & flagToTest) !== 0; +} + +function getVisibilityName (stage: ShaderStageFlagBit): string { + let count = 0; + let str = ''; + if (hasFlag(stage, ShaderStageFlagBit.VERTEX)) { + if (count++) { + str += ' | '; + } + str += 'Vertex'; + } + if (hasFlag(stage, ShaderStageFlagBit.CONTROL)) { + if (count++) { + str += ' | '; + } + str += 'Control'; + } + if (hasFlag(stage, ShaderStageFlagBit.EVALUATION)) { + if (count++) { + str += ' | '; + } + str += 'Evaluation'; + } + if (hasFlag(stage, ShaderStageFlagBit.GEOMETRY)) { + if (count++) { + str += ' | '; + } + str += 'Geometry'; + } + if (hasFlag(stage, ShaderStageFlagBit.FRAGMENT)) { + if (count++) { + str += ' | '; + } + str += 'Fragment'; + } + if (hasFlag(stage, ShaderStageFlagBit.COMPUTE)) { + if (count++) { + str += ' | '; + } + str += 'Compute'; + } + if (stage === ShaderStageFlagBit.ALL) { + if (count++) { + str += ' | '; + } + str += 'All'; + } + return str; +} + +class PrintVisitor extends DefaultVisitor { + discoverVertex (u: number, g: LayoutGraphData) { + const ppl: PipelineLayoutData = g.getLayout(u); + const name: string = g._names[u]; + const freq: UpdateFrequency = g._updateFrequencies[u]; + this.oss += `${this.space}"${name}": `; + if (g.holds(LayoutGraphDataValue.RenderStage, u)) { + this.oss += `RenderStage {\n`; + } else { + this.oss += `RenderPhase {\n`; + } + this.space += ' '; + + // eslint-disable-next-line no-loop-func + ppl.descriptorSets.forEach((value, key) => { + this.oss += `${this.space}DescriptorSet<${getUpdateFrequencyName(key)}> {\n`; + this.space += ' '; + const uniformBlocks = value.descriptorSetLayoutData.uniformBlocks; + uniformBlocks.forEach((uniformBlock, attrNameID) => { + const name = g.valueNames[attrNameID]; + this.oss += `${this.space}UniformBlock "${name}" {\n`; + for (const u of uniformBlock.members) { + if (u.count > 1) { + this.oss += `${this.space} ${u.name}[${u.count}]: ${getName(u.type)}\n`; + } else { + this.oss += `${this.space} ${u.name}: ${getName(u.type)}\n`; + } + } + this.oss += `${this.space}}\n`; + }); + + const blocks = value.descriptorSetLayoutData.descriptorBlocks; + for (let j = 0; j < blocks.length; ++j) { + const block = blocks[j]; + this.oss += `${this.space}Block<${getDescriptorTypeOrderName(block.type)}, ${getVisibilityName(block.visibility)}> {\n`; + this.oss += `${this.space} capacity: ${block.capacity}\n`; + this.oss += `${this.space} count: ${block.descriptors.length}\n`; + if (block.descriptors.length > 0) { + this.oss += `${this.space} Descriptors{ \n`; + const count = 0; + for (let k = 0; k < block.descriptors.length; ++k) { + const d: DescriptorData = block.descriptors[k]; + // if (count++) { + this.oss += this.space; + this.oss += ' '; + const n: string = g.valueNames[d.descriptorID]; + this.oss += `"${n}`; + if (d.count !== 1) { + this.oss += `[${d.count}]`; + } + this.oss += '"'; + // } + this.oss += '\n'; + } + this.oss += `${this.space} }\n`; + } + this.oss += `${this.space}}\n`; + } + this.space = this.space.substring(0, this.space.length - 4); + this.oss += `${this.space}}\n`; + }); + } + finishVertex (v: number, g: LayoutGraphData) { + this.space = this.space.substring(0, this.space.length - 4); + this.oss += `${this.space}}\n`; + } + space = ''; + oss = ''; +} + export class WebLayoutGraphBuilder extends LayoutGraphBuilder { private _data: LayoutGraphData; private _device: Device; @@ -15,13 +193,6 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { this._data = dataIn; } - private add_vertex (g: LayoutGraphData, tag: T, object, name: string, parentID = 0xFFFFFFFF): number { - const layouts: PipelineLayoutData = new PipelineLayoutData(); - // eslint-disable-next-line max-len - layouts.descriptorSets.set(UpdateFrequency.PER_INSTANCE, new DescriptorSetData(new DescriptorSetLayoutData(), null, null)); - return g.addVertex(tag, object, name, UpdateFrequency.PER_INSTANCE, layouts, parentID); - } - private getGfxType (type: DescriptorTypeOrder): DescriptorType | null { switch (type) { case DescriptorTypeOrder.UNIFORM_BUFFER: @@ -48,58 +219,6 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { } } - private hasFlag (flags, flagToTest): boolean { - return (flags & flagToTest) !== 0; - } - - private getName (stage: ShaderStageFlagBit): string { - let count = 0; - let str = ''; - if (this.hasFlag(stage, ShaderStageFlagBit.VERTEX)) { - if (count++) { - str += ' | '; - } - str += 'Vertex'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.CONTROL)) { - if (count++) { - str += ' | '; - } - str += 'Control'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.EVALUATION)) { - if (count++) { - str += ' | '; - } - str += 'Evaluation'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.GEOMETRY)) { - if (count++) { - str += ' | '; - } - str += 'Geometry'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.FRAGMENT)) { - if (count++) { - str += ' | '; - } - str += 'Fragment'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.COMPUTE)) { - if (count++) { - str += ' | '; - } - str += 'Compute'; - } - if (stage === ShaderStageFlagBit.ALL) { - if (count++) { - str += ' | '; - } - str += 'All'; - } - return str; - } - private createDescriptorSetLayout (layoutData: DescriptorSetLayoutData) { const info: DescriptorSetLayoutInfo = new DescriptorSetLayoutInfo(); for (let i = 0; i < layoutData.descriptorBlocks.length; ++i) { @@ -128,11 +247,16 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { } public addRenderStage (name: string): number { - return this.add_vertex(this._data, LayoutGraphDataValue.RenderStage, new RenderStageData(), name); + return this._data.addVertex(LayoutGraphDataValue.RenderStage, + new RenderStageData(), name, + UpdateFrequency.PER_PASS, new PipelineLayoutData()); } public addRenderPhase (name: string, parentID: number): number { - return this.add_vertex(this._data, LayoutGraphDataValue.RenderPhase, new RenderPhaseData(), name, parentID); + return this._data.addVertex(LayoutGraphDataValue.RenderPhase, + new RenderPhaseData(), name, + UpdateFrequency.PER_QUEUE, new PipelineLayoutData(), + parentID); } public addShader (name: string, parentPhaseID: number): void { @@ -154,30 +278,49 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { console.error('error uniform'); return; } + let data: DescriptorSetData | undefined = ppl.descriptorSets.get(index.updateFrequency); + if (!data) { + data = new DescriptorSetData(new DescriptorSetLayoutData(), null, null); + ppl.descriptorSets.set(index.updateFrequency, data); + } + const layout = data.descriptorSetLayoutData; + + const dstBlock = new DescriptorBlockData(index.descriptorType, index.visibility, block.capacity); + layout.descriptorBlocks.push(dstBlock); + dstBlock.offset = layout.capacity; + dstBlock.capacity = block.capacity; + for (let j = 0; j < block.descriptors.length; ++j) { + const name: string = block.descriptorNames[j]; + const d: Descriptor = block.descriptors[j]; + let nameID: number | undefined = g.attributeIndex.get(name); + if (nameID === undefined) { + const id = g.valueNames.length; + g.attributeIndex.set(name, id); + g.valueNames.push(name); + } + + nameID = g.attributeIndex.get(name); + const data: DescriptorData = new DescriptorData(nameID); + data.count = d.count; + dstBlock.descriptors.push(data); + } + layout.capacity += block.capacity; + } + + public addUniformBlock (nodeID: number, index: DescriptorBlockIndex, name: string, uniformBlock: UniformBlock): void { + const g: LayoutGraphData = this._data; + const ppl: PipelineLayoutData = g.getLayout(nodeID); const layout: DescriptorSetLayoutData | undefined = ppl.descriptorSets.get(index.updateFrequency)?.descriptorSetLayoutData; if (layout !== undefined) { - const dstBlock = new DescriptorBlockData(index.descriptorType, index.visibility, block.capacity); - layout.descriptorBlocks.push(dstBlock); - dstBlock.offset = layout.capacity; - dstBlock.capacity = block.capacity; - for (let j = 0; j < block.descriptors.length; ++j) { - const name: string = block.descriptorNames[j]; - const d: Descriptor = block.descriptors[j]; - let nameID: number | undefined = g.attributeIndex.get(name); - if (nameID === undefined) { - const id = g.valueNames.length; - g.attributeIndex.set(name, id); - g.valueNames.push(name); - } - - nameID = g.attributeIndex.get(name); - const data: DescriptorData = new DescriptorData(nameID); - data.count = d.count; - dstBlock.descriptors.push(data); + let nameID: number | undefined = g.attributeIndex.get(name); + if (nameID === undefined) { + const id = g.valueNames.length; + g.attributeIndex.set(name, id); + g.valueNames.push(name); } - layout.capacity += block.capacity; - } else { - console.error('no layout'); + + nameID = g.attributeIndex.get(name); + layout.uniformBlocks.set(nameID as number, uniformBlock); } } @@ -213,54 +356,18 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { level.descriptorSet = (this._device.createDescriptorSet(new DescriptorSetInfo(layout))); }); } - + if (DEBUG) { + console.log(this.print()); + } return 0; } public print (): string { - let oss = ''; const g: LayoutGraphData = this._data; - for (let i = 0; i < g._layouts.length; ++i) { - const ppl: PipelineLayoutData = g.getLayout(i); - const name: string = g._names[i]; - const freq: UpdateFrequency = g._updateFrequencies[i]; - - oss += `"${name}": `; - oss += `<${getUpdateFrequencyName(freq)}> {\n`; - - // eslint-disable-next-line no-loop-func - ppl.descriptorSets.forEach((value, key) => { - oss += `Set<${getUpdateFrequencyName(key)}> {\n`; - const blocks = value.descriptorSetLayoutData.descriptorBlocks; - for (let j = 0; j < blocks.length; ++j) { - const block = blocks[j]; - oss += `Block<${getDescriptorTypeOrderName(block.type)}, ${this.getName(block.visibility)}> {\n`; - oss += `capacity: ${block.capacity},\n`; - oss += `count: ${block.descriptors.length},\n`; - if (block.descriptors.length > 0) { - oss += 'Descriptors{ \n'; - const count = 0; - for (let k = 0; k < block.descriptors.length; ++k) { - const d: DescriptorData = block.descriptors[k]; - // if (count++) { - oss += ' '; - const n: string = g.valueNames[d.descriptorID]; - oss += `"${n}`; - if (d.count !== 1) { - oss += `[${d.count}]`; - } - oss += '"'; - // } - oss += '\n'; - } - oss += ' }\n'; - } - oss += '}\n'; - } - oss += '}\n'; - }); - } - return oss; + const visitor = new PrintVisitor(); + const colorMap = new VectorGraphColorMap(g.numVertices()); + depthFirstSearch(g, visitor, colorMap); + return visitor.oss; } public get data () { diff --git a/cocos/core/pipeline/custom/web-pipeline.ts b/cocos/core/pipeline/custom/web-pipeline.ts index 513867c09f..441a81f811 100644 --- a/cocos/core/pipeline/custom/web-pipeline.ts +++ b/cocos/core/pipeline/custom/web-pipeline.ts @@ -25,13 +25,13 @@ /* eslint-disable max-len */ import { systemInfo } from 'pal/system-info'; -import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, StoreOp, LoadOp, ClearFlagBit, DescriptorSet, deviceManager } from '../../gfx/index'; +import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, StoreOp, LoadOp, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer } from '../../gfx/index'; import { Mat4, Quat, Vec2, Vec4 } from '../../math'; -import { QueueHint, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; -import { AccessType, AttachmentType, Blit, ComputePass, ComputeView, CopyPair, CopyPass, Dispatch, ManagedResource, MovePair, MovePass, PresentPass, RasterPass, RasterView, RenderData, RenderGraph, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData } from './render-graph'; -import { ComputePassBuilder, ComputeQueueBuilder, CopyPassBuilder, LayoutGraphBuilder, MovePassBuilder, Pipeline, RasterPassBuilder, RasterQueueBuilder, SceneTask, SceneTransversal, SceneVisitor, Setter } from './pipeline'; +import { ComputeView, LightInfo, LightingMode, QueueHint, RasterView, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; +import { Blit, ClearView, ComputePass, CopyPair, CopyPass, Dispatch, ManagedResource, MovePair, MovePass, PresentPass, RasterPass, RenderData, RenderGraph, RenderGraphComponent, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData } from './render-graph'; +import { ComputePassBuilder, ComputeQueueBuilder, CopyPassBuilder, LayoutGraphBuilder, MovePassBuilder, Pipeline, PipelineBuilder, RasterPassBuilder, RasterQueueBuilder, SceneTask, SceneTransversal, SceneVisitor, Setter } from './pipeline'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { Model, Camera, SKYBOX_FLAG, Light, LightType, ShadowType, DirectionalLight, Shadows } from '../../renderer/scene'; +import { Model, Camera, Light } from '../../renderer/scene'; import { legacyCC } from '../../global-exports'; import { LayoutGraphData } from './layout-graph'; import { Executor } from './executor'; @@ -43,13 +43,15 @@ import { MacroRecord, RenderScene } from '../../renderer'; import { GlobalDSManager } from '../global-descriptor-set-manager'; import { supportsR32FloatTexture, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from '../define'; import { OS } from '../../../../pal/system-info/enum-type'; -import { WebDescriptorHierarchy } from './web-descriptor-hierarchy'; import { Compiler } from './compiler'; -import { PipelineUBO } from './ubos'; +import { PipelineUBO } from '../pipeline-ubo'; import { builtinResMgr } from '../../builtin/builtin-res-mgr'; import { Texture2D } from '../../assets/texture-2d'; import { WebLayoutGraphBuilder } from './web-layout-graph'; import { GeometryRenderer } from '../geometry-renderer'; +import { Material } from '../../assets'; +import { DeferredPipelineBuilder, ForwardPipelineBuilder } from './builtin-pipelines'; +import { RenderGraphPrintVisitor } from './debug'; export class WebSetter { constructor (data: RenderData) { @@ -125,6 +127,17 @@ function setCameraValues (setter: Setter, setter.setVec4('cc_viewPort', new Vec4(camera.viewport.x, camera.viewport.y, camera.viewport.z, camera.viewport.w)); } +function getFirstChildLayoutName (lg: LayoutGraphData, parentID: number): string { + if (lg.numVertices() && parentID !== 0xFFFFFFFF && lg.numChildren(parentID)) { + const childNodes = lg.children(parentID); + if (childNodes.next().value && childNodes.next().value.target !== lg.nullVertex()) { + const ququeLayoutID = childNodes.next().value.target; + return lg.getName(ququeLayoutID); + } + } + return ''; +} + export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuilder { constructor (data: RenderData, renderGraph: RenderGraph, vertID: number, queue: RenderQueue, pipeline: PipelineSceneData) { super(data); @@ -133,10 +146,9 @@ export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuild this._queue = queue; this._pipeline = pipeline; } - addSceneOfCamera (camera: Camera, light: Light | null, sceneFlags: SceneFlags, name = 'Camera'): void { - const sceneData = new SceneData(name, sceneFlags); + addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags: SceneFlags, name = 'Camera'): void { + const sceneData = new SceneData(name, sceneFlags, light); sceneData.camera = camera; - sceneData.light = light; this._renderGraph.addVertex( RenderGraphValue.Scene, sceneData, name, '', new RenderData(), false, this._vertID, ); @@ -149,9 +161,28 @@ export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuild RenderGraphValue.Scene, sceneData, sceneName, '', new RenderData(), false, this._vertID, ); } - addFullscreenQuad (shader: string, layoutName = '', name = 'Quad'): void { + addFullscreenQuad (material: Material, sceneFlags = SceneFlags.NONE, name = 'Quad'): void { this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(shader), name, '', new RenderData(), false, this._vertID, + RenderGraphValue.Blit, new Blit(material, sceneFlags, null), + name, '', new RenderData(), false, this._vertID, + ); + } + addCameraQuad (camera: Camera, material: Material, sceneFlags: SceneFlags) { + this._renderGraph.addVertex( + RenderGraphValue.Blit, new Blit(material, sceneFlags, camera), + 'CameraQuad', '', new RenderData(), false, this._vertID, + ); + } + clearRenderTarget (name: string, color: Color) { + this._renderGraph.addVertex( + RenderGraphValue.Clear, [new ClearView(name, ClearFlagBit.COLOR, color)], + 'ClearRenderTarget', '', new RenderData(), false, this._vertID, + ); + } + setViewport (viewport: Viewport) { + this._renderGraph.addVertex( + RenderGraphValue.Viewport, viewport, + 'Viewport', '', new RenderData(), false, this._vertID, ); } private readonly _renderGraph: RenderGraph; @@ -161,12 +192,18 @@ export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuild } export class WebRasterPassBuilder extends WebSetter implements RasterPassBuilder { - constructor (data: RenderData, renderGraph: RenderGraph, vertID: number, pass: RasterPass, pipeline: PipelineSceneData) { + constructor (data: RenderData, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, vertID: number, pass: RasterPass, pipeline: PipelineSceneData) { super(data); this._renderGraph = renderGraph; + this._layoutGraph = layoutGraph; this._vertID = vertID; this._pass = pass; this._pipeline = pipeline; + + const layoutName = this._renderGraph.component( + RenderGraphComponent.Layout, this._vertID, + ); + this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } addRasterView (name: string, view: RasterView) { this._pass.rasterViews.set(name, view); @@ -178,40 +215,49 @@ export class WebRasterPassBuilder extends WebSetter implements RasterPassBuilder this._pass.computeViews.set(name, [view]); } } - addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, layoutName = '', name = 'Queue') { - if (layoutName === '') { - switch (hint) { - case QueueHint.RENDER_OPAQUE: - layoutName = 'Opaque'; - break; - case QueueHint.RENDER_CUTOUT: - layoutName = 'Cutout'; - break; - case QueueHint.RENDER_TRANSPARENT: - layoutName = 'Transparent'; - break; - default: - throw Error('cannot infer layoutName from QueueHint'); - } - } + + addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, name = 'Queue') { const queue = new RenderQueue(hint); const data = new RenderData(); const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, name, layoutName, data, false, this._vertID, + RenderGraphValue.Queue, queue, name, '', data, false, this._vertID, ); return new WebRasterQueueBuilder(data, this._renderGraph, queueID, queue, this._pipeline); } - addFullscreenQuad (shader: string, layoutName = '', name = 'Quad') { - this._renderGraph.addVertex( - RenderGraphValue.Blit, - new Blit(shader), - name, layoutName, new RenderData(), false, this._vertID, + + addFullscreenQuad (material: Material, sceneFlags = SceneFlags.NONE, name = 'FullscreenQuad') { + const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); + const queueId = this._renderGraph.addVertex( + RenderGraphValue.Queue, queue, + 'Queue', '', new RenderData(), + false, this._vertID, ); + this._renderGraph.addVertex( + RenderGraphValue.Blit, new Blit(material, sceneFlags, null), + name, '', new RenderData(), false, queueId, + ); + } + + addCameraQuad (camera: Camera, material: Material, sceneFlags: SceneFlags, name = 'CameraQuad') { + const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); + const queueId = this._renderGraph.addVertex( + RenderGraphValue.Queue, queue, + 'Queue', '', new RenderData(), false, this._vertID, + ); + this._renderGraph.addVertex( + RenderGraphValue.Blit, new Blit(material, sceneFlags, camera), + name, '', new RenderData(), false, queueId, + ); + } + setViewport (viewport: Viewport): void { + this._pass.viewport.copy(viewport); } private readonly _renderGraph: RenderGraph; private readonly _vertID: number; + private readonly _layoutID: number; private readonly _pass: RasterPass; private readonly _pipeline: PipelineSceneData; + private readonly _layoutGraph: LayoutGraphData; } export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBuilder { @@ -226,12 +272,11 @@ export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBui threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, - layoutName = '', name = 'Dispatch') { this._renderGraph.addVertex( RenderGraphValue.Dispatch, new Dispatch(shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ), - name, layoutName, new RenderData(), false, this._vertID, + name, '', new RenderData(), false, this._vertID, ); } private readonly _renderGraph: RenderGraph; @@ -241,12 +286,18 @@ export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBui } export class WebComputePassBuilder extends WebSetter implements ComputePassBuilder { - constructor (data: RenderData, renderGraph: RenderGraph, vertID: number, pass: ComputePass, pipeline: PipelineSceneData) { + constructor (data: RenderData, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, vertID: number, pass: ComputePass, pipeline: PipelineSceneData) { super(data); this._renderGraph = renderGraph; + this._layoutGraph = layoutGraph; this._vertID = vertID; this._pass = pass; this._pipeline = pipeline; + + const layoutName = this._renderGraph.component( + RenderGraphComponent.Layout, this._vertID, + ); + this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } addComputeView (name: string, view: ComputeView) { if (this._pass.computeViews.has(name)) { @@ -255,11 +306,11 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild this._pass.computeViews.set(name, [view]); } } - addQueue (layoutName = '', name = 'Queue') { + addQueue (name = 'Queue') { const queue = new RenderQueue(); const data = new RenderData(); const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, name, layoutName, data, false, this._vertID, + RenderGraphValue.Queue, queue, name, '', data, false, this._vertID, ); return new WebComputeQueueBuilder(data, this._renderGraph, queueID, queue, this._pipeline); } @@ -267,16 +318,17 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, - layoutName = '', name = 'Dispatch') { this._renderGraph.addVertex( RenderGraphValue.Dispatch, new Dispatch(shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ), - name, layoutName, new RenderData(), false, this._vertID, + name, '', new RenderData(), false, this._vertID, ); } private readonly _renderGraph: RenderGraph; + private readonly _layoutGraph: LayoutGraphData; private readonly _vertID: number; + private readonly _layoutID: number; private readonly _pass: ComputePass; private readonly _pipeline: PipelineSceneData; } @@ -317,6 +369,39 @@ function isManaged (residency: ResourceResidency): boolean { } export class WebPipeline extends Pipeline { + public get device (): Device { + return this._device; + } + public containsResource (name: string): boolean { + return this._resourceGraph.contains(name); + } + public addComputePass(layoutName: string, name: string): ComputePassBuilder; + public addComputePass(layoutName: string): ComputePassBuilder; + public addComputePass (layoutName: any, name?: any): ComputePassBuilder { + throw new Error('Method not implemented.'); + } + public addMovePass (name: string): MovePassBuilder { + throw new Error('Method not implemented.'); + } + public addCopyPass (name: string): CopyPassBuilder { + throw new Error('Method not implemented.'); + } + public presentAll (): void { + throw new Error('Method not implemented.'); + } + public get lightingMode (): LightingMode { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this._lightingMode; + } + public set lightingMode (mode: LightingMode) { + this._lightingMode = mode; + } + public createSceneTransversal (camera: Camera, scene: RenderScene): SceneTransversal { + throw new Error('Method not implemented.'); + } + public get layoutGraphBuilder (): LayoutGraphBuilder { + return new WebLayoutGraphBuilder(this._device, this._layoutGraph); + } protected _generateConstantMacros (clusterEnabled: boolean) { let str = ''; str += `#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE ${this._device.getFormatFeatures(Format.RGBA32F) @@ -333,21 +418,34 @@ export class WebPipeline extends Pipeline { public activate (swapchain: Swapchain): boolean { this._device = deviceManager.gfxDevice; this._globalDSManager = new GlobalDSManager(this._device); - this._macros.CC_USE_HDR = this._pipelineSceneData.isHDR; + this.setMacroBool('CC_USE_HDR', this._pipelineSceneData.isHDR); this._generateConstantMacros(false); this._pipelineSceneData.activate(this._device); - const descH = new WebDescriptorHierarchy(); - //descH.addEffect(new EffectAsset()); this._pipelineUBO.activate(this._device, this); + const isFloat = supportsR32FloatTexture(this._device) ? 0 : 1; + this.setMacroInt('CC_SHADOWMAP_FORMAT', isFloat); + // 0: SHADOWMAP_LINER_DEPTH_OFF, 1: SHADOWMAP_LINER_DEPTH_ON. + const isLinear = this._device.gfxAPI === API.WEBGL ? 1 : 0; + this.setMacroInt('CC_SHADOWMAP_USE_LINEAR_DEPTH', isLinear); + const root = legacyCC.director.root; + // enable the deferred pipeline + if (root.useDeferredPipeline) { + this.setMacroInt('CC_PIPELINE_TYPE', 1); + } const shadowMapSampler = this._globalDSManager.pointSampler; this.descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, shadowMapSampler); this.descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); this.descriptorSet.bindSampler(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, shadowMapSampler); this.descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); this.descriptorSet.update(); + this.layoutGraphBuilder.compile(); + + this._forward = new ForwardPipelineBuilder(); + this._deferred = new DeferredPipelineBuilder(); return true; } public destroy (): boolean { + this._globalDSManager?.globalDescriptorSet.destroy(); this._globalDSManager?.destroy(); this._pipelineSceneData?.destroy(); return true; @@ -364,6 +462,9 @@ export class WebPipeline extends Pipeline { public get descriptorSet (): DescriptorSet { return this._globalDSManager.globalDescriptorSet; } + public get commandBuffers (): CommandBuffer[] { + return [this._device.commandBuffer]; + } public get pipelineSceneData (): PipelineSceneData { return this._pipelineSceneData; } @@ -385,6 +486,27 @@ export class WebPipeline extends Pipeline { public set shadingScale (scale: number) { this._pipelineSceneData.shadingScale = scale; } + public getMacroString (name: string): string { + const str = this._macros[name]; + if (str === undefined) { + return ''; + } + return str as string; + } + public getMacroInt (name: string): number { + const value = this._macros[name]; + if (value === undefined) { + return 0; + } + return value as number; + } + public getMacroBool (name: string): boolean { + const value = this._macros[name]; + if (value === undefined) { + return false; + } + return value as boolean; + } public setMacroString (name: string, value: string): void { this._macros[name] = value; } @@ -394,9 +516,6 @@ export class WebPipeline extends Pipeline { public setMacroBool (name: string, value: boolean): void { this._macros[name] = value; } - public get device () { - return this._device; - } public onGlobalPipelineStateChanged (): void { // do nothing } @@ -438,7 +557,7 @@ export class WebPipeline extends Pipeline { desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.flags = ResourceFlags.COLOR_ATTACHMENT; + desc.flags = ResourceFlags.COLOR_ATTACHMENT | ResourceFlags.SAMPLED; assert(isManaged(residency)); return this._resourceGraph.addVertex( @@ -457,7 +576,7 @@ export class WebPipeline extends Pipeline { desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.flags = ResourceFlags.DEPTH_STENCIL_ATTACHMENT; + desc.flags = ResourceFlags.DEPTH_STENCIL_ATTACHMENT | ResourceFlags.SAMPLED; return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), @@ -488,133 +607,47 @@ export class WebPipeline extends Pipeline { throw new Error('Cannot run without creating rendergraph'); } if (!this._executor) { - this._executor = new Executor(this, this._pipelineUBO, this._device, this._resourceGraph); + this._executor = new Executor(this, this._pipelineUBO, this._device, + this._resourceGraph, this.layoutGraph, this.width, this.height); } this._executor.execute(this._renderGraph); } - protected _buildShadowPass (automata: WebPipeline, - light: Readonly, - shadows: Readonly, - passName: Readonly, - width: Readonly, - height: Readonly, - bCastShadow: Readonly) { - if (bCastShadow) { - if (!automata.resourceGraph.contains(this._dsShadowMap)) { - const format = supportsR32FloatTexture(this._device) ? Format.R32F : Format.RGBA8; - automata.addRenderTarget(this._dsShadowMap, format, width, height, ResourceResidency.PERSISTENT); - } - const pass = automata.addRasterPass(width, height, '_', passName); - pass.addRasterView(this._dsShadowMap, new RasterView('_', - AccessType.WRITE, AttachmentType.RENDER_TARGET, - LoadOp.CLEAR, StoreOp.STORE, - ClearFlagBit.COLOR, - new Color(0, 0, 0, 0))); - const queue = pass.addQueue(QueueHint.RENDER_OPAQUE); - queue.addScene(`${passName}_shadowScene`, - SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT | SceneFlags.SHADOW_CASTER); - // setCameraValues(queue, camera, light, shadows); - } - } - protected _buildShadowPasses (automata: WebPipeline, validLights: Light[], - mainLight: Readonly | null, - pplScene: Readonly, - name: Readonly): void { - const shadows = pplScene.shadows; - if (!shadows.enabled || shadows.type !== ShadowType.ShadowMap) { - return; - } - const castShadowObjects = pplScene.csmLayers.castShadowObjects; - const validPunctualLights = pplScene.validPunctualLights; - - // force clean up - validLights.length = 0; - - // pick spot lights - let numSpotLights = 0; - for (let i = 0; numSpotLights < shadows.maxReceived && i < validPunctualLights.length; ++i) { - const light = validPunctualLights[i]; - if (light.type === LightType.SPOT) { - validLights.push(light); - ++numSpotLights; - } - } - - // build shadow map - const bCastShadow = castShadowObjects.length !== 0; - const mapWidth = bCastShadow ? shadows.size.x : 1; - const mapHeight = bCastShadow ? shadows.size.y : 1; - - // main light - if (mainLight) { - const passName = `MainLightShadow${name}`; - this._buildShadowPass(automata, mainLight, shadows, - passName, mapWidth, mapHeight, bCastShadow); - } - // spot lights - for (let i = 0; i !== validLights.length; ++i) { - const passName = `SpotLight${i.toString()}Shadow${name}`; - this._buildShadowPass(automata, validLights[i], shadows, - passName, mapWidth, mapHeight, bCastShadow); - } - } - private readonly _validLights: Light[] = []; - private readonly _dsShadowMap = 'dsShadowMap'; - render (cameras: Camera[]) { - if (cameras.length === 0) { - return; - } + protected _applySize (cameras: Camera[]) { + let newWidth = this._width; + let newHeight = this._height; cameras.forEach((camera) => { + const window = camera.window; + newWidth = Math.max(window.width, newWidth); + newHeight = Math.max(window.height, newHeight); if (!this._cameras.includes(camera)) { this._cameras.push(camera); } }); + if (newWidth !== this._width || newHeight !== this._height) { + this._width = newWidth; + this._height = newHeight; + } + } + + private _width = 0; + private _height = 0; + get width () { return this._width; } + get height () { return this._height; } + render (cameras: Camera[]) { + if (cameras.length === 0) { + return; + } + this._applySize(cameras); // build graph this.beginFrame(); - for (let i = 0; i < cameras.length; i++) { - const camera = cameras[i]; - if (camera.scene) { - const idx = this._cameras.indexOf(camera); - this._buildShadowPasses(this, this._validLights, - camera.scene.mainLight, - this._pipelineSceneData, - `Camera${idx}`); - - const window = camera.window; - const width = Math.floor(window.width); - const height = Math.floor(window.height); - const forwardPassRTName = `dsForwardPassColorCamera${idx}`; - const forwardPassDSName = `dsForwardPassDSCamera${idx}`; - if (!this.resourceGraph.contains(forwardPassRTName)) { - this.addRenderTexture(forwardPassRTName, Format.RGBA8, width, height, camera.window); - this.addDepthStencil(forwardPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); - } - const forwardPass = this.addRasterPass(width, height, '_', `CameraForwardPass${idx}`); - if (this.resourceGraph.contains(this._dsShadowMap)) { - forwardPass.addRasterView(this._dsShadowMap, new RasterView('_', - AccessType.READ, AttachmentType.RENDER_TARGET, - LoadOp.CLEAR, StoreOp.DISCARD, - ClearFlagBit.NONE, - new Color(0, 0, 0, 1))); - } - const passView = new RasterView('_', - AccessType.WRITE, AttachmentType.RENDER_TARGET, - LoadOp.CLEAR, StoreOp.STORE, - camera.clearFlag, - new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); - const passDSView = new RasterView('_', - AccessType.WRITE, AttachmentType.DEPTH_STENCIL, - LoadOp.CLEAR, StoreOp.STORE, - camera.clearFlag, - new Color(1, 0, 0, 0)); - forwardPass.addRasterView(forwardPassRTName, passView); - forwardPass.addRasterView(forwardPassDSName, passDSView); - forwardPass - .addQueue(QueueHint.RENDER_OPAQUE) - .addSceneOfCamera(camera, null, SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT); - forwardPass - .addQueue(QueueHint.RENDER_TRANSPARENT) - .addSceneOfCamera(camera, null, SceneFlags.TRANSPARENT_OBJECT); + if (this.builder) { + this.builder.setup(cameras, this); + } else { + const root = legacyCC.director.root; + if (root.useDeferredPipeline) { + this._deferred.setup(cameras, this); + } else { + this._forward.setup(cameras, this); } } this.compile(); @@ -624,43 +657,17 @@ export class WebPipeline extends Pipeline { addRasterPass (width: number, height: number, layoutName: string, name = 'Raster'): RasterPassBuilder { const pass = new RasterPass(); + pass.viewport.width = width; + pass.viewport.height = height; + const data = new RenderData(); const vertID = this._renderGraph!.addVertex( RenderGraphValue.Raster, pass, name, layoutName, data, false, ); - const result = new WebRasterPassBuilder(data, this._renderGraph!, vertID, pass, this._pipelineSceneData); + const result = new WebRasterPassBuilder(data, this._renderGraph!, this._layoutGraph, vertID, pass, this._pipelineSceneData); this._updateRasterPassConstants(result, width, height); return result; } - addComputePass (layoutName: string, name = 'Compute'): ComputePassBuilder { - const pass = new ComputePass(); - const data = new RenderData(); - const vertID = this._renderGraph!.addVertex( - RenderGraphValue.Compute, pass, name, layoutName, new RenderData(), false, - ); - return new WebComputePassBuilder(data, this._renderGraph!, vertID, pass, this._pipelineSceneData); - } - addMovePass (name = 'Move'): MovePassBuilder { - const pass = new MovePass(); - const vertID = this._renderGraph!.addVertex(RenderGraphValue.Move, pass, name, '', new RenderData(), false); - return new WebMovePassBuilder(this._renderGraph!, vertID, pass); - } - addCopyPass (name = 'Copy'): CopyPassBuilder { - const pass = new CopyPass(); - const vertID = this._renderGraph!.addVertex(RenderGraphValue.Copy, pass, name, '', new RenderData(), false); - return new WebCopyPassBuilder(this._renderGraph!, vertID, pass); - } - presentAll (): void { - const pass = new PresentPass(); - // TODO: add swapchains to present pass - this._renderGraph!.addVertex(RenderGraphValue.Present, pass, '', '', new RenderData(), false); - } - createSceneTransversal (camera: Camera, scene: RenderScene): SceneTransversal { - return new WebSceneTransversal(camera, this.pipelineSceneData); - } - get layoutGraphBuilder (): LayoutGraphBuilder { - return new WebLayoutGraphBuilder(this._device, this._layoutGraph); - } public getDescriptorSetLayout (shaderName: string, freq: UpdateFrequency): DescriptorSetLayout { const lg = this._layoutGraph; const phaseID = lg.shaderLayoutIndex.get(shaderName)!; @@ -689,18 +696,23 @@ export class WebPipeline extends Pipeline { new Vec4(shadingWidth, shadingHeight, 1.0 / shadingWidth, 1.0 / shadingHeight)); } + public static MAX_BLOOM_FILTER_PASS_NUM = 6; private _device!: Device; private _globalDSManager!: GlobalDSManager; private readonly _macros: MacroRecord = {}; private readonly _pipelineSceneData: PipelineSceneData = new PipelineSceneData(); private _constantMacros = ''; + private _lightingMode = LightingMode.DEFAULT; private _profiler: Model | null = null; private _pipelineUBO: PipelineUBO = new PipelineUBO(); private _cameras: Camera[] = []; - private readonly _layoutGraph: LayoutGraphData = new LayoutGraphData(); + private _layoutGraph: LayoutGraphData = new LayoutGraphData(); private readonly _resourceGraph: ResourceGraph = new ResourceGraph(); private _renderGraph: RenderGraph | null = null; private _compiler: Compiler | null = null; private _executor: Executor | null = null; + private _forward!: ForwardPipelineBuilder; + private _deferred!: DeferredPipelineBuilder; + public builder: PipelineBuilder | null = null; } diff --git a/cocos/core/pipeline/custom/web-scene.ts b/cocos/core/pipeline/custom/web-scene.ts index 17877e73dc..a06bdadae5 100644 --- a/cocos/core/pipeline/custom/web-scene.ts +++ b/cocos/core/pipeline/custom/web-scene.ts @@ -23,16 +23,15 @@ THE SOFTWARE. ****************************************************************************/ -import { intersect, Sphere } from '../../geometry'; -import { legacyCC } from '../../global-exports'; -import { Mat4, Vec3, Color } from '../../math'; +import { Frustum, intersect } from '../../geometry'; +import { Mat4, Vec3 } from '../../math'; import { RenderScene } from '../../renderer'; -import { Camera, SphereLight, DirectionalLight, Model, Shadows, ShadowType, SKYBOX_FLAG, SubModel } from '../../renderer/scene'; -import { IRenderObject, IRenderPass } from '../define'; +import { Camera, DirectionalLight, Model, Shadows, ShadowType, SKYBOX_FLAG, SubModel } from '../../renderer/scene'; +import { IRenderObject, IRenderPass, UBOShadow } from '../define'; import { PipelineSceneData } from '../pipeline-scene-data'; import { SceneTask, SceneTransversal, SceneVisitor } from './pipeline'; import { TaskType } from './types'; -import { ShadowLayerVolume } from '../shadow/csm-layers'; +import { PipelineUBO } from '../pipeline-ubo'; export class RenderObject implements IRenderObject { public model: Model; @@ -50,44 +49,22 @@ export class RenderInfo implements IRenderPass { public subModel; public passIdx = -1; } + export class WebSceneTask extends SceneTask { - constructor (scneData: PipelineSceneData, camera: Camera, visitor: SceneVisitor) { + constructor (scneData: PipelineSceneData, ubo: PipelineUBO, camera: Camera | null, visitor: SceneVisitor) { super(); - this._scene = camera.scene!; - this._camera = camera; + if (camera) { + this._scene = camera.scene!; + this._camera = camera; + } this._visitor = visitor; this._sceneData = scneData; + this._ubo = ubo; } get taskType (): TaskType { return TaskType.SYNC; } - public static shadowCulling (camera: Camera, sceneData: PipelineSceneData, layer: ShadowLayerVolume) { - const csmLayers = sceneData.csmLayers; - const castShadowObjects = csmLayers.castShadowObjects; - const dirLightFrustum = layer.validFrustum; - const dirShadowObjects = layer.shadowObjects; - dirShadowObjects.length = 0; - const visibility = camera.visibility; - for (let i = 0; i < castShadowObjects.length; i++) { - const castShadowObject = castShadowObjects[i]; - const model = castShadowObject.model; - // filter model by view visibility - if (model.enabled) { - if (model.node && ((visibility & model.node.layer) === model.node.layer)) { - // shadow render Object - if (dirShadowObjects != null && model.castShadow && model.worldBounds) { - // frustum culling - // eslint-disable-next-line no-lonely-if - if (intersect.aabbFrustum(model.worldBounds, dirLightFrustum)) { - dirShadowObjects.push(castShadowObject); - } - } - } - } - } - } - protected _updateDirLight (light: DirectionalLight) { const shadows = this._sceneData.shadows; @@ -113,6 +90,20 @@ export class WebSceneTask extends SceneTask { m.m13 = ly * d; m.m14 = lz * d; m.m15 = 1; + this._ubo.updateShadowUBORange(UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET, shadows.matLight); + } + + protected _getCameraWorldMatrix (out: Mat4, camera: Camera) { + if (!camera.node) { return; } + + const cameraNode = camera.node; + const position = cameraNode.getWorldPosition(); + const rotation = cameraNode.getWorldRotation(); + + Mat4.fromRT(out, rotation, position); + out.m08 *= -1.0; + out.m09 *= -1.0; + out.m10 *= -1.0; } protected _getRenderObject (model: Model, camera: Camera) { @@ -127,24 +118,29 @@ export class WebSceneTask extends SceneTask { } protected _sceneCulling () { - const scene = this._scene; - const camera = this._camera; - const mainLight = scene.mainLight; + if (!this.camera) { return; } + const scene = this.renderScene; + const camera = this.camera; + const mainLight = scene!.mainLight; const sceneData = this._sceneData; const shadows = sceneData.shadows; const skybox = sceneData.skybox; const csmLayers = sceneData.csmLayers; - const renderObjects = sceneData.renderObjects; renderObjects.length = 0; const castShadowObjects = csmLayers.castShadowObjects; castShadowObjects.length = 0; + const csmLayerObjects = csmLayers.layerObjects; + csmLayerObjects.clear(); if (shadows.enabled) { + this._ubo.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor); if (shadows.type === ShadowType.ShadowMap) { - // update lightFrustum - csmLayers.update(sceneData, camera); + // update CSM layers + if (mainLight && mainLight.node) { + csmLayers.update(sceneData, camera); + } } } @@ -158,7 +154,7 @@ export class WebSceneTask extends SceneTask { renderObjects.push(this._getRenderObject(skybox.model, camera)); } - const models = scene.models; + const models = scene!.models; const visibility = camera.visibility; for (let i = 0; i < models.length; i++) { @@ -168,6 +164,7 @@ export class WebSceneTask extends SceneTask { if (model.enabled) { if (model.castShadow) { castShadowObjects.push(this._getRenderObject(model, camera)); + csmLayerObjects.push(this._getRenderObject(model, camera)); } if (model.node && ((visibility & model.node.layer) === model.node.layer) @@ -193,34 +190,39 @@ export class WebSceneTask extends SceneTask { } get camera () { return this._camera; } - get scene (): RenderScene { + get renderScene () { return this._scene; } get visitor () { return this._visitor; } + get dirLightFrustum () { return this._dirLightFrustum; } get sceneData (): PipelineSceneData { return this._sceneData; } - private _scene: RenderScene; - private _camera: Camera; + private _scene: RenderScene | null = null; + private _camera: Camera | null = null; private _visitor: SceneVisitor; private _sceneData: PipelineSceneData; + private _dirLightFrustum = new Frustum(); + protected _ubo: PipelineUBO; } export class WebSceneTransversal extends SceneTransversal { public preRenderPass (visitor: SceneVisitor): SceneTask { - return new WebSceneTask(this._sceneData, this._camera, visitor); + return new WebSceneTask(this._sceneData, this._ubo, this._camera, visitor); } public postRenderPass (visitor: SceneVisitor): SceneTask { - return new WebSceneTask(this._sceneData, this._camera, visitor); + return new WebSceneTask(this._sceneData, this._ubo, this._camera, visitor); } - constructor (camera: Camera, sceneData: PipelineSceneData) { + constructor (camera: Camera | null, sceneData: PipelineSceneData, ubo: PipelineUBO) { super(); this._camera = camera; - this._scene = camera.scene!; + if (camera) this._scene = camera.scene!; this._sceneData = sceneData; + this._ubo = ubo; } public transverse (visitor: SceneVisitor): SceneTask { - return new WebSceneTask(this._sceneData, this._camera, visitor); + return new WebSceneTask(this._sceneData, this._ubo, this._camera, visitor); } - protected _scene: RenderScene; - protected _camera: Camera; + protected _scene: RenderScene | null = null; + protected _camera: Camera | null = null; + protected _ubo: PipelineUBO; protected _sceneData: PipelineSceneData; } diff --git a/cocos/core/pipeline/pipeline-ubo.ts b/cocos/core/pipeline/pipeline-ubo.ts index 0ba29bda3d..f65eae6fde 100644 --- a/cocos/core/pipeline/pipeline-ubo.ts +++ b/cocos/core/pipeline/pipeline-ubo.ts @@ -28,7 +28,7 @@ import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, API } from '../gfx'; import { Camera } from '../renderer/scene/camera'; import { Mat4, Vec3, Vec4, Color } from '../math'; -import { RenderPipeline } from './render-pipeline'; +import { PipelineRuntime } from './custom/pipeline'; import { legacyCC } from '../global-exports'; import { CSMLevel, PCFType, Shadows, ShadowType } from '../renderer/scene/shadows'; import { updatePlanarNormalAndDistance, updatePlanarPROJ } from './scene-culling'; @@ -87,7 +87,7 @@ export class PipelineUBO { } } - public static updateCameraUBOView (pipeline: RenderPipeline, bufferView: Float32Array, + public static updateCameraUBOView (pipeline: PipelineRuntime, bufferView: Float32Array, camera: Camera) { const scene = camera.scene ? camera.scene : legacyCC.director.getScene().renderScene; const mainLight = scene.mainLight; @@ -201,7 +201,7 @@ export class PipelineUBO { return 0.0; } - public static updateShadowUBOView (pipeline: RenderPipeline, shadowBufferView: Float32Array, + public static updateShadowUBOView (pipeline: PipelineRuntime, shadowBufferView: Float32Array, csmBufferView: Float32Array, camera: Camera) { const device = pipeline.device; const mainLight = camera.scene!.mainLight; @@ -290,7 +290,7 @@ export class PipelineUBO { } } - public static updateShadowUBOLightView (pipeline: RenderPipeline, shadowBufferView: Float32Array, light: Light, level: number) { + public static updateShadowUBOLightView (pipeline: PipelineRuntime, shadowBufferView: Float32Array, light: Light, level: number) { const device = pipeline.device; const sceneData = pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; @@ -397,7 +397,7 @@ export class PipelineUBO { protected _csmUBO = new Float32Array(UBOCSM.COUNT); static _combineSignY = 0; protected declare _device: Device; - protected declare _pipeline: RenderPipeline; + protected declare _pipeline: PipelineRuntime; /** *|combinedSignY|clipSpaceSignY|screenSpaceSignY| Backends | @@ -416,7 +416,7 @@ export class PipelineUBO { PipelineUBO._combineSignY = (device.capabilities.screenSpaceSignY * 0.5 + 0.5) << 1 | (device.capabilities.clipSpaceSignY * 0.5 + 0.5); } - public activate (device: Device, pipeline: RenderPipeline) { + public activate (device: Device, pipeline: PipelineRuntime) { this._device = device; this._pipeline = pipeline; const ds = this._pipeline.descriptorSet; diff --git a/cocos/core/pipeline/planar-shadow-queue.ts b/cocos/core/pipeline/planar-shadow-queue.ts index 5ec1517544..a0049614f8 100644 --- a/cocos/core/pipeline/planar-shadow-queue.ts +++ b/cocos/core/pipeline/planar-shadow-queue.ts @@ -32,7 +32,7 @@ import { Model, Camera } from '../renderer/scene'; import { RenderInstancedQueue } from './render-instanced-queue'; import { ShadowType } from '../renderer/scene/shadows'; import { Layers } from '../scene-graph/layers'; -import { RenderPipeline } from './render-pipeline'; +import { PipelineRuntime } from './custom/pipeline'; const _ab = new AABB(); @@ -40,15 +40,14 @@ export class PlanarShadowQueue { private _pendingModels: Model[] = []; private _castModels:Model[] = []; private _instancedQueue = new RenderInstancedQueue(); - private _pipeline: RenderPipeline; + private _pipeline: PipelineRuntime; - constructor (pipeline: RenderPipeline) { + constructor (pipeline: PipelineRuntime) { this._pipeline = pipeline; } public gatherShadowPasses (camera: Camera, cmdBuff: CommandBuffer) { const pipelineSceneData = this._pipeline.pipelineSceneData; - const pipelineUBO = this._pipeline.pipelineUBO; const shadows = pipelineSceneData.shadows; this._instancedQueue.clear(); this._pendingModels.length = 0; diff --git a/cocos/core/pipeline/render-additive-light-queue.ts b/cocos/core/pipeline/render-additive-light-queue.ts index f169c54790..dd527d995e 100644 --- a/cocos/core/pipeline/render-additive-light-queue.ts +++ b/cocos/core/pipeline/render-additive-light-queue.ts @@ -24,7 +24,6 @@ */ import { BatchingSchemes, Pass } from '../renderer/core/pass'; -import { RenderPipeline } from './render-pipeline'; import { Model } from '../renderer/scene/model'; import { PipelineStateManager } from './pipeline-state-manager'; import { Vec3, nextPow2, Mat4, Color } from '../math'; @@ -44,6 +43,7 @@ import { SetIndex, UBOForwardLight, UBOShadow, UNIFORM_SHADOWMAP_BINDING, import { updatePlanarNormalAndDistance, updatePlanarPROJ } from './scene-culling'; import { Camera, ShadowType } from '../renderer/scene'; import { GlobalDSManager } from './global-descriptor-set-manager'; +import { PipelineRuntime } from './custom/pipeline'; interface IAdditiveLightPass { subModel: SubModel; @@ -111,7 +111,7 @@ function isInstancedOrBatched (model: Model) { * @zh 叠加光照队列。 */ export class RenderAdditiveLightQueue { - private _pipeline: RenderPipeline; + private _pipeline: PipelineRuntime; private _device: Device; private _lightPasses: IAdditiveLightPass[] = []; private _instancedLightPassPool = _lightPassPool.alloc(); @@ -127,7 +127,7 @@ export class RenderAdditiveLightQueue { private _batchedQueue: RenderBatchedQueue; private _lightMeterScale = 10000.0; - constructor (pipeline: RenderPipeline) { + constructor (pipeline: PipelineRuntime) { this._pipeline = pipeline; this._device = pipeline.device; this._instancedQueue = new RenderInstancedQueue(); diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index ff07bf5052..360cce60a3 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -386,6 +386,30 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi } } + public getMacroString (name: string): string { + const str = this._macros[name]; + if (str === undefined) { + return ''; + } + return str as string; + } + + public getMacroInt (name: string): number { + const value = this._macros[name]; + if (value === undefined) { + return 0; + } + return value as number; + } + + public getMacroBool (name: string): boolean { + const value = this._macros[name]; + if (value === undefined) { + return false; + } + return value as boolean; + } + public setMacroString (name: string, value: string): void { this._macros[name] = value; } diff --git a/cocos/core/pipeline/render-shadow-map-batched-queue.ts b/cocos/core/pipeline/render-shadow-map-batched-queue.ts index 14dd0733cf..a3e6c74aae 100644 --- a/cocos/core/pipeline/render-shadow-map-batched-queue.ts +++ b/cocos/core/pipeline/render-shadow-map-batched-queue.ts @@ -35,9 +35,9 @@ import { ShadowType } from '../renderer/scene/shadows'; import { Light, LightType } from '../renderer/scene/light'; import { intersect } from '../geometry'; import { Model } from '../renderer/scene/model'; -import { RenderPipeline } from './render-pipeline'; import { Camera, DirectionalLight, SpotLight } from '../renderer/scene'; import { shadowCulling } from './scene-culling'; +import { PipelineRuntime } from './custom/pipeline'; const _phaseID = getPhaseID('shadow-caster'); function getShadowPassIndex (subModel: SubModel) : number { @@ -55,14 +55,14 @@ function getShadowPassIndex (subModel: SubModel) : number { * 阴影渲染队列 */ export class RenderShadowMapBatchedQueue { - private _pipeline: RenderPipeline; + private _pipeline: PipelineRuntime; private _subModelsArray: SubModel[] = []; private _passArray: Pass[] = []; private _shaderArray: Shader[] = []; private _instancedQueue: RenderInstancedQueue; private _batchedQueue: RenderBatchedQueue; - public constructor (pipeline: RenderPipeline) { + public constructor (pipeline: PipelineRuntime) { this._pipeline = pipeline; this._instancedQueue = new RenderInstancedQueue(); this._batchedQueue = new RenderBatchedQueue(); diff --git a/cocos/core/renderer/core/program-lib.ts b/cocos/core/renderer/core/program-lib.ts index fa4499856b..04d9231d07 100644 --- a/cocos/core/renderer/core/program-lib.ts +++ b/cocos/core/renderer/core/program-lib.ts @@ -443,28 +443,9 @@ class ProgramLib { const tmpl = this._templates[name]; const tmplInfo = this._templateInfos[tmpl.hash]; if (!tmplInfo.pipelineLayout) { - const director = legacyCC.director; - if (director.root.usesCustomPipeline) { - const root = legacyCC.director.root; - const ppl: Pipeline = root.customPipeline; - insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals'); - const globalDS = ppl.getDescriptorSetLayout(name, UpdateFrequency.PER_PASS); - const materialDS = ppl.getDescriptorSetLayout(name, UpdateFrequency.PER_BATCH); - const localDS = ppl.getDescriptorSetLayout(name, UpdateFrequency.PER_INSTANCE); - if (globalDS) { - tmplInfo.setLayouts[SetIndex.GLOBAL] = globalDS; - } - if (materialDS) { - tmplInfo.setLayouts[SetIndex.MATERIAL] = materialDS; - } - if (localDS) { - tmplInfo.setLayouts[SetIndex.LOCAL] = localDS; - } - } else { - this.getDescriptorSetLayout(device, name); // ensure set layouts have been created - insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals'); - tmplInfo.setLayouts[SetIndex.GLOBAL] = pipeline.descriptorSetLayout; - } + this.getDescriptorSetLayout(device, name); // ensure set layouts have been created + insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals'); + tmplInfo.setLayouts[SetIndex.GLOBAL] = pipeline.descriptorSetLayout; tmplInfo.pipelineLayout = device.createPipelineLayout(new PipelineLayoutInfo(tmplInfo.setLayouts)); } diff --git a/cocos/core/root.jsb.ts b/cocos/core/root.jsb.ts index af8290a8ec..9e1b3c32d5 100644 --- a/cocos/core/root.jsb.ts +++ b/cocos/core/root.jsb.ts @@ -3,8 +3,8 @@ import { warnID } from './platform/debug'; import legacyCC from '../../predefine'; import { DataPoolManager } from '../3d/skeletal-animation/data-pool-manager'; import { Device, deviceManager } from './gfx'; -import { registerRebuildLayoutGraph } from './pipeline/custom/index.jsb'; import { DebugView } from './pipeline/debug-view'; +import { buildDeferredLayout, buildForwardLayout } from './pipeline/custom/effect'; declare const nr: any; declare const jsb: any; @@ -188,9 +188,15 @@ const oldSetPipeline = rootProto.setRenderPipeline; rootProto.setRenderPipeline = function (pipeline) { let ppl; if (this.usesCustomPipeline) { - ppl = oldSetPipeline.call(this, null); - registerRebuildLayoutGraph(); - + const result = oldSetPipeline.call(this, null); + const ppl = this.customPipeline; + if (this.useDeferredPipeline) { + buildDeferredLayout(ppl); + } else { + buildForwardLayout(ppl); + } + ppl.layoutGraphBuilder.compile(); + return result; } else { if (!pipeline) { // pipeline should not be created in C++, ._ctor need to be triggered diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 2e82d53f87..56377397aa 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ +import { DEV, HTML5, TEST } from 'internal:constants'; import { Pool } from './memop'; import { RenderPipeline, createDefaultPipeline, DeferredPipeline } from './pipeline'; import { DebugView } from './pipeline/debug-view'; @@ -118,7 +119,7 @@ export class Root { * 启用自定义渲染管线 */ public get usesCustomPipeline (): boolean { - return this._usesCustomPipeline; + return this._usesCustomPipeline && !DEV && (HTML5 || TEST); } /** diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index 3f1b52bc1c..2eb6a33189 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -222,6 +222,12 @@ "description": "i18n:ENGINE.features.marionette.description", "wechatPlugin": false, "category": "animation" + }, + "custom-pipeline": { + "default": ["custom-pipeline"], + "label": "i18n:ENGINE.features.custom_pipeline.label", + "description": "i18n:ENGINE.features.custom_pipeline.description", + "wechatPlugin": false } }, "categories": { diff --git a/native/cocos/core/Root.cpp b/native/cocos/core/Root.cpp index 8a726c3ed1..378e255d58 100644 --- a/native/cocos/core/Root.cpp +++ b/native/cocos/core/Root.cpp @@ -140,6 +140,9 @@ public: void render(const ccstd::vector &cameras) override { pipeline->render(cameras); } + gfx::Device* getDevice() const override { + return pipeline->getDevice(); + } const MacroRecord &getMacros() const override { return pipeline->getMacros(); } @@ -149,6 +152,12 @@ public: gfx::DescriptorSetLayout *getDescriptorSetLayout() const override { return pipeline->getDescriptorSetLayout(); } + gfx::DescriptorSet *getDescriptorSet() const override { + return pipeline->getDescriptorSet(); + } + ccstd::vector getCommandBuffers() const override { + return pipeline->getCommandBuffers(); + } pipeline::PipelineSceneData *getPipelineSceneData() const override { return pipeline->getPipelineSceneData(); } @@ -170,6 +179,31 @@ public: void setShadingScale(float scale) override { pipeline->setShadingScale(scale); } + const ccstd::string& getMacroString(const ccstd::string& name) const override { + static const ccstd::string EMPTY_STRING; + const auto& macros = pipeline->getMacros(); + auto iter = macros.find(name); + if (iter == macros.end()) { + return EMPTY_STRING; + } + return ccstd::get(iter->second); + } + int32_t getMacroInt(const ccstd::string &name) const override { + const auto& macros = pipeline->getMacros(); + auto iter = macros.find(name); + if (iter == macros.end()) { + return 0; + } + return ccstd::get(iter->second); + } + bool getMacroBool(const ccstd::string &name) const override { + const auto& macros = pipeline->getMacros(); + auto iter = macros.find(name); + if (iter == macros.end()) { + return false; + } + return ccstd::get(iter->second); + } void setMacroString(const ccstd::string &name, const ccstd::string &value) override { pipeline->setValue(name, value); } diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphFwd.h b/native/cocos/renderer/pipeline/custom/LayoutGraphFwd.h index 95524c4ce6..9c3906d8a0 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphFwd.h +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphFwd.h @@ -32,7 +32,6 @@ #pragma once #include #include "cocos/base/std/variant.h" -#include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/pipeline/custom/RenderCommonFwd.h" namespace cc { diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h index 389d76f198..64558e1e7f 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h @@ -39,7 +39,6 @@ #include "cocos/base/std/container/string.h" #include "cocos/base/std/container/vector.h" #include "cocos/base/std/hash/hash.h" -#include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/gfx-base/GFXDescriptorSet.h" #include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" #include "cocos/renderer/pipeline/custom/GraphTypes.h" @@ -410,10 +409,10 @@ struct DescriptorSetLayoutData { DescriptorSetLayoutData& operator=(DescriptorSetLayoutData&& rhs) = default; DescriptorSetLayoutData& operator=(DescriptorSetLayoutData const& rhs) = delete; - uint32_t slot{0xFFFFFFFF}; - uint32_t capacity{0}; - ccstd::pmr::vector descriptorBlocks; - ccstd::pmr::unordered_map uniformBlocks; + uint32_t slot{0xFFFFFFFF}; + uint32_t capacity{0}; + ccstd::pmr::vector descriptorBlocks; + ccstd::pmr::unordered_map uniformBlocks; }; struct DescriptorSetData { diff --git a/native/cocos/renderer/pipeline/custom/NativeLayoutGraphImpl.cpp b/native/cocos/renderer/pipeline/custom/NativeLayoutGraphImpl.cpp index 5fb9045154..295f75fbf7 100644 --- a/native/cocos/renderer/pipeline/custom/NativeLayoutGraphImpl.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeLayoutGraphImpl.cpp @@ -103,6 +103,25 @@ void NativeLayoutGraphBuilder::addDescriptorBlock( layout.capacity += block.capacity; } +void NativeLayoutGraphBuilder::addUniformBlock(uint32_t nodeID, const DescriptorBlockIndex& index, const ccstd::string& name, const gfx::UniformBlock& uniformBlock) { + auto &g = *data; + auto &ppl = get(LayoutGraphData::Layout, g, nodeID); + auto &layout = ppl.descriptorSets[index.updateFrequency].descriptorSetLayoutData; + auto iter = g.attributeIndex.find(boost::string_view(name)); + if (iter == g.attributeIndex.end()) { + auto attrID = gsl::narrow_cast(g.valueNames.size()); + g.valueNames.emplace_back(name); + bool added = false; + std::tie(iter, added) = g.attributeIndex.emplace( + std::piecewise_construct, + std::forward_as_tuple(name), + std::forward_as_tuple(NameLocalID{attrID})); + CC_ENSURES(added); + } + const auto &nameID = iter->second; + layout.uniformBlocks.emplace(nameID, uniformBlock); +} + namespace { gfx::DescriptorType getGfxType(DescriptorTypeOrder type) { @@ -187,6 +206,10 @@ int NativeLayoutGraphBuilder::compile() { } } +#ifdef _DEBUG + CC_LOG_DEBUG(print().c_str()); +#endif // _DEBUG + return 0; } diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp b/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp index 2dcc81ecd1..5be7d4d25c 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp @@ -33,6 +33,7 @@ #include "NativePipelineTypes.h" #include "base/Macros.h" #include "base/Ptr.h" +#include "base/std/container/string.h" #include "boost/utility/string_view_fwd.hpp" #include "cocos/base/StringUtil.h" #include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" @@ -62,9 +63,7 @@ #include "pipeline/custom/Range.h" #include "pipeline/custom/RenderGraphTypes.h" #include "pipeline/custom/RenderInterfaceTypes.h" -#if CC_USE_DEBUG_RENDERER - #include "profiler/DebugRenderer.h" -#endif +#include "profiler/DebugRenderer.h" namespace cc { @@ -83,6 +82,14 @@ NativePipeline::NativePipeline(const allocator_type &alloc) noexcept resourceGraph(alloc), renderGraph(alloc) {} +gfx::Device* NativePipeline::getDevice() const { + return device; +} + +bool NativePipeline::containsResource(const ccstd::string &name) const { + return contains(name.c_str(), resourceGraph); +} + // NOLINTNEXTLINE uint32_t NativePipeline::addRenderTexture(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, scene::RenderWindow *renderWindow) { ResourceDesc desc{}; @@ -184,6 +191,8 @@ RasterPassBuilder *NativePipeline::addRasterPass( RasterPass pass(renderGraph.get_allocator()); pass.width = width; pass.height = height; + pass.viewport.width = width; + pass.viewport.height = height; auto passID = addVertex( RasterTag{}, @@ -206,7 +215,8 @@ RasterPassBuilder *NativePipeline::addRasterPass(uint32_t width, uint32_t height } // NOLINTNEXTLINE -ComputePassBuilder *NativePipeline::addComputePass(const ccstd::string &layoutName, const ccstd::string &name) { +ComputePassBuilder *NativePipeline::addComputePass(const ccstd::string &layoutName, + const ccstd::string &name) { auto passID = addVertex( ComputeTag{}, std::forward_as_tuple(name.c_str()), @@ -275,10 +285,10 @@ LayoutGraphBuilder *NativePipeline::getLayoutGraphBuilder() { return ccnew NativeLayoutGraphBuilder(device, &layoutGraph); } -gfx::DescriptorSetLayout *NativePipeline::getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) { +gfx::DescriptorSetLayout *NativePipeline::getDescriptorSetLayout(const ccstd::string& shaderName, UpdateFrequency freq) { auto iter = layoutGraph.shaderLayoutIndex.find(boost::string_view(shaderName)); if (iter != layoutGraph.shaderLayoutIndex.end()) { - const auto &layouts = get(LayoutGraphData::Layout, layoutGraph, iter->second).descriptorSets; + const auto& layouts = get(LayoutGraphData::Layout, layoutGraph, iter->second).descriptorSets; auto iter2 = layouts.find(freq); if (iter2 != layouts.end()) { return iter2->second.descriptorSetLayout.get(); @@ -289,6 +299,14 @@ gfx::DescriptorSetLayout *NativePipeline::getDescriptorSetLayout(const ccstd::st return nullptr; } +gfx::DescriptorSet *NativePipeline::getDescriptorSet() const { + return globalDSManager->getGlobalDescriptorSet(); +} + +ccstd::vector NativePipeline::getCommandBuffers() const { + return ccstd::vector(1, device->getCommandBuffer()); +} + namespace { void generateConstantMacros( @@ -320,9 +338,7 @@ bool NativePipeline::activate(gfx::Swapchain *swapchainIn) { macros["CC_PIPELINE_TYPE"] = 0; globalDSManager->activate(device); pipelineSceneData->activate(device); -#if CC_USE_DEBUG_RENDERER DebugRenderer::getInstance()->activate(device); -#endif // generate macros here rather than construct func because _clusterEnabled // switch may be changed in root.ts setRenderPipeline() function which is after @@ -498,15 +514,40 @@ void NativePipeline::setShadingScale(float scale) { pipelineSceneData->setShadingScale(scale); } -void NativePipeline::setMacroString(const ccstd::string &name, const ccstd::string &value) { +const ccstd::string& NativePipeline::getMacroString(const ccstd::string& name) const { + static const ccstd::string EMPTY_STRING; + auto iter = macros.find(name); + if (iter == macros.end()) { + return EMPTY_STRING; + } + return ccstd::get(iter->second); +} + +int32_t NativePipeline::getMacroInt(const ccstd::string& name) const { + auto iter = macros.find(name); + if (iter == macros.end()) { + return 0; + } + return ccstd::get(iter->second); +} + +bool NativePipeline::getMacroBool(const ccstd::string& name) const { + auto iter = macros.find(name); + if (iter == macros.end()) { + return false; + } + return ccstd::get(iter->second); +} + +void NativePipeline::setMacroString(const ccstd::string& name, const ccstd::string& value) { macros[name] = value; } -void NativePipeline::setMacroInt(const ccstd::string &name, int32_t value) { +void NativePipeline::setMacroInt(const ccstd::string& name, int32_t value) { macros[name] = value; } -void NativePipeline::setMacroBool(const ccstd::string &name, bool value) { +void NativePipeline::setMacroBool(const ccstd::string& name, bool value) { macros[name] = value; } diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index c8bdb6cde0..f0222f83c5 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -53,6 +53,7 @@ public: uint32_t addRenderPhase(const ccstd::string& name, uint32_t parentID) override; void addShader(const ccstd::string& name, uint32_t parentPhaseID) override; void addDescriptorBlock(uint32_t nodeID, const DescriptorBlockIndex& index, const DescriptorBlockFlattened& block) override; + void addUniformBlock(uint32_t nodeID, const DescriptorBlockIndex& index, const ccstd::string& name, const gfx::UniformBlock& uniformBlock) override; void reserveDescriptorBlock(uint32_t nodeID, const DescriptorBlockIndex& index, const DescriptorBlockFlattened& block) override; int compile() override; @@ -65,17 +66,20 @@ public: class NativeRasterQueueBuilder final : public RasterQueueBuilder { public: NativeRasterQueueBuilder() = default; - NativeRasterQueueBuilder(RenderGraph* renderGraphIn, uint32_t queueIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn) noexcept // NOLINT + NativeRasterQueueBuilder(RenderGraph* renderGraphIn, uint32_t queueIDIn, const LayoutGraphData* layoutGraphIn) noexcept : renderGraph(renderGraphIn), layoutGraph(layoutGraphIn), - queueID(queueIDIn), - layoutID(layoutIDIn) {} + queueID(queueIDIn) {} - void addSceneOfCamera(scene::Camera* camera, scene::Light* light, SceneFlags sceneFlags, const ccstd::string& name) override; - void addSceneOfCamera(scene::Camera* camera, scene::Light* light, SceneFlags sceneFlags) override; + void addSceneOfCamera(scene::Camera* camera, LightInfo light, SceneFlags sceneFlags, const ccstd::string& name) override; + void addSceneOfCamera(scene::Camera* camera, LightInfo light, SceneFlags sceneFlags) override; void addScene(const ccstd::string& name, SceneFlags sceneFlags) override; - void addFullscreenQuad(const ccstd::string& shader, const ccstd::string& name) override; - void addFullscreenQuad(const ccstd::string& shader) override; + void addFullscreenQuad(cc::Material *material, SceneFlags sceneFlags, const ccstd::string& name) override; + void addFullscreenQuad(cc::Material *material, SceneFlags sceneFlags) override; + void addCameraQuad(scene::Camera* camera, cc::Material *material, SceneFlags sceneFlags, const ccstd::string& name) override; + void addCameraQuad(scene::Camera* camera, cc::Material *material, SceneFlags sceneFlags) override; + void clearRenderTarget(const ccstd::string &name, const gfx::Color &color) override; + void setViewport(const gfx::Viewport &viewport) override; void setMat4(const ccstd::string& name, const cc::Mat4& mat) override; void setQuaternion(const ccstd::string& name, const cc::Quaternion& quat) override; @@ -93,7 +97,6 @@ public: RenderGraph* renderGraph{nullptr}; const LayoutGraphData* layoutGraph{nullptr}; uint32_t queueID{RenderGraph::null_vertex()}; - uint32_t layoutID{LayoutGraphData::null_vertex()}; }; class NativeRasterPassBuilder final : public RasterPassBuilder { @@ -105,14 +108,15 @@ public: passID(passIDIn), layoutID(layoutIDIn) {} - void addRasterView(const ccstd::string& name, const RasterView& view) override; - void addComputeView(const ccstd::string& name, const ComputeView& view) override; - RasterQueueBuilder *addQueue(QueueHint hint, const ccstd::string& layoutName, const ccstd::string& name) override; - RasterQueueBuilder *addQueue(QueueHint hint, const ccstd::string& layoutName) override; + void addRasterView(const ccstd::string& name, const RasterView& view) override; + void addComputeView(const ccstd::string& name, const ComputeView& view) override; + RasterQueueBuilder *addQueue(QueueHint hint, const ccstd::string& name) override; RasterQueueBuilder *addQueue(QueueHint hint) override; - void addFullscreenQuad(const ccstd::string& shader, const ccstd::string& layoutName, const ccstd::string& name) override; - void addFullscreenQuad(const ccstd::string& shader, const ccstd::string& layoutName) override; - void addFullscreenQuad(const ccstd::string& shader) override; + void addFullscreenQuad(cc::Material *material, SceneFlags sceneFlags, const ccstd::string& name) override; + void addFullscreenQuad(cc::Material *material, SceneFlags sceneFlags) override; + void addCameraQuad(scene::Camera* camera, cc::Material *material, SceneFlags sceneFlags, const ccstd::string& name) override; + void addCameraQuad(scene::Camera* camera, cc::Material *material, SceneFlags sceneFlags) override; + void setViewport(const gfx::Viewport &viewport) override; void setMat4(const ccstd::string& name, const cc::Mat4& mat) override; void setQuaternion(const ccstd::string& name, const cc::Quaternion& quat) override; @@ -136,14 +140,12 @@ public: class NativeComputeQueueBuilder final : public ComputeQueueBuilder { public: NativeComputeQueueBuilder() = default; - NativeComputeQueueBuilder(RenderGraph* renderGraphIn, uint32_t queueIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn) noexcept // NOLINT + NativeComputeQueueBuilder(RenderGraph* renderGraphIn, uint32_t queueIDIn, const LayoutGraphData* layoutGraphIn) noexcept : renderGraph(renderGraphIn), layoutGraph(layoutGraphIn), - queueID(queueIDIn), - layoutID(layoutIDIn) {} + queueID(queueIDIn) {} - void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& layoutName, const ccstd::string& name) override; - void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& layoutName) override; + void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& name) override; void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ) override; void setMat4(const ccstd::string& name, const cc::Mat4& mat) override; @@ -162,7 +164,6 @@ public: RenderGraph* renderGraph{nullptr}; const LayoutGraphData* layoutGraph{nullptr}; uint32_t queueID{RenderGraph::null_vertex()}; - uint32_t layoutID{LayoutGraphData::null_vertex()}; }; class NativeComputePassBuilder final : public ComputePassBuilder { @@ -176,12 +177,10 @@ public: void addComputeView(const ccstd::string& name, const ComputeView& view) override; - ComputeQueueBuilder *addQueue(const ccstd::string& layoutName, const ccstd::string& name) override; - ComputeQueueBuilder *addQueue(const ccstd::string& layoutName) override; + ComputeQueueBuilder *addQueue(const ccstd::string& name) override; ComputeQueueBuilder *addQueue() override; - void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& layoutName, const ccstd::string& name) override; - void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& layoutName) override; + void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& name) override; void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ) override; void setMat4(const ccstd::string& name, const cc::Mat4& mat) override; @@ -251,18 +250,20 @@ public: NativePipeline(const allocator_type& alloc) noexcept; // NOLINT - uint32_t addRenderTexture(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, scene::RenderWindow* renderWindow) override; - uint32_t addRenderTarget(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) override; - uint32_t addDepthStencil(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) override; - void beginFrame() override; - void endFrame() override; - RasterPassBuilder *addRasterPass(uint32_t width, uint32_t height, const ccstd::string& layoutName, const ccstd::string& name) override; - RasterPassBuilder *addRasterPass(uint32_t width, uint32_t height, const ccstd::string& layoutName) override; + bool containsResource(const ccstd::string& name) const override; + uint32_t addRenderTexture(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, scene::RenderWindow* renderWindow) override; + uint32_t addRenderTarget(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) override; + uint32_t addDepthStencil(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) override; + + void beginFrame() override; + void endFrame() override; + RasterPassBuilder *addRasterPass(uint32_t width, uint32_t height, const ccstd::string& layoutName, const ccstd::string& name) override; + RasterPassBuilder *addRasterPass(uint32_t width, uint32_t height, const ccstd::string& layoutName) override; ComputePassBuilder *addComputePass(const ccstd::string& layoutName, const ccstd::string& name) override; ComputePassBuilder *addComputePass(const ccstd::string& layoutName) override; - MovePassBuilder *addMovePass(const ccstd::string& name) override; - CopyPassBuilder *addCopyPass(const ccstd::string& name) override; - void presentAll() override; + MovePassBuilder *addMovePass(const ccstd::string& name) override; + CopyPassBuilder *addCopyPass(const ccstd::string& name) override; + void presentAll() override; SceneTransversal *createSceneTransversal(const scene::Camera *camera, const scene::RenderScene *scene) override; LayoutGraphBuilder *getLayoutGraphBuilder() override; @@ -272,17 +273,24 @@ public: bool destroy() noexcept override; void render(const ccstd::vector& cameras) override; - const MacroRecord &getMacros() const override; - pipeline::GlobalDSManager *getGlobalDSManager() const override; - gfx::DescriptorSetLayout *getDescriptorSetLayout() const override; + gfx::Device* getDevice() const override; + const MacroRecord &getMacros() const override; + pipeline::GlobalDSManager *getGlobalDSManager() const override; + gfx::DescriptorSetLayout *getDescriptorSetLayout() const override; + gfx::DescriptorSet *getDescriptorSet() const override; + ccstd::vector getCommandBuffers() const override; pipeline::PipelineSceneData *getPipelineSceneData() const override; - const ccstd::string &getConstantMacros() const override; - scene::Model *getProfiler() const override; - void setProfiler(scene::Model *profiler) override; + const ccstd::string &getConstantMacros() const override; + scene::Model *getProfiler() const override; + void setProfiler(scene::Model *profiler) override; pipeline::GeometryRenderer *getGeometryRenderer() const override; float getShadingScale() const override; - void setShadingScale(float scale) override; + void setShadingScale(float scale) override; + + const ccstd::string& getMacroString(const ccstd::string& name) const override; + int32_t getMacroInt(const ccstd::string& name) const override; + bool getMacroBool(const ccstd::string& name) const override; void setMacroString(const ccstd::string& name, const ccstd::string& value) override; void setMacroInt(const ccstd::string& name, int32_t value) override; @@ -301,6 +309,7 @@ public: ccstd::string constantMacros; std::unique_ptr globalDSManager; scene::Model* profiler{nullptr}; + LightingMode lightingMode{LightingMode::DEFAULT}; IntrusivePtr pipelineSceneData; LayoutGraphData layoutGraph; framegraph::FrameGraph frameGraph; diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraphSetup.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraphSetup.cpp index f966a4d113..65076d2116 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraphSetup.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraphSetup.cpp @@ -1,8 +1,11 @@ -#include "NativePipelineTypes.h" -#include "NativePipelineGraphs.h" -#include "RenderGraphGraphs.h" #include "LayoutGraphGraphs.h" +#include "NativePipelineGraphs.h" +#include "NativePipelineTypes.h" +#include "RenderGraphGraphs.h" +#include "gfx-base/GFXDef-common.h" #include "pipeline/custom/RenderCommonTypes.h" +#include "pipeline/custom/RenderGraphFwd.h" +#include "pipeline/custom/RenderGraphTypes.h" namespace cc { @@ -30,12 +33,12 @@ void NativeRasterPassBuilder::addComputeView(const ccstd::string &name, const Co iter->second.emplace_back(view); } -void NativeRasterQueueBuilder::addSceneOfCamera(scene::Camera *camera, scene::Light* light, SceneFlags sceneFlags, const ccstd::string &name) { +void NativeRasterQueueBuilder::addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags, const ccstd::string &name) { SceneData scene(renderGraph->get_allocator()); scene.name = name; scene.flags = sceneFlags; scene.camera = camera; - scene.light = light; + scene.light = std::move(light); auto sceneID = addVertex( SceneTag{}, std::forward_as_tuple(name.c_str()), @@ -47,8 +50,8 @@ void NativeRasterQueueBuilder::addSceneOfCamera(scene::Camera *camera, scene::Li CC_ENSURES(sceneID != RenderGraph::null_vertex()); } -void NativeRasterQueueBuilder::addSceneOfCamera(scene::Camera *camera, scene::Light* light, SceneFlags sceneFlags) { - addSceneOfCamera(camera, light, sceneFlags, "Camera"); +void NativeRasterQueueBuilder::addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) { + addSceneOfCamera(camera, std::move(light), sceneFlags, "Camera"); } void NativeRasterQueueBuilder::addScene(const ccstd::string &name, SceneFlags sceneFlags) { @@ -68,20 +71,66 @@ void NativeRasterQueueBuilder::addScene(const ccstd::string &name, SceneFlags sc } void NativeRasterQueueBuilder::addFullscreenQuad( - const ccstd::string &shader, const ccstd::string &name) { // NOLINT(bugprone-easily-swappable-parameters) + Material *material, SceneFlags sceneFlags, const ccstd::string &name) { auto drawID = addVertex( BlitTag{}, std::forward_as_tuple(name.c_str()), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(), - std::forward_as_tuple(shader.c_str()), + std::forward_as_tuple(material, sceneFlags, nullptr), *renderGraph, queueID); CC_ENSURES(drawID != RenderGraph::null_vertex()); } -void NativeRasterQueueBuilder::addFullscreenQuad(const ccstd::string &shader) { - addFullscreenQuad(shader, "FullscreenQuad"); +void NativeRasterQueueBuilder::addFullscreenQuad(Material *material, SceneFlags sceneFlags) { + addFullscreenQuad(material, sceneFlags, "FullscreenQuad"); +} + +void NativeRasterQueueBuilder::addCameraQuad( + scene::Camera *camera, cc::Material *material, + SceneFlags sceneFlags, const ccstd::string &name) { + auto drawID = addVertex( + BlitTag{}, + std::forward_as_tuple(name), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(material, sceneFlags, camera), + *renderGraph, queueID); + CC_ENSURES(drawID != RenderGraph::null_vertex()); +} + +void NativeRasterQueueBuilder::addCameraQuad( + scene::Camera *camera, cc::Material *material, SceneFlags sceneFlags) { + addCameraQuad(camera, material, sceneFlags, "CameraQuad"); +} + +void NativeRasterQueueBuilder::clearRenderTarget(const ccstd::string &name, const gfx::Color &color) { + ccstd::pmr::vector clears(renderGraph->get_allocator()); + clears.emplace_back(name.c_str(), gfx::ClearFlagBit::COLOR, color); + + auto clearID = addVertex( + ClearTag{}, + std::forward_as_tuple("ClearRenderTarget"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(clears)), + *renderGraph, queueID); + CC_ENSURES(clearID != RenderGraph::null_vertex()); +} + +void NativeRasterQueueBuilder::setViewport(const gfx::Viewport &viewport) { + auto viewportID = addVertex( + ViewportTag{}, + std::forward_as_tuple("Viewport"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(viewport), + *renderGraph, queueID); + CC_ENSURES(viewportID != RenderGraph::null_vertex()); } namespace { @@ -225,54 +274,29 @@ void NativeRasterQueueBuilder::setSampler(const ccstd::string &name, gfx::Sample } RasterQueueBuilder *NativeRasterPassBuilder::addQueue( - QueueHint hint, - const ccstd::string &layoutName, const ccstd::string &name) { // NOLINT(bugprone-easily-swappable-parameters) + QueueHint hint, const ccstd::string &name) { // NOLINT(bugprone-easily-swappable-parameters) auto queueID = addVertex( QueueTag{}, std::forward_as_tuple(name.c_str()), - std::forward_as_tuple(layoutName.c_str()), + std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(hint), *renderGraph, passID); - auto queueLayoutID = locate(layoutID, layoutName, *layoutGraph); - - return new NativeRasterQueueBuilder(renderGraph, queueID, layoutGraph, queueLayoutID); + return new NativeRasterQueueBuilder(renderGraph, queueID, layoutGraph); } -RasterQueueBuilder *NativeRasterPassBuilder::addQueue( - QueueHint hint, - const ccstd::string &layoutName) { - return addQueue(hint, layoutName, "Queue"); -} - -namespace { - -const ccstd::pmr::string &getFirstChildLayoutName( - const LayoutGraphData &lg, - LayoutGraphData::vertex_descriptor parentID) { - auto childNodes = children(parentID, lg); - CC_EXPECTS(childNodes.first->target != LayoutGraphData::null_vertex()); - CC_EXPECTS(std::distance(childNodes.first, childNodes.second) == 1); - auto queueLayoutID = childNodes.first->target; - const auto &layoutName = get(LayoutGraphData::Name, lg, queueLayoutID); - return layoutName; -} - -} // namespace - RasterQueueBuilder *NativeRasterPassBuilder::addQueue(QueueHint hint) { - const auto &layoutName = getFirstChildLayoutName(*layoutGraph, passID); - return addQueue(hint, layoutName.c_str(), "Queue"); // NOLINT(readability-redundant-string-cstr) + return addQueue(hint, "Queue"); } void NativeRasterPassBuilder::addFullscreenQuad( - const ccstd::string &shader, const ccstd::string &layoutName, const ccstd::string &name) { // NOLINT(bugprone-easily-swappable-parameters) + Material *material, SceneFlags sceneFlags, const ccstd::string &name) { // NOLINT(bugprone-easily-swappable-parameters) auto queueID = addVertex( QueueTag{}, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple(layoutName.c_str()), + std::forward_as_tuple("Queue"), + std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(QueueHint::RENDER_TRANSPARENT), @@ -280,22 +304,49 @@ void NativeRasterPassBuilder::addFullscreenQuad( addVertex( BlitTag{}, - std::forward_as_tuple("FullscreenQuad"), + std::forward_as_tuple(name), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(), - std::forward_as_tuple(shader.c_str()), + std::forward_as_tuple(material, sceneFlags, nullptr), *renderGraph, queueID); } void NativeRasterPassBuilder::addFullscreenQuad( - const ccstd::string &shader, const ccstd::string &layoutName) { // NOLINT(bugprone-easily-swappable-parameters) - return addFullscreenQuad(shader, layoutName, "FullscreenQuad"); + Material *material, SceneFlags sceneFlags) { + return addFullscreenQuad(material, sceneFlags, "FullscreenQuad"); } -void NativeRasterPassBuilder::addFullscreenQuad(const ccstd::string &shader) { - const auto &layoutName = getFirstChildLayoutName(*layoutGraph, passID); - return addFullscreenQuad(shader, layoutName.c_str()); // NOLINT(readability-redundant-string-cstr) +void NativeRasterPassBuilder::addCameraQuad( + scene::Camera *camera, cc::Material *material, + SceneFlags sceneFlags, const ccstd::string &name) { + auto queueID = addVertex( + QueueTag{}, + std::forward_as_tuple("Queue"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(QueueHint::RENDER_TRANSPARENT), + *renderGraph, passID); + + addVertex( + BlitTag{}, + std::forward_as_tuple(name), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(material, sceneFlags, camera), + *renderGraph, queueID); +} + +void NativeRasterPassBuilder::addCameraQuad( + scene::Camera *camera, cc::Material *material, SceneFlags sceneFlags) { + return addCameraQuad(camera, material, sceneFlags, "CameraQuad"); +} + +void NativeRasterPassBuilder::setViewport(const gfx::Viewport &viewport) { + auto& pass = get(RasterTag{}, passID, *renderGraph); + pass.viewport = viewport; } void NativeRasterPassBuilder::setMat4(const ccstd::string &name, const Mat4 &mat) { @@ -354,24 +405,23 @@ void NativeRasterPassBuilder::setSampler(const ccstd::string &name, gfx::Sampler } // NativeComputeQueue -void NativeComputeQueueBuilder::addDispatch(const ccstd::string &shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string &layoutName, const ccstd::string &name) { // NOLINT(bugprone-easily-swappable-parameters) +void NativeComputeQueueBuilder::addDispatch(const ccstd::string &shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string &name) { addVertex( DispatchTag{}, std::forward_as_tuple(name.c_str()), - std::forward_as_tuple(layoutName.c_str()), std::forward_as_tuple(), std::forward_as_tuple(), - std::forward_as_tuple(shader.c_str(), threadGroupCountX, threadGroupCountY, threadGroupCountZ), - *renderGraph, queueID); -} - -void NativeComputeQueueBuilder::addDispatch(const ccstd::string &shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string &layoutName) { - addDispatch(shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ, layoutName.c_str(), "Dispatch"); // NOLINT(readability-redundant-string-cstr) + std::forward_as_tuple(), + std::forward_as_tuple( + shader.c_str(), + threadGroupCountX, + threadGroupCountY, + threadGroupCountZ), + *renderGraph); } void NativeComputeQueueBuilder::addDispatch(const ccstd::string &shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ) { - const auto &layoutName = getFirstChildLayoutName(*layoutGraph, queueID); - addDispatch(shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ, layoutName.c_str()); // NOLINT(readability-redundant-string-cstr) + addDispatch(shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ, "Dispatch"); } void NativeComputeQueueBuilder::setMat4(const ccstd::string &name, const Mat4 &mat) { @@ -443,50 +493,31 @@ void NativeComputePassBuilder::addComputeView(const ccstd::string &name, const C iter->second.emplace_back(view); } -ComputeQueueBuilder *NativeComputePassBuilder::addQueue( - const ccstd::string &layoutName, const ccstd::string &name) { // NOLINT(bugprone-easily-swappable-parameters) - +ComputeQueueBuilder *NativeComputePassBuilder::addQueue(const ccstd::string &name) { auto queueID = addVertex( QueueTag{}, std::forward_as_tuple(name.c_str()), - std::forward_as_tuple(layoutName.c_str()), + std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(QueueHint::NONE), *renderGraph, passID); - auto queueLayoutID = locate(layoutID, layoutName, *layoutGraph); - - return new NativeComputeQueueBuilder(renderGraph, queueID, layoutGraph, queueLayoutID); -} - -ComputeQueueBuilder *NativeComputePassBuilder::addQueue(const ccstd::string &layoutName) { - auto queueID = addVertex( - QueueTag{}, - std::forward_as_tuple("Compute"), - std::forward_as_tuple(layoutName.c_str()), - std::forward_as_tuple(), - std::forward_as_tuple(), - std::forward_as_tuple(), - *renderGraph, passID); - - auto queueLayoutID = locate(layoutID, layoutName, *layoutGraph); - - return new NativeComputeQueueBuilder(renderGraph, queueID, layoutGraph, queueLayoutID); + return new NativeComputeQueueBuilder(renderGraph, queueID, layoutGraph); } ComputeQueueBuilder *NativeComputePassBuilder::addQueue() { - const auto &layoutName = getFirstChildLayoutName(*layoutGraph, passID); - return addQueue(layoutName.c_str()); // NOLINT + return addQueue("Queue"); } void NativeComputePassBuilder::addDispatch( - const ccstd::string &shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, - const ccstd::string &layoutName, const ccstd::string &name) { // NOLINT(bugprone-easily-swappable-parameters) + const ccstd::string &shader, + uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, + const ccstd::string &name) { auto queueID = addVertex( QueueTag{}, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple(layoutName.c_str()), + std::forward_as_tuple("Queue"), + std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(), @@ -503,17 +534,9 @@ void NativeComputePassBuilder::addDispatch( } void NativeComputePassBuilder::addDispatch( - const ccstd::string &shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string &layoutName) { - addDispatch(shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ, layoutName, "Dispatch"); -} - -void NativeComputePassBuilder::addDispatch( - const ccstd::string &shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ) { - const auto &layoutName = getFirstChildLayoutName(*layoutGraph, passID); - - addDispatch( - shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ, - layoutName.c_str()); // NOLINT(readability-redundant-string-cstr) + const ccstd::string &shader, + uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ) { + addDispatch(shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ, "Dispatch"); } void NativeComputePassBuilder::setMat4(const ccstd::string &name, const Mat4 &mat) { diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h b/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h index a1feb6c568..fd501f13a4 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h @@ -31,6 +31,7 @@ // clang-format off #pragma once #include "cocos/base/std/variant.h" +#include "cocos/renderer/gfx-base/GFXDef-common.h" namespace cc { @@ -55,6 +56,16 @@ struct TextureTag; enum class TaskType; enum class SceneFlags : uint32_t; +enum class LightingMode : uint32_t; +enum class AttachmentType; +enum class AccessType; + +struct RasterView; + +enum class ClearValueType; + +struct ComputeView; +struct LightInfo; } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp index eda6387a5b..7163b8bddc 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp @@ -29,8 +29,162 @@ * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ // clang-format off +#include "cocos/bindings/auto/jsb_gfx_auto.h" +#include "cocos/bindings/auto/jsb_scene_auto.h" #include "cocos/renderer/pipeline/custom/JsbConversion.h" #include "cocos/renderer/pipeline/custom/RenderCommonJsb.h" #include "cocos/renderer/pipeline/custom/RenderCommonTypes.h" +bool nativevalue_to_se(const cc::render::RasterView &from, se::Value &to, se::Object *ctx) { // NOLINT + se::HandleObject obj(se::Object::createPlainObject()); + se::Value tmp; + + nativevalue_to_se(from.slotName, tmp, ctx); + obj->setProperty("slotName", tmp); + + nativevalue_to_se(from.accessType, tmp, ctx); + obj->setProperty("accessType", tmp); + + nativevalue_to_se(from.attachmentType, tmp, ctx); + obj->setProperty("attachmentType", tmp); + + nativevalue_to_se(from.loadOp, tmp, ctx); + obj->setProperty("loadOp", tmp); + + nativevalue_to_se(from.storeOp, tmp, ctx); + obj->setProperty("storeOp", tmp); + + nativevalue_to_se(from.clearFlags, tmp, ctx); + obj->setProperty("clearFlags", tmp); + + nativevalue_to_se(from.clearColor, tmp, ctx); + obj->setProperty("clearColor", tmp); + + to.setObject(obj); + return true; +} + +bool nativevalue_to_se(const cc::render::ComputeView &from, se::Value &to, se::Object *ctx) { // NOLINT + se::HandleObject obj(se::Object::createPlainObject()); + se::Value tmp; + + nativevalue_to_se(from.name, tmp, ctx); + obj->setProperty("name", tmp); + + nativevalue_to_se(from.accessType, tmp, ctx); + obj->setProperty("accessType", tmp); + + nativevalue_to_se(from.clearFlags, tmp, ctx); + obj->setProperty("clearFlags", tmp); + + nativevalue_to_se(from.clearColor, tmp, ctx); + obj->setProperty("clearColor", tmp); + + nativevalue_to_se(from.clearValueType, tmp, ctx); + obj->setProperty("clearValueType", tmp); + + to.setObject(obj); + return true; +} + +bool nativevalue_to_se(const cc::render::LightInfo &from, se::Value &to, se::Object *ctx) { // NOLINT + se::HandleObject obj(se::Object::createPlainObject()); + se::Value tmp; + + nativevalue_to_se(from.light, tmp, ctx); + obj->setProperty("light", tmp); + + nativevalue_to_se(from.level, tmp, ctx); + obj->setProperty("level", tmp); + + to.setObject(obj); + return true; +} + +template <> +bool sevalue_to_native(const se::Value &from, cc::render::RasterView *to, se::Object *ctx) { // NOLINT + SE_PRECONDITION2(from.isObject(), false, " Convert parameter to RasterView failed !"); + + auto *obj = const_cast(from.toObject()); + bool ok = true; + se::Value field; + obj->getProperty("slotName", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->slotName), ctx); + } + obj->getProperty("accessType", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->accessType), ctx); + } + obj->getProperty("attachmentType", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->attachmentType), ctx); + } + obj->getProperty("loadOp", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->loadOp), ctx); + } + obj->getProperty("storeOp", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->storeOp), ctx); + } + obj->getProperty("clearFlags", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->clearFlags), ctx); + } + obj->getProperty("clearColor", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->clearColor), ctx); + } + return ok; +} + +template <> +bool sevalue_to_native(const se::Value &from, cc::render::ComputeView *to, se::Object *ctx) { // NOLINT + SE_PRECONDITION2(from.isObject(), false, " Convert parameter to ComputeView failed !"); + + auto *obj = const_cast(from.toObject()); + bool ok = true; + se::Value field; + obj->getProperty("name", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->name), ctx); + } + obj->getProperty("accessType", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->accessType), ctx); + } + obj->getProperty("clearFlags", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->clearFlags), ctx); + } + obj->getProperty("clearColor", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->clearColor), ctx); + } + obj->getProperty("clearValueType", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->clearValueType), ctx); + } + return ok; +} + +template <> +bool sevalue_to_native(const se::Value &from, cc::render::LightInfo *to, se::Object *ctx) { // NOLINT + SE_PRECONDITION2(from.isObject(), false, " Convert parameter to LightInfo failed !"); + + auto *obj = const_cast(from.toObject()); + bool ok = true; + se::Value field; + obj->getProperty("light", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->light), ctx); + } + obj->getProperty("level", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->level), ctx); + } + return ok; +} + // clang-format on diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.h b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.h index 288bd6d01f..aefc4ae8b2 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.h @@ -33,4 +33,20 @@ #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/renderer/pipeline/custom/RenderCommonFwd.h" +bool nativevalue_to_se(const cc::render::RasterView &from, se::Value &to, se::Object *ctx); // NOLINT + +bool nativevalue_to_se(const cc::render::ComputeView &from, se::Value &to, se::Object *ctx); // NOLINT + +bool nativevalue_to_se(const cc::render::LightInfo &from, se::Value &to, se::Object *ctx); // NOLINT + +// if function overload is used, android build fails +template <> +bool sevalue_to_native(const se::Value &from, cc::render::RasterView *to, se::Object *ctx); // NOLINT + +template <> +bool sevalue_to_native(const se::Value &from, cc::render::ComputeView *to, se::Object *ctx); // NOLINT + +template <> +bool sevalue_to_native(const se::Value &from, cc::render::LightInfo *to, se::Object *ctx); // NOLINT + // clang-format on diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonNames.h b/native/cocos/renderer/pipeline/custom/RenderCommonNames.h index e79ebdd6a7..873c195ccb 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonNames.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonNames.h @@ -99,6 +99,39 @@ inline const char* getName(TaskType e) noexcept { } return ""; } +inline const char* getName(LightingMode e) noexcept { + switch (e) { + case LightingMode::NONE: return "NONE"; + case LightingMode::DEFAULT: return "DEFAULT"; + case LightingMode::CLUSTERED: return "CLUSTERED"; + } + return ""; +} +inline const char* getName(AttachmentType e) noexcept { + switch (e) { + case AttachmentType::RENDER_TARGET: return "RENDER_TARGET"; + case AttachmentType::DEPTH_STENCIL: return "DEPTH_STENCIL"; + } + return ""; +} +inline const char* getName(AccessType e) noexcept { + switch (e) { + case AccessType::READ: return "READ"; + case AccessType::READ_WRITE: return "READ_WRITE"; + case AccessType::WRITE: return "WRITE"; + } + return ""; +} +inline const char* getName(const RasterView& /*v*/) noexcept { return "RasterView"; } +inline const char* getName(ClearValueType e) noexcept { + switch (e) { + case ClearValueType::FLOAT_TYPE: return "FLOAT_TYPE"; + case ClearValueType::INT_TYPE: return "INT_TYPE"; + } + return ""; +} +inline const char* getName(const ComputeView& /*v*/) noexcept { return "ComputeView"; } +inline const char* getName(const LightInfo& /*v*/) noexcept { return "LightInfo"; } } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp index b6d8880543..9931e66b53 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp @@ -31,4 +31,59 @@ // clang-format off #include "RenderCommonTypes.h" +namespace cc { + +namespace render { + +RasterView::RasterView(const allocator_type& alloc) noexcept +: slotName(alloc) {} + +RasterView::RasterView(ccstd::pmr::string slotNameIn, AccessType accessTypeIn, AttachmentType attachmentTypeIn, gfx::LoadOp loadOpIn, gfx::StoreOp storeOpIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, const allocator_type& alloc) noexcept +: slotName(std::move(slotNameIn), alloc), + accessType(accessTypeIn), + attachmentType(attachmentTypeIn), + loadOp(loadOpIn), + storeOp(storeOpIn), + clearFlags(clearFlagsIn), + clearColor(clearColorIn) {} + +RasterView::RasterView(RasterView&& rhs, const allocator_type& alloc) +: slotName(std::move(rhs.slotName), alloc), + accessType(rhs.accessType), + attachmentType(rhs.attachmentType), + loadOp(rhs.loadOp), + storeOp(rhs.storeOp), + clearFlags(rhs.clearFlags), + clearColor(rhs.clearColor) {} + +RasterView::RasterView(RasterView const& rhs, const allocator_type& alloc) +: slotName(rhs.slotName, alloc), + accessType(rhs.accessType), + attachmentType(rhs.attachmentType), + loadOp(rhs.loadOp), + storeOp(rhs.storeOp), + clearFlags(rhs.clearFlags), + clearColor(rhs.clearColor) {} + +ComputeView::ComputeView(const allocator_type& alloc) noexcept +: name(alloc) {} + +ComputeView::ComputeView(ComputeView&& rhs, const allocator_type& alloc) +: name(std::move(rhs.name), alloc), + accessType(rhs.accessType), + clearFlags(rhs.clearFlags), + clearColor(rhs.clearColor), + clearValueType(rhs.clearValueType) {} + +ComputeView::ComputeView(ComputeView const& rhs, const allocator_type& alloc) +: name(rhs.name, alloc), + accessType(rhs.accessType), + clearFlags(rhs.clearFlags), + clearColor(rhs.clearColor), + clearValueType(rhs.clearValueType) {} + +} // namespace render + +} // namespace cc + // clang-format on diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h index bc0d25ff0a..b6eae836e8 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h @@ -30,7 +30,11 @@ */ // clang-format off #pragma once +#include "cocos/base/Ptr.h" +#include "cocos/base/std/container/string.h" +#include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/pipeline/custom/RenderCommonFwd.h" +#include "cocos/scene/Light.h" namespace cc { @@ -126,10 +130,17 @@ enum class TaskType { enum class SceneFlags : uint32_t { NONE = 0, - OPAQUE_OBJECT = 0x1, - CUTOUT_OBJECT = 0x2, - TRANSPARENT_OBJECT = 0x4, - SHADOW_CASTER = 0x8, + OPAQUE_OBJECT = 1, + CUTOUT_OBJECT = 2, + TRANSPARENT_OBJECT = 4, + SHADOW_CASTER = 8, + UI = 16, + DEFAULT_LIGHTING = 32, + VOLUMETRIC_LIGHTING = 64, + CLUSTERED_LIGHTING = 128, + PLANAR_SHADOW = 256, + GEOMETRY = 512, + PROFILER = 1024, ALL = 0xFFFFFFFF, }; @@ -157,6 +168,92 @@ constexpr bool any(SceneFlags e) noexcept { return !!e; } +enum class LightingMode : uint32_t { + NONE, + DEFAULT, + CLUSTERED, +}; + +enum class AttachmentType { + RENDER_TARGET, + DEPTH_STENCIL, +}; + +enum class AccessType { + READ, + READ_WRITE, + WRITE, +}; + +struct RasterView { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {slotName.get_allocator().resource()}; + } + + RasterView(const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; // NOLINT + RasterView(ccstd::pmr::string slotNameIn, AccessType accessTypeIn, AttachmentType attachmentTypeIn, gfx::LoadOp loadOpIn, gfx::StoreOp storeOpIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; + RasterView(RasterView&& rhs, const allocator_type& alloc); + RasterView(RasterView const& rhs, const allocator_type& alloc); + + RasterView(RasterView&& rhs) noexcept = default; + RasterView(RasterView const& rhs) = delete; + RasterView& operator=(RasterView&& rhs) = default; + RasterView& operator=(RasterView const& rhs) = default; + + ccstd::pmr::string slotName; + AccessType accessType{AccessType::WRITE}; + AttachmentType attachmentType{AttachmentType::RENDER_TARGET}; + gfx::LoadOp loadOp{gfx::LoadOp::LOAD}; + gfx::StoreOp storeOp{gfx::StoreOp::STORE}; + gfx::ClearFlagBit clearFlags{gfx::ClearFlagBit::ALL}; + gfx::Color clearColor; +}; + +enum class ClearValueType { + FLOAT_TYPE, + INT_TYPE, +}; + +struct ComputeView { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {name.get_allocator().resource()}; + } + + ComputeView(const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; // NOLINT + ComputeView(ComputeView&& rhs, const allocator_type& alloc); + ComputeView(ComputeView const& rhs, const allocator_type& alloc); + + ComputeView(ComputeView&& rhs) noexcept = default; + ComputeView(ComputeView const& rhs) = delete; + ComputeView& operator=(ComputeView&& rhs) = default; + ComputeView& operator=(ComputeView const& rhs) = default; + + bool isRead() const { + return accessType != AccessType::WRITE; + } + bool isWrite() const { + return accessType != AccessType::READ; + } + + ccstd::pmr::string name; + AccessType accessType{AccessType::READ}; + gfx::ClearFlagBit clearFlags{gfx::ClearFlagBit::NONE}; + gfx::Color clearColor; + ClearValueType clearValueType{ClearValueType::FLOAT_TYPE}; +}; + +struct LightInfo { + LightInfo() = default; + LightInfo(IntrusivePtr lightIn, uint32_t levelIn) noexcept + : light(std::move(lightIn)), + level(levelIn) {} + + IntrusivePtr light; + uint32_t level{0}; +}; + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h b/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h index 0de53d2c5c..fd95b76d4d 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h @@ -31,7 +31,6 @@ // clang-format off #pragma once #include "cocos/base/std/variant.h" -#include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/pipeline/PipelineSceneData.h" #include "cocos/renderer/pipeline/custom/RenderCommonFwd.h" #include "cocos/scene/Camera.h" @@ -51,15 +50,6 @@ struct PersistentTextureTag; struct FramebufferTag; struct SwapchainTag; struct ResourceGraph; - -enum class AttachmentType; -enum class AccessType; - -struct RasterView; - -enum class ClearValueType; - -struct ComputeView; struct RasterSubpass; struct SubpassGraph; struct RasterPass; @@ -74,6 +64,9 @@ struct SceneTag; struct DispatchTag; struct BlitTag; struct PresentTag; +struct ClearTag; +struct ViewportTag; +struct ClearView; struct RenderQueue; struct SceneData; struct Dispatch; diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h b/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h index c073c761ba..9d5a41b48c 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h @@ -2161,6 +2161,12 @@ id(RenderGraph::vertex_descriptor u, const RenderGraph& g) noexcept { }, [](const impl::ValueHandle& h) { return h.value; + }, + [](const impl::ValueHandle& h) { + return h.value; + }, + [](const impl::ValueHandle& h) { + return h.value; }), g.vertices[u].handle); } @@ -2199,6 +2205,12 @@ tag(RenderGraph::vertex_descriptor u, const RenderGraph& g) noexcept { }, [](const impl::ValueHandle&) { return RenderGraph::VertexTag{DispatchTag{}}; + }, + [](const impl::ValueHandle&) { + return RenderGraph::VertexTag{ClearTag{}}; + }, + [](const impl::ValueHandle&) { + return RenderGraph::VertexTag{ViewportTag{}}; }), g.vertices[u].handle); } @@ -2237,6 +2249,12 @@ value(RenderGraph::vertex_descriptor u, RenderGraph& g) noexcept { }, [&](const impl::ValueHandle& h) { return RenderGraph::VertexValue{&g.dispatches[h.value]}; + }, + [&](const impl::ValueHandle& h) { + return RenderGraph::VertexValue{&g.clearViews[h.value]}; + }, + [&](const impl::ValueHandle& h) { + return RenderGraph::VertexValue{&g.viewports[h.value]}; }), g.vertices[u].handle); } @@ -2275,6 +2293,12 @@ value(RenderGraph::vertex_descriptor u, const RenderGraph& g) noexcept { }, [&](const impl::ValueHandle& h) { return RenderGraph::VertexConstValue{&g.dispatches[h.value]}; + }, + [&](const impl::ValueHandle& h) { + return RenderGraph::VertexConstValue{&g.clearViews[h.value]}; + }, + [&](const impl::ValueHandle& h) { + return RenderGraph::VertexConstValue{&g.viewports[h.value]}; }), g.vertices[u].handle); } @@ -2363,6 +2387,22 @@ holds(RenderGraph::vertex_descriptor v, const RenderGraph& g) noexc g.vertices[v].handle); } +template <> +inline bool +holds(RenderGraph::vertex_descriptor v, const RenderGraph& g) noexcept { + return ccstd::holds_alternative< + impl::ValueHandle>( + g.vertices[v].handle); +} + +template <> +inline bool +holds(RenderGraph::vertex_descriptor v, const RenderGraph& g) noexcept { + return ccstd::holds_alternative< + impl::ValueHandle>( + g.vertices[v].handle); +} + template inline bool holds_alternative(RenderGraph::vertex_descriptor v, const RenderGraph& g) noexcept; // NOLINT @@ -2447,6 +2487,22 @@ holds_alternative(RenderGraph::vertex_descriptor v, const RenderGraph& g.vertices[v].handle); } +template <> +inline bool +holds_alternative>(RenderGraph::vertex_descriptor v, const RenderGraph& g) noexcept { // NOLINT + return ccstd::holds_alternative< + impl::ValueHandle>( + g.vertices[v].handle); +} + +template <> +inline bool +holds_alternative(RenderGraph::vertex_descriptor v, const RenderGraph& g) noexcept { // NOLINT + return ccstd::holds_alternative< + impl::ValueHandle>( + g.vertices[v].handle); +} + template inline ValueT& get(RenderGraph::vertex_descriptor /*v*/, RenderGraph& /*g*/); @@ -2541,6 +2597,24 @@ get(RenderGraph::vertex_descriptor v, RenderGraph& g) { return g.dispatches[handle.value]; } +template <> +inline ccstd::pmr::vector& +get>(RenderGraph::vertex_descriptor v, RenderGraph& g) { + auto& handle = ccstd::get< + impl::ValueHandle>( + g.vertices[v].handle); + return g.clearViews[handle.value]; +} + +template <> +inline gfx::Viewport& +get(RenderGraph::vertex_descriptor v, RenderGraph& g) { + auto& handle = ccstd::get< + impl::ValueHandle>( + g.vertices[v].handle); + return g.viewports[handle.value]; +} + template inline const ValueT& get(RenderGraph::vertex_descriptor /*v*/, const RenderGraph& /*g*/); @@ -2635,6 +2709,24 @@ get(RenderGraph::vertex_descriptor v, const RenderGraph& g) { return g.dispatches[handle.value]; } +template <> +inline const ccstd::pmr::vector& +get>(RenderGraph::vertex_descriptor v, const RenderGraph& g) { + const auto& handle = ccstd::get< + impl::ValueHandle>( + g.vertices[v].handle); + return g.clearViews[handle.value]; +} + +template <> +inline const gfx::Viewport& +get(RenderGraph::vertex_descriptor v, const RenderGraph& g) { + const auto& handle = ccstd::get< + impl::ValueHandle>( + g.vertices[v].handle); + return g.viewports[handle.value]; +} + inline RasterPass& get(RasterTag /*tag*/, RenderGraph::vertex_descriptor v, RenderGraph& g) { auto& handle = ccstd::get< @@ -2715,6 +2807,22 @@ get(DispatchTag /*tag*/, RenderGraph::vertex_descriptor v, RenderGraph& g) { return g.dispatches[handle.value]; } +inline ccstd::pmr::vector& +get(ClearTag /*tag*/, RenderGraph::vertex_descriptor v, RenderGraph& g) { + auto& handle = ccstd::get< + impl::ValueHandle>( + g.vertices[v].handle); + return g.clearViews[handle.value]; +} + +inline gfx::Viewport& +get(ViewportTag /*tag*/, RenderGraph::vertex_descriptor v, RenderGraph& g) { + auto& handle = ccstd::get< + impl::ValueHandle>( + g.vertices[v].handle); + return g.viewports[handle.value]; +} + inline const RasterPass& get(RasterTag /*tag*/, RenderGraph::vertex_descriptor v, const RenderGraph& g) { const auto& handle = ccstd::get< @@ -2795,6 +2903,22 @@ get(DispatchTag /*tag*/, RenderGraph::vertex_descriptor v, const RenderGraph& g) return g.dispatches[handle.value]; } +inline const ccstd::pmr::vector& +get(ClearTag /*tag*/, RenderGraph::vertex_descriptor v, const RenderGraph& g) { + const auto& handle = ccstd::get< + impl::ValueHandle>( + g.vertices[v].handle); + return g.clearViews[handle.value]; +} + +inline const gfx::Viewport& +get(ViewportTag /*tag*/, RenderGraph::vertex_descriptor v, const RenderGraph& g) { + const auto& handle = ccstd::get< + impl::ValueHandle>( + g.vertices[v].handle); + return g.viewports[handle.value]; +} + template inline ValueT* get_if(RenderGraph::vertex_descriptor v, RenderGraph* pGraph) noexcept; // NOLINT @@ -2969,6 +3093,40 @@ get_if(RenderGraph::vertex_descriptor v, RenderGraph* pGraph) noexcept return ptr; } +template <> +inline ccstd::pmr::vector* +get_if>(RenderGraph::vertex_descriptor v, RenderGraph* pGraph) noexcept { // NOLINT + ccstd::pmr::vector* ptr = nullptr; + if (!pGraph) { + return ptr; + } + auto& g = *pGraph; + auto* pHandle = ccstd::get_if< + impl::ValueHandle>( + &g.vertices[v].handle); + if (pHandle) { + ptr = &g.clearViews[pHandle->value]; + } + return ptr; +} + +template <> +inline gfx::Viewport* +get_if(RenderGraph::vertex_descriptor v, RenderGraph* pGraph) noexcept { // NOLINT + gfx::Viewport* ptr = nullptr; + if (!pGraph) { + return ptr; + } + auto& g = *pGraph; + auto* pHandle = ccstd::get_if< + impl::ValueHandle>( + &g.vertices[v].handle); + if (pHandle) { + ptr = &g.viewports[pHandle->value]; + } + return ptr; +} + template inline const ValueT* get_if(RenderGraph::vertex_descriptor v, const RenderGraph* pGraph) noexcept; // NOLINT @@ -3143,6 +3301,40 @@ get_if(RenderGraph::vertex_descriptor v, const RenderGraph* pGraph) no return ptr; } +template <> +inline const ccstd::pmr::vector* +get_if>(RenderGraph::vertex_descriptor v, const RenderGraph* pGraph) noexcept { // NOLINT + const ccstd::pmr::vector* ptr = nullptr; + if (!pGraph) { + return ptr; + } + const auto& g = *pGraph; + const auto* pHandle = ccstd::get_if< + impl::ValueHandle>( + &g.vertices[v].handle); + if (pHandle) { + ptr = &g.clearViews[pHandle->value]; + } + return ptr; +} + +template <> +inline const gfx::Viewport* +get_if(RenderGraph::vertex_descriptor v, const RenderGraph* pGraph) noexcept { // NOLINT + const gfx::Viewport* ptr = nullptr; + if (!pGraph) { + return ptr; + } + const auto& g = *pGraph; + const auto* pHandle = ccstd::get_if< + impl::ValueHandle>( + &g.vertices[v].handle); + if (pHandle) { + ptr = &g.viewports[pHandle->value]; + } + return ptr; +} + // Vertex Constant Getter template inline decltype(auto) @@ -3284,6 +3476,20 @@ inline void remove_vertex_value_impl(const RenderGraph::VertexHandle& h, RenderG return; } impl::reindexVectorHandle(g.vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.clearViews.erase(g.clearViews.begin() + std::ptrdiff_t(h.value)); + if (h.value == g.clearViews.size()) { + return; + } + impl::reindexVectorHandle(g.vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.viewports.erase(g.viewports.begin() + std::ptrdiff_t(h.value)); + if (h.value == g.viewports.size()) { + return; + } + impl::reindexVectorHandle(g.vertices, h.value); }), h); } @@ -3392,6 +3598,24 @@ void addVertexImpl( // NOLINT g.dispatches.emplace_back(std::forward(val)); } +template +void addVertexImpl( // NOLINT + ValueT &&val, RenderGraph &g, RenderGraph::Vertex &vert, // NOLINT + std::enable_if_t, ccstd::pmr::vector>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.clearViews.size())}; + g.clearViews.emplace_back(std::forward(val)); +} + +template +void addVertexImpl( // NOLINT + ValueT &&val, RenderGraph &g, RenderGraph::Vertex &vert, // NOLINT + std::enable_if_t, gfx::Viewport>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.viewports.size())}; + g.viewports.emplace_back(std::forward(val)); +} + template inline RenderGraph::vertex_descriptor addVertex(Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, ValueT&& val, RenderGraph& g, RenderGraph::vertex_descriptor u = RenderGraph::null_vertex()) { @@ -3526,6 +3750,28 @@ void addVertexImpl(DispatchTag /*tag*/, Tuple &&val, RenderGraph &g, RenderGraph std::forward(val)); } +template +void addVertexImpl(ClearTag /*tag*/, Tuple &&val, RenderGraph &g, RenderGraph::Vertex &vert) { + invoke_hpp::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.clearViews.size())}; + g.clearViews.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +void addVertexImpl(ViewportTag /*tag*/, Tuple &&val, RenderGraph &g, RenderGraph::Vertex &vert) { + invoke_hpp::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.viewports.size())}; + g.viewports.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + template inline RenderGraph::vertex_descriptor addVertex(Tag tag, Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, ValueT&& val, RenderGraph& g, RenderGraph::vertex_descriptor u = RenderGraph::null_vertex()) { diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphJsb.cpp b/native/cocos/renderer/pipeline/custom/RenderGraphJsb.cpp index b1628fd247..bc61fb0025 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphJsb.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderGraphJsb.cpp @@ -30,62 +30,11 @@ */ // clang-format off #include "cocos/bindings/auto/jsb_gfx_auto.h" +#include "cocos/bindings/auto/jsb_scene_auto.h" #include "cocos/renderer/pipeline/custom/JsbConversion.h" #include "cocos/renderer/pipeline/custom/RenderGraphJsb.h" #include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" -bool nativevalue_to_se(const cc::render::RasterView &from, se::Value &to, se::Object *ctx) { // NOLINT - se::HandleObject obj(se::Object::createPlainObject()); - se::Value tmp; - - nativevalue_to_se(from.slotName, tmp, ctx); - obj->setProperty("slotName", tmp); - - nativevalue_to_se(from.accessType, tmp, ctx); - obj->setProperty("accessType", tmp); - - nativevalue_to_se(from.attachmentType, tmp, ctx); - obj->setProperty("attachmentType", tmp); - - nativevalue_to_se(from.loadOp, tmp, ctx); - obj->setProperty("loadOp", tmp); - - nativevalue_to_se(from.storeOp, tmp, ctx); - obj->setProperty("storeOp", tmp); - - nativevalue_to_se(from.clearFlags, tmp, ctx); - obj->setProperty("clearFlags", tmp); - - nativevalue_to_se(from.clearColor, tmp, ctx); - obj->setProperty("clearColor", tmp); - - to.setObject(obj); - return true; -} - -bool nativevalue_to_se(const cc::render::ComputeView &from, se::Value &to, se::Object *ctx) { // NOLINT - se::HandleObject obj(se::Object::createPlainObject()); - se::Value tmp; - - nativevalue_to_se(from.name, tmp, ctx); - obj->setProperty("name", tmp); - - nativevalue_to_se(from.accessType, tmp, ctx); - obj->setProperty("accessType", tmp); - - nativevalue_to_se(from.clearFlags, tmp, ctx); - obj->setProperty("clearFlags", tmp); - - nativevalue_to_se(from.clearColor, tmp, ctx); - obj->setProperty("clearColor", tmp); - - nativevalue_to_se(from.clearValueType, tmp, ctx); - obj->setProperty("clearValueType", tmp); - - to.setObject(obj); - return true; -} - bool nativevalue_to_se(const cc::render::CopyPair &from, se::Value &to, se::Object *ctx) { // NOLINT se::HandleObject obj(se::Object::createPlainObject()); se::Value tmp; @@ -153,72 +102,21 @@ bool nativevalue_to_se(const cc::render::MovePair &from, se::Value &to, se::Obje return true; } -template <> -bool sevalue_to_native(const se::Value &from, cc::render::RasterView *to, se::Object *ctx) { // NOLINT - SE_PRECONDITION2(from.isObject(), false, " Convert parameter to RasterView failed !"); +bool nativevalue_to_se(const cc::render::ClearView &from, se::Value &to, se::Object *ctx) { // NOLINT + se::HandleObject obj(se::Object::createPlainObject()); + se::Value tmp; - auto *obj = const_cast(from.toObject()); - bool ok = true; - se::Value field; - obj->getProperty("slotName", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->slotName), ctx); - } - obj->getProperty("accessType", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->accessType), ctx); - } - obj->getProperty("attachmentType", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->attachmentType), ctx); - } - obj->getProperty("loadOp", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->loadOp), ctx); - } - obj->getProperty("storeOp", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->storeOp), ctx); - } - obj->getProperty("clearFlags", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->clearFlags), ctx); - } - obj->getProperty("clearColor", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->clearColor), ctx); - } - return ok; -} + nativevalue_to_se(from.slotName, tmp, ctx); + obj->setProperty("slotName", tmp); -template <> -bool sevalue_to_native(const se::Value &from, cc::render::ComputeView *to, se::Object *ctx) { // NOLINT - SE_PRECONDITION2(from.isObject(), false, " Convert parameter to ComputeView failed !"); + nativevalue_to_se(from.clearFlags, tmp, ctx); + obj->setProperty("clearFlags", tmp); - auto *obj = const_cast(from.toObject()); - bool ok = true; - se::Value field; - obj->getProperty("name", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->name), ctx); - } - obj->getProperty("accessType", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->accessType), ctx); - } - obj->getProperty("clearFlags", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->clearFlags), ctx); - } - obj->getProperty("clearColor", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->clearColor), ctx); - } - obj->getProperty("clearValueType", &field, true); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->clearValueType), ctx); - } - return ok; + nativevalue_to_se(from.clearColor, tmp, ctx); + obj->setProperty("clearColor", tmp); + + to.setObject(obj); + return true; } template <> @@ -309,4 +207,26 @@ bool sevalue_to_native(const se::Value &from, cc::render:: return ok; } +template <> +bool sevalue_to_native(const se::Value &from, cc::render::ClearView *to, se::Object *ctx) { // NOLINT + SE_PRECONDITION2(from.isObject(), false, " Convert parameter to ClearView failed !"); + + auto *obj = const_cast(from.toObject()); + bool ok = true; + se::Value field; + obj->getProperty("slotName", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->slotName), ctx); + } + obj->getProperty("clearFlags", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->clearFlags), ctx); + } + obj->getProperty("clearColor", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->clearColor), ctx); + } + return ok; +} + // clang-format on diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphJsb.h b/native/cocos/renderer/pipeline/custom/RenderGraphJsb.h index 6aeb8715d9..15be814257 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphJsb.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphJsb.h @@ -34,25 +34,20 @@ #include "cocos/renderer/pipeline/custom/RenderCommonJsb.h" #include "cocos/renderer/pipeline/custom/RenderGraphFwd.h" -bool nativevalue_to_se(const cc::render::RasterView &from, se::Value &to, se::Object *ctx); // NOLINT - -bool nativevalue_to_se(const cc::render::ComputeView &from, se::Value &to, se::Object *ctx); // NOLINT - bool nativevalue_to_se(const cc::render::CopyPair &from, se::Value &to, se::Object *ctx); // NOLINT bool nativevalue_to_se(const cc::render::MovePair &from, se::Value &to, se::Object *ctx); // NOLINT +bool nativevalue_to_se(const cc::render::ClearView &from, se::Value &to, se::Object *ctx); // NOLINT + // if function overload is used, android build fails -template <> -bool sevalue_to_native(const se::Value &from, cc::render::RasterView *to, se::Object *ctx); // NOLINT - -template <> -bool sevalue_to_native(const se::Value &from, cc::render::ComputeView *to, se::Object *ctx); // NOLINT - template <> bool sevalue_to_native(const se::Value &from, cc::render::CopyPair *to, se::Object *ctx); // NOLINT template <> bool sevalue_to_native(const se::Value &from, cc::render::MovePair *to, se::Object *ctx); // NOLINT +template <> +bool sevalue_to_native(const se::Value &from, cc::render::ClearView *to, se::Object *ctx); // NOLINT + // clang-format on diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphNames.h b/native/cocos/renderer/pipeline/custom/RenderGraphNames.h index b75d45d667..7dbed39cdf 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphNames.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphNames.h @@ -48,30 +48,6 @@ inline const char* getName(const PersistentTextureTag& /*v*/) noexcept { return inline const char* getName(const FramebufferTag& /*v*/) noexcept { return "Framebuffer"; } inline const char* getName(const SwapchainTag& /*v*/) noexcept { return "Swapchain"; } inline const char* getName(const ResourceGraph& /*v*/) noexcept { return "ResourceGraph"; } -inline const char* getName(AttachmentType e) noexcept { - switch (e) { - case AttachmentType::RENDER_TARGET: return "RENDER_TARGET"; - case AttachmentType::DEPTH_STENCIL: return "DEPTH_STENCIL"; - } - return ""; -} -inline const char* getName(AccessType e) noexcept { - switch (e) { - case AccessType::READ: return "READ"; - case AccessType::READ_WRITE: return "READ_WRITE"; - case AccessType::WRITE: return "WRITE"; - } - return ""; -} -inline const char* getName(const RasterView& /*v*/) noexcept { return "RasterView"; } -inline const char* getName(ClearValueType e) noexcept { - switch (e) { - case ClearValueType::FLOAT_TYPE: return "FLOAT_TYPE"; - case ClearValueType::INT_TYPE: return "INT_TYPE"; - } - return ""; -} -inline const char* getName(const ComputeView& /*v*/) noexcept { return "ComputeView"; } inline const char* getName(const RasterSubpass& /*v*/) noexcept { return "RasterSubpass"; } inline const char* getName(const SubpassGraph& /*v*/) noexcept { return "SubpassGraph"; } inline const char* getName(const RasterPass& /*v*/) noexcept { return "RasterPass"; } @@ -86,6 +62,9 @@ inline const char* getName(const SceneTag& /*v*/) noexcept { return "Scene"; } inline const char* getName(const DispatchTag& /*v*/) noexcept { return "Dispatch"; } inline const char* getName(const BlitTag& /*v*/) noexcept { return "Blit"; } inline const char* getName(const PresentTag& /*v*/) noexcept { return "Present"; } +inline const char* getName(const ClearTag& /*v*/) noexcept { return "Clear"; } +inline const char* getName(const ViewportTag& /*v*/) noexcept { return "Viewport"; } +inline const char* getName(const ClearView& /*v*/) noexcept { return "ClearView"; } inline const char* getName(const RenderQueue& /*v*/) noexcept { return "RenderQueue"; } inline const char* getName(const SceneData& /*v*/) noexcept { return "SceneData"; } inline const char* getName(const Dispatch& /*v*/) noexcept { return "Dispatch"; } diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp index 9d483edfb8..bd4985d493 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp @@ -97,53 +97,6 @@ ResourceGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) inEdges(rhs.inEdges, alloc), handle(rhs.handle) {} -RasterView::RasterView(const allocator_type& alloc) noexcept -: slotName(alloc) {} - -RasterView::RasterView(ccstd::pmr::string slotNameIn, AccessType accessTypeIn, AttachmentType attachmentTypeIn, gfx::LoadOp loadOpIn, gfx::StoreOp storeOpIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, const allocator_type& alloc) noexcept -: slotName(std::move(slotNameIn), alloc), - accessType(accessTypeIn), - attachmentType(attachmentTypeIn), - loadOp(loadOpIn), - storeOp(storeOpIn), - clearFlags(clearFlagsIn), - clearColor(clearColorIn) {} - -RasterView::RasterView(RasterView&& rhs, const allocator_type& alloc) -: slotName(std::move(rhs.slotName), alloc), - accessType(rhs.accessType), - attachmentType(rhs.attachmentType), - loadOp(rhs.loadOp), - storeOp(rhs.storeOp), - clearFlags(rhs.clearFlags), - clearColor(rhs.clearColor) {} - -RasterView::RasterView(RasterView const& rhs, const allocator_type& alloc) -: slotName(rhs.slotName, alloc), - accessType(rhs.accessType), - attachmentType(rhs.attachmentType), - loadOp(rhs.loadOp), - storeOp(rhs.storeOp), - clearFlags(rhs.clearFlags), - clearColor(rhs.clearColor) {} - -ComputeView::ComputeView(const allocator_type& alloc) noexcept -: name(alloc) {} - -ComputeView::ComputeView(ComputeView&& rhs, const allocator_type& alloc) -: name(std::move(rhs.name), alloc), - accessType(rhs.accessType), - clearFlags(rhs.clearFlags), - clearColor(rhs.clearColor), - clearValueType(rhs.clearValueType) {} - -ComputeView::ComputeView(ComputeView const& rhs, const allocator_type& alloc) -: name(rhs.name, alloc), - accessType(rhs.accessType), - clearFlags(rhs.clearFlags), - clearColor(rhs.clearColor), - clearValueType(rhs.clearValueType) {} - RasterSubpass::RasterSubpass(const allocator_type& alloc) noexcept : rasterViews(alloc), computeViews(alloc) {} @@ -201,7 +154,8 @@ RasterPass::RasterPass(RasterPass&& rhs, const allocator_type& alloc) computeViews(std::move(rhs.computeViews), alloc), subpassGraph(std::move(rhs.subpassGraph), alloc), width(rhs.width), - height(rhs.height) {} + height(rhs.height), + viewport(rhs.viewport) {} RasterPass::RasterPass(RasterPass const& rhs, const allocator_type& alloc) : isValid(rhs.isValid), @@ -209,7 +163,8 @@ RasterPass::RasterPass(RasterPass const& rhs, const allocator_type& alloc) computeViews(rhs.computeViews, alloc), subpassGraph(rhs.subpassGraph, alloc), width(rhs.width), - height(rhs.height) {} + height(rhs.height), + viewport(rhs.viewport) {} ComputePass::ComputePass(const allocator_type& alloc) noexcept : computeViews(alloc) {} @@ -318,19 +273,38 @@ RaytracePass::RaytracePass(RaytracePass&& rhs, const allocator_type& alloc) RaytracePass::RaytracePass(RaytracePass const& rhs, const allocator_type& alloc) : computeViews(rhs.computeViews, alloc) {} +ClearView::ClearView(const allocator_type& alloc) noexcept +: slotName(alloc) {} + +ClearView::ClearView(ccstd::pmr::string slotNameIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, const allocator_type& alloc) noexcept +: slotName(std::move(slotNameIn), alloc), + clearFlags(clearFlagsIn), + clearColor(clearColorIn) {} + +ClearView::ClearView(ClearView&& rhs, const allocator_type& alloc) +: slotName(std::move(rhs.slotName), alloc), + clearFlags(rhs.clearFlags), + clearColor(rhs.clearColor) {} + +ClearView::ClearView(ClearView const& rhs, const allocator_type& alloc) +: slotName(rhs.slotName, alloc), + clearFlags(rhs.clearFlags), + clearColor(rhs.clearColor) {} + SceneData::SceneData(const allocator_type& alloc) noexcept : name(alloc), scenes(alloc) {} -SceneData::SceneData(ccstd::pmr::string nameIn, SceneFlags flagsIn, const allocator_type& alloc) noexcept +SceneData::SceneData(ccstd::pmr::string nameIn, SceneFlags flagsIn, LightInfo lightIn, const allocator_type& alloc) noexcept : name(std::move(nameIn), alloc), + light(std::move(lightIn)), flags(flagsIn), scenes(alloc) {} SceneData::SceneData(SceneData&& rhs, const allocator_type& alloc) : name(std::move(rhs.name), alloc), camera(rhs.camera), - light(rhs.light), + light(std::move(rhs.light)), flags(rhs.flags), scenes(std::move(rhs.scenes), alloc) {} @@ -362,18 +336,6 @@ Dispatch::Dispatch(Dispatch const& rhs, const allocator_type& alloc) threadGroupCountY(rhs.threadGroupCountY), threadGroupCountZ(rhs.threadGroupCountZ) {} -Blit::Blit(const allocator_type& alloc) noexcept -: shader(alloc) {} - -Blit::Blit(ccstd::pmr::string shaderIn, const allocator_type& alloc) noexcept -: shader(std::move(shaderIn), alloc) {} - -Blit::Blit(Blit&& rhs, const allocator_type& alloc) -: shader(std::move(rhs.shader), alloc) {} - -Blit::Blit(Blit const& rhs, const allocator_type& alloc) -: shader(rhs.shader, alloc) {} - PresentPass::PresentPass(const allocator_type& alloc) noexcept : presents(alloc) {} @@ -412,6 +374,8 @@ RenderGraph::RenderGraph(const allocator_type& alloc) noexcept scenes(alloc), blits(alloc), dispatches(alloc), + clearViews(alloc), + viewports(alloc), index(alloc) {} RenderGraph::RenderGraph(RenderGraph&& rhs, const allocator_type& alloc) @@ -431,6 +395,8 @@ RenderGraph::RenderGraph(RenderGraph&& rhs, const allocator_type& alloc) scenes(std::move(rhs.scenes), alloc), blits(std::move(rhs.blits), alloc), dispatches(std::move(rhs.dispatches), alloc), + clearViews(std::move(rhs.clearViews), alloc), + viewports(std::move(rhs.viewports), alloc), index(std::move(rhs.index), alloc) {} // ContinuousContainer diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h index bf346426ba..db49fc9bc5 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h @@ -37,8 +37,8 @@ #include "cocos/base/Ptr.h" #include "cocos/base/std/container/string.h" #include "cocos/base/std/container/vector.h" +#include "cocos/math/Geometry.h" #include "cocos/renderer/gfx-base/GFXBuffer.h" -#include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/gfx-base/GFXFramebuffer.h" #include "cocos/renderer/gfx-base/GFXSwapchain.h" #include "cocos/renderer/gfx-base/GFXTexture.h" @@ -253,76 +253,6 @@ struct ResourceGraph { PmrUnorderedStringMap valueIndex; }; -enum class AttachmentType { - RENDER_TARGET, - DEPTH_STENCIL, -}; - -enum class AccessType { - READ, - READ_WRITE, - WRITE, -}; - -struct RasterView { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {slotName.get_allocator().resource()}; - } - - RasterView(const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; // NOLINT - RasterView(ccstd::pmr::string slotNameIn, AccessType accessTypeIn, AttachmentType attachmentTypeIn, gfx::LoadOp loadOpIn, gfx::StoreOp storeOpIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; - RasterView(RasterView&& rhs, const allocator_type& alloc); - RasterView(RasterView const& rhs, const allocator_type& alloc); - - RasterView(RasterView&& rhs) noexcept = default; - RasterView(RasterView const& rhs) = delete; - RasterView& operator=(RasterView&& rhs) = default; - RasterView& operator=(RasterView const& rhs) = default; - - ccstd::pmr::string slotName; - AccessType accessType{AccessType::WRITE}; - AttachmentType attachmentType{AttachmentType::RENDER_TARGET}; - gfx::LoadOp loadOp{gfx::LoadOp::LOAD}; - gfx::StoreOp storeOp{gfx::StoreOp::STORE}; - gfx::ClearFlagBit clearFlags{gfx::ClearFlagBit::ALL}; - gfx::Color clearColor; -}; - -enum class ClearValueType { - FLOAT_TYPE, - INT_TYPE, -}; - -struct ComputeView { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {name.get_allocator().resource()}; - } - - ComputeView(const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; // NOLINT - ComputeView(ComputeView&& rhs, const allocator_type& alloc); - ComputeView(ComputeView const& rhs, const allocator_type& alloc); - - ComputeView(ComputeView&& rhs) noexcept = default; - ComputeView(ComputeView const& rhs) = delete; - ComputeView& operator=(ComputeView&& rhs) = default; - ComputeView& operator=(ComputeView const& rhs) = default; - - bool isRead() const { - return accessType != AccessType::WRITE; - } - bool isWrite() const { - return accessType != AccessType::READ; - } - - ccstd::pmr::string name; - AccessType accessType{AccessType::READ}; - gfx::ClearFlagBit clearFlags{gfx::ClearFlagBit::NONE}; - gfx::Color clearColor; - ClearValueType clearValueType{ClearValueType::FLOAT_TYPE}; -}; - struct RasterSubpass { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -485,6 +415,7 @@ struct RasterPass { SubpassGraph subpassGraph; uint32_t width{0}; uint32_t height{0}; + gfx::Viewport viewport; }; struct ComputePass { @@ -617,6 +548,29 @@ struct SceneTag {}; struct DispatchTag {}; struct BlitTag {}; struct PresentTag {}; +struct ClearTag {}; +struct ViewportTag {}; + +struct ClearView { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {slotName.get_allocator().resource()}; + } + + ClearView(const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; // NOLINT + ClearView(ccstd::pmr::string slotNameIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; + ClearView(ClearView&& rhs, const allocator_type& alloc); + ClearView(ClearView const& rhs, const allocator_type& alloc); + + ClearView(ClearView&& rhs) noexcept = default; + ClearView(ClearView const& rhs) = delete; + ClearView& operator=(ClearView&& rhs) = default; + ClearView& operator=(ClearView const& rhs) = default; + + ccstd::pmr::string slotName; + gfx::ClearFlagBit clearFlags{gfx::ClearFlagBit::ALL}; + gfx::Color clearColor; +}; struct RenderQueue { RenderQueue() = default; @@ -633,7 +587,7 @@ struct SceneData { } SceneData(const allocator_type& alloc) noexcept; // NOLINT - SceneData(ccstd::pmr::string nameIn, SceneFlags flagsIn, const allocator_type& alloc) noexcept; + SceneData(ccstd::pmr::string nameIn, SceneFlags flagsIn, LightInfo lightIn, const allocator_type& alloc) noexcept; SceneData(SceneData&& rhs, const allocator_type& alloc); SceneData(SceneData const& rhs, const allocator_type& alloc); @@ -644,7 +598,7 @@ struct SceneData { ccstd::pmr::string name; scene::Camera* camera{nullptr}; - scene::Light* light{nullptr}; + LightInfo light; SceneFlags flags{SceneFlags::NONE}; ccstd::pmr::vector scenes; }; @@ -672,22 +626,15 @@ struct Dispatch { }; struct Blit { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {shader.get_allocator().resource()}; - } + Blit() = default; + Blit(IntrusivePtr materialIn, SceneFlags sceneFlagsIn, scene::Camera* cameraIn) noexcept + : material(std::move(materialIn)), + sceneFlags(sceneFlagsIn), + camera(cameraIn) {} - Blit(const allocator_type& alloc) noexcept; // NOLINT - Blit(ccstd::pmr::string shaderIn, const allocator_type& alloc) noexcept; - Blit(Blit&& rhs, const allocator_type& alloc); - Blit(Blit const& rhs, const allocator_type& alloc); - - Blit(Blit&& rhs) noexcept = default; - Blit(Blit const& rhs) = delete; - Blit& operator=(Blit&& rhs) = default; - Blit& operator=(Blit const& rhs) = default; - - ccstd::pmr::string shader; + IntrusivePtr material; + SceneFlags sceneFlags{SceneFlags::NONE}; + scene::Camera* camera{nullptr}; }; struct Present { @@ -857,9 +804,9 @@ struct RenderGraph { } // PolymorphicGraph - using VertexTag = ccstd::variant; - using VertexValue = ccstd::variant; - using VertexConstValue = ccstd::variant; + using VertexTag = ccstd::variant; + using VertexValue = ccstd::variant*, gfx::Viewport*>; + using VertexConstValue = ccstd::variant*, const gfx::Viewport*>; using VertexHandle = ccstd::variant< impl::ValueHandle, impl::ValueHandle, @@ -870,7 +817,9 @@ struct RenderGraph { impl::ValueHandle, impl::ValueHandle, impl::ValueHandle, - impl::ValueHandle>; + impl::ValueHandle, + impl::ValueHandle, + impl::ValueHandle>; // ContinuousContainer void reserve(vertices_size_type sz); @@ -934,16 +883,18 @@ struct RenderGraph { ccstd::pmr::vector data; ccstd::pmr::vector valid; // PolymorphicGraph - ccstd::pmr::vector rasterPasses; - ccstd::pmr::vector computePasses; - ccstd::pmr::vector copyPasses; - ccstd::pmr::vector movePasses; - ccstd::pmr::vector presentPasses; - ccstd::pmr::vector raytracePasses; - ccstd::pmr::vector renderQueues; - ccstd::pmr::vector scenes; - ccstd::pmr::vector blits; - ccstd::pmr::vector dispatches; + ccstd::pmr::vector rasterPasses; + ccstd::pmr::vector computePasses; + ccstd::pmr::vector copyPasses; + ccstd::pmr::vector movePasses; + ccstd::pmr::vector presentPasses; + ccstd::pmr::vector raytracePasses; + ccstd::pmr::vector renderQueues; + ccstd::pmr::vector scenes; + ccstd::pmr::vector blits; + ccstd::pmr::vector dispatches; + ccstd::pmr::vector> clearViews; + ccstd::pmr::vector viewports; // Members PmrUnorderedStringMap index; }; diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h index 828cd5fff3..12f4506960 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h @@ -51,6 +51,7 @@ class SceneTask; class SceneTransversal; class LayoutGraphBuilder; class Pipeline; +class PipelineBuilder; class Factory; } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h index aaf024c2a2..0eb775ed73 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h @@ -80,17 +80,24 @@ public: virtual bool destroy() noexcept = 0; virtual void render(const ccstd::vector& cameras) = 0; - virtual const MacroRecord &getMacros() const = 0; - virtual pipeline::GlobalDSManager *getGlobalDSManager() const = 0; - virtual gfx::DescriptorSetLayout *getDescriptorSetLayout() const = 0; + virtual gfx::Device* getDevice() const = 0; + virtual const MacroRecord &getMacros() const = 0; + virtual pipeline::GlobalDSManager *getGlobalDSManager() const = 0; + virtual gfx::DescriptorSetLayout *getDescriptorSetLayout() const = 0; + virtual gfx::DescriptorSet *getDescriptorSet() const = 0; + virtual ccstd::vector getCommandBuffers() const = 0; virtual pipeline::PipelineSceneData *getPipelineSceneData() const = 0; - virtual const ccstd::string &getConstantMacros() const = 0; - virtual scene::Model *getProfiler() const = 0; - virtual void setProfiler(scene::Model *profiler) = 0; + virtual const ccstd::string &getConstantMacros() const = 0; + virtual scene::Model *getProfiler() const = 0; + virtual void setProfiler(scene::Model *profiler) = 0; virtual pipeline::GeometryRenderer *getGeometryRenderer() const = 0; virtual float getShadingScale() const = 0; - virtual void setShadingScale(float scale) = 0; + virtual void setShadingScale(float scale) = 0; + + virtual const ccstd::string& getMacroString(const ccstd::string& name) const = 0; + virtual int32_t getMacroInt(const ccstd::string& name) const = 0; + virtual bool getMacroBool(const ccstd::string& name) const = 0; virtual void setMacroString(const ccstd::string& name, const ccstd::string& value) = 0; virtual void setMacroInt(const ccstd::string& name, int32_t value) = 0; @@ -138,11 +145,15 @@ public: ~RasterQueueBuilder() noexcept override = 0; - virtual void addSceneOfCamera(scene::Camera* camera, scene::Light* light, SceneFlags sceneFlags, const ccstd::string& name) = 0; - virtual void addSceneOfCamera(scene::Camera* camera, scene::Light* light, SceneFlags sceneFlags) = 0; + virtual void addSceneOfCamera(scene::Camera* camera, LightInfo light, SceneFlags sceneFlags, const ccstd::string& name) = 0; + virtual void addSceneOfCamera(scene::Camera* camera, LightInfo light, SceneFlags sceneFlags) = 0; virtual void addScene(const ccstd::string& name, SceneFlags sceneFlags) = 0; - virtual void addFullscreenQuad(const ccstd::string& shader, const ccstd::string& name) = 0; - virtual void addFullscreenQuad(const ccstd::string& shader) = 0; + virtual void addFullscreenQuad(cc::Material *material, SceneFlags sceneFlags, const ccstd::string& name) = 0; + virtual void addFullscreenQuad(cc::Material *material, SceneFlags sceneFlags) = 0; + virtual void addCameraQuad(scene::Camera* camera, cc::Material *material, SceneFlags sceneFlags, const ccstd::string& name) = 0; + virtual void addCameraQuad(scene::Camera* camera, cc::Material *material, SceneFlags sceneFlags) = 0; + virtual void clearRenderTarget(const ccstd::string &name, const gfx::Color &color) = 0; + virtual void setViewport(const gfx::Viewport &viewport) = 0; }; inline RasterQueueBuilder::~RasterQueueBuilder() noexcept = default; @@ -153,14 +164,15 @@ public: ~RasterPassBuilder() noexcept override = 0; - virtual void addRasterView(const ccstd::string& name, const RasterView& view) = 0; - virtual void addComputeView(const ccstd::string& name, const ComputeView& view) = 0; - virtual RasterQueueBuilder *addQueue(QueueHint hint, const ccstd::string& layoutName, const ccstd::string& name) = 0; - virtual RasterQueueBuilder *addQueue(QueueHint hint, const ccstd::string& layoutName) = 0; + virtual void addRasterView(const ccstd::string& name, const RasterView& view) = 0; + virtual void addComputeView(const ccstd::string& name, const ComputeView& view) = 0; + virtual RasterQueueBuilder *addQueue(QueueHint hint, const ccstd::string& name) = 0; virtual RasterQueueBuilder *addQueue(QueueHint hint) = 0; - virtual void addFullscreenQuad(const ccstd::string& shader, const ccstd::string& layoutName, const ccstd::string& name) = 0; - virtual void addFullscreenQuad(const ccstd::string& shader, const ccstd::string& layoutName) = 0; - virtual void addFullscreenQuad(const ccstd::string& shader) = 0; + virtual void addFullscreenQuad(cc::Material *material, SceneFlags sceneFlags, const ccstd::string& name) = 0; + virtual void addFullscreenQuad(cc::Material *material, SceneFlags sceneFlags) = 0; + virtual void addCameraQuad(scene::Camera* camera, cc::Material *material, SceneFlags sceneFlags, const ccstd::string& name) = 0; + virtual void addCameraQuad(scene::Camera* camera, cc::Material *material, SceneFlags sceneFlags) = 0; + virtual void setViewport(const gfx::Viewport &viewport) = 0; }; inline RasterPassBuilder::~RasterPassBuilder() noexcept = default; @@ -171,8 +183,7 @@ public: ~ComputeQueueBuilder() noexcept override = 0; - virtual void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& layoutName, const ccstd::string& name) = 0; - virtual void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& layoutName) = 0; + virtual void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& name) = 0; virtual void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ) = 0; }; @@ -186,12 +197,10 @@ public: virtual void addComputeView(const ccstd::string& name, const ComputeView& view) = 0; - virtual ComputeQueueBuilder *addQueue(const ccstd::string& layoutName, const ccstd::string& name) = 0; - virtual ComputeQueueBuilder *addQueue(const ccstd::string& layoutName) = 0; + virtual ComputeQueueBuilder *addQueue(const ccstd::string& name) = 0; virtual ComputeQueueBuilder *addQueue() = 0; - virtual void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& layoutName, const ccstd::string& name) = 0; - virtual void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& layoutName) = 0; + virtual void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, const ccstd::string& name) = 0; virtual void addDispatch(const ccstd::string& shader, uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ) = 0; }; @@ -298,6 +307,7 @@ public: virtual uint32_t addRenderPhase(const ccstd::string& name, uint32_t parentID) = 0; virtual void addShader(const ccstd::string& name, uint32_t parentPhaseID) = 0; virtual void addDescriptorBlock(uint32_t nodeID, const DescriptorBlockIndex& index, const DescriptorBlockFlattened& block) = 0; + virtual void addUniformBlock(uint32_t nodeID, const DescriptorBlockIndex& index, const ccstd::string& name, const gfx::UniformBlock& uniformBlock) = 0; virtual void reserveDescriptorBlock(uint32_t nodeID, const DescriptorBlockIndex& index, const DescriptorBlockFlattened& block) = 0; virtual int compile() = 0; @@ -312,18 +322,20 @@ public: ~Pipeline() noexcept override = 0; - virtual uint32_t addRenderTexture(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, scene::RenderWindow* renderWindow) = 0; - virtual uint32_t addRenderTarget(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) = 0; - virtual uint32_t addDepthStencil(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) = 0; - virtual void beginFrame() = 0; - virtual void endFrame() = 0; - virtual RasterPassBuilder *addRasterPass(uint32_t width, uint32_t height, const ccstd::string& layoutName, const ccstd::string& name) = 0; - virtual RasterPassBuilder *addRasterPass(uint32_t width, uint32_t height, const ccstd::string& layoutName) = 0; + virtual bool containsResource(const ccstd::string& name) const = 0; + virtual uint32_t addRenderTexture(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, scene::RenderWindow* renderWindow) = 0; + virtual uint32_t addRenderTarget(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) = 0; + virtual uint32_t addDepthStencil(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) = 0; + + virtual void beginFrame() = 0; + virtual void endFrame() = 0; + virtual RasterPassBuilder *addRasterPass(uint32_t width, uint32_t height, const ccstd::string& layoutName, const ccstd::string& name) = 0; + virtual RasterPassBuilder *addRasterPass(uint32_t width, uint32_t height, const ccstd::string& layoutName) = 0; virtual ComputePassBuilder *addComputePass(const ccstd::string& layoutName, const ccstd::string& name) = 0; virtual ComputePassBuilder *addComputePass(const ccstd::string& layoutName) = 0; - virtual MovePassBuilder *addMovePass(const ccstd::string& name) = 0; - virtual CopyPassBuilder *addCopyPass(const ccstd::string& name) = 0; - virtual void presentAll() = 0; + virtual MovePassBuilder *addMovePass(const ccstd::string& name) = 0; + virtual CopyPassBuilder *addCopyPass(const ccstd::string& name) = 0; + virtual void presentAll() = 0; virtual SceneTransversal *createSceneTransversal(const scene::Camera *camera, const scene::RenderScene *scene) = 0; virtual LayoutGraphBuilder *getLayoutGraphBuilder() = 0; @@ -332,6 +344,21 @@ public: inline Pipeline::~Pipeline() noexcept = default; +class PipelineBuilder { +public: + PipelineBuilder() noexcept = default; + PipelineBuilder(PipelineBuilder&& rhs) = delete; + PipelineBuilder(PipelineBuilder const& rhs) = delete; + PipelineBuilder& operator=(PipelineBuilder&& rhs) = delete; + PipelineBuilder& operator=(PipelineBuilder const& rhs) = delete; + + virtual ~PipelineBuilder() noexcept = 0; + + virtual void setup(const ccstd::vector& cameras, Pipeline* pipeline) = 0; +}; + +inline PipelineBuilder::~PipelineBuilder() noexcept = default; + class Factory { public: static Pipeline *createPipeline(); diff --git a/native/tools/tojs/render.ini b/native/tools/tojs/render.ini index b5239bad81..ec9be54ee6 100644 --- a/native/tools/tojs/render.ini +++ b/native/tools/tojs/render.ini @@ -30,14 +30,14 @@ headers = %(cocosdir)s/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h hpp_headers = -cpp_headers = cocos/bindings/auto/jsb_gfx_auto.h cocos/bindings/auto/jsb_scene_auto.h cocos/renderer/pipeline/custom/LayoutGraphJsb.h cocos/renderer/pipeline/custom/RenderCommonJsb.h cocos/renderer/pipeline/custom/RenderGraphJsb.h cocos/renderer/pipeline/GeometryRenderer.h cocos/renderer/pipeline/GlobalDescriptorSetManager.h +cpp_headers = cocos/bindings/auto/jsb_gfx_auto.h cocos/bindings/auto/jsb_scene_auto.h cocos/renderer/pipeline/GeometryRenderer.h cocos/renderer/pipeline/GlobalDescriptorSetManager.h cocos/renderer/pipeline/custom/LayoutGraphJsb.h cocos/renderer/pipeline/custom/RenderCommonJsb.h cocos/renderer/pipeline/custom/RenderGraphJsb.h replace_headers = # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu.*$". -classes = PipelineRuntime Setter RasterQueueBuilder RasterPassBuilder ComputeQueueBuilder ComputePassBuilder MovePassBuilder CopyPassBuilder SceneVisitor SceneTask SceneTransversal LayoutGraphBuilder Pipeline Factory +classes = PipelineRuntime Setter RasterQueueBuilder RasterPassBuilder ComputeQueueBuilder ComputePassBuilder MovePassBuilder CopyPassBuilder SceneVisitor SceneTask SceneTransversal LayoutGraphBuilder Pipeline PipelineBuilder Factory classes_need_extend = @@ -53,7 +53,7 @@ skip = PipelineRuntime::[getMacros setValue isOcclusionQueryEnabled], skip_public_fields = -getter_setter = PipelineRuntime::[globalDSManager descriptorSetLayout pipelineSceneData constantMacros profiler geometryRenderer shadingScale], +getter_setter = PipelineRuntime::[device globalDSManager descriptorSetLayout descriptorSet commandBuffers pipelineSceneData constantMacros profiler geometryRenderer shadingScale], SceneVisitor::[pipelineSceneData], SceneTask::[taskType], Pipeline::[layoutGraphBuilder] @@ -73,7 +73,7 @@ base_classes_to_skip = # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = PipelineRuntime Setter RasterQueueBuilder RasterPassBuilder ComputeQueueBuilder ComputePassBuilder MovePassBuilder CopyPassBuilder SceneVisitor SceneTask SceneTransversal LayoutGraphBuilder Pipeline +abstract_classes = PipelineRuntime Setter RasterQueueBuilder RasterPassBuilder ComputeQueueBuilder ComputePassBuilder MovePassBuilder CopyPassBuilder SceneVisitor SceneTask SceneTransversal LayoutGraphBuilder Pipeline PipelineBuilder persistent_classes = From 40d5a1d0ab4fe13d3a0febf7ca896fc348ffc544 Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Thu, 21 Jul 2022 12:47:06 +0800 Subject: [PATCH 055/111] [ci skip][AUTO]: Automated code generating update: 88de7636ca7f8f72724eba8e1db87bc25d3f662a (#11646) (#12116) Co-authored-by: cocos-robot --- native/cocos/bindings/auto/jsb_2d_auto.cpp | 157 ++-- native/cocos/bindings/auto/jsb_2d_auto.h | 3 +- .../cocos/bindings/auto/jsb_render_auto.cpp | 675 +++++++++++++----- native/cocos/bindings/auto/jsb_render_auto.h | 18 + 4 files changed, 600 insertions(+), 253 deletions(-) diff --git a/native/cocos/bindings/auto/jsb_2d_auto.cpp b/native/cocos/bindings/auto/jsb_2d_auto.cpp index c31e45d560..f49b70596a 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.cpp +++ b/native/cocos/bindings/auto/jsb_2d_auto.cpp @@ -247,6 +247,22 @@ bool js_register_2d_UIMeshBuffer(se::Object* obj) // NOLINT(readability-identifi se::Object* __jsb_cc_RenderDrawInfo_proto = nullptr; // NOLINT se::Class* __jsb_cc_RenderDrawInfo_class = nullptr; // NOLINT +static bool js_2d_RenderDrawInfo_changeMeshBuffer(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cobj->changeMeshBuffer(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_2d_RenderDrawInfo_changeMeshBuffer) + static bool js_2d_RenderDrawInfo_getAccId(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -256,7 +272,7 @@ static bool js_2d_RenderDrawInfo_getAccId(se::State& s) // NOLINT(readability-id size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 0) { - int result = cobj->getAccId(); + unsigned short result = cobj->getAccId(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); SE_PRECONDITION2(ok, false, "Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); @@ -267,6 +283,26 @@ static bool js_2d_RenderDrawInfo_getAccId(se::State& s) // NOLINT(readability-id } SE_BIND_FUNC_AS_PROP_GET(js_2d_RenderDrawInfo_getAccId) +static bool js_2d_RenderDrawInfo_getAttrSharedBufferForJS(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + se::Object* result = cobj->getAttrSharedBufferForJS(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_2d_RenderDrawInfo_getAttrSharedBufferForJS) + static bool js_2d_RenderDrawInfo_getBufferId(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -276,7 +312,7 @@ static bool js_2d_RenderDrawInfo_getBufferId(se::State& s) // NOLINT(readability size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 0) { - int result = cobj->getBufferId(); + unsigned short result = cobj->getBufferId(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); SE_PRECONDITION2(ok, false, "Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); @@ -507,6 +543,26 @@ static bool js_2d_RenderDrawInfo_getSampler(se::State& s) // NOLINT(readability- } SE_BIND_FUNC_AS_PROP_GET(js_2d_RenderDrawInfo_getSampler) +static bool js_2d_RenderDrawInfo_getStride(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + uint8_t result = cobj->getStride(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC_AS_PROP_GET(js_2d_RenderDrawInfo_getStride) + static bool js_2d_RenderDrawInfo_getSubNode(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -715,7 +771,7 @@ static bool js_2d_RenderDrawInfo_setAccId(se::State& s) // NOLINT(readability-id size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 1) { - HolderType arg0 = {}; + HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); cobj->setAccId(arg0.value()); @@ -735,7 +791,7 @@ static bool js_2d_RenderDrawInfo_setBufferId(se::State& s) // NOLINT(readability size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 1) { - HolderType arg0 = {}; + HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); cobj->setBufferId(arg0.value()); @@ -934,18 +990,14 @@ static bool js_2d_RenderDrawInfo_setRender2dBufferToNative(se::State& s) // NOLI const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; - if (argc == 3) { + if (argc == 1) { HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); - cobj->setRender2dBufferToNative(arg0.value(), arg1.value(), arg2.value()); + cobj->setRender2dBufferToNative(arg0.value()); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } SE_BIND_FUNC(js_2d_RenderDrawInfo_setRender2dBufferToNative) @@ -970,6 +1022,26 @@ static bool js_2d_RenderDrawInfo_setSampler(se::State& s) // NOLINT(readability- } SE_BIND_FUNC_AS_PROP_SET(js_2d_RenderDrawInfo_setSampler) +static bool js_2d_RenderDrawInfo_setStride(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setStride(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC_AS_PROP_SET(js_2d_RenderDrawInfo_setStride) + static bool js_2d_RenderDrawInfo_setSubNode(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -1148,36 +1220,11 @@ SE_BIND_FUNC(js_2d_RenderDrawInfo_uploadBuffers) SE_DECLARE_FINALIZE_FUNC(js_cc_RenderDrawInfo_finalize) -static bool js_2d_RenderDrawInfo_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor_overloaded.c +static bool js_2d_RenderDrawInfo_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c { - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - do { - if (argc == 3) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - HolderType arg1 = {}; - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - HolderType arg2 = {}; - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - if (!ok) { ok = true; break; } - auto *ptr = JSB_MAKE_PRIVATE_OBJECT(cc::RenderDrawInfo, arg0.value(), arg1.value(), arg2.value()); - s.thisObject()->setPrivateObject(ptr); - return true; - } - } while(false); - do { - if (argc == 0) { - auto *ptr = JSB_MAKE_PRIVATE_OBJECT(cc::RenderDrawInfo); - s.thisObject()->setPrivateObject(ptr); - return true; - } - } while(false); - SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); - return false; + auto *ptr = JSB_MAKE_PRIVATE_OBJECT(cc::RenderDrawInfo); + s.thisObject()->setPrivateObject(ptr); + return true; } SE_BIND_CTOR(js_2d_RenderDrawInfo_constructor, __jsb_cc_RenderDrawInfo_class, js_cc_RenderDrawInfo_finalize) @@ -1214,6 +1261,9 @@ bool js_register_2d_RenderDrawInfo(se::Object* obj) // NOLINT(readability-identi cls->defineProperty("model", _SE(js_2d_RenderDrawInfo_getModel_asGetter), _SE(js_2d_RenderDrawInfo_setModel_asSetter)); cls->defineProperty("drawInfoType", _SE(js_2d_RenderDrawInfo_getDrawInfoType_asGetter), _SE(js_2d_RenderDrawInfo_setDrawInfoType_asSetter)); cls->defineProperty("subNode", _SE(js_2d_RenderDrawInfo_getSubNode_asGetter), _SE(js_2d_RenderDrawInfo_setSubNode_asSetter)); + cls->defineProperty("stride", _SE(js_2d_RenderDrawInfo_getStride_asGetter), _SE(js_2d_RenderDrawInfo_setStride_asSetter)); + cls->defineFunction("changeMeshBuffer", _SE(js_2d_RenderDrawInfo_changeMeshBuffer)); + cls->defineFunction("getAttrSharedBufferForJS", _SE(js_2d_RenderDrawInfo_getAttrSharedBufferForJS)); cls->defineFunction("getMeshBuffer", _SE(js_2d_RenderDrawInfo_getMeshBuffer)); cls->defineFunction("requestIA", _SE(js_2d_RenderDrawInfo_requestIA)); cls->defineFunction("resetMeshIA", _SE(js_2d_RenderDrawInfo_resetMeshIA)); @@ -1785,30 +1835,6 @@ static bool js_2d_Batcher2d_getDefaultAttribute(se::State& s) // NOLINT(readabil } SE_BIND_FUNC(js_2d_Batcher2d_getDefaultAttribute) -static bool js_2d_Batcher2d_handleColor(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); - if (nullptr == cobj) return true; - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 3) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - cobj->handleColor(arg0.value(), arg1.value(), arg2.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); - return false; -} -SE_BIND_FUNC(js_2d_Batcher2d_handleColor) - static bool js_2d_Batcher2d_handlePostRender(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -1896,7 +1922,7 @@ static bool js_2d_Batcher2d_syncMeshBuffersToNative(se::State& s) // NOLINT(read size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 2) { - HolderType arg0 = {}; + HolderType arg0 = {}; HolderType, true> arg1 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); @@ -2004,7 +2030,6 @@ bool js_register_2d_Batcher2d(se::Object* obj) // NOLINT(readability-identifier- cls->defineStaticProperty("isJSBClass", _SE(js_2d_getter_return_true), nullptr); #endif cls->defineFunction("getDefaultAttribute", _SE(js_2d_Batcher2d_getDefaultAttribute)); - cls->defineFunction("handleColor", _SE(js_2d_Batcher2d_handleColor)); cls->defineFunction("handlePostRender", _SE(js_2d_Batcher2d_handlePostRender)); cls->defineFunction("initialize", _SE(js_2d_Batcher2d_initialize)); cls->defineFunction("releaseDescriptorSetCache", _SE(js_2d_Batcher2d_releaseDescriptorSetCache)); diff --git a/native/cocos/bindings/auto/jsb_2d_auto.h b/native/cocos/bindings/auto/jsb_2d_auto.h index f54e4f5d07..5091fa8600 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.h +++ b/native/cocos/bindings/auto/jsb_2d_auto.h @@ -37,6 +37,8 @@ extern se::Class * __jsb_cc_RenderDrawInfo_class; // NOLINT bool js_register_cc_RenderDrawInfo(se::Object *obj); // NOLINT +SE_DECLARE_FUNC(js_2d_RenderDrawInfo_changeMeshBuffer); +SE_DECLARE_FUNC(js_2d_RenderDrawInfo_getAttrSharedBufferForJS); SE_DECLARE_FUNC(js_2d_RenderDrawInfo_getMeshBuffer); SE_DECLARE_FUNC(js_2d_RenderDrawInfo_requestIA); SE_DECLARE_FUNC(js_2d_RenderDrawInfo_resetMeshIA); @@ -69,7 +71,6 @@ extern se::Class * __jsb_cc_Batcher2d_class; // NOLINT bool js_register_cc_Batcher2d(se::Object *obj); // NOLINT SE_DECLARE_FUNC(js_2d_Batcher2d_getDefaultAttribute); -SE_DECLARE_FUNC(js_2d_Batcher2d_handleColor); SE_DECLARE_FUNC(js_2d_Batcher2d_handlePostRender); SE_DECLARE_FUNC(js_2d_Batcher2d_initialize); SE_DECLARE_FUNC(js_2d_Batcher2d_releaseDescriptorSetCache); diff --git a/native/cocos/bindings/auto/jsb_render_auto.cpp b/native/cocos/bindings/auto/jsb_render_auto.cpp index e14be9e157..b77e69bf1e 100644 --- a/native/cocos/bindings/auto/jsb_render_auto.cpp +++ b/native/cocos/bindings/auto/jsb_render_auto.cpp @@ -6,11 +6,11 @@ #include "renderer/pipeline/custom/RenderInterfaceTypes.h" #include "cocos/bindings/auto/jsb_gfx_auto.h" #include "cocos/bindings/auto/jsb_scene_auto.h" +#include "cocos/renderer/pipeline/GeometryRenderer.h" +#include "cocos/renderer/pipeline/GlobalDescriptorSetManager.h" #include "cocos/renderer/pipeline/custom/LayoutGraphJsb.h" #include "cocos/renderer/pipeline/custom/RenderCommonJsb.h" #include "cocos/renderer/pipeline/custom/RenderGraphJsb.h" -#include "cocos/renderer/pipeline/GeometryRenderer.h" -#include "cocos/renderer/pipeline/GlobalDescriptorSetManager.h" #ifndef JSB_ALLOC #define JSB_ALLOC(kls, ...) new (std::nothrow) kls(__VA_ARGS__) @@ -74,6 +74,26 @@ static bool js_render_PipelineRuntime_destroy(se::State& s) // NOLINT(readabilit } SE_BIND_FUNC(js_render_PipelineRuntime_destroy) +static bool js_render_PipelineRuntime_getCommandBuffers(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + std::vector result = cobj->getCommandBuffers(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC_AS_PROP_GET(js_render_PipelineRuntime_getCommandBuffers) + static bool js_render_PipelineRuntime_getConstantMacros(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -94,6 +114,26 @@ static bool js_render_PipelineRuntime_getConstantMacros(se::State& s) // NOLINT( } SE_BIND_FUNC_AS_PROP_GET(js_render_PipelineRuntime_getConstantMacros) +static bool js_render_PipelineRuntime_getDescriptorSet(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::gfx::DescriptorSet* result = cobj->getDescriptorSet(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC_AS_PROP_GET(js_render_PipelineRuntime_getDescriptorSet) + static bool js_render_PipelineRuntime_getDescriptorSetLayout(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -114,6 +154,26 @@ static bool js_render_PipelineRuntime_getDescriptorSetLayout(se::State& s) // NO } SE_BIND_FUNC_AS_PROP_GET(js_render_PipelineRuntime_getDescriptorSetLayout) +static bool js_render_PipelineRuntime_getDevice(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::gfx::Device* result = cobj->getDevice(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC_AS_PROP_GET(js_render_PipelineRuntime_getDevice) + static bool js_render_PipelineRuntime_getGeometryRenderer(se::State& s) // NOLINT(readability-identifier-naming) { #if CC_USE_GEOMETRY_RENDERER @@ -158,6 +218,75 @@ static bool js_render_PipelineRuntime_getGlobalDSManager(se::State& s) // NOLINT } SE_BIND_FUNC_AS_PROP_GET(js_render_PipelineRuntime_getGlobalDSManager) +static bool js_render_PipelineRuntime_getMacroBool(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + bool result = cobj->getMacroBool(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_render_PipelineRuntime_getMacroBool) + +static bool js_render_PipelineRuntime_getMacroInt(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + int32_t result = cobj->getMacroInt(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_render_PipelineRuntime_getMacroInt) + +static bool js_render_PipelineRuntime_getMacroString(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + const std::string& result = cobj->getMacroString(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_render_PipelineRuntime_getMacroString) + static bool js_render_PipelineRuntime_getPipelineSceneData(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -367,8 +496,11 @@ bool js_register_render_PipelineRuntime(se::Object* obj) // NOLINT(readability-i #if CC_DEBUG cls->defineStaticProperty("isJSBClass", _SE(js_render_getter_return_true), nullptr); #endif + cls->defineProperty("device", _SE(js_render_PipelineRuntime_getDevice_asGetter), nullptr); cls->defineProperty("globalDSManager", _SE(js_render_PipelineRuntime_getGlobalDSManager_asGetter), nullptr); cls->defineProperty("descriptorSetLayout", _SE(js_render_PipelineRuntime_getDescriptorSetLayout_asGetter), nullptr); + cls->defineProperty("descriptorSet", _SE(js_render_PipelineRuntime_getDescriptorSet_asGetter), nullptr); + cls->defineProperty("commandBuffers", _SE(js_render_PipelineRuntime_getCommandBuffers_asGetter), nullptr); cls->defineProperty("pipelineSceneData", _SE(js_render_PipelineRuntime_getPipelineSceneData_asGetter), nullptr); cls->defineProperty("constantMacros", _SE(js_render_PipelineRuntime_getConstantMacros_asGetter), nullptr); cls->defineProperty("profiler", _SE(js_render_PipelineRuntime_getProfiler_asGetter), _SE(js_render_PipelineRuntime_setProfiler_asSetter)); @@ -376,6 +508,9 @@ bool js_register_render_PipelineRuntime(se::Object* obj) // NOLINT(readability-i cls->defineProperty("shadingScale", _SE(js_render_PipelineRuntime_getShadingScale_asGetter), _SE(js_render_PipelineRuntime_setShadingScale_asSetter)); cls->defineFunction("activate", _SE(js_render_PipelineRuntime_activate)); cls->defineFunction("destroy", _SE(js_render_PipelineRuntime_destroy)); + cls->defineFunction("getMacroBool", _SE(js_render_PipelineRuntime_getMacroBool)); + cls->defineFunction("getMacroInt", _SE(js_render_PipelineRuntime_getMacroInt)); + cls->defineFunction("getMacroString", _SE(js_render_PipelineRuntime_getMacroString)); cls->defineFunction("onGlobalPipelineStateChanged", _SE(js_render_PipelineRuntime_onGlobalPipelineStateChanged)); cls->defineFunction("render", _SE(js_render_PipelineRuntime_render)); cls->defineFunction("setMacroBool", _SE(js_render_PipelineRuntime_setMacroBool)); @@ -667,6 +802,56 @@ bool js_register_render_Setter(se::Object* obj) // NOLINT(readability-identifier se::Object* __jsb_cc_render_RasterQueueBuilder_proto = nullptr; // NOLINT se::Class* __jsb_cc_render_RasterQueueBuilder_class = nullptr; // NOLINT +static bool js_render_RasterQueueBuilder_addCameraQuad(se::State& s) // NOLINT(readability-identifier-naming) +{ + CC_UNUSED bool ok = true; + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2( cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + do { + if (argc == 3) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->addCameraQuad(arg0.value(), arg1.value(), arg2.value()); + return true; + } + } while(false); + + do { + if (argc == 4) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->addCameraQuad(arg0.value(), arg1.value(), arg2.value(), arg3.value()); + return true; + } + } while(false); + + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); + return false; +} +SE_BIND_FUNC(js_render_RasterQueueBuilder_addCameraQuad) + static bool js_render_RasterQueueBuilder_addFullscreenQuad(se::State& s) // NOLINT(readability-identifier-naming) { CC_UNUSED bool ok = true; @@ -675,21 +860,10 @@ static bool js_render_RasterQueueBuilder_addFullscreenQuad(se::State& s) // NOLI if (nullptr == cobj) return true; const auto& args = s.args(); size_t argc = args.size(); - do { - if (argc == 1) { - HolderType arg0 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->addFullscreenQuad(arg0.value()); - return true; - } - } while(false); - do { if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; + HolderType arg0 = {}; + HolderType arg1 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); if (!ok) { ok = true; break; } @@ -700,6 +874,23 @@ static bool js_render_RasterQueueBuilder_addFullscreenQuad(se::State& s) // NOLI } } while(false); + do { + if (argc == 3) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->addFullscreenQuad(arg0.value(), arg1.value(), arg2.value()); + return true; + } + } while(false); + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } @@ -738,7 +929,7 @@ static bool js_render_RasterQueueBuilder_addSceneOfCamera(se::State& s) // NOLIN do { if (argc == 3) { HolderType arg0 = {}; - HolderType arg1 = {}; + HolderType arg1 = {}; HolderType arg2 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -755,7 +946,7 @@ static bool js_render_RasterQueueBuilder_addSceneOfCamera(se::State& s) // NOLIN do { if (argc == 4) { HolderType arg0 = {}; - HolderType arg1 = {}; + HolderType arg1 = {}; HolderType arg2 = {}; HolderType arg3 = {}; @@ -777,6 +968,48 @@ static bool js_render_RasterQueueBuilder_addSceneOfCamera(se::State& s) // NOLIN } SE_BIND_FUNC(js_render_RasterQueueBuilder_addSceneOfCamera) +static bool js_render_RasterQueueBuilder_clearRenderTarget(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->clearRenderTarget(arg0.value(), arg1.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_render_RasterQueueBuilder_clearRenderTarget) + +static bool js_render_RasterQueueBuilder_setViewport(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setViewport(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_render_RasterQueueBuilder_setViewport) + bool js_register_render_RasterQueueBuilder(se::Object* obj) // NOLINT(readability-identifier-naming) { auto* cls = se::Class::create("RasterQueueBuilder", obj, __jsb_cc_render_Setter_proto, nullptr); @@ -784,9 +1017,12 @@ bool js_register_render_RasterQueueBuilder(se::Object* obj) // NOLINT(readabilit #if CC_DEBUG cls->defineStaticProperty("isJSBClass", _SE(js_render_getter_return_true), nullptr); #endif + cls->defineFunction("addCameraQuad", _SE(js_render_RasterQueueBuilder_addCameraQuad)); cls->defineFunction("addFullscreenQuad", _SE(js_render_RasterQueueBuilder_addFullscreenQuad)); cls->defineFunction("addScene", _SE(js_render_RasterQueueBuilder_addScene)); cls->defineFunction("addSceneOfCamera", _SE(js_render_RasterQueueBuilder_addSceneOfCamera)); + cls->defineFunction("clearRenderTarget", _SE(js_render_RasterQueueBuilder_clearRenderTarget)); + cls->defineFunction("setViewport", _SE(js_render_RasterQueueBuilder_setViewport)); cls->install(); JSBClassType::registerClass(cls); @@ -800,6 +1036,56 @@ bool js_register_render_RasterQueueBuilder(se::Object* obj) // NOLINT(readabilit se::Object* __jsb_cc_render_RasterPassBuilder_proto = nullptr; // NOLINT se::Class* __jsb_cc_render_RasterPassBuilder_class = nullptr; // NOLINT +static bool js_render_RasterPassBuilder_addCameraQuad(se::State& s) // NOLINT(readability-identifier-naming) +{ + CC_UNUSED bool ok = true; + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2( cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + do { + if (argc == 3) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->addCameraQuad(arg0.value(), arg1.value(), arg2.value()); + return true; + } + } while(false); + + do { + if (argc == 4) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->addCameraQuad(arg0.value(), arg1.value(), arg2.value(), arg3.value()); + return true; + } + } while(false); + + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); + return false; +} +SE_BIND_FUNC(js_render_RasterPassBuilder_addCameraQuad) + static bool js_render_RasterPassBuilder_addComputeView(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -832,8 +1118,8 @@ static bool js_render_RasterPassBuilder_addFullscreenQuad(se::State& s) // NOLIN size_t argc = args.size(); do { if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; + HolderType arg0 = {}; + HolderType arg1 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); if (!ok) { ok = true; break; } @@ -846,8 +1132,8 @@ static bool js_render_RasterPassBuilder_addFullscreenQuad(se::State& s) // NOLIN do { if (argc == 3) { - HolderType arg0 = {}; - HolderType arg1 = {}; + HolderType arg0 = {}; + HolderType arg1 = {}; HolderType arg2 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -861,17 +1147,6 @@ static bool js_render_RasterPassBuilder_addFullscreenQuad(se::State& s) // NOLIN } } while(false); - do { - if (argc == 1) { - HolderType arg0 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->addFullscreenQuad(arg0.value()); - return true; - } - } while(false); - SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } @@ -885,6 +1160,20 @@ static bool js_render_RasterPassBuilder_addQueue(se::State& s) // NOLINT(readabi if (nullptr == cobj) return true; const auto& args = s.args(); size_t argc = args.size(); + do { + if (argc == 1) { + HolderType arg0 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + cc::render::RasterQueueBuilder* result = cobj->addQueue(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + } while(false); + do { if (argc == 2) { HolderType arg0 = {}; @@ -902,40 +1191,6 @@ static bool js_render_RasterPassBuilder_addQueue(se::State& s) // NOLINT(readabi } } while(false); - do { - if (argc == 3) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - if (!ok) { ok = true; break; } - cc::render::RasterQueueBuilder* result = cobj->addQueue(arg0.value(), arg1.value(), arg2.value()); - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - } while(false); - - do { - if (argc == 1) { - HolderType arg0 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - cc::render::RasterQueueBuilder* result = cobj->addQueue(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - } while(false); - SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } @@ -963,6 +1218,26 @@ static bool js_render_RasterPassBuilder_addRasterView(se::State& s) // NOLINT(re } SE_BIND_FUNC(js_render_RasterPassBuilder_addRasterView) +static bool js_render_RasterPassBuilder_setViewport(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setViewport(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_render_RasterPassBuilder_setViewport) + bool js_register_render_RasterPassBuilder(se::Object* obj) // NOLINT(readability-identifier-naming) { auto* cls = se::Class::create("RasterPassBuilder", obj, __jsb_cc_render_Setter_proto, nullptr); @@ -970,10 +1245,12 @@ bool js_register_render_RasterPassBuilder(se::Object* obj) // NOLINT(readability #if CC_DEBUG cls->defineStaticProperty("isJSBClass", _SE(js_render_getter_return_true), nullptr); #endif + cls->defineFunction("addCameraQuad", _SE(js_render_RasterPassBuilder_addCameraQuad)); cls->defineFunction("addComputeView", _SE(js_render_RasterPassBuilder_addComputeView)); cls->defineFunction("addFullscreenQuad", _SE(js_render_RasterPassBuilder_addFullscreenQuad)); cls->defineFunction("addQueue", _SE(js_render_RasterPassBuilder_addQueue)); cls->defineFunction("addRasterView", _SE(js_render_RasterPassBuilder_addRasterView)); + cls->defineFunction("setViewport", _SE(js_render_RasterPassBuilder_setViewport)); cls->install(); JSBClassType::registerClass(cls); @@ -995,6 +1272,26 @@ static bool js_render_ComputeQueueBuilder_addDispatch(se::State& s) // NOLINT(re if (nullptr == cobj) return true; const auto& args = s.args(); size_t argc = args.size(); + do { + if (argc == 4) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->addDispatch(arg0.value(), arg1.value(), arg2.value(), arg3.value()); + return true; + } + } while(false); + do { if (argc == 5) { HolderType arg0 = {}; @@ -1018,52 +1315,6 @@ static bool js_render_ComputeQueueBuilder_addDispatch(se::State& s) // NOLINT(re } } while(false); - do { - if (argc == 6) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - HolderType arg3 = {}; - HolderType arg4 = {}; - HolderType arg5 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[4], &arg4, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[5], &arg5, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->addDispatch(arg0.value(), arg1.value(), arg2.value(), arg3.value(), arg4.value(), arg5.value()); - return true; - } - } while(false); - - do { - if (argc == 4) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - HolderType arg3 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->addDispatch(arg0.value(), arg1.value(), arg2.value(), arg3.value()); - return true; - } - } while(false); - SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } @@ -1120,6 +1371,26 @@ static bool js_render_ComputePassBuilder_addDispatch(se::State& s) // NOLINT(rea if (nullptr == cobj) return true; const auto& args = s.args(); size_t argc = args.size(); + do { + if (argc == 4) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->addDispatch(arg0.value(), arg1.value(), arg2.value(), arg3.value()); + return true; + } + } while(false); + do { if (argc == 5) { HolderType arg0 = {}; @@ -1143,52 +1414,6 @@ static bool js_render_ComputePassBuilder_addDispatch(se::State& s) // NOLINT(rea } } while(false); - do { - if (argc == 6) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - HolderType arg3 = {}; - HolderType arg4 = {}; - HolderType arg5 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[4], &arg4, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[5], &arg5, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->addDispatch(arg0.value(), arg1.value(), arg2.value(), arg3.value(), arg4.value(), arg5.value()); - return true; - } - } while(false); - - do { - if (argc == 4) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - HolderType arg3 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->addDispatch(arg0.value(), arg1.value(), arg2.value(), arg3.value()); - return true; - } - } while(false); - SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } @@ -1202,6 +1427,17 @@ static bool js_render_ComputePassBuilder_addQueue(se::State& s) // NOLINT(readab if (nullptr == cobj) return true; const auto& args = s.args(); size_t argc = args.size(); + do { + if (argc == 0) { + + cc::render::ComputeQueueBuilder* result = cobj->addQueue(); + ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + } while(false); + do { if (argc == 1) { HolderType arg0 = {}; @@ -1216,34 +1452,6 @@ static bool js_render_ComputePassBuilder_addQueue(se::State& s) // NOLINT(readab } } while(false); - do { - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - cc::render::ComputeQueueBuilder* result = cobj->addQueue(arg0.value(), arg1.value()); - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - } while(false); - - do { - if (argc == 0) { - - cc::render::ComputeQueueBuilder* result = cobj->addQueue(); - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - } while(false); - SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } @@ -1730,6 +1938,32 @@ static bool js_render_LayoutGraphBuilder_addShader(se::State& s) // NOLINT(reada } SE_BIND_FUNC(js_render_LayoutGraphBuilder_addShader) +static bool js_render_LayoutGraphBuilder_addUniformBlock(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 4) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->addUniformBlock(arg0.value(), arg1.value(), arg2.value(), arg3.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 4); + return false; +} +SE_BIND_FUNC(js_render_LayoutGraphBuilder_addUniformBlock) + static bool js_render_LayoutGraphBuilder_clear(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -1821,6 +2055,7 @@ bool js_register_render_LayoutGraphBuilder(se::Object* obj) // NOLINT(readabilit cls->defineFunction("addRenderPhase", _SE(js_render_LayoutGraphBuilder_addRenderPhase)); cls->defineFunction("addRenderStage", _SE(js_render_LayoutGraphBuilder_addRenderStage)); cls->defineFunction("addShader", _SE(js_render_LayoutGraphBuilder_addShader)); + cls->defineFunction("addUniformBlock", _SE(js_render_LayoutGraphBuilder_addUniformBlock)); cls->defineFunction("clear", _SE(js_render_LayoutGraphBuilder_clear)); cls->defineFunction("compile", _SE(js_render_LayoutGraphBuilder_compile)); cls->defineFunction("print", _SE(js_render_LayoutGraphBuilder_print)); @@ -2093,6 +2328,29 @@ static bool js_render_Pipeline_beginFrame(se::State& s) // NOLINT(readability-id } SE_BIND_FUNC(js_render_Pipeline_beginFrame) +static bool js_render_Pipeline_containsResource(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + bool result = cobj->containsResource(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_render_Pipeline_containsResource) + static bool js_render_Pipeline_createSceneTransversal(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -2211,6 +2469,7 @@ bool js_register_render_Pipeline(se::Object* obj) // NOLINT(readability-identifi cls->defineFunction("addRenderTarget", _SE(js_render_Pipeline_addRenderTarget)); cls->defineFunction("addRenderTexture", _SE(js_render_Pipeline_addRenderTexture)); cls->defineFunction("beginFrame", _SE(js_render_Pipeline_beginFrame)); + cls->defineFunction("containsResource", _SE(js_render_Pipeline_containsResource)); cls->defineFunction("createSceneTransversal", _SE(js_render_Pipeline_createSceneTransversal)); cls->defineFunction("endFrame", _SE(js_render_Pipeline_endFrame)); cls->defineFunction("getDescriptorSetLayout", _SE(js_render_Pipeline_getDescriptorSetLayout)); @@ -2222,6 +2481,49 @@ bool js_register_render_Pipeline(se::Object* obj) // NOLINT(readability-identifi __jsb_cc_render_Pipeline_class = cls; + se::ScriptEngine::getInstance()->clearException(); + return true; +} +se::Object* __jsb_cc_render_PipelineBuilder_proto = nullptr; // NOLINT +se::Class* __jsb_cc_render_PipelineBuilder_class = nullptr; // NOLINT + +static bool js_render_PipelineBuilder_setup(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType, true> arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setup(arg0.value(), arg1.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_render_PipelineBuilder_setup) + +bool js_register_render_PipelineBuilder(se::Object* obj) // NOLINT(readability-identifier-naming) +{ + auto* cls = se::Class::create("PipelineBuilder", obj, nullptr, nullptr); + +#if CC_DEBUG + cls->defineStaticProperty("isJSBClass", _SE(js_render_getter_return_true), nullptr); +#endif + cls->defineFunction("setup", _SE(js_render_PipelineBuilder_setup)); + cls->install(); + JSBClassType::registerClass(cls); + + __jsb_cc_render_PipelineBuilder_proto = cls->getProto(); + __jsb_cc_render_PipelineBuilder_class = cls; + + se::ScriptEngine::getInstance()->clearException(); return true; } @@ -2290,6 +2592,7 @@ bool register_all_render(se::Object* obj) // NOLINT js_register_render_MovePassBuilder(ns); js_register_render_PipelineRuntime(ns); js_register_render_Pipeline(ns); + js_register_render_PipelineBuilder(ns); js_register_render_RasterPassBuilder(ns); js_register_render_RasterQueueBuilder(ns); js_register_render_SceneTask(ns); diff --git a/native/cocos/bindings/auto/jsb_render_auto.h b/native/cocos/bindings/auto/jsb_render_auto.h index ad5801dc97..68ee3c9f2b 100644 --- a/native/cocos/bindings/auto/jsb_render_auto.h +++ b/native/cocos/bindings/auto/jsb_render_auto.h @@ -21,6 +21,7 @@ JSB_REGISTER_OBJECT_TYPE(cc::render::SceneTask); JSB_REGISTER_OBJECT_TYPE(cc::render::SceneTransversal); JSB_REGISTER_OBJECT_TYPE(cc::render::LayoutGraphBuilder); JSB_REGISTER_OBJECT_TYPE(cc::render::Pipeline); +JSB_REGISTER_OBJECT_TYPE(cc::render::PipelineBuilder); JSB_REGISTER_OBJECT_TYPE(cc::render::Factory); @@ -31,6 +32,9 @@ bool js_register_cc_render_PipelineRuntime(se::Object *obj); // NOLINT SE_DECLARE_FUNC(js_render_PipelineRuntime_activate); SE_DECLARE_FUNC(js_render_PipelineRuntime_destroy); +SE_DECLARE_FUNC(js_render_PipelineRuntime_getMacroBool); +SE_DECLARE_FUNC(js_render_PipelineRuntime_getMacroInt); +SE_DECLARE_FUNC(js_render_PipelineRuntime_getMacroString); SE_DECLARE_FUNC(js_render_PipelineRuntime_onGlobalPipelineStateChanged); SE_DECLARE_FUNC(js_render_PipelineRuntime_render); SE_DECLARE_FUNC(js_render_PipelineRuntime_setMacroBool); @@ -59,19 +63,24 @@ extern se::Class * __jsb_cc_render_RasterQueueBuilder_class; // NOLINT bool js_register_cc_render_RasterQueueBuilder(se::Object *obj); // NOLINT +SE_DECLARE_FUNC(js_render_RasterQueueBuilder_addCameraQuad); SE_DECLARE_FUNC(js_render_RasterQueueBuilder_addFullscreenQuad); SE_DECLARE_FUNC(js_render_RasterQueueBuilder_addScene); SE_DECLARE_FUNC(js_render_RasterQueueBuilder_addSceneOfCamera); +SE_DECLARE_FUNC(js_render_RasterQueueBuilder_clearRenderTarget); +SE_DECLARE_FUNC(js_render_RasterQueueBuilder_setViewport); extern se::Object *__jsb_cc_render_RasterPassBuilder_proto; // NOLINT extern se::Class * __jsb_cc_render_RasterPassBuilder_class; // NOLINT bool js_register_cc_render_RasterPassBuilder(se::Object *obj); // NOLINT +SE_DECLARE_FUNC(js_render_RasterPassBuilder_addCameraQuad); SE_DECLARE_FUNC(js_render_RasterPassBuilder_addComputeView); SE_DECLARE_FUNC(js_render_RasterPassBuilder_addFullscreenQuad); SE_DECLARE_FUNC(js_render_RasterPassBuilder_addQueue); SE_DECLARE_FUNC(js_render_RasterPassBuilder_addRasterView); +SE_DECLARE_FUNC(js_render_RasterPassBuilder_setViewport); extern se::Object *__jsb_cc_render_ComputeQueueBuilder_proto; // NOLINT extern se::Class * __jsb_cc_render_ComputeQueueBuilder_class; // NOLINT @@ -139,6 +148,7 @@ SE_DECLARE_FUNC(js_render_LayoutGraphBuilder_addDescriptorBlock); SE_DECLARE_FUNC(js_render_LayoutGraphBuilder_addRenderPhase); SE_DECLARE_FUNC(js_render_LayoutGraphBuilder_addRenderStage); SE_DECLARE_FUNC(js_render_LayoutGraphBuilder_addShader); +SE_DECLARE_FUNC(js_render_LayoutGraphBuilder_addUniformBlock); SE_DECLARE_FUNC(js_render_LayoutGraphBuilder_clear); SE_DECLARE_FUNC(js_render_LayoutGraphBuilder_compile); SE_DECLARE_FUNC(js_render_LayoutGraphBuilder_print); @@ -157,11 +167,19 @@ SE_DECLARE_FUNC(js_render_Pipeline_addRasterPass); SE_DECLARE_FUNC(js_render_Pipeline_addRenderTarget); SE_DECLARE_FUNC(js_render_Pipeline_addRenderTexture); SE_DECLARE_FUNC(js_render_Pipeline_beginFrame); +SE_DECLARE_FUNC(js_render_Pipeline_containsResource); SE_DECLARE_FUNC(js_render_Pipeline_createSceneTransversal); SE_DECLARE_FUNC(js_render_Pipeline_endFrame); SE_DECLARE_FUNC(js_render_Pipeline_getDescriptorSetLayout); SE_DECLARE_FUNC(js_render_Pipeline_presentAll); +extern se::Object *__jsb_cc_render_PipelineBuilder_proto; // NOLINT +extern se::Class * __jsb_cc_render_PipelineBuilder_class; // NOLINT + +bool js_register_cc_render_PipelineBuilder(se::Object *obj); // NOLINT + +SE_DECLARE_FUNC(js_render_PipelineBuilder_setup); + extern se::Object *__jsb_cc_render_Factory_proto; // NOLINT extern se::Class * __jsb_cc_render_Factory_class; // NOLINT From 97e883191020d767c32b3ec3ddb6a833478c50e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Thu, 21 Jul 2022 14:23:54 +0800 Subject: [PATCH 056/111] add package-lock.json (#12110) --- .../native-pack-tool/xcode/package-lock.json | 2968 +++++++++++++++++ 1 file changed, 2968 insertions(+) create mode 100644 scripts/native-pack-tool/xcode/package-lock.json diff --git a/scripts/native-pack-tool/xcode/package-lock.json b/scripts/native-pack-tool/xcode/package-lock.json new file mode 100644 index 0000000000..2bbbec03e4 --- /dev/null +++ b/scripts/native-pack-tool/xcode/package-lock.json @@ -0,0 +1,2968 @@ +{ + "name": "xcode", + "version": "3.0.1", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@ampproject/remapping": { + "version": "2.2.0", + "resolved": "https://registry.npmmirror.com/@ampproject/remapping/-/remapping-2.2.0.tgz", + "integrity": "sha512-qRmjj8nj9qmLTQXXmaR1cck3UXSRMPrbsLJAasZpF+t3riI71BXed5ebIOYwQntykeZuhjsdweEc9BxH5Jc26w==", + "dev": true, + "requires": { + "@jridgewell/gen-mapping": "^0.1.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "dependencies": { + "@jridgewell/gen-mapping": { + "version": "0.1.1", + "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.1.1.tgz", + "integrity": "sha512-sQXCasFk+U8lWYEe66WxRDOE9PjVz4vSM51fTu3Hw+ClTpUSQb718772vH3pyS5pShp6lvQM7SxgIDXXXmOX7w==", + "dev": true, + "requires": { + "@jridgewell/set-array": "^1.0.0", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + } + } + }, + "@babel/code-frame": { + "version": "7.18.6", + "resolved": "https://registry.npmmirror.com/@babel/code-frame/-/code-frame-7.18.6.tgz", + "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "dev": true, + "requires": { + "@babel/highlight": "^7.18.6" + } + }, + "@babel/compat-data": { + "version": "7.18.8", + "resolved": "https://registry.npmmirror.com/@babel/compat-data/-/compat-data-7.18.8.tgz", + "integrity": "sha512-HSmX4WZPPK3FUxYp7g2T6EyO8j96HlZJlxmKPSh6KAcqwyDrfx7hKjXpAW/0FhFfTJsR0Yt4lAjLI2coMptIHQ==", + "dev": true + }, + "@babel/core": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/core/-/core-7.18.9.tgz", + "integrity": "sha512-1LIb1eL8APMy91/IMW+31ckrfBM4yCoLaVzoDhZUKSM4cu1L1nIidyxkCgzPAgrC5WEz36IPEr/eSeSF9pIn+g==", + "dev": true, + "requires": { + "@ampproject/remapping": "^2.1.0", + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.18.9", + "@babel/helper-compilation-targets": "^7.18.9", + "@babel/helper-module-transforms": "^7.18.9", + "@babel/helpers": "^7.18.9", + "@babel/parser": "^7.18.9", + "@babel/template": "^7.18.6", + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.1", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "@babel/generator": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/generator/-/generator-7.18.9.tgz", + "integrity": "sha512-wt5Naw6lJrL1/SGkipMiFxJjtyczUWTP38deiP1PO60HsBjDeKk08CGC3S8iVuvf0FmTdgKwU1KIXzSKL1G0Ug==", + "dev": true, + "requires": { + "@babel/types": "^7.18.9", + "@jridgewell/gen-mapping": "^0.3.2", + "jsesc": "^2.5.1" + } + }, + "@babel/helper-compilation-targets": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.18.9.tgz", + "integrity": "sha512-tzLCyVmqUiFlcFoAPLA/gL9TeYrF61VLNtb+hvkuVaB5SUjW7jcfrglBIX1vUIoT7CLP3bBlIMeyEsIl2eFQNg==", + "dev": true, + "requires": { + "@babel/compat-data": "^7.18.8", + "@babel/helper-validator-option": "^7.18.6", + "browserslist": "^4.20.2", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "@babel/helper-environment-visitor": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", + "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", + "dev": true + }, + "@babel/helper-function-name": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/helper-function-name/-/helper-function-name-7.18.9.tgz", + "integrity": "sha512-fJgWlZt7nxGksJS9a0XdSaI4XvpExnNIgRP+rVefWh5U7BL8pPuir6SJUmFKRfjWQ51OtWSzwOxhaH/EBWWc0A==", + "dev": true, + "requires": { + "@babel/template": "^7.18.6", + "@babel/types": "^7.18.9" + } + }, + "@babel/helper-hoist-variables": { + "version": "7.18.6", + "resolved": "https://registry.npmmirror.com/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", + "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", + "dev": true, + "requires": { + "@babel/types": "^7.18.6" + } + }, + "@babel/helper-module-imports": { + "version": "7.18.6", + "resolved": "https://registry.npmmirror.com/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz", + "integrity": "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==", + "dev": true, + "requires": { + "@babel/types": "^7.18.6" + } + }, + "@babel/helper-module-transforms": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/helper-module-transforms/-/helper-module-transforms-7.18.9.tgz", + "integrity": "sha512-KYNqY0ICwfv19b31XzvmI/mfcylOzbLtowkw+mfvGPAQ3kfCnMLYbED3YecL5tPd8nAYFQFAd6JHp2LxZk/J1g==", + "dev": true, + "requires": { + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-module-imports": "^7.18.6", + "@babel/helper-simple-access": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/helper-validator-identifier": "^7.18.6", + "@babel/template": "^7.18.6", + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9" + } + }, + "@babel/helper-simple-access": { + "version": "7.18.6", + "resolved": "https://registry.npmmirror.com/@babel/helper-simple-access/-/helper-simple-access-7.18.6.tgz", + "integrity": "sha512-iNpIgTgyAvDQpDj76POqg+YEt8fPxx3yaNBg3S30dxNKm2SWfYhD0TGrK/Eu9wHpUW63VQU894TsTg+GLbUa1g==", + "dev": true, + "requires": { + "@babel/types": "^7.18.6" + } + }, + "@babel/helper-split-export-declaration": { + "version": "7.18.6", + "resolved": "https://registry.npmmirror.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", + "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", + "dev": true, + "requires": { + "@babel/types": "^7.18.6" + } + }, + "@babel/helper-validator-identifier": { + "version": "7.18.6", + "resolved": "https://registry.npmmirror.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.18.6.tgz", + "integrity": "sha512-MmetCkz9ej86nJQV+sFCxoGGrUbU3q02kgLciwkrt9QqEB7cP39oKEY0PakknEO0Gu20SskMRi+AYZ3b1TpN9g==", + "dev": true + }, + "@babel/helper-validator-option": { + "version": "7.18.6", + "resolved": "https://registry.npmmirror.com/@babel/helper-validator-option/-/helper-validator-option-7.18.6.tgz", + "integrity": "sha512-XO7gESt5ouv/LRJdrVjkShckw6STTaB7l9BrpBaAHDeF5YZT+01PCwmR0SJHnkW6i8OwW/EVWRShfi4j2x+KQw==", + "dev": true + }, + "@babel/helpers": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/helpers/-/helpers-7.18.9.tgz", + "integrity": "sha512-Jf5a+rbrLoR4eNdUmnFu8cN5eNJT6qdTdOg5IHIzq87WwyRw9PwguLFOWYgktN/60IP4fgDUawJvs7PjQIzELQ==", + "dev": true, + "requires": { + "@babel/template": "^7.18.6", + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9" + } + }, + "@babel/highlight": { + "version": "7.18.6", + "resolved": "https://registry.npmmirror.com/@babel/highlight/-/highlight-7.18.6.tgz", + "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "dev": true, + "requires": { + "@babel/helper-validator-identifier": "^7.18.6", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + } + }, + "@babel/parser": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/parser/-/parser-7.18.9.tgz", + "integrity": "sha512-9uJveS9eY9DJ0t64YbIBZICtJy8a5QrDEVdiLCG97fVLpDTpGX7t8mMSb6OWw6Lrnjqj4O8zwjELX3dhoMgiBg==", + "dev": true + }, + "@babel/template": { + "version": "7.18.6", + "resolved": "https://registry.npmmirror.com/@babel/template/-/template-7.18.6.tgz", + "integrity": "sha512-JoDWzPe+wgBsTTgdnIma3iHNFC7YVJoPssVBDjiHfNlyt4YcunDtcDOUmfVDfCK5MfdsaIoX9PkijPhjH3nYUw==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.18.6", + "@babel/parser": "^7.18.6", + "@babel/types": "^7.18.6" + } + }, + "@babel/traverse": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/traverse/-/traverse-7.18.9.tgz", + "integrity": "sha512-LcPAnujXGwBgv3/WHv01pHtb2tihcyW1XuL9wd7jqh1Z8AQkTd+QVjMrMijrln0T7ED3UXLIy36P9Ao7W75rYg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.18.9", + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-function-name": "^7.18.9", + "@babel/helper-hoist-variables": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/parser": "^7.18.9", + "@babel/types": "^7.18.9", + "debug": "^4.1.0", + "globals": "^11.1.0" + } + }, + "@babel/types": { + "version": "7.18.9", + "resolved": "https://registry.npmmirror.com/@babel/types/-/types-7.18.9.tgz", + "integrity": "sha512-WwMLAg2MvJmt/rKEVQBBhIVffMmnilX4oe0sRe7iPOHIGsqpruFHHdrfj4O1CMMtgMtCU4oPafZjDPCRgO57Wg==", + "dev": true, + "requires": { + "@babel/helper-validator-identifier": "^7.18.6", + "to-fast-properties": "^2.0.0" + } + }, + "@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "requires": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true + } + } + }, + "@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmmirror.com/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true + }, + "@jridgewell/gen-mapping": { + "version": "0.3.2", + "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz", + "integrity": "sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==", + "dev": true, + "requires": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + } + }, + "@jridgewell/resolve-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", + "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", + "dev": true + }, + "@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true + }, + "@jridgewell/sourcemap-codec": { + "version": "1.4.14", + "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", + "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", + "dev": true + }, + "@jridgewell/trace-mapping": { + "version": "0.3.14", + "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.14.tgz", + "integrity": "sha512-bJWEfQ9lPTvm3SneWwRFVLzrh6nhjwqw7TUFFBEMzwvg7t7PCDenf2lDwqo4NQXzdpgBXyFgDWnQA+2vkruksQ==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "aggregate-error": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "dev": true, + "requires": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + } + }, + "ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmmirror.com/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ansi-regex": { + "version": "4.1.1", + "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "append-transform": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/append-transform/-/append-transform-1.0.0.tgz", + "integrity": "sha512-P009oYkeHyU742iSZJzZZywj4QRJdnTWffaKuJQLablCZ1uz6/cW4yaRgcDaoQ+uwOxxnt0gRUcwfsNP2ri0gw==", + "dev": true, + "requires": { + "default-require-extensions": "^2.0.0" + } + }, + "archy": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/archy/-/archy-1.0.0.tgz", + "integrity": "sha512-Xg+9RwCg/0p32teKdGMPTPnVXKD0w3DfHnFTficozsAgsvq2XenPJq/MYpzzQ/v8zrOyJn6Ds39VA4JIDwFfqw==", + "dev": true + }, + "arg": { + "version": "4.1.3", + "resolved": "https://registry.npmmirror.com/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmmirror.com/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmmirror.com/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "dev": true, + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", + "dev": true + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmmirror.com/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmmirror.com/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==", + "dev": true + }, + "aws4": { + "version": "1.11.0", + "resolved": "https://registry.npmmirror.com/aws4/-/aws4-1.11.0.tgz", + "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==", + "dev": true + }, + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "base64-js": { + "version": "1.5.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "dev": true, + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "big-integer": { + "version": "1.6.51", + "resolved": "https://repo.huaweicloud.com/repository/npm/big-integer/-/big-integer-1.6.51.tgz", + "integrity": "sha512-GPEid2Y9QU1Exl1rpO9B2IPJGHPSupF5GnVIP0blYvNOMer2bTvSWs1jGOUg04hTmu67nmLsQ9TBo1puaotBHg==" + }, + "bind-obj-methods": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/bind-obj-methods/-/bind-obj-methods-2.0.2.tgz", + "integrity": "sha512-bUkRdEOppT1Xg/jG0+bp0JSjUD9U0r7skxb/42WeBUjfBpW6COQTIgQmKX5J2Z3aMXcORKgN2N+d7IQwTK3pag==", + "dev": true + }, + "bplist-creator": { + "version": "0.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/bplist-creator/-/bplist-creator-0.1.0.tgz", + "integrity": "sha512-sXaHZicyEEmY86WyueLTQesbeoH/mquvarJaQNbjuOQO+7gbFcDEWqKmcWA4cOTLzFlfgvkiVxolk1k5bBIpmg==", + "requires": { + "stream-buffers": "2.2.x" + } + }, + "bplist-parser": { + "version": "0.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/bplist-parser/-/bplist-parser-0.3.1.tgz", + "integrity": "sha512-PyJxiNtA5T2PlLIeBot4lbp7rj4OadzjnMZD/G5zuBNt8ei/yCU7+wW0h2bag9vr8c+/WuRWmSxbqAl9hL1rBA==", + "requires": { + "big-integer": "1.6.x" + } + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "browser-process-hrtime": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", + "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", + "dev": true + }, + "browserslist": { + "version": "4.21.2", + "resolved": "https://registry.npmmirror.com/browserslist/-/browserslist-4.21.2.tgz", + "integrity": "sha512-MonuOgAtUB46uP5CezYbRaYKBNt2LxP0yX+Pmj4LkcDFGkn9Cbpi83d9sCjwQDErXsIJSzY5oKGDbgOlF/LPAA==", + "dev": true, + "requires": { + "caniuse-lite": "^1.0.30001366", + "electron-to-chromium": "^1.4.188", + "node-releases": "^2.0.6", + "update-browserslist-db": "^1.0.4" + } + }, + "buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "caching-transform": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/caching-transform/-/caching-transform-3.0.2.tgz", + "integrity": "sha512-Mtgcv3lh3U0zRii/6qVgQODdPA4G3zhG+jtbCWj39RXuUFTMzH0vcdMtaJS1jPowd+It2Pqr6y3NJMQqOqCE2w==", + "dev": true, + "requires": { + "hasha": "^3.0.0", + "make-dir": "^2.0.0", + "package-hash": "^3.0.0", + "write-file-atomic": "^2.4.2" + } + }, + "camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmmirror.com/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true + }, + "caniuse-lite": { + "version": "1.0.30001367", + "resolved": "https://registry.npmmirror.com/caniuse-lite/-/caniuse-lite-1.0.30001367.tgz", + "integrity": "sha512-XDgbeOHfifWV3GEES2B8rtsrADx4Jf+juKX2SICJcaUhjYBO3bR96kvEIHa15VU6ohtOhBZuPGGYGbXMRn0NCw==", + "dev": true + }, + "capture-stack-trace": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/capture-stack-trace/-/capture-stack-trace-1.0.1.tgz", + "integrity": "sha512-mYQLZnx5Qt1JgB1WEiMCf2647plpGeQ2NMR/5L0HNZzGQo4fuSPnK+wjfPnKZV0aiJDgzmWqqkV/g7JD+DW0qw==", + "dev": true + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmmirror.com/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==", + "dev": true + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmmirror.com/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmmirror.com/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "dev": true + }, + "clean-yaml-object": { + "version": "0.1.0", + "resolved": "https://registry.npmmirror.com/clean-yaml-object/-/clean-yaml-object-0.1.0.tgz", + "integrity": "sha512-3yONmlN9CSAkzNwnRCiJQ7Q2xK5mWuEfL3PuTZcAUzhObbXsfsnMptJzXwz93nc5zn9V9TwCVMmV7w4xsm43dw==", + "dev": true + }, + "cliui": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "dev": true, + "requires": { + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmmirror.com/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "dev": true + }, + "combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmmirror.com/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "convert-source-map": { + "version": "1.8.0", + "resolved": "https://registry.npmmirror.com/convert-source-map/-/convert-source-map-1.8.0.tgz", + "integrity": "sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.1" + }, + "dependencies": { + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + } + } + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==", + "dev": true + }, + "coveralls": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/coveralls/-/coveralls-3.1.1.tgz", + "integrity": "sha512-+dxnG2NHncSD1NrqbSM3dn/lE57O6Qf/koe9+I7c+wzkqRmEvcp0kgJdxKInzYzkICKkFMZsX3Vct3++tsF9ww==", + "dev": true, + "requires": { + "js-yaml": "^3.13.1", + "lcov-parse": "^1.0.0", + "log-driver": "^1.2.7", + "minimist": "^1.2.5", + "request": "^2.88.2" + } + }, + "cp-file": { + "version": "6.2.0", + "resolved": "https://registry.npmmirror.com/cp-file/-/cp-file-6.2.0.tgz", + "integrity": "sha512-fmvV4caBnofhPe8kOcitBwSn2f39QLjnAnGq3gO9dfd75mUytzKNZB1hde6QHunW2Rt+OwuBOMc3i1tNElbszA==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "make-dir": "^2.0.0", + "nested-error-stacks": "^2.0.0", + "pify": "^4.0.1", + "safe-buffer": "^5.0.1" + } + }, + "cross-spawn": { + "version": "4.0.2", + "resolved": "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-4.0.2.tgz", + "integrity": "sha512-yAXz/pA1tD8Gtg2S98Ekf/sewp3Lcp3YoFKJ4Hkp5h5yLWnKVTDU0kwjKJ8NDCYcfTLfyGkzTikst+jWypT1iA==", + "dev": true, + "requires": { + "lru-cache": "^4.0.1", + "which": "^1.2.9" + } + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmmirror.com/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "debug": { + "version": "4.3.4", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "requires": { + "ms": "2.1.2" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "dev": true + }, + "default-require-extensions": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/default-require-extensions/-/default-require-extensions-2.0.0.tgz", + "integrity": "sha512-B0n2zDIXpzLzKeoEozorDSa1cHc1t0NjmxP0zuAxbizNU2MBqYJJKYXrrFdKuQliojXynrxgd7l4ahfg/+aA5g==", + "dev": true, + "requires": { + "strip-bom": "^3.0.0" + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true + }, + "diff": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/diff/-/diff-1.4.0.tgz", + "integrity": "sha512-VzVc42hMZbYU9Sx/ltb7KYuQ6pqAw+cbFWVy4XKdkuEL2CFaRLGEnISPs7YdzaUGpi+CpIqvRmu7hPQ4T7EQ5w==", + "dev": true + }, + "domain-browser": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/domain-browser/-/domain-browser-1.2.0.tgz", + "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==", + "dev": true + }, + "ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmmirror.com/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==", + "dev": true, + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "ejs": { + "version": "2.7.4", + "resolved": "https://registry.npmmirror.com/ejs/-/ejs-2.7.4.tgz", + "integrity": "sha512-7vmuyh5+kuUyJKePhQfRQBhXV5Ce+RnaeeQArKu1EAMpL3WbgMt5WG6uQZpEVvYSSsxMXRKOewtDk9RaTKXRlA==", + "dev": true + }, + "electron-to-chromium": { + "version": "1.4.196", + "resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.4.196.tgz", + "integrity": "sha512-uxMa/Dt7PQsLBVXwH+t6JvpHJnrsYBaxWKi/J6HE+/nBtoHENhwBoNkgkm226/Kfxeg0z1eMQLBRPPKcDH8xWA==", + "dev": true + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmmirror.com/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "es6-error": { + "version": "4.1.1", + "resolved": "https://registry.npmmirror.com/es6-error/-/es6-error-4.1.1.tgz", + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "dev": true + }, + "escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true + }, + "esm": { + "version": "3.2.25", + "resolved": "https://registry.npmmirror.com/esm/-/esm-3.2.25.tgz", + "integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==", + "dev": true + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmmirror.com/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + }, + "events-to-array": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/events-to-array/-/events-to-array-1.1.2.tgz", + "integrity": "sha512-inRWzRY7nG+aXZxBzEqYKB3HPgwflZRopAjDCHv0whhRx+MTUr1ei0ICZUypdyE0HRm4L2d5VEcIqLD6yl+BFA==", + "dev": true + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==", + "dev": true + }, + "fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmmirror.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "find-cache-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/find-cache-dir/-/find-cache-dir-2.1.0.tgz", + "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^2.0.0", + "pkg-dir": "^3.0.0" + } + }, + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "requires": { + "locate-path": "^3.0.0" + } + }, + "foreground-child": { + "version": "1.5.6", + "resolved": "https://registry.npmmirror.com/foreground-child/-/foreground-child-1.5.6.tgz", + "integrity": "sha512-3TOY+4TKV0Ml83PXJQY+JFQaHNV38lzQDIzzXYg1kWdBLenGgoZhAs0CKgzI31vi2pWEpQMq/Yi4bpKwCPkw7g==", + "dev": true, + "requires": { + "cross-spawn": "^4", + "signal-exit": "^3.0.0" + } + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmmirror.com/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==", + "dev": true + }, + "form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmmirror.com/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dev": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + } + }, + "fromentries": { + "version": "1.3.2", + "resolved": "https://registry.npmmirror.com/fromentries/-/fromentries-1.3.2.tgz", + "integrity": "sha512-cHEpEQHUg0f8XdtZCc2ZAhrHzKzT0MrFUTcvx+hfxYu7rGMDc5SKoXFh+n4YigxsHXRzc6OrCshdR1bWH6HHyg==", + "dev": true + }, + "fs-exists-cached": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/fs-exists-cached/-/fs-exists-cached-1.0.0.tgz", + "integrity": "sha512-kSxoARUDn4F2RPXX48UXnaFKwVU7Ivd/6qpzZL29MCDmr9sTvybv4gFCp+qaI4fM9m0z9fgz/yJvi56GAz+BZg==", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "function-loop": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/function-loop/-/function-loop-1.0.2.tgz", + "integrity": "sha512-Iw4MzMfS3udk/rqxTiDDCllhGwlOrsr50zViTOO/W6lS/9y6B1J0BD2VZzrnWUYBJsl3aeqjgR5v7bWWhZSYbA==", + "dev": true + }, + "gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmmirror.com/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true + }, + "get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmmirror.com/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmmirror.com/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "7.2.3", + "resolved": "https://registry.npmmirror.com/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "globals": { + "version": "11.12.0", + "resolved": "https://registry.npmmirror.com/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true + }, + "graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==", + "dev": true + }, + "har-validator": { + "version": "5.1.5", + "resolved": "https://registry.npmmirror.com/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "dev": true, + "requires": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" + } + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true + }, + "hasha": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/hasha/-/hasha-3.0.0.tgz", + "integrity": "sha512-w0Kz8lJFBoyaurBiNrIvxPqr/gJ6fOfSkpAPOepN3oECqGJag37xPbOv57izi/KP8auHgNYxn5fXtAb+1LsJ6w==", + "dev": true, + "requires": { + "is-stream": "^1.0.1" + } + }, + "hosted-git-info": { + "version": "2.8.9", + "resolved": "https://registry.npmmirror.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz", + "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", + "dev": true + }, + "html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmmirror.com/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true + }, + "indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmmirror.com/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmmirror.com/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true + }, + "is-core-module": { + "version": "2.9.0", + "resolved": "https://registry.npmmirror.com/is-core-module/-/is-core-module-2.9.0.tgz", + "integrity": "sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "dev": true + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==", + "dev": true + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==", + "dev": true + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true, + "optional": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmmirror.com/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==", + "dev": true + }, + "istanbul-lib-coverage": { + "version": "2.0.5", + "resolved": "https://registry.npmmirror.com/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz", + "integrity": "sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA==", + "dev": true + }, + "istanbul-lib-hook": { + "version": "2.0.7", + "resolved": "https://registry.npmmirror.com/istanbul-lib-hook/-/istanbul-lib-hook-2.0.7.tgz", + "integrity": "sha512-vrRztU9VRRFDyC+aklfLoeXyNdTfga2EI3udDGn4cZ6fpSXpHLV9X6CHvfoMCPtggg8zvDDmC4b9xfu0z6/llA==", + "dev": true, + "requires": { + "append-transform": "^1.0.0" + } + }, + "istanbul-lib-instrument": { + "version": "3.3.0", + "resolved": "https://registry.npmmirror.com/istanbul-lib-instrument/-/istanbul-lib-instrument-3.3.0.tgz", + "integrity": "sha512-5nnIN4vo5xQZHdXno/YDXJ0G+I3dAm4XgzfSVTPLQpj/zAV2dV6Juy0yaf10/zrJOJeHoN3fraFe+XRq2bFVZA==", + "dev": true, + "requires": { + "@babel/generator": "^7.4.0", + "@babel/parser": "^7.4.3", + "@babel/template": "^7.4.0", + "@babel/traverse": "^7.4.3", + "@babel/types": "^7.4.0", + "istanbul-lib-coverage": "^2.0.5", + "semver": "^6.0.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "istanbul-lib-processinfo": { + "version": "2.0.3", + "resolved": "https://registry.npmmirror.com/istanbul-lib-processinfo/-/istanbul-lib-processinfo-2.0.3.tgz", + "integrity": "sha512-NkwHbo3E00oybX6NGJi6ar0B29vxyvNwoC7eJ4G4Yq28UfY758Hgn/heV8VRFhevPED4LXfFz0DQ8z/0kw9zMg==", + "dev": true, + "requires": { + "archy": "^1.0.0", + "cross-spawn": "^7.0.3", + "istanbul-lib-coverage": "^3.2.0", + "p-map": "^3.0.0", + "rimraf": "^3.0.0", + "uuid": "^8.3.2" + }, + "dependencies": { + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmmirror.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "dev": true + }, + "rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmmirror.com/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "istanbul-lib-report": { + "version": "2.0.8", + "resolved": "https://registry.npmmirror.com/istanbul-lib-report/-/istanbul-lib-report-2.0.8.tgz", + "integrity": "sha512-fHBeG573EIihhAblwgxrSenp0Dby6tJMFR/HvlerBsrCTD5bkUuoNtn3gVh29ZCS824cGGBPn7Sg7cNk+2xUsQ==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^2.0.5", + "make-dir": "^2.1.0", + "supports-color": "^6.1.0" + }, + "dependencies": { + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmmirror.com/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "istanbul-lib-source-maps": { + "version": "3.0.6", + "resolved": "https://registry.npmmirror.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.6.tgz", + "integrity": "sha512-R47KzMtDJH6X4/YW9XTx+jrLnZnscW4VpNN+1PViSYTejLVPWv7oov+Duf8YQSPyVRUvueQqz1TcsC6mooZTXw==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^2.0.5", + "make-dir": "^2.1.0", + "rimraf": "^2.6.3", + "source-map": "^0.6.1" + } + }, + "istanbul-reports": { + "version": "2.2.7", + "resolved": "https://registry.npmmirror.com/istanbul-reports/-/istanbul-reports-2.2.7.tgz", + "integrity": "sha512-uu1F/L1o5Y6LzPVSVZXNOoD/KXpJue9aeLRd0sM9uMXfZvzomB0WxVamWb5ue8kA2vVWEmW7EG+A5n3f1kqHKg==", + "dev": true, + "requires": { + "html-escaper": "^2.0.0" + } + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmmirror.com/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==", + "dev": true + }, + "jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmmirror.com/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true + }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, + "json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmmirror.com/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmmirror.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmmirror.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "dev": true + }, + "json5": { + "version": "2.2.1", + "resolved": "https://registry.npmmirror.com/json5/-/json5-2.2.1.tgz", + "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", + "dev": true + }, + "jsprim": { + "version": "1.4.2", + "resolved": "https://registry.npmmirror.com/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", + "dev": true, + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.4.0", + "verror": "1.10.0" + } + }, + "lcov-parse": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/lcov-parse/-/lcov-parse-1.0.0.tgz", + "integrity": "sha512-aprLII/vPzuQvYZnDRU78Fns9I2Ag3gi4Ipga/hxnVMCZC8DnR2nI7XBqrPoywGfxqIx/DgarGvDJZAD3YBTgQ==", + "dev": true + }, + "load-json-file": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/load-json-file/-/load-json-file-4.0.0.tgz", + "integrity": "sha512-Kx8hMakjX03tiGTLAIdJ+lL0htKnXjEZN6hk/tozf/WOuYGdZBJrZ+rCJRbVCugsjB3jMLn9746NsQIf5VjBMw==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^4.0.0", + "pify": "^3.0.0", + "strip-bom": "^3.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/pify/-/pify-3.0.0.tgz", + "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", + "dev": true + } + } + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "lodash.flattendeep": { + "version": "4.4.0", + "resolved": "https://registry.npmmirror.com/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz", + "integrity": "sha512-uHaJFihxmJcEX3kT4I23ABqKKalJ/zDrDg0lsFtc1h+3uw49SIJ5beyhx5ExVRti3AvKoOJngIj7xz3oylPdWQ==", + "dev": true + }, + "log-driver": { + "version": "1.2.7", + "resolved": "https://registry.npmmirror.com/log-driver/-/log-driver-1.2.7.tgz", + "integrity": "sha512-U7KCmLdqsGHBLeWqYlFA0V0Sl6P08EE1ZrmA9cxjUE0WVqT9qnyVDPz1kzpFEP0jdJuFnasWIfSd7fsaNXkpbg==", + "dev": true + }, + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmmirror.com/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, + "merge-source-map": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/merge-source-map/-/merge-source-map-1.1.0.tgz", + "integrity": "sha512-Qkcp7P2ygktpMPh2mCQZaf3jhN6D3Z/qVZHSdWvQ+2Ef5HgRAPBO57A77+ENm0CPx2+1Ce/MYKi3ymqdfuqibw==", + "dev": true, + "requires": { + "source-map": "^0.6.1" + } + }, + "mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true + }, + "mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "requires": { + "mime-db": "1.52.0" + } + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmmirror.com/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", + "dev": true + }, + "minipass": { + "version": "2.9.0", + "resolved": "https://registry.npmmirror.com/minipass/-/minipass-2.9.0.tgz", + "integrity": "sha512-wxfUjg9WebH+CUDX/CdbRlh5SmfZiy/hpkxaRI16Y9W56Pa75sWgd/rvFilSgrauD9NyFymP/+JFV3KwzIsJeg==", + "dev": true, + "requires": { + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" + }, + "dependencies": { + "yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true + } + } + }, + "mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmmirror.com/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "requires": { + "minimist": "^1.2.6" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "nested-error-stacks": { + "version": "2.1.1", + "resolved": "https://registry.npmmirror.com/nested-error-stacks/-/nested-error-stacks-2.1.1.tgz", + "integrity": "sha512-9iN1ka/9zmX1ZvLV9ewJYEk9h7RyRRtqdK0woXcqohu8EWIerfPUjYJPg0ULy0UqP7cslmdGc8xKDJcojlKiaw==", + "dev": true + }, + "node-preload": { + "version": "0.2.1", + "resolved": "https://registry.npmmirror.com/node-preload/-/node-preload-0.2.1.tgz", + "integrity": "sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==", + "dev": true, + "requires": { + "process-on-spawn": "^1.0.0" + } + }, + "node-releases": { + "version": "2.0.6", + "resolved": "https://registry.npmmirror.com/node-releases/-/node-releases-2.0.6.tgz", + "integrity": "sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg==", + "dev": true + }, + "nodeunit": { + "version": "0.11.3", + "resolved": "https://registry.npmmirror.com/nodeunit/-/nodeunit-0.11.3.tgz", + "integrity": "sha512-gDNxrDWpx07BxYNO/jn1UrGI1vNhDQZrIFphbHMcTCDc5mrrqQBWfQMXPHJ5WSgbFwD1D6bv4HOsqtTrPG03AA==", + "dev": true, + "requires": { + "ejs": "^2.5.2", + "tap": "^12.0.1" + } + }, + "normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmmirror.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "requires": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "nyc": { + "version": "15.1.0", + "resolved": "https://registry.npmmirror.com/nyc/-/nyc-15.1.0.tgz", + "integrity": "sha512-jMW04n9SxKdKi1ZMGhvUTHBN0EICCRkHemEoE5jm6mTYcqcdas0ATzgUgejlQUHMvpnOZqGB5Xxsv9KxJW1j8A==", + "dev": true, + "requires": { + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "caching-transform": "^4.0.0", + "convert-source-map": "^1.7.0", + "decamelize": "^1.2.0", + "find-cache-dir": "^3.2.0", + "find-up": "^4.1.0", + "foreground-child": "^2.0.0", + "get-package-type": "^0.1.0", + "glob": "^7.1.6", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-hook": "^3.0.0", + "istanbul-lib-instrument": "^4.0.0", + "istanbul-lib-processinfo": "^2.0.2", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.0.2", + "make-dir": "^3.0.0", + "node-preload": "^0.2.1", + "p-map": "^3.0.0", + "process-on-spawn": "^1.0.0", + "resolve-from": "^5.0.0", + "rimraf": "^3.0.0", + "signal-exit": "^3.0.2", + "spawn-wrap": "^2.0.0", + "test-exclude": "^6.0.0", + "yargs": "^15.0.2" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "append-transform": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/append-transform/-/append-transform-2.0.0.tgz", + "integrity": "sha512-7yeyCEurROLQJFv5Xj4lEGTy0borxepjFv1g22oAdqFu//SrAlDl1O1Nxx15SH1RoliUml6p8dwJW9jvZughhg==", + "dev": true, + "requires": { + "default-require-extensions": "^3.0.0" + } + }, + "caching-transform": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/caching-transform/-/caching-transform-4.0.0.tgz", + "integrity": "sha512-kpqOvwXnjjN44D89K5ccQC+RUrsy7jB/XLlRrx0D7/2HNcTPqzsb6XgYoErwko6QsV184CA2YgS1fxDiiDZMWA==", + "dev": true, + "requires": { + "hasha": "^5.0.0", + "make-dir": "^3.0.0", + "package-hash": "^4.0.0", + "write-file-atomic": "^3.0.0" + } + }, + "cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dev": true, + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "default-require-extensions": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/default-require-extensions/-/default-require-extensions-3.0.0.tgz", + "integrity": "sha512-ek6DpXq/SCpvjhpFsLFRVtIxJCRw6fUR42lYMVZuUMK7n8eMz4Uh5clckdBjEpLhn/gEBZo7hDJnJcwdKLKQjg==", + "dev": true, + "requires": { + "strip-bom": "^4.0.0" + } + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "find-cache-dir": { + "version": "3.3.2", + "resolved": "https://registry.npmmirror.com/find-cache-dir/-/find-cache-dir-3.3.2.tgz", + "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" + } + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "foreground-child": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/foreground-child/-/foreground-child-2.0.0.tgz", + "integrity": "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.0", + "signal-exit": "^3.0.2" + } + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "hasha": { + "version": "5.2.2", + "resolved": "https://registry.npmmirror.com/hasha/-/hasha-5.2.2.tgz", + "integrity": "sha512-Hrp5vIK/xr5SkeN2onO32H0MgNZ0f17HRNH39WfL0SYUNOTZ5Lz1TJ8Pajo/87dYGEFlLMm7mIc/k/s6Bvz9HQ==", + "dev": true, + "requires": { + "is-stream": "^2.0.0", + "type-fest": "^0.8.0" + } + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true + }, + "istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmmirror.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "dev": true + }, + "istanbul-lib-hook": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/istanbul-lib-hook/-/istanbul-lib-hook-3.0.0.tgz", + "integrity": "sha512-Pt/uge1Q9s+5VAZ+pCo16TYMWPBIl+oaNIjgLQxcX0itS6ueeaA+pEfThZpH8WxhFgCiEb8sAJY6MdUKgiIWaQ==", + "dev": true, + "requires": { + "append-transform": "^2.0.0" + } + }, + "istanbul-lib-instrument": { + "version": "4.0.3", + "resolved": "https://registry.npmmirror.com/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz", + "integrity": "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==", + "dev": true, + "requires": { + "@babel/core": "^7.7.5", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.0.0", + "semver": "^6.3.0" + } + }, + "istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" + } + }, + "istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmmirror.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + } + }, + "istanbul-reports": { + "version": "3.1.5", + "resolved": "https://registry.npmmirror.com/istanbul-reports/-/istanbul-reports-3.1.5.tgz", + "integrity": "sha512-nUsEMa9pBt/NOHqbcbeJEgqIlY/K7rVWUX6Lql2orY5e9roQOthbR3vtY4zzf2orPELg80fnxxk9zUyPlgwD1w==", + "dev": true, + "requires": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "requires": { + "semver": "^6.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "package-hash": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/package-hash/-/package-hash-4.0.0.tgz", + "integrity": "sha512-whdkPIooSu/bASggZ96BWVvZTRMOFxnyUG5PnTSGKoJE2gd5mbVNmR2Nj20QFzxYYgAXpoqC+AiXzl+UMRh7zQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.15", + "hasha": "^5.0.0", + "lodash.flattendeep": "^4.4.0", + "release-zalgo": "^1.0.0" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmmirror.com/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "requires": { + "find-up": "^4.0.0" + } + }, + "resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true + }, + "rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "spawn-wrap": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/spawn-wrap/-/spawn-wrap-2.0.0.tgz", + "integrity": "sha512-EeajNjfN9zMnULLwhZZQU3GWBoFNkbngTUPfaawT4RkMiviTxcX0qfhVbGey39mfctfDHkWtuecgQ8NJcyQWHg==", + "dev": true, + "requires": { + "foreground-child": "^2.0.0", + "is-windows": "^1.0.2", + "make-dir": "^3.0.0", + "rimraf": "^3.0.0", + "signal-exit": "^3.0.2", + "which": "^2.0.1" + } + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.1" + } + }, + "strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmmirror.com/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "requires": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + } + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + }, + "write-file-atomic": { + "version": "3.0.3", + "resolved": "https://registry.npmmirror.com/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "dev": true, + "requires": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + } + }, + "yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmmirror.com/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "dev": true, + "requires": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + } + }, + "yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } + }, + "oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmmirror.com/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "opener": { + "version": "1.5.2", + "resolved": "https://registry.npmmirror.com/opener/-/opener-1.5.2.tgz", + "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", + "dev": true + }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha512-B5JU3cabzk8c67mRRd3ECmROafjYMXbuzlwtqdM8IbS8ktlTix8aFGb2bAGKrSRIlnfKwovGUUr72JUPyOb6kQ==", + "dev": true + }, + "own-or": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/own-or/-/own-or-1.0.0.tgz", + "integrity": "sha512-NfZr5+Tdf6MB8UI9GLvKRs4cXY8/yB0w3xtt84xFdWy8hkGjn+JFc60VhzS/hFRfbyxFcGYMTjnF4Me+RbbqrA==", + "dev": true + }, + "own-or-env": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/own-or-env/-/own-or-env-1.0.2.tgz", + "integrity": "sha512-NQ7v0fliWtK7Lkb+WdFqe6ky9XAzYmlkXthQrBbzlYbmFKoAYbDDcwmOm6q8kOuwSRXW8bdL5ORksploUJmWgw==", + "dev": true, + "requires": { + "own-or": "^1.0.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmmirror.com/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-map": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/p-map/-/p-map-3.0.0.tgz", + "integrity": "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==", + "dev": true, + "requires": { + "aggregate-error": "^3.0.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmmirror.com/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "package-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/package-hash/-/package-hash-3.0.0.tgz", + "integrity": "sha512-lOtmukMDVvtkL84rJHI7dpTYq+0rli8N2wlnqUcBuDWCfVhRUfOmnR9SsoHFMLpACvEV60dX7rd0rFaYDZI+FA==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.15", + "hasha": "^3.0.0", + "lodash.flattendeep": "^4.4.0", + "release-zalgo": "^1.0.0" + } + }, + "parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha512-aOIos8bujGN93/8Ox/jPLh7RwVnPEysynVFE+fQZyg6jKELEHwzgKdLRFHUgXJL6kylijVSBC4BvN9OmsB48Rw==", + "dev": true, + "requires": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + } + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmmirror.com/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "path-type": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/path-type/-/path-type-3.0.0.tgz", + "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", + "dev": true, + "requires": { + "pify": "^3.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/pify/-/pify-3.0.0.tgz", + "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", + "dev": true + } + } + }, + "pegjs": { + "version": "0.10.0", + "resolved": "https://registry.npmmirror.com/pegjs/-/pegjs-0.10.0.tgz", + "integrity": "sha512-qI5+oFNEGi3L5HAxDwN2LA4Gg7irF70Zs25edhjld9QemOgp0CbvMtbFcMvFtEo1OityPrcCzkQFB8JP/hxgow==", + "dev": true + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==", + "dev": true + }, + "picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "pify": { + "version": "4.0.1", + "resolved": "https://registry.npmmirror.com/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true + }, + "pkg-dir": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/pkg-dir/-/pkg-dir-3.0.0.tgz", + "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", + "dev": true, + "requires": { + "find-up": "^3.0.0" + } + }, + "plist": { + "version": "3.0.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/plist/-/plist-3.0.6.tgz", + "integrity": "sha512-WiIVYyrp8TD4w8yCvyeIr+lkmrGRd5u0VbRnU+tP/aRLxP/YadJUYOMZJ/6hIa3oUyVCsycXvtNRgd5XBJIbiA==", + "requires": { + "base64-js": "^1.5.1", + "xmlbuilder": "^15.1.1" + } + }, + "process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true, + "optional": true + }, + "process-on-spawn": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/process-on-spawn/-/process-on-spawn-1.0.0.tgz", + "integrity": "sha512-1WsPDsUSMmZH5LeMLegqkPDrsGgsWwk1Exipy2hvB0o/F0ASzbpIctSCcZIK1ykJvtTJULEH+20WOFjMvGnCTg==", + "dev": true, + "requires": { + "fromentries": "^1.2.0" + } + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha512-b/YwNhb8lk1Zz2+bXXpS/LK9OisiZZ1SNsSLxN1x2OXVEhW2Ckr/7mWE5vrC1ZTiJlD9g19jWszTmJsB+oEpFQ==", + "dev": true + }, + "psl": { + "version": "1.9.0", + "resolved": "https://registry.npmmirror.com/psl/-/psl-1.9.0.tgz", + "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", + "dev": true + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmmirror.com/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true + }, + "qs": { + "version": "6.5.3", + "resolved": "https://registry.npmmirror.com/qs/-/qs-6.5.3.tgz", + "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", + "dev": true + }, + "read-pkg": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/read-pkg/-/read-pkg-3.0.0.tgz", + "integrity": "sha512-BLq/cCO9two+lBgiTYNqD6GdtK8s4NpaWrl6/rCO9w0TUS8oJl7cmToOZfRYllKTISY6nt1U7jQ53brmKqY6BA==", + "dev": true, + "requires": { + "load-json-file": "^4.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^3.0.0" + } + }, + "read-pkg-up": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/read-pkg-up/-/read-pkg-up-4.0.0.tgz", + "integrity": "sha512-6etQSH7nJGsK0RbG/2TeDzZFa8shjQ1um+SwQQ5cwKy0dhSXdOncEhb1CPpvQG4h7FyOV6EB6YlV0yJvZQNAkA==", + "dev": true, + "requires": { + "find-up": "^3.0.0", + "read-pkg": "^3.0.0" + } + }, + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmmirror.com/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "optional": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + }, + "dependencies": { + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true, + "optional": true + } + } + }, + "release-zalgo": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/release-zalgo/-/release-zalgo-1.0.0.tgz", + "integrity": "sha512-gUAyHVHPPC5wdqX/LG4LWtRYtgjxyX78oanFNTMMyFEfOqdC54s3eE82imuWKbOeqYht2CrNf64Qb8vgmmtZGA==", + "dev": true, + "requires": { + "es6-error": "^4.0.1" + } + }, + "request": { + "version": "2.88.2", + "resolved": "https://registry.npmmirror.com/request/-/request-2.88.2.tgz", + "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "dev": true, + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.5.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "dependencies": { + "uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmmirror.com/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "dev": true + } + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true + }, + "require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true + }, + "resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmmirror.com/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dev": true, + "requires": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + } + }, + "resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true + }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmmirror.com/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmmirror.com/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmmirror.com/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "simple-plist": { + "version": "1.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/simple-plist/-/simple-plist-1.3.1.tgz", + "integrity": "sha512-iMSw5i0XseMnrhtIzRb7XpQEXepa9xhWxGUojHBL43SIpQuDQkh3Wpy67ZbDzZVr6EKxvwVChnVpdl8hEVLDiw==", + "requires": { + "bplist-creator": "0.1.0", + "bplist-parser": "0.3.1", + "plist": "^3.0.5" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmmirror.com/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmmirror.com/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "spawn-wrap": { + "version": "1.4.3", + "resolved": "https://registry.npmmirror.com/spawn-wrap/-/spawn-wrap-1.4.3.tgz", + "integrity": "sha512-IgB8md0QW/+tWqcavuFgKYR/qIRvJkRLPJDFaoXtLLUaVcCDK0+HeFTkmQHj3eprcYhc+gOl0aEA1w7qZlYezw==", + "dev": true, + "requires": { + "foreground-child": "^1.5.6", + "mkdirp": "^0.5.0", + "os-homedir": "^1.0.1", + "rimraf": "^2.6.2", + "signal-exit": "^3.0.2", + "which": "^1.3.0" + } + }, + "spdx-correct": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/spdx-correct/-/spdx-correct-3.1.1.tgz", + "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "dev": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.3.0", + "resolved": "https://registry.npmmirror.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", + "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", + "dev": true + }, + "spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmmirror.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.11", + "resolved": "https://registry.npmmirror.com/spdx-license-ids/-/spdx-license-ids-3.0.11.tgz", + "integrity": "sha512-Ctl2BrFiM0X3MANYgj3CkygxhRmr9mi6xhejbdO960nF6EDJApTYpn0BQnDKlnNBULKiCN1n3w9EBkHK8ZWg+g==", + "dev": true + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true + }, + "sshpk": { + "version": "1.17.0", + "resolved": "https://registry.npmmirror.com/sshpk/-/sshpk-1.17.0.tgz", + "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==", + "dev": true, + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "stack-utils": { + "version": "1.0.5", + "resolved": "https://registry.npmmirror.com/stack-utils/-/stack-utils-1.0.5.tgz", + "integrity": "sha512-KZiTzuV3CnSnSvgMRrARVCj+Ht7rMbauGDK0LdVFRGyenwdylpajAp4Q0i6SX8rEmbTpMMf6ryq2gb8pPq2WgQ==", + "dev": true, + "requires": { + "escape-string-regexp": "^2.0.0" + }, + "dependencies": { + "escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true + } + } + }, + "stream-buffers": { + "version": "2.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/stream-buffers/-/stream-buffers-2.2.0.tgz", + "integrity": "sha512-uyQK/mx5QjHun80FLJTfaWE7JtwfRMKBLkMne6udYOmvH0CawotVa7TfgYHzAnpphn4+TweIx1QKMnRIbipmUg==" + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + }, + "dependencies": { + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true, + "optional": true + } + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmmirror.com/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true + }, + "tap": { + "version": "12.7.0", + "resolved": "https://registry.npmmirror.com/tap/-/tap-12.7.0.tgz", + "integrity": "sha512-SjglJmRv0pqrQQ7d5ZBEY8ZOqv3nYDBXEX51oyycOH7piuhn82JKT/yDNewwmOsodTD/RZL9MccA96EjDgK+Eg==", + "dev": true, + "requires": { + "bind-obj-methods": "^2.0.0", + "browser-process-hrtime": "^1.0.0", + "capture-stack-trace": "^1.0.0", + "clean-yaml-object": "^0.1.0", + "color-support": "^1.1.0", + "coveralls": "^3.0.2", + "domain-browser": "^1.2.0", + "esm": "^3.2.5", + "foreground-child": "^1.3.3", + "fs-exists-cached": "^1.0.0", + "function-loop": "^1.0.1", + "glob": "^7.1.3", + "isexe": "^2.0.0", + "js-yaml": "^3.13.1", + "minipass": "^2.3.5", + "mkdirp": "^0.5.1", + "nyc": "^14.0.0", + "opener": "^1.5.1", + "os-homedir": "^1.0.2", + "own-or": "^1.0.0", + "own-or-env": "^1.0.1", + "rimraf": "^2.6.3", + "signal-exit": "^3.0.0", + "source-map-support": "^0.5.10", + "stack-utils": "^1.0.2", + "tap-mocha-reporter": "^3.0.9", + "tap-parser": "^7.0.0", + "tmatch": "^4.0.0", + "trivial-deferred": "^1.0.1", + "ts-node": "^8.0.2", + "tsame": "^2.0.1", + "typescript": "^3.3.3", + "write-file-atomic": "^2.4.2", + "yapool": "^1.0.0" + }, + "dependencies": { + "nyc": { + "version": "14.1.1", + "resolved": "https://registry.npmmirror.com/nyc/-/nyc-14.1.1.tgz", + "integrity": "sha512-OI0vm6ZGUnoGZv/tLdZ2esSVzDwUC88SNs+6JoSOMVxA+gKMB8Tk7jBwgemLx4O40lhhvZCVw1C+OYLOBOPXWw==", + "dev": true, + "requires": { + "archy": "^1.0.0", + "caching-transform": "^3.0.2", + "convert-source-map": "^1.6.0", + "cp-file": "^6.2.0", + "find-cache-dir": "^2.1.0", + "find-up": "^3.0.0", + "foreground-child": "^1.5.6", + "glob": "^7.1.3", + "istanbul-lib-coverage": "^2.0.5", + "istanbul-lib-hook": "^2.0.7", + "istanbul-lib-instrument": "^3.3.0", + "istanbul-lib-report": "^2.0.8", + "istanbul-lib-source-maps": "^3.0.6", + "istanbul-reports": "^2.2.4", + "js-yaml": "^3.13.1", + "make-dir": "^2.1.0", + "merge-source-map": "^1.1.0", + "resolve-from": "^4.0.0", + "rimraf": "^2.6.3", + "signal-exit": "^3.0.2", + "spawn-wrap": "^1.4.2", + "test-exclude": "^5.2.3", + "uuid": "^3.3.2", + "yargs": "^13.2.2", + "yargs-parser": "^13.0.0" + } + }, + "uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmmirror.com/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "dev": true + } + } + }, + "tap-mocha-reporter": { + "version": "3.0.9", + "resolved": "https://registry.npmmirror.com/tap-mocha-reporter/-/tap-mocha-reporter-3.0.9.tgz", + "integrity": "sha512-VO07vhC9EG27EZdOe7bWBj1ldbK+DL9TnRadOgdQmiQOVZjFpUEQuuqO7+rNSO2kfmkq5hWeluYXDWNG/ytXTQ==", + "dev": true, + "requires": { + "color-support": "^1.1.0", + "debug": "^2.1.3", + "diff": "^1.3.2", + "escape-string-regexp": "^1.0.3", + "glob": "^7.0.5", + "js-yaml": "^3.3.1", + "readable-stream": "^2.1.5", + "tap-parser": "^5.1.0", + "unicode-length": "^1.0.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmmirror.com/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true + }, + "tap-parser": { + "version": "5.4.0", + "resolved": "https://registry.npmmirror.com/tap-parser/-/tap-parser-5.4.0.tgz", + "integrity": "sha512-BIsIaGqv7uTQgTW1KLTMNPSEQf4zDDPgYOBRdgOfuB+JFOLRBfEu6cLa/KvMvmqggu1FKXDfitjLwsq4827RvA==", + "dev": true, + "requires": { + "events-to-array": "^1.0.1", + "js-yaml": "^3.2.7", + "readable-stream": "^2" + } + } + } + }, + "tap-parser": { + "version": "7.0.0", + "resolved": "https://registry.npmmirror.com/tap-parser/-/tap-parser-7.0.0.tgz", + "integrity": "sha512-05G8/LrzqOOFvZhhAk32wsGiPZ1lfUrl+iV7+OkKgfofZxiceZWMHkKmow71YsyVQ8IvGBP2EjcIjE5gL4l5lA==", + "dev": true, + "requires": { + "events-to-array": "^1.0.1", + "js-yaml": "^3.2.7", + "minipass": "^2.2.0" + } + }, + "test-exclude": { + "version": "5.2.3", + "resolved": "https://registry.npmmirror.com/test-exclude/-/test-exclude-5.2.3.tgz", + "integrity": "sha512-M+oxtseCFO3EDtAaGH7iiej3CBkzXqFMbzqYAACdzKui4eZA+pq3tZEwChvOdNfa7xxy8BfbmgJSIr43cC/+2g==", + "dev": true, + "requires": { + "glob": "^7.1.3", + "minimatch": "^3.0.4", + "read-pkg-up": "^4.0.0", + "require-main-filename": "^2.0.0" + } + }, + "tmatch": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/tmatch/-/tmatch-4.0.0.tgz", + "integrity": "sha512-Ynn2Gsp+oCvYScQXeV+cCs7citRDilq0qDXA6tuvFwDgiYyyaq7D5vKUlAPezzZR5NDobc/QMeN6e5guOYmvxg==", + "dev": true + }, + "to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "dev": true + }, + "tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmmirror.com/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dev": true, + "requires": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + } + }, + "trivial-deferred": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/trivial-deferred/-/trivial-deferred-1.0.1.tgz", + "integrity": "sha512-dagAKX7vaesNNAwOc9Np9C2mJ+7YopF4lk+jE2JML9ta4kZ91Y6UruJNH65bLRYoUROD8EY+Pmi44qQWwXR7sw==", + "dev": true + }, + "ts-node": { + "version": "8.10.2", + "resolved": "https://registry.npmmirror.com/ts-node/-/ts-node-8.10.2.tgz", + "integrity": "sha512-ISJJGgkIpDdBhWVu3jufsWpK3Rzo7bdiIXJjQc0ynKxVOVcg2oIrf2H2cejminGrptVc6q6/uynAHNCuWGbpVA==", + "dev": true, + "requires": { + "arg": "^4.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "source-map-support": "^0.5.17", + "yn": "3.1.1" + }, + "dependencies": { + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmmirror.com/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true + } + } + }, + "tsame": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/tsame/-/tsame-2.0.1.tgz", + "integrity": "sha512-jxyxgKVKa4Bh5dPcO42TJL22lIvfd9LOVJwdovKOnJa4TLLrHxquK+DlGm4rkGmrcur+GRx+x4oW00O2pY/fFw==", + "dev": true + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmmirror.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dev": true, + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmmirror.com/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==", + "dev": true + }, + "type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmmirror.com/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "dev": true + }, + "typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmmirror.com/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dev": true, + "requires": { + "is-typedarray": "^1.0.0" + } + }, + "typescript": { + "version": "3.9.10", + "resolved": "https://registry.npmmirror.com/typescript/-/typescript-3.9.10.tgz", + "integrity": "sha512-w6fIxVE/H1PkLKcCPsFqKE7Kv7QUwhU8qQY2MueZXWx5cPZdwFupLgKK3vntcK98BtNHZtAF4LA/yl2a7k8R6Q==", + "dev": true + }, + "unicode-length": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/unicode-length/-/unicode-length-1.0.3.tgz", + "integrity": "sha512-rZKNhIqioUp7H49afr26tivLDCvUSqOXwmwEEnsCwnPX67S1CYbOL45Y5IP3K/XHN73/lg21HlrB8SNlYXKQTg==", + "dev": true, + "requires": { + "punycode": "^1.3.2", + "strip-ansi": "^3.0.1" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha512-TIGnTpdo+E3+pCyAluZvtED5p5wCqLdezCyhPZzKPcxvFplEt4i+W7OONCKgeZFT3+y5NZZfOOS/Bdcanm1MYA==", + "dev": true + }, + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmmirror.com/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha512-VhumSSbBqDTP8p2ZLKj40UjBCV4+v8bUSEpUb4KjRgWk9pbqGF4REFj6KEagidb2f/M6AzC0EmFyDNGaw9OCzg==", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "update-browserslist-db": { + "version": "1.0.5", + "resolved": "https://registry.npmmirror.com/update-browserslist-db/-/update-browserslist-db-1.0.5.tgz", + "integrity": "sha512-dteFFpCyvuDdr9S/ff1ISkKt/9YZxKjI9WlRR99c180GaztJtRa/fn18FdxGVKVsnPY7/a/FDN68mcvUmP4U7Q==", + "dev": true, + "requires": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" + } + }, + "uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmmirror.com/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "optional": true + }, + "uuid": { + "version": "7.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/uuid/-/uuid-7.0.3.tgz", + "integrity": "sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==" + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmmirror.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmmirror.com/verror/-/verror-1.10.0.tgz", + "integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmmirror.com/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha512-B+enWhmw6cjfVC7kS8Pj9pCrKSc5txArRyaYGe088shv/FGWH+0Rjx/xPgtsWfsUtS27FkP697E4DDhgrgoc0Q==", + "dev": true + }, + "wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, + "write-file-atomic": { + "version": "2.4.3", + "resolved": "https://registry.npmmirror.com/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" + } + }, + "xmlbuilder": { + "version": "15.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==" + }, + "y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmmirror.com/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "dev": true + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha512-ncTzHV7NvsQZkYe1DW7cbDLm0YpzHmZF5r/iyP3ZnQtMiJ+pjzisCiMNI+Sj+xQF5pXhSHxSB3uDbsBTzY/c2A==", + "dev": true + }, + "yapool": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/yapool/-/yapool-1.0.0.tgz", + "integrity": "sha512-RONBZndo8Lo8pKPfORRxr2DIk2NZKIml654o4kaIu7RXVxQCKsAN6AqrcoZsI3h+2H5YO2mD/04Wy4LbAgd+Pg==", + "dev": true + }, + "yargs": { + "version": "13.3.2", + "resolved": "https://registry.npmmirror.com/yargs/-/yargs-13.3.2.tgz", + "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", + "dev": true, + "requires": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.2" + } + }, + "yargs-parser": { + "version": "13.1.2", + "resolved": "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-13.1.2.tgz", + "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + }, + "yn": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true + } + } +} From 4a5af0811f3c4949ec286df4b3b6c47367251a17 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Thu, 21 Jul 2022 14:40:04 +0800 Subject: [PATCH 057/111] [bug] fix IBL miplevel exceed limit (#12117) --- editor/assets/chunks/common/texture/cubemap.chunk | 4 ++-- editor/assets/chunks/legacy/shading-standard-base.chunk | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/editor/assets/chunks/common/texture/cubemap.chunk b/editor/assets/chunks/common/texture/cubemap.chunk index 096cf8963f..87fd12895e 100644 --- a/editor/assets/chunks/common/texture/cubemap.chunk +++ b/editor/assets/chunks/common/texture/cubemap.chunk @@ -7,7 +7,7 @@ #endif //#todo: add GL400 calcmip - float mip = roughness * mipCount; + float mip = roughness * (mipCount - 1.0); float delta = (dot(dFdx(R), dFdy(R))) * 1000.0; float mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0)); @@ -35,7 +35,7 @@ roughness = pow(roughness, 0.5); #endif - vec4 envmap = fragTextureLod(cc_environment, R, roughness * mipCount); + vec4 envmap = fragTextureLod(cc_environment, R, roughness * (mipCount - 1.0)); #if CC_USE_IBL == IBL_RGBE return unpackRGBE(envmap); diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk b/editor/assets/chunks/legacy/shading-standard-base.chunk index 85b2e0a578..faf8886408 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk @@ -43,7 +43,7 @@ vec3 BRDFApprox (vec3 specular, float roughness, float NoV) { #pragma extension([GL_OES_standard_derivatives, __VERSION__ < 110]) vec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) { #if CC_USE_IBL - float mip = roughness * mipCount; + float mip = roughness * (mipCount - 1.0); float delta = (dot(dFdx(R), dFdy(R))) * 1000.0; float mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0)); From 939f4c5704683bfc73b827bc1f8c048f48f7457f Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Thu, 21 Jul 2022 14:41:18 +0800 Subject: [PATCH 058/111] fix crash at server_mode due to use wrong header file (#12119) * fix crash at server_mode due to use wrong header file --- native/CMakeLists.txt | 2 +- .../interfaces/modules/canvas/CanvasRenderingContext2D.cpp | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index d42d87fc2b..da68cc29e2 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -499,7 +499,7 @@ cocos_source_files( cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.cpp cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h ) -if(USE_SERVER_MODE AND (NOT MACOSX)) +if(USE_SERVER_MODE) cocos_source_files( cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.cpp cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.h diff --git a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp index 5f271d7611..6f0ec972ff 100644 --- a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp +++ b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp @@ -33,7 +33,9 @@ #include "math/Math.h" #include "platform/FileUtils.h" -#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) +#if defined(CC_SERVER_MODE) + #include "platform/empty/modules/CanvasRenderingContext2DDelegate.h" +#elif (CC_PLATFORM == CC_PLATFORM_WINDOWS) #include "platform/win32/modules/CanvasRenderingContext2DDelegate.h" #elif (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) #include "platform/java/modules/CanvasRenderingContext2DDelegate.h" From ccb5fb97e09e14f171b1dc64388e7270f7a86f1f Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 21 Jul 2022 14:47:13 +0800 Subject: [PATCH 059/111] prevent adding more than one rendering component to a node (#12121) --- cocos/2d/framework/ui-renderer.ts | 3 +-- cocos/core/components/renderer.ts | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index 99cb72f8d6..54da6921c5 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -25,7 +25,7 @@ import { DEBUG, EDITOR, JSB } from 'internal:constants'; import { - ccclass, executeInEditMode, requireComponent, disallowMultiple, tooltip, + ccclass, executeInEditMode, requireComponent, tooltip, type, displayOrder, serializable, override, visible, displayName, disallowAnimation, } from 'cc.decorator'; import { Color } from '../../core/math'; @@ -114,7 +114,6 @@ export enum InstanceMaterialType { */ @ccclass('cc.UIRenderer') @requireComponent(UITransform) -@disallowMultiple @executeInEditMode export class UIRenderer extends Renderer { /** diff --git a/cocos/core/components/renderer.ts b/cocos/core/components/renderer.ts index bee78aefd0..0d4f7c57eb 100644 --- a/cocos/core/components/renderer.ts +++ b/cocos/core/components/renderer.ts @@ -25,7 +25,7 @@ import { EDITOR } from 'internal:constants'; import { - ccclass, type, displayOrder, displayName, serializable, + ccclass, type, displayOrder, displayName, serializable, disallowMultiple, } from 'cc.decorator'; import { Material } from '../assets/material'; import { Component } from './component'; @@ -55,6 +55,7 @@ const _matInsInfo: IMaterialInstanceInfo = { * 默认情况下,渲染组件使用共享材质进行渲染,材质实例也不会被创建出来。仅在用户通过 [[material]],[[materials]] 和 [[getMaterialInstance]] 接口获取材质时才会创建材质实例。 */ @ccclass('cc.Renderer') +@disallowMultiple export class Renderer extends Component { /** * @en Get the default shared material From bbfafa4e9a15bbbd215d5a1d5fc07189c6303a28 Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Thu, 21 Jul 2022 14:55:27 +0800 Subject: [PATCH 060/111] Added interface for copying text to clipboard (#12029) * Added interface for copying text to clipboard * Bind the context to the function --- cocos/native-binding/impl.ts | 1 + cocos/native-binding/index.ts | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index 6cdb99890c..8f143d55bc 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -6,4 +6,5 @@ export const native = { zipUtils: globalJsb.zipUtils, fileUtils: globalJsb.fileUtils, DebugRenderer: globalJsb.DebugRenderer, + copyTextToClipboard: globalJsb.copyTextToClipboard?.bind(globalJsb), }; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index f920bde7a6..b9f5c76f43 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -36,6 +36,12 @@ export declare namespace native { */ export type DownloaderTask = { requestURL: string, storagePath: string, identifier: string }; + /** + * @en Copy text to clipboard @zh 拷贝字符串到剪切板 + * @param text + */ + export function copyTextToClipboard(text:string): void; + /** * @en DownloaderHints @zh 下载任务的配置接口 * @param countOfMaxProcessingTasks From eab5f52c9290193c4d88eaca7723f94623ea81e2 Mon Sep 17 00:00:00 2001 From: zhakesi Date: Thu, 21 Jul 2022 15:47:52 +0800 Subject: [PATCH 061/111] fix tiledLayer addUserNode (#12122) --- cocos/tiledmap/tiled-layer.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/tiledmap/tiled-layer.ts b/cocos/tiledmap/tiled-layer.ts index 94464da9d2..f646bee684 100644 --- a/cocos/tiledmap/tiled-layer.ts +++ b/cocos/tiledmap/tiled-layer.ts @@ -1482,6 +1482,7 @@ export class TiledLayer extends UIRenderer { } public prepareDrawData () { + this._drawInfoList.length = 0; const entity = this.renderEntity; entity.clearDynamicRenderDrawInfos(); const tiledDataArray = this._tiledDataArray; From d861c680159723fceb40a6c2550318e6789a8a45 Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Thu, 21 Jul 2022 16:34:50 +0800 Subject: [PATCH 062/111] add custom pipeline (#12124) --- editor/engine-features/render-config.json | 2 +- editor/i18n/en/localization.js | 4 ++++ editor/i18n/zh/localization.js | 4 ++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index 2eb6a33189..2c102f4374 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -224,7 +224,7 @@ "category": "animation" }, "custom-pipeline": { - "default": ["custom-pipeline"], + "default": [], "label": "i18n:ENGINE.features.custom_pipeline.label", "description": "i18n:ENGINE.features.custom_pipeline.description", "wechatPlugin": false diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 1125566083..34b7cc869a 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -915,6 +915,10 @@ module.exports = { label: "Marionette Animation System", description: "Enable the Marionette animation system", }, + custom_pipeline: { + label: "Custom Render Pipeline (Experimental)", + description: "Enable custom render pipeline", + }, }, renderable_2d: { srcBlendFactor: 'Specifies the source blend mode, it will clone a new material object.', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index f75c669399..9fc10844e5 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -896,6 +896,10 @@ module.exports = { label: "Marionette 动画系统", description: "启用 Marionette 动画系统。", }, + custom_pipeline: { + label: "自定义渲染管线(实验)", + description: "启用自定义渲染管线。", + }, }, renderable_2d: { srcBlendFactor: '指定源的混合模式,这会克隆一个新的材质对象,注意这带来的性能和内存损耗', From d0d01abbf5d0405853ad01b6c0eadebf3483e16c Mon Sep 17 00:00:00 2001 From: zxx43 Date: Thu, 21 Jul 2022 16:55:03 +0800 Subject: [PATCH 063/111] call stop when destroy particle (#11923) --- cocos/particle/particle-system.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cocos/particle/particle-system.ts b/cocos/particle/particle-system.ts index 0111cd98c1..76cc6f685b 100644 --- a/cocos/particle/particle-system.ts +++ b/cocos/particle/particle-system.ts @@ -989,6 +989,14 @@ export class ParticleSystem extends ModelRenderer { } protected onDestroy () { + this.stop(); + if (this.processor.getModel()?.scene) { + this.processor.detachFromScene(); + if (this._trailModule && this._trailModule.enable) { + this._trailModule._detachFromScene(); + } + } + legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this); // this._system.remove(this); this.processor.onDestroy(); From b84a2769444f46a60048fcf782942cc4cad79c8c Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Thu, 21 Jul 2022 17:50:29 +0800 Subject: [PATCH 064/111] [optimization] compress csm ubo (#12111) --- .../custom/web-descriptor-hierarchy.ts | 2 +- cocos/core/pipeline/custom/web-scene.ts | 47 -------- cocos/core/pipeline/define.ts | 24 ++-- cocos/core/pipeline/pipeline-ubo.ts | 40 ++++--- .../pipeline/render-additive-light-queue.ts | 8 +- cocos/core/pipeline/scene-culling.ts | 106 +----------------- cocos/core/pipeline/shadow/csm-layers.ts | 28 ++--- cocos/core/pipeline/shadow/shadow-flow.ts | 8 +- .../builtin/functionalities/shadow-map.chunk | 37 ++++-- .../chunks/builtin/uniforms/cc-csm.chunk | 7 +- .../chunks/builtin/uniforms/cc-shadow.chunk | 1 - .../render-to-scene/pipeline/forward-fs.chunk | 4 +- native/cocos/renderer/pipeline/Define.cpp | 8 +- native/cocos/renderer/pipeline/Define.h | 16 +-- .../cocos/renderer/pipeline/PipelineUBO.cpp | 37 +++--- native/cocos/renderer/pipeline/PipelineUBO.h | 1 + .../pipeline/RenderAdditiveLightQueue.cpp | 7 +- .../cocos/renderer/pipeline/SceneCulling.cpp | 105 ----------------- native/cocos/renderer/pipeline/SceneCulling.h | 5 - .../renderer/pipeline/shadow/CSMLayers.cpp | 10 +- .../renderer/pipeline/shadow/CSMLayers.h | 9 +- .../renderer/pipeline/shadow/ShadowFlow.cpp | 2 +- .../renderer/pipeline/shadow/ShadowFlow.h | 4 - 23 files changed, 126 insertions(+), 390 deletions(-) diff --git a/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts b/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts index 9273cf8671..ef2db896a5 100644 --- a/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts +++ b/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts @@ -372,7 +372,6 @@ export class WebDescriptorHierarchy { if (hasCCShadow) { const shadowDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, UBOShadow.BINDING, 'CCShadow', globalUniformTarget); - this.setUniform(shadowDB, 'cc_matLightPlaneProj', Type.MAT4, 1); this.setUniform(shadowDB, 'cc_matLightView', Type.MAT4, 1); this.setUniform(shadowDB, 'cc_matLightViewProj', Type.MAT4, 1); this.setUniform(shadowDB, 'cc_shadowInvProjDepthInfo', Type.FLOAT4, 1); @@ -382,6 +381,7 @@ export class WebDescriptorHierarchy { this.setUniform(shadowDB, 'cc_shadowWHPBInfo', Type.FLOAT4, 1); this.setUniform(shadowDB, 'cc_shadowLPNNInfo', Type.FLOAT4, 1); this.setUniform(shadowDB, 'cc_shadowColor', Type.FLOAT4, 1); + this.setUniform(shadowDB, 'cc_planarNDInfo', Type.FLOAT4, 1); this.setDescriptor(globalUniformTarget, 'CCShadow', Type.UNKNOWN); } diff --git a/cocos/core/pipeline/custom/web-scene.ts b/cocos/core/pipeline/custom/web-scene.ts index a06bdadae5..12faee61ca 100644 --- a/cocos/core/pipeline/custom/web-scene.ts +++ b/cocos/core/pipeline/custom/web-scene.ts @@ -65,47 +65,6 @@ export class WebSceneTask extends SceneTask { return TaskType.SYNC; } - protected _updateDirLight (light: DirectionalLight) { - const shadows = this._sceneData.shadows; - - const dir = light.direction; - const n = shadows.normal; const d = shadows.distance + 0.001; // avoid z-fighting - const NdL = Vec3.dot(n, dir); const scale = 1 / NdL; - const lx = dir.x * scale; const ly = dir.y * scale; const lz = dir.z * scale; - const nx = n.x; const ny = n.y; const nz = n.z; - const m = shadows.matLight; - m.m00 = 1 - nx * lx; - m.m01 = -nx * ly; - m.m02 = -nx * lz; - m.m03 = 0; - m.m04 = -ny * lx; - m.m05 = 1 - ny * ly; - m.m06 = -ny * lz; - m.m07 = 0; - m.m08 = -nz * lx; - m.m09 = -nz * ly; - m.m10 = 1 - nz * lz; - m.m11 = 0; - m.m12 = lx * d; - m.m13 = ly * d; - m.m14 = lz * d; - m.m15 = 1; - this._ubo.updateShadowUBORange(UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET, shadows.matLight); - } - - protected _getCameraWorldMatrix (out: Mat4, camera: Camera) { - if (!camera.node) { return; } - - const cameraNode = camera.node; - const position = cameraNode.getWorldPosition(); - const rotation = cameraNode.getWorldRotation(); - - Mat4.fromRT(out, rotation, position); - out.m08 *= -1.0; - out.m09 *= -1.0; - out.m10 *= -1.0; - } - protected _getRenderObject (model: Model, camera: Camera) { let depth = 0; if (model.node) { @@ -144,12 +103,6 @@ export class WebSceneTask extends SceneTask { } } - if (mainLight) { - if (shadows.type === ShadowType.Planar) { - this._updateDirLight(mainLight); - } - } - if (skybox.enabled && skybox.model && (camera.clearFlag & SKYBOX_FLAG)) { renderObjects.push(this._getRenderObject(skybox.model, camera)); } diff --git a/cocos/core/pipeline/define.ts b/cocos/core/pipeline/define.ts index 7ca29cd926..8f5ad4464d 100644 --- a/cocos/core/pipeline/define.ts +++ b/cocos/core/pipeline/define.ts @@ -261,8 +261,7 @@ globalDescriptorSetLayout.bindings[UBOCamera.BINDING] = UBOCamera.DESCRIPTOR; * @zh 这个 UBO 仅仅只给 'cast shadow(fixed || csm)' && 'dir fixed area shadow' && 'spot shadow' && 'sphere shadow' && 'planar shadow' 使用 */ export class UBOShadow { - public static readonly MAT_LIGHT_PLANE_PROJ_OFFSET = 0; - public static readonly MAT_LIGHT_VIEW_OFFSET = UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET + 16; + public static readonly MAT_LIGHT_VIEW_OFFSET = 0; public static readonly MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadow.MAT_LIGHT_VIEW_OFFSET + 16; public static readonly SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET + 16; public static readonly SHADOW_PROJ_DEPTH_INFO_OFFSET = UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 4; @@ -278,7 +277,6 @@ export class UBOShadow { public static readonly BINDING = PipelineGlobalBindings.UBO_SHADOW; public static readonly DESCRIPTOR = new DescriptorSetLayoutBinding(UBOShadow.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL); public static readonly LAYOUT = new UniformBlock(SetIndex.GLOBAL, UBOShadow.BINDING, UBOShadow.NAME, [ - new Uniform('cc_matLightPlaneProj', Type.MAT4, 1), new Uniform('cc_matLightView', Type.MAT4, 1), new Uniform('cc_matLightViewProj', Type.MAT4, 1), new Uniform('cc_shadowInvProjDepthInfo', Type.FLOAT4, 1), @@ -300,27 +298,29 @@ globalDescriptorSetLayout.bindings[UBOShadow.BINDING] = UBOShadow.DESCRIPTOR; */ export class UBOCSM { public static readonly CSM_LEVEL_COUNT = 4; - public static readonly MAT_CSM_VIEW_OFFSET = 0; - public static readonly MAT_CSM_VIEW_PROJ_OFFSET = UBOCSM.MAT_CSM_VIEW_OFFSET + 16 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly MAT_CSM_VIEW_PROJ_ATLAS_OFFSET = UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly CSM_PROJ_DEPTH_INFO_OFFSET = UBOCSM.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_VIEW_DIR_0_OFFSET = 0; + public static readonly CSM_VIEW_DIR_1_OFFSET = UBOCSM.CSM_VIEW_DIR_0_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_VIEW_DIR_2_OFFSET = UBOCSM.CSM_VIEW_DIR_1_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_ATLAS_OFFSET = UBOCSM.CSM_VIEW_DIR_2_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly MAT_CSM_VIEW_PROJ_OFFSET = UBOCSM.CSM_ATLAS_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_PROJ_DEPTH_INFO_OFFSET = UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * UBOCSM.CSM_LEVEL_COUNT; public static readonly CSM_PROJ_INFO_OFFSET = UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; public static readonly CSM_SPLITS_INFO_OFFSET = UBOCSM.CSM_PROJ_INFO_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly CSM_INFO_OFFSET = UBOCSM.CSM_SPLITS_INFO_OFFSET + 4; - public static readonly COUNT: number = UBOCSM.CSM_INFO_OFFSET + 4; + public static readonly COUNT: number = UBOCSM.CSM_SPLITS_INFO_OFFSET + 4; public static readonly SIZE = UBOCSM.COUNT * 4; public static readonly NAME = 'CCCSM'; public static readonly BINDING = PipelineGlobalBindings.UBO_CSM; public static readonly DESCRIPTOR = new DescriptorSetLayoutBinding(UBOCSM.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL); public static readonly LAYOUT = new UniformBlock(SetIndex.GLOBAL, UBOCSM.BINDING, UBOCSM.NAME, [ - new Uniform('cc_matCSMView', Type.MAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmViewDir0', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmViewDir1', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmViewDir2', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmAtlas', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), new Uniform('cc_matCSMViewProj', Type.MAT4, UBOCSM.CSM_LEVEL_COUNT), - new Uniform('cc_matCSMViewProjAtlas', Type.MAT4, UBOCSM.CSM_LEVEL_COUNT), new Uniform('cc_csmProjDepthInfo', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), new Uniform('cc_csmProjInfo', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), new Uniform('cc_csmSplitsInfo', Type.FLOAT4, 1), - new Uniform('cc_csmInfo', Type.FLOAT4, 1), ], 1); } globalDescriptorSetLayout.layouts[UBOCSM.NAME] = UBOCSM.LAYOUT; diff --git a/cocos/core/pipeline/pipeline-ubo.ts b/cocos/core/pipeline/pipeline-ubo.ts index f65eae6fde..1a84ab35cb 100644 --- a/cocos/core/pipeline/pipeline-ubo.ts +++ b/cocos/core/pipeline/pipeline-ubo.ts @@ -25,25 +25,25 @@ import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UBOCSM } from './define'; -import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, API } from '../gfx'; +import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../gfx'; import { Camera } from '../renderer/scene/camera'; import { Mat4, Vec3, Vec4, Color } from '../math'; import { PipelineRuntime } from './custom/pipeline'; import { legacyCC } from '../global-exports'; import { CSMLevel, PCFType, Shadows, ShadowType } from '../renderer/scene/shadows'; -import { updatePlanarNormalAndDistance, updatePlanarPROJ } from './scene-culling'; import { Light, LightType } from '../renderer/scene/light'; import { DirectionalLight, SpotLight } from '../renderer/scene'; import { RenderWindow } from '../renderer/core/render-window'; import { builtinResMgr } from '../builtin/builtin-res-mgr'; import { Texture2D } from '../assets'; -import { DebugView, DebugViewCompositeType } from './debug-view'; +import { DebugViewCompositeType } from './debug-view'; const _matShadowView = new Mat4(); const _matShadowProj = new Mat4(); const _matShadowViewProj = new Mat4(); const _vec4ShadowInfo = new Vec4(); const _lightDir = new Vec4(0.0, 0.0, 1.0, 0.0); +const _tempVec3 = new Vec3(); export class PipelineUBO { public static updateGlobalUBOView (window: RenderWindow, bufferView: Float32Array) { @@ -201,6 +201,14 @@ export class PipelineUBO { return 0.0; } + public static updatePlanarNormalAndDistance (shadowInfo: Shadows, shadowUBO: Float32Array) { + Vec3.normalize(_tempVec3, shadowInfo.normal); + shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3.x; + shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3.y; + shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 2] = _tempVec3.z; + shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = -shadowInfo.distance; + } + public static updateShadowUBOView (pipeline: PipelineRuntime, shadowBufferView: Float32Array, csmBufferView: Float32Array, camera: Camera) { const device = pipeline.device; @@ -243,18 +251,24 @@ export class PipelineUBO { _vec4ShadowInfo.set(0, packing, mainLight.shadowNormalBias, 0); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); } else { + const layerThreshold = this.getPCFRadius(shadowInfo, mainLight); for (let i = 0; i < mainLight.csmLevel; i++) { - cv[UBOCSM.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; - const matShadowView = csmLayers.layers[i].matShadowView; - Mat4.toArray(cv, matShadowView, UBOCSM.MAT_CSM_VIEW_OFFSET + 16 * i); + _vec4ShadowInfo.set(matShadowView.m00, matShadowView.m04, matShadowView.m08, layerThreshold); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_0_OFFSET + 4 * i); + _vec4ShadowInfo.set(matShadowView.m01, matShadowView.m05, matShadowView.m09, 0.0); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_1_OFFSET + 4 * i); + _vec4ShadowInfo.set(matShadowView.m02, matShadowView.m06, matShadowView.m10, 0.0); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_2_OFFSET + 4 * i); + + const csmAtlas = csmLayers.layers[i].csmAtlas; + Vec4.toArray(cv, csmAtlas, UBOCSM.CSM_ATLAS_OFFSET + 4 * i); + + cv[UBOCSM.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; const matShadowViewProj = csmLayers.layers[i].matShadowViewProj; Mat4.toArray(cv, matShadowViewProj, UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); - const matShadowViewProjAtlas = csmLayers.layers[i].matShadowViewProjAtlas; - Mat4.toArray(cv, matShadowViewProjAtlas, UBOCSM.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * i); - const matShadowProj = csmLayers.layers[i].matShadowProj; cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; @@ -267,11 +281,6 @@ export class PipelineUBO { cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; } - cv[UBOCSM.CSM_INFO_OFFSET + 0] = 0; - cv[UBOCSM.CSM_INFO_OFFSET + 1] = this.getPCFRadius(shadowInfo, mainLight); - cv[UBOCSM.CSM_INFO_OFFSET + 2] = 0; - cv[UBOCSM.CSM_INFO_OFFSET + 3] = 0; - _vec4ShadowInfo.set(0, 0, 0, 1.0 - mainLight.shadowSaturation); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); @@ -282,8 +291,7 @@ export class PipelineUBO { Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); } } else { - updatePlanarPROJ(shadowInfo, mainLight, sv); - updatePlanarNormalAndDistance(shadowInfo, sv); + PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, sv); } Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); diff --git a/cocos/core/pipeline/render-additive-light-queue.ts b/cocos/core/pipeline/render-additive-light-queue.ts index dd527d995e..44487057e9 100644 --- a/cocos/core/pipeline/render-additive-light-queue.ts +++ b/cocos/core/pipeline/render-additive-light-queue.ts @@ -40,9 +40,9 @@ import { getPhaseID } from './pass-phase'; import { Light, LightType } from '../renderer/scene/light'; import { SetIndex, UBOForwardLight, UBOShadow, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, supportsR32FloatTexture } from './define'; -import { updatePlanarNormalAndDistance, updatePlanarPROJ } from './scene-culling'; import { Camera, ShadowType } from '../renderer/scene'; import { GlobalDSManager } from './global-descriptor-set-manager'; +import { PipelineUBO } from './pipeline-ubo'; import { PipelineRuntime } from './custom/pipeline'; interface IAdditiveLightPass { @@ -345,8 +345,7 @@ export class RenderAdditiveLightQueue { case LightType.SPHERE: { // planar PROJ if (mainLight) { - updatePlanarPROJ(shadowInfo, mainLight, this._shadowUBO); - updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); + PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); } this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; @@ -368,8 +367,7 @@ export class RenderAdditiveLightQueue { // planar PROJ if (mainLight) { - updatePlanarPROJ(shadowInfo, mainLight, this._shadowUBO); - updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); + PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); } // light view diff --git a/cocos/core/pipeline/scene-culling.ts b/cocos/core/pipeline/scene-culling.ts index 2579f2b288..52ca536887 100644 --- a/cocos/core/pipeline/scene-culling.ts +++ b/cocos/core/pipeline/scene-culling.ts @@ -23,15 +23,14 @@ THE SOFTWARE. */ -import { AABB, Frustum, intersect, Sphere } from '../geometry'; +import { intersect, Sphere } from '../geometry'; import { Model } from '../renderer/scene/model'; import { Camera, SKYBOX_FLAG } from '../renderer/scene/camera'; -import { Vec3, Mat4, Color } from '../math'; +import { Vec3 } from '../math'; import { RenderPipeline } from './render-pipeline'; import { Pool } from '../memop'; import { IRenderObject, UBOShadow } from './define'; -import { ShadowType, Shadows, CSMLevel, CSMOptimizationMode } from '../renderer/scene/shadows'; -import { SphereLight, DirectionalLight } from '../renderer/scene'; +import { ShadowType, Shadows, CSMOptimizationMode } from '../renderer/scene/shadows'; import { PipelineSceneData } from './pipeline-scene-data'; import { ShadowLayerVolume } from './shadow/csm-layers'; @@ -52,99 +51,6 @@ function getRenderObject (model: Model, camera: Camera) { return ro; } -function updateSphereLight (pipeline: RenderPipeline, light: SphereLight) { - const shadows = pipeline.pipelineSceneData.shadows; - - const pos = light.node!.worldPosition; - const n = shadows.normal; const d = shadows.distance + 0.001; // avoid z-fighting - const NdL = Vec3.dot(n, pos); - const lx = pos.x; const ly = pos.y; const lz = pos.z; - const nx = n.x; const ny = n.y; const nz = n.z; - const m = shadows.matLight; - m.m00 = NdL - d - lx * nx; - m.m01 = -ly * nx; - m.m02 = -lz * nx; - m.m03 = -nx; - m.m04 = -lx * ny; - m.m05 = NdL - d - ly * ny; - m.m06 = -lz * ny; - m.m07 = -ny; - m.m08 = -lx * nz; - m.m09 = -ly * nz; - m.m10 = NdL - d - lz * nz; - m.m11 = -nz; - m.m12 = lx * d; - m.m13 = ly * d; - m.m14 = lz * d; - m.m15 = NdL; - - pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET, shadows.matLight); -} - -function updateDirLight (pipeline: RenderPipeline, light: DirectionalLight) { - const shadows = pipeline.pipelineSceneData.shadows; - - const dir = light.direction; - const n = shadows.normal; const d = shadows.distance + 0.001; // avoid z-fighting - const NdL = Vec3.dot(n, dir); const scale = 1 / NdL; - const lx = dir.x * scale; const ly = dir.y * scale; const lz = dir.z * scale; - const nx = n.x; const ny = n.y; const nz = n.z; - const m = shadows.matLight; - m.m00 = 1 - nx * lx; - m.m01 = -nx * ly; - m.m02 = -nx * lz; - m.m03 = 0; - m.m04 = -ny * lx; - m.m05 = 1 - ny * ly; - m.m06 = -ny * lz; - m.m07 = 0; - m.m08 = -nz * lx; - m.m09 = -nz * ly; - m.m10 = 1 - nz * lz; - m.m11 = 0; - m.m12 = lx * d; - m.m13 = ly * d; - m.m14 = lz * d; - m.m15 = 1; - - pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET, shadows.matLight); -} - -export function updatePlanarPROJ (shadowInfo: Shadows, light: DirectionalLight, shadowUBO: Float32Array) { - const dir = light.direction; - const n = shadowInfo.normal; const d = shadowInfo.distance + 0.001; // avoid z-fighting - const NdL = Vec3.dot(n, dir); const scale = 1 / NdL; - const lx = dir.x * scale; const ly = dir.y * scale; const lz = dir.z * scale; - const nx = n.x; const ny = n.y; const nz = n.z; - const m = shadowInfo.matLight; - m.m00 = 1 - nx * lx; - m.m01 = -nx * ly; - m.m02 = -nx * lz; - m.m03 = 0; - m.m04 = -ny * lx; - m.m05 = 1 - ny * ly; - m.m06 = -ny * lz; - m.m07 = 0; - m.m08 = -nz * lx; - m.m09 = -nz * ly; - m.m10 = 1 - nz * lz; - m.m11 = 0; - m.m12 = lx * d; - m.m13 = ly * d; - m.m14 = lz * d; - m.m15 = 1; - - Mat4.toArray(shadowUBO, m, UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET); -} - -export function updatePlanarNormalAndDistance (shadowInfo: Shadows, shadowUBO: Float32Array) { - Vec3.normalize(_tempVec3, shadowInfo.normal); - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3.x; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3.y; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 2] = _tempVec3.z; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = -shadowInfo.distance; -} - export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Camera) { const sceneData = pipeline.pipelineSceneData; const validPunctualLights = sceneData.validPunctualLights; @@ -239,12 +145,6 @@ export function sceneCulling (pipeline: RenderPipeline, camera: Camera) { } } - if (mainLight) { - if (shadows.type === ShadowType.Planar) { - updateDirLight(pipeline, mainLight); - } - } - if (skybox.enabled && skybox.model && (camera.clearFlag & SKYBOX_FLAG)) { renderObjects.push(getRenderObject(skybox.model, camera)); } diff --git a/cocos/core/pipeline/shadow/csm-layers.ts b/cocos/core/pipeline/shadow/csm-layers.ts index ba0f759874..5ca571e06a 100644 --- a/cocos/core/pipeline/shadow/csm-layers.ts +++ b/cocos/core/pipeline/shadow/csm-layers.ts @@ -20,7 +20,7 @@ */ import { DirectionalLight, Camera, Shadows, CSMLevel, CSMOptimizationMode } from '../../renderer/scene'; -import { Mat4, Vec3, Vec2, Quat } from '../../math'; +import { Mat4, Vec3, Vec2, Vec4 } from '../../math'; import { Frustum, AABB } from '../../geometry'; import { IRenderObject } from '../define'; import { legacyCC } from '../../global-exports'; @@ -43,8 +43,6 @@ const _snap = new Vec3(); const _maxVec3 = new Vec3(10000000, 10000000, 10000000); const _minVec3 = new Vec3(-10000000, -10000000, -10000000); const _shadowPos = new Vec3(); -const _bias = new Vec3(); -const _scale = new Vec3(); let _maxLayerPosz = 0.0; let _maxLayerFarPlane = 0.0; @@ -218,8 +216,7 @@ export class CSMShadowLayer extends ShadowLayerVolume { protected _splitCameraNear = 0; protected _splitCameraFar = 0; - protected _matShadowAtlas: Mat4 = new Mat4(); - protected _matShadowViewProjAtlas: Mat4 = new Mat4(); + protected _csmAtlas: Vec4 = new Vec4(); constructor (level: number) { super(level); @@ -240,18 +237,11 @@ export class CSMShadowLayer extends ShadowLayerVolume { this._splitCameraFar = val; } - get matShadowAtlas () { - return this._matShadowAtlas; + get csmAtlas () { + return this._csmAtlas; } - set matShadowViewAtlas (val) { - this._matShadowAtlas = val; - } - - get matShadowViewProjAtlas () { - return this._matShadowViewProjAtlas; - } - set matShadowViewProjAtlas (val) { - this._matShadowViewProjAtlas = val; + set csmAtlas (val) { + this._csmAtlas = val; } public destroy () { @@ -262,9 +252,7 @@ export class CSMShadowLayer extends ShadowLayerVolume { const clipSpaceSignY = legacyCC.director.root.device.capabilities.clipSpaceSignY; const x = level % 2 - 0.5; const y = (0.5 - Math.floor(level / 2)) * clipSpaceSignY; - _bias.set(x, y, 0); - _scale.set(0.5, 0.5, 1); - Mat4.fromRTS(this._matShadowAtlas, Quat.IDENTITY, _bias, _scale); + this._csmAtlas.set(0.5, 0.5, x, y); } } @@ -392,8 +380,6 @@ export class CSMLayers { const far = csmLayer.splitCameraFar; csmLayer.calculateSplitFrustum(camera, _mat4Trans, near, far); csmLayer.createMatrix(dirLight, shadowMapWidth, false); - - Mat4.multiply(csmLayer.matShadowViewProjAtlas, csmLayer.matShadowAtlas, csmLayer.matShadowViewProj); } if (level === CSMLevel.LEVEL_1) { diff --git a/cocos/core/pipeline/shadow/shadow-flow.ts b/cocos/core/pipeline/shadow/shadow-flow.ts index 94e63477b4..5444843e43 100644 --- a/cocos/core/pipeline/shadow/shadow-flow.ts +++ b/cocos/core/pipeline/shadow/shadow-flow.ts @@ -24,7 +24,7 @@ */ import { ccclass } from 'cc.decorator'; -import { PIPELINE_FLOW_SHADOW, supportsR32FloatTexture } from '../define'; +import { PIPELINE_FLOW_SHADOW, supportsR32FloatTexture, UBOCamera, UBOCSM, UBOGlobal, UBOShadow } from '../define'; import { IRenderFlowInfo, RenderFlow } from '../render-flow'; import { ForwardFlowPriority } from '../enum'; import { ShadowStage } from './shadow-stage'; @@ -41,10 +41,6 @@ import { Camera } from '../../renderer/scene'; import { SpotLight } from '../../renderer/scene/spot-light'; const _validLights: Light[] = []; -// csm uniform used vectors count -const CSM_UNIFORM_VECTORS = 61; -// all global uniform used vectors count -const GLOBAL_UNIFORM_VECTORS = 64; /** * @en Shadow map render flow @@ -89,7 +85,7 @@ export class ShadowFlow extends RenderFlow { // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. pipeline.pipelineSceneData.csmSupported = pipeline.device.capabilities.maxFragmentUniformVectors - >= (CSM_UNIFORM_VECTORS + GLOBAL_UNIFORM_VECTORS); + >= (UBOGlobal.COUNT + UBOCamera.COUNT + UBOShadow.COUNT + UBOCSM.COUNT) / 4; pipeline.macros.CC_SUPPORT_CASCADED_SHADOW_MAP = pipeline.pipelineSceneData.csmSupported; pipeline.onGlobalPipelineStateChanged(); diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk index 10431d7a42..137f3e6742 100644 --- a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk @@ -42,6 +42,18 @@ float CCGetLinearDepth(vec3 worldPos) { CC_HANDLE_NDC_SAMPLE_FLIP(shadowNDCPos.xy); return true; } + + vec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias, vec3 matViewDir0, vec3 matViewDir1, vec3 matViewDir2, vec2 projScaleXY) + { + vec4 newShadowPos = shadowPos; + if (normalBias > EPSILON_LOWP) + { + vec3 viewNormal = vec3(dot(matViewDir0, worldNormal), dot(matViewDir1, worldNormal), dot(matViewDir2, worldNormal)); + if (viewNormal.z < 0.1) + newShadowPos.xy += viewNormal.xy * projScaleXY * normalBias * clamp(viewNormal.z, 0.001, 0.1); + } + return newShadowPos; + } vec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias, mat4 matLightView, vec2 projScaleXY) { @@ -215,21 +227,22 @@ float CCGetLinearDepth(vec3 worldPos) { } #if CC_SUPPORT_CASCADED_SHADOW_MAP - int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec4 matShadowViewLine0, out vec4 matShadowViewLine1, out vec4 matShadowViewLine2, out vec4 matShadowViewLine3, vec3 worldPos) { + int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec3 shadowViewDir0, out vec3 shadowViewDir1, out vec3 shadowViewDir2, vec3 worldPos) { int layer = -1; + highp float layerThreshold = cc_csmViewDir0[0].w; for (int i = 0; i < NUMCASCADES; i++) { vec4 shadowPos = cc_matCSMViewProj[i] * vec4(worldPos.xyz, 1.0); vec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5; - if (clipPos.x >= (0.0 + cc_csmInfo.y) && clipPos.x <= (1.0 - cc_csmInfo.y) && - clipPos.y >= (0.0 + cc_csmInfo.y) && clipPos.y <= (1.0 - cc_csmInfo.y) && + if (clipPos.x >= (0.0 + layerThreshold) && clipPos.x <= (1.0 - layerThreshold) && + clipPos.y >= (0.0 + layerThreshold) && clipPos.y <= (1.0 - layerThreshold) && clipPos.z >= 0.0 && clipPos.z <= 1.0 && layer < 0) { - csmPos = cc_matCSMViewProjAtlas[i] * vec4(worldPos.xyz, 1.0); + csmPos = cc_matCSMViewProj[i] * vec4(worldPos.xyz, 1.0); + csmPos.xy = csmPos.xy * cc_csmAtlas[i].xy + cc_csmAtlas[i].zw; shadowProjDepthInfo = cc_csmProjDepthInfo[i]; shadowProjInfo = cc_csmProjInfo[i]; - matShadowViewLine0 = cc_matCSMView[i][0]; - matShadowViewLine1 = cc_matCSMView[i][1]; - matShadowViewLine2 = cc_matCSMView[i][2]; - matShadowViewLine3 = cc_matCSMView[i][3]; + shadowViewDir0 = cc_csmViewDir0[i].xyz; + shadowViewDir1 = cc_csmViewDir1[i].xyz; + shadowViewDir2 = cc_csmViewDir2[i].xyz; layer = i; } } @@ -240,12 +253,12 @@ float CCGetLinearDepth(vec3 worldPos) { { vec4 csmPos = vec4(1.0); vec4 shadowProjDepthInfo, shadowProjInfo; - mat4 matLightView; - int level = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, matLightView[0], matLightView[1], matLightView[2], matLightView[3], worldPos); + vec3 shadowViewDir0, shadowViewDir1, shadowViewDir2; + int level = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, shadowViewDir0, shadowViewDir1, shadowViewDir2, worldPos); if (level < 0) { return 1.0; } float realtimeShadow = 1.0; - vec4 pos = ApplyShadowDepthBias_FaceNormal(csmPos, N, shadowBias.y, matLightView, shadowProjInfo.xy); + vec4 pos = ApplyShadowDepthBias_FaceNormal(csmPos, N, shadowBias.y, shadowViewDir0, shadowViewDir1, shadowViewDir2, shadowProjInfo.xy); pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, shadowProjDepthInfo.x, shadowProjDepthInfo.y); float pcf = cc_shadowWHPBInfo.z; @@ -261,7 +274,7 @@ float CCGetLinearDepth(vec3 worldPos) { return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); } #else - int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec4 matShadowViewLine0, out vec4 matShadowViewLine1, out vec4 matShadowViewLine2, out vec4 matShadowViewLine3, vec3 worldPos) { + int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec3 shadowViewDir0, out vec3 shadowViewDir1, out vec3 shadowViewDir2, vec3 worldPos) { return -1; } diff --git a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk index 88f5d43faf..809eb9691d 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk @@ -3,11 +3,12 @@ #pragma define NUMCASCADES 4 #pragma builtin(global) layout(set = 0, binding = 3) uniform CCCSM { - highp mat4 cc_matCSMView[NUMCASCADES]; + highp vec4 cc_csmViewDir0[NUMCASCADES]; //[0].w->layer blank threshold + highp vec4 cc_csmViewDir1[NUMCASCADES]; + highp vec4 cc_csmViewDir2[NUMCASCADES]; + highp vec4 cc_csmAtlas[NUMCASCADES]; highp mat4 cc_matCSMViewProj[NUMCASCADES]; - highp mat4 cc_matCSMViewProjAtlas[NUMCASCADES]; highp vec4 cc_csmProjDepthInfo[NUMCASCADES]; highp vec4 cc_csmProjInfo[NUMCASCADES]; highp vec4 cc_csmSplitsInfo; // x-> level_1 far, y-> level_2 far, z-> level_3 far, w-> level_4 far - highp vec4 cc_csmInfo; // y-> radius }; diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk index fb8990efe5..c26340e9e1 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk @@ -3,7 +3,6 @@ #pragma define NUMCASCADES 4 #pragma builtin(global) layout(set = 0, binding = 2) uniform CCShadow { - highp mat4 cc_matLightPlaneProj; highp mat4 cc_matLightView; highp mat4 cc_matLightViewProj; highp vec4 cc_shadowInvProjDepthInfo; // x -> cc_matLightInvProj[10]([2][2]); y -> cc_matLightInvProj[14]([2][3]); z -> cc_matLightInvProj[11]([3][2]); w -> cc_matLightInvProj[15]([3][3]); diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk index 9776b74e4b..f3f97bb6b9 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk @@ -20,8 +20,8 @@ void main() { { vec4 csmPos; vec4 shadowProjDepthInfo, shadowProjInfo; - mat4 matLightView; - int csmLayer = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, matLightView[0], matLightView[1], matLightView[2], matLightView[3], surfaceData.worldPos); + vec3 shadowViewDir0, shadowViewDir1, shadowViewDir2; + int csmLayer = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, shadowViewDir0, shadowViewDir1, shadowViewDir2, surfaceData.worldPos); bool OutOfRange = csmLayer < 0; if (OutOfRange) colDebugCSMLayer = vec3(1.0); diff --git a/native/cocos/renderer/pipeline/Define.cpp b/native/cocos/renderer/pipeline/Define.cpp index 493ace0ad0..ab7257a70a 100644 --- a/native/cocos/renderer/pipeline/Define.cpp +++ b/native/cocos/renderer/pipeline/Define.cpp @@ -147,7 +147,6 @@ const gfx::UniformBlock UBOShadow::LAYOUT = { UBOShadow::BINDING, UBOShadow::NAME, { - {"cc_matLightPlaneProj", gfx::Type::MAT4, 1}, {"cc_matLightView", gfx::Type::MAT4, 1}, {"cc_matLightViewProj", gfx::Type::MAT4, 1}, {"cc_shadowInvProjDepthInfo", gfx::Type::FLOAT4, 1}, @@ -175,13 +174,14 @@ const gfx::UniformBlock UBOCSM::LAYOUT = { UBOCSM::BINDING, UBOCSM::NAME, { - {"cc_matCSMView", gfx::Type::MAT4, UBOCSM::CSM_LEVEL_COUNT}, + {"cc_csmViewDir0", gfx::Type::FLOAT4, UBOCSM::CSM_LEVEL_COUNT}, + {"cc_csmViewDir1", gfx::Type::FLOAT4, UBOCSM::CSM_LEVEL_COUNT}, + {"cc_csmViewDir2", gfx::Type::FLOAT4, UBOCSM::CSM_LEVEL_COUNT}, + {"cc_csmAtlas", gfx::Type::FLOAT4, UBOCSM::CSM_LEVEL_COUNT}, {"cc_matCSMViewProj", gfx::Type::MAT4, UBOCSM::CSM_LEVEL_COUNT}, - {"cc_matCSMViewProjAtlas", gfx::Type::MAT4, UBOCSM::CSM_LEVEL_COUNT}, {"cc_csmProjDepthInfo", gfx::Type::FLOAT4, UBOCSM::CSM_LEVEL_COUNT}, {"cc_csmProjInfo", gfx::Type::FLOAT4, UBOCSM::CSM_LEVEL_COUNT}, {"cc_csmSplitsInfo", gfx::Type::FLOAT4, 1}, - {"cc_csmInfo", gfx::Type::FLOAT4, 1}, }, 1, }; diff --git a/native/cocos/renderer/pipeline/Define.h b/native/cocos/renderer/pipeline/Define.h index ea8e3749f0..5897f6a5c4 100644 --- a/native/cocos/renderer/pipeline/Define.h +++ b/native/cocos/renderer/pipeline/Define.h @@ -460,8 +460,7 @@ struct CC_DLL UBOCamera { }; struct CC_DLL UBOShadow { - static constexpr uint32_t MAT_LIGHT_PLANE_PROJ_OFFSET = 0; - static constexpr uint32_t MAT_LIGHT_VIEW_OFFSET = MAT_LIGHT_PLANE_PROJ_OFFSET + 16; + static constexpr uint32_t MAT_LIGHT_VIEW_OFFSET = 0; static constexpr uint32_t MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadow::MAT_LIGHT_VIEW_OFFSET + 16; static constexpr uint32_t SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = UBOShadow::MAT_LIGHT_VIEW_PROJ_OFFSET + 16; static constexpr uint32_t SHADOW_PROJ_DEPTH_INFO_OFFSET = UBOShadow::SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 4; @@ -481,14 +480,15 @@ struct CC_DLL UBOShadow { struct CC_DLL UBOCSM { static constexpr uint32_t CSM_LEVEL_COUNT = 4; - static constexpr uint32_t MAT_CSM_VIEW_LEVELS_OFFSET = 0; - static constexpr uint32_t MAT_CSM_VIEW_PROJ_LEVELS_OFFSET = UBOCSM::MAT_CSM_VIEW_LEVELS_OFFSET + 16 * UBOCSM::CSM_LEVEL_COUNT; - static constexpr uint32_t MAT_CSM_VIEW_PROJ_ATLAS_LEVELS_OFFSET = UBOCSM::MAT_CSM_VIEW_PROJ_LEVELS_OFFSET + 16 * UBOCSM::CSM_LEVEL_COUNT; - static constexpr uint32_t CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET = UBOCSM::MAT_CSM_VIEW_PROJ_ATLAS_LEVELS_OFFSET + 16 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t CSM_VIEW_DIR_0_OFFSET = 0; + static constexpr uint32_t CSM_VIEW_DIR_1_OFFSET = UBOCSM::CSM_VIEW_DIR_0_OFFSET + 4 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t CSM_VIEW_DIR_2_OFFSET = UBOCSM::CSM_VIEW_DIR_1_OFFSET + 4 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t CSM_ATLAS_OFFSET = UBOCSM::CSM_VIEW_DIR_2_OFFSET + 4 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t MAT_CSM_VIEW_PROJ_LEVELS_OFFSET = UBOCSM::CSM_ATLAS_OFFSET + 4 * UBOCSM::CSM_LEVEL_COUNT; + static constexpr uint32_t CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET = UBOCSM::MAT_CSM_VIEW_PROJ_LEVELS_OFFSET + 16 * UBOCSM::CSM_LEVEL_COUNT; static constexpr uint32_t CSM_PROJ_INFO_LEVELS_OFFSET = UBOCSM::CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET + 4 * UBOCSM::CSM_LEVEL_COUNT; static constexpr uint32_t CSM_SPLITS_INFO_OFFSET = UBOCSM::CSM_PROJ_INFO_LEVELS_OFFSET + 4 * UBOCSM::CSM_LEVEL_COUNT; - static constexpr uint32_t CSM_INFO_OFFSET = UBOCSM::CSM_SPLITS_INFO_OFFSET + 4; - static constexpr uint32_t COUNT = UBOCSM::CSM_INFO_OFFSET + 4; + static constexpr uint32_t COUNT = UBOCSM::CSM_SPLITS_INFO_OFFSET + 4; static constexpr uint32_t SIZE = UBOCSM::COUNT * 4; static constexpr uint32_t BINDING = static_cast(PipelineGlobalBindings::UBO_CSM); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; diff --git a/native/cocos/renderer/pipeline/PipelineUBO.cpp b/native/cocos/renderer/pipeline/PipelineUBO.cpp index 28e0caec78..2d66e711d5 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.cpp +++ b/native/cocos/renderer/pipeline/PipelineUBO.cpp @@ -233,18 +233,29 @@ void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, ccstd::arr const float shadowLPNNInfos[4] = {0.0F, packing, mainLight->getShadowNormalBias(), 0.0F}; memcpy(sv.data() + UBOShadow::SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET, &shadowLPNNInfos, sizeof(shadowLPNNInfos)); } else { + const auto layerThreshold = PipelineUBO::getPCFRadius(shadowInfo, mainLight); for (uint32_t i = 0; i < static_cast(mainLight->getCSMLevel()); ++i) { + const Mat4 &matShadowView = csmLayers->getLayers()[i]->getMatShadowView(); + const float csmViewDir0[4] = {matShadowView.m[0], matShadowView.m[4], matShadowView.m[8], layerThreshold}; + memcpy(cv.data() + UBOCSM::CSM_VIEW_DIR_0_OFFSET + i * 4, &csmViewDir0, sizeof(csmViewDir0)); + + const float csmViewDir1[4] = {matShadowView.m[1], matShadowView.m[5], matShadowView.m[9], 0.0F}; + memcpy(cv.data() + UBOCSM::CSM_VIEW_DIR_1_OFFSET + i * 4, &csmViewDir1, sizeof(csmViewDir1)); + + const float csmViewDir2[4] = {matShadowView.m[2], matShadowView.m[6], matShadowView.m[10], 0.0F}; + memcpy(cv.data() + UBOCSM::CSM_VIEW_DIR_2_OFFSET + i * 4, &csmViewDir2, sizeof(csmViewDir2)); + + const auto &csmAtlas = csmLayers->getLayers()[i]->getCSMAtlas(); + const float csmAtlasOffsets[4] = {csmAtlas.x, csmAtlas.y, csmAtlas.z, csmAtlas.w}; + memcpy(cv.data() + UBOCSM::CSM_ATLAS_OFFSET + i * 4, &csmAtlasOffsets, sizeof(csmAtlasOffsets)); + + cv[UBOCSM::CSM_SPLITS_INFO_OFFSET + i] = csmLayers->getLayers()[i]->getSplitCameraFar() / mainLight->getShadowDistance(); - const Mat4 &matShadowView = csmLayers->getLayers()[i]->getMatShadowView(); - memcpy(cv.data() + UBOCSM::MAT_CSM_VIEW_LEVELS_OFFSET + i * 16, matShadowView.m, sizeof(matShadowView)); const Mat4 &matShadowViewProj = csmLayers->getLayers()[i]->getMatShadowViewProj(); memcpy(cv.data() + UBOCSM::MAT_CSM_VIEW_PROJ_LEVELS_OFFSET + i * 16, matShadowViewProj.m, sizeof(matShadowViewProj)); - const Mat4 &matShadowViewProjAtlas = csmLayers->getLayers()[i]->getMatShadowViewProjAtlas(); - memcpy(cv.data() + UBOCSM::MAT_CSM_VIEW_PROJ_ATLAS_LEVELS_OFFSET + i * 16, matShadowViewProjAtlas.m, sizeof(matShadowViewProjAtlas)); - const Mat4 &matShadowProj = csmLayers->getLayers()[i]->getMatShadowProj(); const float shadowProjDepthInfos[4] = {matShadowProj.m[10], matShadowProj.m[14], matShadowProj.m[11], matShadowProj.m[15]}; memcpy(cv.data() + UBOCSM::CSM_PROJ_DEPTH_INFO_LEVELS_OFFSET + i * 4, &shadowProjDepthInfos, sizeof(shadowProjDepthInfos)); @@ -253,11 +264,6 @@ void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, ccstd::arr memcpy(cv.data() + UBOCSM::CSM_PROJ_INFO_LEVELS_OFFSET + i * 4, &shadowProjInfos, sizeof(shadowProjInfos)); } - cv[UBOCSM::CSM_INFO_OFFSET + 0] = 0.0F; - cv[UBOCSM::CSM_INFO_OFFSET + 1] = getPCFRadius(shadowInfo, mainLight); - cv[UBOCSM::CSM_INFO_OFFSET + 2] = 0.0F; - cv[UBOCSM::CSM_INFO_OFFSET + 3] = 0.0F; - const float shadowNFLSInfos[4] = {0.0F, 0.0F, 0.0F, 1.0F - mainLight->getShadowSaturation()}; memcpy(sv.data() + UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET, &shadowNFLSInfos, sizeof(shadowNFLSInfos)); @@ -268,8 +274,7 @@ void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, ccstd::arr memcpy(sv.data() + UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET, &shadowWHPBInfos, sizeof(shadowWHPBInfos)); } } else if (mainLight && shadowInfo->getType() == scene::ShadowType::PLANAR) { - updateDirLight(shadowInfo, mainLight, shadowBufferView); - updatePlanarNormalAndDistance(shadowInfo, shadowBufferView); + PipelineUBO::updatePlanarNormalAndDistance(shadowInfo, shadowBufferView); } memcpy(sv.data() + UBOShadow::SHADOW_COLOR_OFFSET, shadowInfo->getShadowColor4f().data(), sizeof(float) * 4); @@ -281,7 +286,7 @@ void PipelineUBO::updateShadowUBOLightView(const RenderPipeline *pipeline, ccstd const auto *sceneData = pipeline->getPipelineSceneData(); const CSMLayers *csmLayers = sceneData->getCSMLayers(); const auto *shadowInfo = sceneData->getShadows(); - auto *device = gfx::Device::getInstance(); + const auto *device = gfx::Device::getInstance(); auto &shadowUBO = *shadowBufferView; const bool hFTexture = supportsR32FloatTexture(device); const float packing = hFTexture ? 0.0F : 1.0F; @@ -394,6 +399,12 @@ float PipelineUBO::getPCFRadius(const scene::Shadows *shadowInfo, const scene::D return 0.0F; // PCFType.HARD } +void PipelineUBO::updatePlanarNormalAndDistance(const scene::Shadows *shadowInfo, ccstd::array *shadowUBO) { + const Vec3 normal = shadowInfo->getNormal().getNormalized(); + const float planarNDInfo[4] = {normal.x, normal.y, normal.z, -shadowInfo->getDistance()}; + memcpy(shadowUBO->data() + UBOShadow::PLANAR_NORMAL_DISTANCE_INFO_OFFSET, &planarNDInfo, sizeof(planarNDInfo)); +} + void PipelineUBO::initCombineSignY() const { const float screenSpaceSignY = _device->getCapabilities().screenSpaceSignY * 0.5F + 0.5F; const float clipSpaceSignY = _device->getCapabilities().clipSpaceSignY * 0.5F + 0.5F; diff --git a/native/cocos/renderer/pipeline/PipelineUBO.h b/native/cocos/renderer/pipeline/PipelineUBO.h index 87227e581f..62106b8294 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.h +++ b/native/cocos/renderer/pipeline/PipelineUBO.h @@ -46,6 +46,7 @@ public: static void updateShadowUBOLightView(const RenderPipeline *pipeline, ccstd::array *shadowBufferView, const scene::Light *light, uint32_t level); static uint8_t getCombineSignY(); + static void updatePlanarNormalAndDistance(const ::cc::scene::Shadows *shadowInfo, ccstd::array *shadowUBO); PipelineUBO() = default; ~PipelineUBO() = default; diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp index fd4615390f..a161e261fa 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp @@ -33,7 +33,6 @@ #include "RenderAdditiveLightQueue.h" #include "RenderBatchedQueue.h" #include "RenderInstancedQueue.h" -#include "SceneCulling.h" #include "base/Utils.h" #include "forward/ForwardPipeline.h" #include "gfx-base/GFXDevice.h" @@ -348,8 +347,7 @@ void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *cam case scene::LightType::SPHERE: { // update planar PROJ if (mainLight) { - updateDirLight(shadowInfo, mainLight, &_shadowUBO); - updatePlanarNormalAndDistance(shadowInfo, &_shadowUBO); + PipelineUBO::updatePlanarNormalAndDistance(shadowInfo, &_shadowUBO); } // Reserve sphere light shadow interface @@ -364,8 +362,7 @@ void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *cam const auto *spotLight = static_cast(light); // update planar PROJ if (mainLight) { - updateDirLight(shadowInfo, mainLight, &_shadowUBO); - updatePlanarNormalAndDistance(shadowInfo, &_shadowUBO); + PipelineUBO::updatePlanarNormalAndDistance(shadowInfo, &_shadowUBO); } const auto &matShadowCamera = light->getNode()->getWorldMatrix(); diff --git a/native/cocos/renderer/pipeline/SceneCulling.cpp b/native/cocos/renderer/pipeline/SceneCulling.cpp index c4a370b0f0..0a90ddc404 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.cpp +++ b/native/cocos/renderer/pipeline/SceneCulling.cpp @@ -61,99 +61,6 @@ RenderObject genRenderObject(const scene::Model *model, const scene::Camera *cam return {depth, model}; } -void getShadowWorldMatrix(const geometry::Sphere *sphere, const cc::Quaternion &rotation, const cc::Vec3 &dir, cc::Mat4 *shadowWorldMat, cc::Vec3 *out) { - cc::Vec3 translation(dir); - translation.negate(); - const auto distance = sphere->getRadius() * COEFFICIENT_OF_EXPANSION; - translation.scale(distance); - translation.add(sphere->getCenter()); - out->set(translation); - - Mat4::fromRT(rotation, translation, shadowWorldMat); -} - -void updateSphereLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd::array *shadowUBO) { - const auto *node = light->getNode(); - if (!node->getChangedFlags() && !shadowInfo->isShadowMapDirty()) { - return; - } - - shadowInfo->setShadowMapDirty(false); - const auto &position = node->getWorldPosition(); - const auto &normal = shadowInfo->getNormal(); - const auto distance = shadowInfo->getDistance() + 0.001F; // avoid z-fighting - const auto ndL = normal.dot(position); - const auto lx = position.x; - const auto ly = position.y; - const auto lz = position.z; - const auto nx = normal.x; - const auto ny = normal.y; - const auto nz = normal.z; - auto &matLight = shadowInfo->getMatLight(); - matLight.m[0] = ndL - distance - lx * nx; - matLight.m[1] = -ly * nx; - matLight.m[2] = -lz * nx; - matLight.m[3] = -nx; - matLight.m[4] = -lx * ny; - matLight.m[5] = ndL - distance - ly * ny; - matLight.m[6] = -lz * ny; - matLight.m[7] = -ny; - matLight.m[8] = -lx * nz; - matLight.m[9] = -ly * nz; - matLight.m[10] = ndL - distance - lz * nz; - matLight.m[11] = -nz; - matLight.m[12] = lx * distance; - matLight.m[13] = ly * distance; - matLight.m[14] = lz * distance; - matLight.m[15] = ndL; - - memcpy(shadowUBO->data() + UBOShadow::MAT_LIGHT_PLANE_PROJ_OFFSET, matLight.m, sizeof(matLight)); -} - -void updateDirLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd::array *shadowUBO) { - const auto *node = light->getNode(); - const auto &rotation = node->getWorldRotation(); - const Quaternion qt(rotation.x, rotation.y, rotation.z, rotation.w); - cc::Vec3 forward(0.0F, 0.0F, -1.0F); - forward.transformQuat(qt); - const auto &normal = shadowInfo->getNormal(); - const auto distance = shadowInfo->getDistance() + 0.001F; // avoid z-fighting - const auto ndL = normal.dot(forward); - const auto scale = 1.0F / ndL; - const auto lx = forward.x * scale; - const auto ly = forward.y * scale; - const auto lz = forward.z * scale; - const auto nx = normal.x; - const auto ny = normal.y; - const auto nz = normal.z; - auto &matLight = shadowInfo->getMatLight(); - matLight.m[0] = 1 - nx * lx; - matLight.m[1] = -nx * ly; - matLight.m[2] = -nx * lz; - matLight.m[3] = 0; - matLight.m[4] = -ny * lx; - matLight.m[5] = 1 - ny * ly; - matLight.m[6] = -ny * lz; - matLight.m[7] = 0; - matLight.m[8] = -nz * lx; - matLight.m[9] = -nz * ly; - matLight.m[10] = 1 - nz * lz; - matLight.m[11] = 0; - matLight.m[12] = lx * distance; - matLight.m[13] = ly * distance; - matLight.m[14] = lz * distance; - matLight.m[15] = 1; - - memcpy(shadowUBO->data() + UBOShadow::MAT_LIGHT_PLANE_PROJ_OFFSET, matLight.m, sizeof(matLight)); - memcpy(shadowUBO->data() + UBOShadow::SHADOW_COLOR_OFFSET, shadowInfo->getShadowColor4f().data(), sizeof(float) * 4); -} - -void updatePlanarNormalAndDistance(const scene::Shadows* shadowInfo, ccstd::array* shadowUBO) { - const Vec3 normal = shadowInfo->getNormal().getNormalized(); - const float planarNDInfo[4] = {normal.x, normal.y, normal.z, -shadowInfo->getDistance()}; - memcpy(shadowUBO->data() + UBOShadow::PLANAR_NORMAL_DISTANCE_INFO_OFFSET, &planarNDInfo, sizeof(planarNDInfo)); -} - void validPunctualLightsCulling(const RenderPipeline* pipeline, const scene::Camera* camera) { const auto *const scene = camera->getScene(); PipelineSceneData *sceneData = pipeline->getPipelineSceneData(); @@ -186,18 +93,6 @@ void validPunctualLightsCulling(const RenderPipeline* pipeline, const scene::Cam } } -void updateDirFrustum(const geometry::Sphere *cameraBoundingSphere, const Quaternion &rotation, float range, geometry::Frustum *dirLightFrustum) { - const float radius = cameraBoundingSphere->getRadius(); - const cc::Vec3 &position = cameraBoundingSphere->getCenter(); - Mat4 matWorldTrans; - Mat4::fromRT(rotation, position, &matWorldTrans); - matWorldTrans.m[8] *= -1.0F; - matWorldTrans.m[9] *= -1.0F; - matWorldTrans.m[10] *= -1.0F; - - dirLightFrustum->createOrtho(radius, radius, -range, radius, matWorldTrans); -} - // Todo If you want to optimize the cutting efficiency, you can get it from the octree void shadowCulling(const RenderPipeline* pipeline, const scene::Camera* camera, ShadowTransformInfo* layer) { const auto *sceneData = pipeline->getPipelineSceneData(); diff --git a/native/cocos/renderer/pipeline/SceneCulling.h b/native/cocos/renderer/pipeline/SceneCulling.h index 8ca2148502..aa266e868f 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.h +++ b/native/cocos/renderer/pipeline/SceneCulling.h @@ -49,10 +49,5 @@ RenderObject genRenderObject(const scene::Model *, const scene::Camera *); void validPunctualLightsCulling(const RenderPipeline* pipeline, const scene::Camera* camera); void shadowCulling(const RenderPipeline*, const scene::Camera*, ShadowTransformInfo*); void sceneCulling(const RenderPipeline*, scene::Camera*); -void updateSphereLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd::array *); -void updateDirLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd::array *); -void updatePlanarNormalAndDistance(const ::cc::scene::Shadows* shadowInfo, ccstd::array* shadowUBO); -void getShadowWorldMatrix(const geometry::Sphere *sphere, const cc::Quaternion &rotation, const cc::Vec3 &dir, cc::Mat4 *shadowWorldMat, cc::Vec3 *out); -void updateDirFrustum(const geometry::Sphere *cameraBoundingSphere, const Quaternion &rotation, float range, geometry::Frustum *dirLightFrustum); } // namespace pipeline } // namespace cc diff --git a/native/cocos/renderer/pipeline/shadow/CSMLayers.cpp b/native/cocos/renderer/pipeline/shadow/CSMLayers.cpp index 38ea84b649..c2472f5f2f 100644 --- a/native/cocos/renderer/pipeline/shadow/CSMLayers.cpp +++ b/native/cocos/renderer/pipeline/shadow/CSMLayers.cpp @@ -22,7 +22,6 @@ #include "CSMLayers.h" #include "core/Root.h" #include "gfx-base/GFXDevice.h" -#include "math/Quaternion.h" #include "pipeline/PipelineSceneData.h" #include "pipeline/RenderPipeline.h" #include "pipeline/custom/RenderInterfaceTypes.h" @@ -135,8 +134,6 @@ void ShadowTransformInfo::calculateSplitFrustum(float start, float end, float as } CSMLayerInfo::CSMLayerInfo(uint32_t level) : ShadowTransformInfo(level) { - _matShadowAtlas.setZero(); - _matShadowViewProjAtlas.setZero(); calculateAtlas(level); } @@ -145,9 +142,7 @@ void CSMLayerInfo::calculateAtlas(uint32_t level) { const float clipSpaceSignY = device->getCapabilities().clipSpaceSignY; const float x = floorf(static_cast(level % 2U)) - 0.5F; const float y = clipSpaceSignY * (0.5F - floorf(static_cast(level) / 2U)); - const Vec3 bias(x, y, 0.0F); - const Vec3 scale(0.5F, 0.5F, 1.0F); - Mat4::fromRTS(Quaternion::identity(), bias, scale, &_matShadowAtlas); + _csmAtlas.set(0.5F, 0.5F, x, y); } CSMLayers::CSMLayers() { @@ -266,9 +261,6 @@ void CSMLayers::calculateCSM(const scene::Camera *camera, const scene::Direction const float farClamp = layer->getSplitCameraFar(); layer->calculateSplitFrustum(nearClamp, farClamp, camera->getAspect(), camera->getFov(), mat4Trans); layer->createMatrix(layer->getSplitFrustum(), dirLight, shadowMapWidth, false); - Mat4 matShadowViewProjAtlas; - Mat4::multiply(layer->getMatShadowAtlas(), layer->getMatShadowViewProj(), &matShadowViewProjAtlas); - layer->setMatShadowViewProjAtlas(matShadowViewProjAtlas); } if (level == scene::CSMLevel::LEVEL_1) { diff --git a/native/cocos/renderer/pipeline/shadow/CSMLayers.h b/native/cocos/renderer/pipeline/shadow/CSMLayers.h index 2d334ddaf2..27687cb0a5 100644 --- a/native/cocos/renderer/pipeline/shadow/CSMLayers.h +++ b/native/cocos/renderer/pipeline/shadow/CSMLayers.h @@ -107,11 +107,7 @@ public: inline float getSplitCameraFar() const { return _splitCameraFar; } inline void setSplitCameraFar(float splitCameraFar) { _splitCameraFar = splitCameraFar; } - inline const Mat4 &getMatShadowAtlas() const { return _matShadowAtlas; } - inline void setMatShadowAtlas(const Mat4 &matShadowAtlas) { _matShadowAtlas = matShadowAtlas; } - - inline const Mat4 &getMatShadowViewProjAtlas() const { return _matShadowViewProjAtlas; } - inline void setMatShadowViewProjAtlas(const Mat4 &matShadowViewProjAtlas) { _matShadowViewProjAtlas = matShadowViewProjAtlas; } + inline const Vec4 &getCSMAtlas() const { return _csmAtlas; } private: void calculateAtlas(uint32_t level); @@ -119,8 +115,7 @@ private: float _splitCameraNear{0.0F}; float _splitCameraFar{0.0F}; - Mat4 _matShadowAtlas; - Mat4 _matShadowViewProjAtlas; + Vec4 _csmAtlas; }; class CSMLayers { diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index f9903e42f4..4a9f72d723 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -79,7 +79,7 @@ void ShadowFlow::activate(RenderPipeline *pipeline) { // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. const auto csmSupported = pipeline->getDevice()->getCapabilities().maxFragmentUniformVectors >= - CSM_UNIFORM_VECTORS + GLOBAL_UNIFORM_VECTORS; + (UBOGlobal::COUNT + UBOCamera::COUNT + UBOShadow::COUNT + UBOCSM::COUNT) >> 2; pipeline->getPipelineSceneData()->setCSMSupported(csmSupported); pipeline->setValue("CC_SUPPORT_CASCADED_SHADOW_MAP", csmSupported); diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.h b/native/cocos/renderer/pipeline/shadow/ShadowFlow.h index 373f279c60..e46663054c 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.h +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.h @@ -59,10 +59,6 @@ private: void initShadowFrameBuffer(const RenderPipeline* pipeline, const scene::Light* light); static RenderFlowInfo initInfo; - // csm uniform used vectors count. - static const uint32_t CSM_UNIFORM_VECTORS = 61U; - // all global uniform used vectors count. - static const uint32_t GLOBAL_UNIFORM_VECTORS = 64U; // weak reference gfx::RenderPass *_renderPass{nullptr}; From acbb536c489130089b4eb3e80153160663f7eab9 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 21 Jul 2022 17:58:15 +0800 Subject: [PATCH 065/111] Protect corrupted node and component in editor (#12120) * Protect corrupted node and component in editor * Improvement * Unify Node._registerIfAttached * Fix ci --- cocos/core/scene-graph/base-node-dev.ts | 46 +++++++++++++++---------- cocos/core/scene-graph/base-node.ts | 31 +++-------------- cocos/core/scene-graph/scene.ts | 1 + 3 files changed, 33 insertions(+), 45 deletions(-) diff --git a/cocos/core/scene-graph/base-node-dev.ts b/cocos/core/scene-graph/base-node-dev.ts index 0377b84386..4de4000e25 100644 --- a/cocos/core/scene-graph/base-node-dev.ts +++ b/cocos/core/scene-graph/base-node-dev.ts @@ -149,30 +149,40 @@ export function baseNodePolyfill (BaseNode) { if (EDITOR || TEST) { BaseNode.prototype._registerIfAttached = function (register) { - const attachedObjsForEditor = legacyCC.engine.attachedObjsForEditor; - if (register) { - attachedObjsForEditor[this._id] = this; - for (let i = this._components.length - 1; i >= 0; i--) { - const comp = this._components[i]; - if (!comp) { - this._components.splice(i, 1); - console.error(`component attached to node:${this.name} is invalid for some reason`); - continue; + if (!this._id) { + console.warn(`Node(${this && this.name}}) is invalid or its data is corrupted.`); + return; + } + if (EditorExtends.Node && EditorExtends.Component) { + if (register) { + EditorExtends.Node.add(this._id, this); + + for (let i = 0; i < this._components.length; i++) { + const comp = this._components[i]; + if (!comp || !comp._id) { + console.warn(`Component attached to node:${this.name} is corrupted`); + } else { + EditorExtends.Component.add(comp._id, comp); + } } - attachedObjsForEditor[comp._id] = comp; - } - legacyCC.engine.emit('node-attach-to-scene', this); - } else { - legacyCC.engine.emit('node-detach-from-scene', this); - delete attachedObjsForEditor[this._id]; - for (const comp of this._components) { - delete attachedObjsForEditor[comp._id]; + } else { + for (let i = 0; i < this._components.length; i++) { + const comp = this._components[i]; + if (!comp || !comp._id) { + console.warn(`Component attached to node:${this.name} is corrupted`); + } else { + EditorExtends.Component.remove(comp._id); + } + } + + EditorExtends.Node.remove(this._id); } } + const children = this._children; for (let i = 0, len = children.length; i < len; ++i) { const child = children[i]; - child._registerIfAttached(register); + child._registerIfAttached!(register); } }; } diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index 2627deaf18..c831d7c419 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -29,7 +29,7 @@ import { Component } from '../components/component'; import { property } from '../data/decorators/property'; import { CCObject } from '../data/object'; import { Event } from '../../input/types'; -import { errorID, warnID, error, log, getError } from '../platform/debug'; +import { errorID, warnID, error, warn, log, getError } from '../platform/debug'; import { ISchedulable } from '../scheduler'; import IdGenerator from '../utils/id-generator'; import * as js from '../utils/js'; @@ -361,32 +361,6 @@ export class BaseNode extends CCObject implements ISchedulable { } } - protected _registerIfAttached = !EDITOR ? undefined : function _registerIfAttached (this: BaseNode, register) { - if (EditorExtends.Node && EditorExtends.Component) { - if (register) { - EditorExtends.Node.add(this._id, this); - - for (let i = 0; i < this._components.length; i++) { - const comp = this._components[i]; - EditorExtends.Component.add(comp._id, comp); - } - } else { - for (let i = 0; i < this._components.length; i++) { - const comp = this._components[i]; - EditorExtends.Component.remove(comp._id); - } - - EditorExtends.Node.remove(this._id); - } - } - - const children = this._children; - for (let i = 0, len = children.length; i < len; ++i) { - const child = children[i]; - child._registerIfAttached!(register); - } - }; - constructor (name?: string) { super(name); this._name = name !== undefined ? name : 'New Node'; @@ -1345,9 +1319,11 @@ export class BaseNode extends CCObject implements ISchedulable { const inCurrentSceneNow = newParent && newParent.isChildOf(scene); if (!inCurrentSceneBefore && inCurrentSceneNow) { // attached + // @ts-expect-error Polyfilled functions in base-node-dev.ts this._registerIfAttached!(true); } else if (inCurrentSceneBefore && !inCurrentSceneNow) { // detached + // @ts-expect-error Polyfilled functions in base-node-dev.ts this._registerIfAttached!(false); } @@ -1369,6 +1345,7 @@ export class BaseNode extends CCObject implements ISchedulable { const parent = this._parent; const destroyByParent: boolean = (!!parent) && ((parent._objFlags & Destroying) !== 0); if (!destroyByParent && EDITOR) { + // @ts-expect-error Polyfilled functions in base-node-dev.ts this._registerIfAttached!(false); } diff --git a/cocos/core/scene-graph/scene.ts b/cocos/core/scene-graph/scene.ts index 65be90ba01..9f0466292a 100644 --- a/cocos/core/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -331,6 +331,7 @@ export class Scene extends BaseNode { active = (active !== false); if (EDITOR) { // register all nodes to editor + // @ts-expect-error Polyfilled functions in base-node-dev.ts this._registerIfAttached!(active); } legacyCC.director._nodeActivator.activateNode(this, active); From d09963b497ac7813771f73a0161eb53c83033aa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=90=89=E6=9E=97?= <798080536@qq.com> Date: Thu, 21 Jul 2022 18:26:22 +0800 Subject: [PATCH 066/111] crop debug renderer & geometry renderer & occlusion query by default (#12132) * crop debug renderer & geometry renderer & occlusion query by default --- editor/engine-features/render-config.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index 2c102f4374..47c1977ee6 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -129,7 +129,7 @@ "wechatPlugin": true }, "occlusion-query": { - "default": ["occlusion-query"], + "default": [], "label": "i18n:ENGINE.features.occlusion_query.label", "description": "i18n:ENGINE.features.occlusion_query.description", "native": "USE_OCCLUSION_QUERY", @@ -137,7 +137,7 @@ "category": "3d" }, "geometry-renderer": { - "default": ["geometry-renderer"], + "default": [], "label": "i18n:ENGINE.features.geometry_renderer.label", "description": "i18n:ENGINE.features.geometry_renderer.description", "native": "USE_GEOMETRY_RENDERER", @@ -145,7 +145,7 @@ "category": "3d" }, "debug-renderer": { - "default": ["debug-renderer"], + "default": [], "label": "i18n:ENGINE.features.debug_renderer.label", "description": "i18n:ENGINE.features.debug_renderer.description", "native": "USE_DEBUG_RENDERER", From fc4f02432744696ee2d18c2e32692c41f2feb627 Mon Sep 17 00:00:00 2001 From: timlyeee <43355299+timlyeee@users.noreply.github.com> Date: Thu, 21 Jul 2022 18:31:30 +0800 Subject: [PATCH 067/111] update documentations of reflection, bridge and jsbBridgeWrapper (#12097) --- @types/jsb.d.ts | 51 ------- cocos/native-binding/impl.ts | 126 +++++++++++++++++ cocos/native-binding/index.ts | 131 +++++++++++++++++- platforms/native/engine/index.js | 3 - platforms/native/engine/jsb-bridge-wrapper.js | 88 ------------ platforms/native/engine/jsb-bridge.js | 43 ------ platforms/native/engine/jsb-reflection.js | 45 ------ 7 files changed, 255 insertions(+), 232 deletions(-) delete mode 100644 platforms/native/engine/jsb-bridge-wrapper.js delete mode 100644 platforms/native/engine/jsb-bridge.js delete mode 100644 platforms/native/engine/jsb-reflection.js diff --git a/@types/jsb.d.ts b/@types/jsb.d.ts index 588f5e757c..f8c0a5a4f5 100644 --- a/@types/jsb.d.ts +++ b/@types/jsb.d.ts @@ -148,57 +148,6 @@ declare namespace jsb { export function getOriginalPCMBuffer (url: string, channelID: number): ArrayBuffer | undefined; } - export namespace reflection{ - /** - * https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html - * call OBJC/Java static methods - * - * @param className - * @param methodName - * @param methodSignature - * @param parameters - */ - export function callStaticMethod (className: string, methodName: string, methodSignature: string, ...parameters:any): any; - } - export namespace bridge{ - /** - * send to native with at least one argument. - */ - export function sendToNative(arg0: string, arg1?: string): void; - /** - * save your own callback controller with a js function, - * use jsb.bridge.onNative = (arg0: String, arg1: String)=>{...} - * @param args : received from native - */ - export function onNative(arg0: string, arg1?: string|null): void; - } - /** - * Listener for jsbBridgeWrapper's event. - * It takes one argument as string which is transferred by jsbBridge. - */ - export type OnNativeEventListener = (arg: string) => void; - export namespace jsbBridgeWrapper { - /** If there's no event registered, the wrapper will create one */ - export function addNativeEventListener(eventName: string, listener: OnNativeEventListener); - /** - * Dispatch the event registered on Objective-C, Java etc. - * No return value in JS to tell you if it works. - */ - export function dispatchEventToNative(eventName: string, arg?: string); - /** - * Remove all listeners relative. - */ - export function removeAllListenersForEvent(eventName: string); - /** - * Remove the listener specified - */ - export function removeNativeEventListener(eventName: string, listener: OnNativeEventListener); - /** - * Remove all events, use it carefully! - */ - export function removeAllListeners(); - } - export interface ManifestAsset { md5: string; path: string; diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index 8f143d55bc..b2ac5a301c 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -1,4 +1,130 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://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 { sys } from "../core/platform/sys"; +import { NATIVE } from 'internal:constants'; const globalJsb = globalThis.jsb ?? {}; +if( NATIVE ){ + Object.defineProperty(globalJsb, 'reflection', { + get () { + if (globalJsb.__bridge !== undefined) return globalJsb.__bridge; + if (globalThis.JavascriptJavaBridge && (sys.os === sys.OS.ANDROID || sys.os === sys.OS.OHOS)) { + globalJsb.__bridge = new globalThis.JavascriptJavaBridge(); + } else if (globalThis.JavaScriptObjCBridge && (sys.os === sys.OS.IOS || sys.os === sys.OS.OSX)) { + globalJsb.__bridge = new globalThis.JavaScriptObjCBridge(); + } else { + globalJsb.__bridge = null; + } + return globalJsb.__bridge; + }, + enumerable: true, + configurable: true, + set (value) { + globalJsb.__bridge = value; + }, + }); + Object.defineProperty(globalJsb, 'bridge', { + get () { + if (globalJsb.__ccbridge !== undefined) return globalJsb.__ccbridge; + if (window.ScriptNativeBridge && sys.os === sys.OS.ANDROID || sys.os === sys.OS.IOS || sys.os === sys.OS.OSX || sys.os === sys.OS.OHOS) { + globalJsb.__ccbridge = new ScriptNativeBridge(); + } else { + globalJsb.__ccbridge = null; + } + return globalJsb.__ccbridge; + }, + enumerable: true, + configurable: true, + set (value) { + globalJsb.__ccbridge = value; + }, + }); + const JsbBridgeWrapper = { + eventMap: new Map(), + addNativeEventListener (eventName, listener) { + if (!this.eventMap.get(eventName)) { + this.eventMap.set(eventName, []); + } + const arr = this.eventMap.get(eventName); + if (!arr.find(listener)) { + arr.push(listener); + } + }, + dispatchEventToNative (eventName, arg) { + globalJsb.bridge.sendToNative(eventName, arg); + }, + removeAllListenersForEvent (eventName) { + return this.eventMap.delete(eventName); + }, + removeNativeEventListener (eventName, listener) { + const arr = this.eventMap.get(eventName); + if (!arr) { + return false; + } + for (let i = 0, l = arr.length; i < l; i++) { + if (arr[i] === listener) { + arr.splice(i, 1); + return true; + } + } + return true; + }, + removeAllListeners () { + this.eventMap.clear(); + }, + triggerEvent (eventName, arg) { + const arr = this.eventMap.get(eventName); + if (!arr) { + console.error(`${eventName} does not exist`); + return; + } + arr.map((listener) => listener.call(null, arg)); + }, + }; + + Object.defineProperty(globalJsb, 'jsbBridgeWrapper', { + get () { + if (globalJsb.__JsbBridgeWrapper !== undefined) return globalJsb.__JsbBridgeWrapper; + + if (window.ScriptNativeBridge && sys.os === sys.OS.ANDROID || sys.os === sys.OS.IOS || sys.os === sys.OS.OSX || sys.os === sys.OS.OHOS) { + globalJsb.__JsbBridgeWrapper = JsbBridgeWrapper; + globalJsb.bridge.onNative = (methodName, arg1) => { + console.log(`Trigger event: ${methodName} with argeter: ${arg1}`); + globalJsb.__JsbBridgeWrapper.triggerEvent(methodName, arg1); + }; + } else { + globalJsb.__JsbBridgeWrapper = null; + } + return globalJsb.__JsbBridgeWrapper; + }, + enumerable: true, + configurable: true, + set (value) { + globalJsb.__JsbBridgeWrapper = value; + }, + }); +} export const native = { DownloaderHints: globalJsb.DownloaderHints, diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index b9f5c76f43..5a19c2764e 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -853,7 +853,7 @@ export declare namespace native { * @en DebugRenderer class used to output debug text on screen * @zh 用于输出屏幕调试文字的调试渲染器类 */ - export class DebugRenderer { + export class DebugRenderer { /** * @en get DebugRenderer instance * @zh 获取调试渲染器实例 @@ -869,5 +869,132 @@ export declare namespace native { * @param info @en the output text information @zh 输出的文本属性 */ addText(text:string, screenPos: Vec2, info?: DebugTextInfo): void; - } + } + + export namespace reflection { + /** + * https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html + * @en call Objective-C/Java static methods + * @zh 调用 Objective-C/Java 静态方法 + * + * @param className : @en the class name of the Objective-C/Java class @zh Objective-C/Java 类的类名 + * @param methodName : @en the method name of the Objective-C/Java class @zh Objective-C/Java 类的方法名 + * @param methodSignature : @en the method signature of the Objective-C/Java class @zh Objective-C/Java 方法签名 + * @param parameters : @en the parameters of the Objective-C/Java class to translate @zh 传递至该 Objective-C/Java 方法的参数 + */ + export function callStaticMethod (methodName: string, methodSignature: string, ...parameters:any): any; + } + + /** + * @en + * The API to listen and dispatch events on Objc/JAVA without reflection, + * Function onNative can only be overriden once by time. + * https://docs.cocos.com/creator/manual/en/advanced-topics/js-java-bridge.html + * Sample: + * ``` + * native.bridge.onNative = (event, data) => { + * if (event === 'send_message') { + * console.log(data); + * } + * } + * ``` + * ``` + * // Java codes + * JsbBridge.sendToScript('send_message', 'hello world'); + * ``` + * @zh + * 不使用反射机制来调用和监听Objc/JAVA事件的接口, + * 同一时间只能重载一个onNative函数 + * https://docs.cocos.com/creator/manual/zh/advanced-topics/js-java-bridge.html + * 示例: + * ``` + * native.bridge.onNative = (event, data) => { + * if (event === 'send_message') { + * console.log(data); + * } + * } + * ``` + * ```java + * JsbBridge.sendToScript('send_message', 'hello world'); + * ``` + */ + export namespace bridge { + /** + * @en send to native with maxmimum of 2 parameters + * @zh 向原生发送消息,可接受1到2个参数。 + * @param arg0 : @en the first parameter @zh 第一个参数 + * @param arg1 : @en the second parameter @zh 第二个参数 + */ + export function sendToNative(arg0: string, arg1?: string): void; + /** + * @en + * Define your own js callback function. When native scripts run sendToScript, this callback will be called. + * usage: jsb.bridge.onNative = (arg0: String, arg1: String) => {...} + * @zh + * 定义自己的js回调函数,当原生调用 sendToScript 时,该回调函数被触发。 + * 使用 jsb.bridge.onNative = (arg0: String, arg1: String) => {...} + * + * @param arg0 : @en the first parameter @zh 第一个参数 + * @param arg1 : @en the second parameter @zh 第二个参数 + */ + export function onNative(arg0: string, arg1?: string|null): void; + } + /** + * @en + * Listener for jsbBridgeWrapper's event. + * It takes one argument as data which is transferred by jsbBridge. + * @zh + * jsbBridgeWrapper 的事件监听器, + * 它接受一个字符串参数,这个参数是通过 jsbBridge 进行传递的数据 + * @param arg: @en the data transferred by jsbBridge @zh jsbBridge 进行传递的数据 + */ + export type OnNativeEventListener = (arg: string) => void; + /** + * @en + * A high level API to call Objc/JAVA methods. + * Use bridge to implement it. If use jsbBridgeWrapper, bridge should not be used. + * https://docs.cocos.com/creator/manual/en/advanced-topics/jsb-bridge-wrapper.html + * @zh + * 高级 API,用于调用 Objc/JAVA 方法。 + * 该方法封装在bridge之上,如果使用 jsbBridgeWrapper,bridge 不应该被使用。 + * https://docs.cocos.com/creator/manual/zh/advanced-topics/jsb-bridge-wrapper.html + */ + export namespace jsbBridgeWrapper { + /** + * @en + * Register one listener to the event + * @zh + * 给事件注册一个监听 + * @param event : @en the event name @zh 事件名称 + * @param listener : @en the listener @zh 监听器 + */ + export function addNativeEventListener(event: string, listener: OnNativeEventListener); + /** + * @en + * Dispatch the event registered on Objective-C, Java etc. + * @zh + * 调用 Objective-C、Java 等的注册的事件。 + * @param event : @en the event name @zh 事件名称 + * @param data : @en the data @zh 数据 + */ + export function dispatchEventToNative(event: string, arg?: string); + /** + * @en Remove all listeners listennig to event. + * @zh 移除指定事件的所有监听。 + * @param event : @en the event name @zh 事件名称 + */ + export function removeAllListenersForEvent(event: string); + /** + * @en Remove the listener specified. + * @zh 移除指定的事件监听器 + * @param event : @en the event name @zh 事件名称 + */ + export function removeNativeEventListener(event: string, listener: OnNativeEventListener); + /** + * @en Remove all events, use it carefully! + * @zh 移除所有事件,请小心使用! + * @param event : @en the event name @zh 事件名称 + */ + export function removeAllListeners(); + } } diff --git a/platforms/native/engine/index.js b/platforms/native/engine/index.js index 7af523b66b..1987139121 100644 --- a/platforms/native/engine/index.js +++ b/platforms/native/engine/index.js @@ -22,9 +22,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -require('./jsb-reflection.js'); -require('./jsb-bridge.js'); -require('./jsb-bridge-wrapper.js'); require('./jsb-assets-manager.js'); require('./jsb-game.js'); diff --git a/platforms/native/engine/jsb-bridge-wrapper.js b/platforms/native/engine/jsb-bridge-wrapper.js deleted file mode 100644 index 6a71e32f5c..0000000000 --- a/platforms/native/engine/jsb-bridge-wrapper.js +++ /dev/null @@ -1,88 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - https://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. - ****************************************************************************/ -const JsbBridgeWrapper = { - eventMap: new Map(), - addNativeEventListener (eventName, listener) { - if (!this.eventMap.get(eventName)) { - this.eventMap.set(eventName, []); - } - const arr = this.eventMap.get(eventName); - if (!arr.find(listener)) { - arr.push(listener); - } - }, - dispatchEventToNative (eventName, arg) { - jsb.bridge.sendToNative(eventName, arg); - }, - removeAllListenersForEvent (eventName) { - return this.eventMap.delete(eventName); - }, - removeNativeEventListener (eventName, listener) { - const arr = this.eventMap.get(eventName); - if (!arr) { - return false; - } - for (let i = 0, l = arr.length; i < l; i++) { - if (arr[i] === listener) { - arr.splice(i, 1); - return true; - } - } - return true; - }, - removeAllListeners () { - this.eventMap.clear(); - }, - triggerEvent (eventName, arg) { - const arr = this.eventMap.get(eventName); - if (!arr) { - console.error(`${eventName} does not exist`); - return; - } - arr.map((listener) => listener.call(null, arg)); - }, -}; - -Object.defineProperty(jsb, 'jsbBridgeWrapper', { - get () { - if (jsb.__JsbBridgeWrapper !== undefined) return jsb.__JsbBridgeWrapper; - - if (window.ScriptNativeBridge && cc.sys.os === cc.sys.OS.ANDROID || cc.sys.os === cc.sys.OS.IOS || cc.sys.os === cc.sys.OS.OSX || cc.sys.os === cc.sys.OS.OHOS) { - jsb.__JsbBridgeWrapper = JsbBridgeWrapper; - jsb.bridge.onNative = (methodName, arg1) => { - console.log(`Trigger event: ${methodName} with argeter: ${arg1}`); - jsb.__JsbBridgeWrapper.triggerEvent(methodName, arg1); - }; - } else { - jsb.__JsbBridgeWrapper = null; - } - return jsb.__JsbBridgeWrapper; - }, - enumerable: true, - configurable: true, - set (value) { - jsb.__JsbBridgeWrapper = value; - }, -}); diff --git a/platforms/native/engine/jsb-bridge.js b/platforms/native/engine/jsb-bridge.js deleted file mode 100644 index 2f9643ad52..0000000000 --- a/platforms/native/engine/jsb-bridge.js +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - https://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. - ****************************************************************************/ - -// JS to Native bridges -// set to lazy -Object.defineProperty(jsb, 'bridge', { - get () { - if (jsb.__ccbridge !== undefined) return jsb.__ccbridge; - if (window.ScriptNativeBridge && cc.sys.os === cc.sys.OS.ANDROID || cc.sys.os === cc.sys.OS.IOS || cc.sys.os === cc.sys.OS.OSX || cc.sys.os === cc.sys.OS.OHOS) { - jsb.__ccbridge = new ScriptNativeBridge(); - } else { - jsb.__ccbridge = null; - } - return jsb.__ccbridge; - }, - enumerable: true, - configurable: true, - set (value) { - jsb.__ccbridge = value; - }, -}); diff --git a/platforms/native/engine/jsb-reflection.js b/platforms/native/engine/jsb-reflection.js deleted file mode 100644 index c68a3940cd..0000000000 --- a/platforms/native/engine/jsb-reflection.js +++ /dev/null @@ -1,45 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - https://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. - ****************************************************************************/ - -// JS to Native bridges -// set to lazy -Object.defineProperty(jsb, 'reflection', { - get () { - if (jsb.__bridge !== undefined) return jsb.__bridge; - if (window.JavascriptJavaBridge && (cc.sys.os === cc.sys.OS.ANDROID || cc.sys.os === cc.sys.OS.OHOS)) { - jsb.__bridge = new JavascriptJavaBridge(); - } else if (window.JavaScriptObjCBridge && (cc.sys.os === cc.sys.OS.IOS || cc.sys.os === cc.sys.OS.OSX)) { - jsb.__bridge = new JavaScriptObjCBridge(); - } else { - jsb.__bridge = null; - } - return jsb.__bridge; - }, - enumerable: true, - configurable: true, - set (value) { - jsb.__bridge = value; - }, -}); From f76a30dcace70a07c0886a36dd5364e28bde238e Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Thu, 21 Jul 2022 18:47:52 +0800 Subject: [PATCH 068/111] Add ->(geometry, profiler, planarShadow) and update shadowmap (#45) (#12129) Co-authored-by: GengineJS <476393671@qq.com> --- .../core/pipeline/custom/builtin-pipelines.ts | 15 ++++++--- cocos/core/pipeline/custom/executor.ts | 33 +++++++++++++++++-- cocos/core/pipeline/custom/web-pipeline.ts | 12 +++++++ 3 files changed, 53 insertions(+), 7 deletions(-) diff --git a/cocos/core/pipeline/custom/builtin-pipelines.ts b/cocos/core/pipeline/custom/builtin-pipelines.ts index 35fc3a7a6e..bd06683baa 100644 --- a/cocos/core/pipeline/custom/builtin-pipelines.ts +++ b/cocos/core/pipeline/custom/builtin-pipelines.ts @@ -115,7 +115,8 @@ export function buildShadowPasses (cameraName: string, camera: Camera, ppl: Pipe buildShadowPass(cameraInfo.mainLightShadowNames[0], ppl, camera, mainLight, 0, mapWidth, mapHeight); } else { - for (let i = 0; i < mainLight.csmLevel; i++) { + const csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1; + for (let i = 0; i < csmLevel; i++) { cameraInfo.mainLightShadowNames[i] = `MainLightShadow${cameraName}`; buildShadowPass(cameraInfo.mainLightShadowNames[i], ppl, camera, mainLight, i, mapWidth, mapHeight); @@ -209,10 +210,12 @@ export class ForwardPipelineBuilder extends PipelineBuilder { forwardPass.addRasterView(forwardPassDSName, passDSView); forwardPass .addQueue(QueueHint.RENDER_OPAQUE) - .addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT | SceneFlags.DEFAULT_LIGHTING); + .addSceneOfCamera(camera, new LightInfo(), + SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT + | SceneFlags.PLANAR_SHADOW | SceneFlags.DEFAULT_LIGHTING); forwardPass .addQueue(QueueHint.RENDER_TRANSPARENT) - .addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.UI); + .addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.UI | SceneFlags.GEOMETRY | SceneFlags.PROFILER); } } } @@ -406,7 +409,8 @@ export class DeferredPipelineBuilder extends PipelineBuilder { camera, this._deferredData._deferredLightingMaterial, SceneFlags.VOLUMETRIC_LIGHTING, ); - lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT); + lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), + SceneFlags.TRANSPARENT_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.GEOMETRY); // Postprocess const postprocessPassRTName = `postprocessPassRTName${cameraID}`; const postprocessPassDS = `postprocessPassDS${cameraID}`; @@ -441,7 +445,8 @@ export class DeferredPipelineBuilder extends PipelineBuilder { postprocessPass.addRasterView(postprocessPassRTName, postprocessPassView); postprocessPass.addRasterView(postprocessPassDS, postprocessPassDSView); postprocessPass.addQueue(QueueHint.NONE).addFullscreenQuad(this._deferredData._deferredPostMaterial, SceneFlags.NONE); - postprocessPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), SceneFlags.UI); + postprocessPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), + SceneFlags.UI | SceneFlags.PROFILER); } } readonly _deferredData = new DeferredData(); diff --git a/cocos/core/pipeline/custom/executor.ts b/cocos/core/pipeline/custom/executor.ts index 05d0e1bc58..9d6867f1b9 100644 --- a/cocos/core/pipeline/custom/executor.ts +++ b/cocos/core/pipeline/custom/executor.ts @@ -66,6 +66,8 @@ import { WebSceneVisitor } from './web-scene-visitor'; import { stringify, parse } from './utils'; import { RenderAdditiveLightQueue } from '../render-additive-light-queue'; import { RenderShadowMapBatchedQueue } from '../render-shadow-map-batched-queue'; +import { renderProfiler } from '../pipeline-funcs'; +import { PlanarShadowQueue } from '../planar-shadow-queue'; class DeviceResource { protected _context: ExecutorContext; @@ -451,6 +453,7 @@ class SubmitInfo { public batches = new Set(); public opaqueList: RenderInfo[] = []; public transparentList: RenderInfo[] = []; + public planarQueue: PlanarShadowQueue | null = null; public shadowMap: RenderShadowMapBatchedQueue | null = null; public additiveLight: RenderAdditiveLightQueue | null = null; } @@ -826,11 +829,15 @@ class DevicePreSceneTask extends WebSceneTask { } } } + const pipeline = this._currentQueue.devicePass.context.pipeline; if (sceneFlag & SceneFlags.DEFAULT_LIGHTING) { - const pipeline = this._currentQueue.devicePass.context.pipeline; this._submitInfo.additiveLight = new RenderAdditiveLightQueue(pipeline); this._submitInfo.additiveLight.gatherLightPasses(this.camera, this._cmdBuff); } + if (sceneFlag & SceneFlags.PLANAR_SHADOW) { + this._submitInfo.planarQueue = new PlanarShadowQueue(pipeline); + this._submitInfo.planarQueue.gatherShadowPasses(this.camera, this._cmdBuff); + } this._submitInfo.opaqueList.sort(this._opaqueCompareFn); this._submitInfo.transparentList.sort(this._transparentCompareFn); } @@ -1125,8 +1132,20 @@ class DeviceSceneTask extends WebSceneTask { this._renderPass, devicePass.context.commandBuffer); } + + private _recordPlanarShadows () { + const devicePass = this._currentQueue.devicePass; + const submitMap = devicePass.submitMap; + const context = devicePass.context; + submitMap.get(this.camera!)?.planarQueue?.recordCommandBuffer(context.device, + this._renderPass, + devicePass.context.commandBuffer); + } + public submit () { const area = this._generateRenderArea(); + const devicePass = this._currentQueue.devicePass; + const context = devicePass.context; if (!this._currentQueue.devicePass.viewport) { this.visitor.setViewport(new Viewport(area.x, area.y, area.width, area.height)); this.visitor.setScissor(area); @@ -1140,14 +1159,24 @@ class DeviceSceneTask extends WebSceneTask { this._recordShadowMap(); return; } + const graphSceneData = this.graphScene.scene!; this._recordOpaqueList(); this._recordInstences(); this._recordBatches(); this._recordAdditiveLights(); + this._recordPlanarShadows(); this._recordTransparentList(); - if (this.graphScene.scene!.flags & SceneFlags.UI) { + if (graphSceneData.flags & SceneFlags.GEOMETRY) { + this.camera!.geometryRenderer?.render(devicePass.renderPass, + context.commandBuffer, context.pipeline.pipelineSceneData); + } + if (graphSceneData.flags & SceneFlags.UI) { this._recordUI(); } + if (graphSceneData.flags & SceneFlags.PROFILER) { + renderProfiler(context.device, devicePass.renderPass, + context.commandBuffer, context.pipeline.profiler, this.camera!); + } } } diff --git a/cocos/core/pipeline/custom/web-pipeline.ts b/cocos/core/pipeline/custom/web-pipeline.ts index 441a81f811..98f757e1b8 100644 --- a/cocos/core/pipeline/custom/web-pipeline.ts +++ b/cocos/core/pipeline/custom/web-pipeline.ts @@ -52,6 +52,7 @@ import { GeometryRenderer } from '../geometry-renderer'; import { Material } from '../../assets'; import { DeferredPipelineBuilder, ForwardPipelineBuilder } from './builtin-pipelines'; import { RenderGraphPrintVisitor } from './debug'; +import { decideProfilerCamera } from '../pipeline-funcs'; export class WebSetter { constructor (data: RenderData) { @@ -427,6 +428,12 @@ export class WebPipeline extends Pipeline { // 0: SHADOWMAP_LINER_DEPTH_OFF, 1: SHADOWMAP_LINER_DEPTH_ON. const isLinear = this._device.gfxAPI === API.WEBGL ? 1 : 0; this.setMacroInt('CC_SHADOWMAP_USE_LINEAR_DEPTH', isLinear); + + // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. + this.pipelineSceneData.csmSupported = this.device.capabilities.maxFragmentUniformVectors + >= (WebPipeline.CSM_UNIFORM_VECTORS + WebPipeline.GLOBAL_UNIFORM_VECTORS); + this.setMacroBool('CC_SUPPORT_CASCADED_SHADOW_MAP', this.pipelineSceneData.csmSupported); + const root = legacyCC.director.root; // enable the deferred pipeline if (root.useDeferredPipeline) { @@ -638,6 +645,7 @@ export class WebPipeline extends Pipeline { return; } this._applySize(cameras); + decideProfilerCamera(cameras); // build graph this.beginFrame(); if (this.builder) { @@ -715,4 +723,8 @@ export class WebPipeline extends Pipeline { private _forward!: ForwardPipelineBuilder; private _deferred!: DeferredPipelineBuilder; public builder: PipelineBuilder | null = null; + // csm uniform used vectors count + public static CSM_UNIFORM_VECTORS = 61; + // all global uniform used vectors count + public static GLOBAL_UNIFORM_VECTORS = 64; } From 2e69f679d3c733c087372e7bc82f68ba4193d211 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Thu, 21 Jul 2022 19:20:42 +0800 Subject: [PATCH 069/111] reflection convolutional map baking speed optimization (#12112) --- cocos/core/renderer/scene/skybox.ts | 100 +++++++++++++++---- cocos/core/scene-graph/scene-globals.jsb.ts | 4 + cocos/core/scene-graph/scene-globals.ts | 53 +++++++++- editor/assets/effects/pipeline/skybox.effect | 18 +++- editor/assets/effects/surfaces/sky.effect | 32 ++++-- native/cocos/scene/Skybox.cpp | 87 ++++++++++++++-- native/cocos/scene/Skybox.h | 11 ++ native/tools/tojs/scene.ini | 2 +- 8 files changed, 261 insertions(+), 46 deletions(-) diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index cc684368da..4b23715426 100644 --- a/cocos/core/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -150,11 +150,13 @@ export class Skybox { * @zh 是否使用离线烘焙的卷积图? */ get useConvolutionMap (): boolean { + if (this.reflectionMap) { + return this.reflectionMap.isUsingOfflineMipmaps(); + } if (this.envmap) { return this.envmap.isUsingOfflineMipmaps(); - } else { - return false; } + return false; } /** @@ -200,15 +202,15 @@ export class Skybox { } } - public setSkyboxMaterial (skyboxMat: Material | null) { - if (skyboxMat) { - this._editableMaterial = new MaterialInstance({ parent: skyboxMat }); - this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + get reflectionMap (): TextureCube | null { + const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; + if (isHDR) { + return this._reflectionHDR; } else { - this._editableMaterial = null; + return this._reflectionLDR; } - this._updatePipeline(); } + protected _envmapLDR: TextureCube | null = null; protected _envmapHDR: TextureCube | null = null; protected _diffuseMapLDR: TextureCube | null = null; @@ -222,6 +224,8 @@ export class Skybox { protected _useDiffuseMap = false; protected _editableMaterial: MaterialInstance | null = null; protected _activated = false; + protected _reflectionHDR: TextureCube | null = null; + protected _reflectionLDR: TextureCube | null = null; public initialize (skyboxInfo: SkyboxInfo) { this._activated = false; @@ -258,6 +262,39 @@ export class Skybox { this._updatePipeline(); } + /** + * @en Set custom skybox material + * @zh 设置自定义的天空盒材质 + * @param skyboxMat @en Skybox material @zh 天空盒材质 + */ + public setSkyboxMaterial (skyboxMat: Material | null) { + if (skyboxMat) { + this._editableMaterial = new MaterialInstance({ parent: skyboxMat }); + this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + } else { + this._editableMaterial = null; + } + this._updatePipeline(); + } + + /** + * @en Set the environment reflection convolution map + * @zh 设置环境反射卷积图 + * @param reflectionHDR @en Reflection convolution map for HDR mode @zh HDR 模式下的反射卷积图 + * @param reflectionLDR @en Reflection convolution map for LDR mode @zh LDR 模式下的反射卷积图 + */ + public setReflectionMaps (reflectionHDR: TextureCube | null, reflectionLDR: TextureCube | null) { + this._reflectionHDR = reflectionHDR; + this._reflectionLDR = reflectionLDR; + this._updateGlobalBinding(); + this._updatePipeline(); + } + + public updateMaterialRenderInfo () { + this._updateGlobalBinding(); + this._updatePipeline(); + } + public activate () { const pipeline = legacyCC.director.root.pipeline; this._globalDSManager = pipeline.globalDSManager; @@ -265,10 +302,9 @@ export class Skybox { if (!this._model) { this._model = legacyCC.director.root.createModel(legacyCC.renderer.scene.Model) as Model; - // @ts-expect-error private member access - this._model._initLocalDescriptors = () => {}; - // @ts-expect-error private member access - this._model._initWorldBoundDescriptors = () => {}; + //The skybox material has added properties of 'environmentMap' that need local ubo + //this._model._initLocalDescriptors = () => {}; + //this._model._initWorldBoundDescriptors = () => {}; } let isRGBE = this._default.isRGBE; let isUseConvolutionMap = this._default.isUsingOfflineMipmaps(); @@ -333,9 +369,19 @@ export class Skybox { if (this.enabled) { if (this._editableMaterial) { - this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + if (this.reflectionMap) { + this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: true }); + this._editableMaterial.setProperty('environmentMap', this.envmap); + } else { + this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: false }); + } } else if (skybox_material) { - skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + if (this.reflectionMap) { + skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: true }); + skybox_material.setProperty('environmentMap', this.envmap); + } else { + skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: false }); + } } } @@ -345,19 +391,26 @@ export class Skybox { } else { this._model.setSubModelMaterial(0, skybox_material!); } + this._updateSubModes(); } } protected _updateGlobalBinding () { if (this._globalDSManager) { const device = deviceManager.gfxDevice; - - const envmap = this.envmap ? this.envmap : this._default; - if (envmap) { - const texture = envmap.getGFXTexture()!; - const sampler = device.getSampler(envmap.getSamplerInfo()); + if (this.reflectionMap) { + const texture = this.reflectionMap.getGFXTexture()!; + const sampler = device.getSampler(this.reflectionMap.getSamplerInfo()); this._globalDSManager.bindSampler(UNIFORM_ENVIRONMENT_BINDING, sampler); this._globalDSManager.bindTexture(UNIFORM_ENVIRONMENT_BINDING, texture); + } else { + const envmap = this.envmap ? this.envmap : this._default; + if (envmap) { + const texture = envmap.getGFXTexture()!; + const sampler = device.getSampler(envmap.getSamplerInfo()); + this._globalDSManager.bindSampler(UNIFORM_ENVIRONMENT_BINDING, sampler); + this._globalDSManager.bindTexture(UNIFORM_ENVIRONMENT_BINDING, texture); + } } const diffuseMap = this.diffuseMap ? this.diffuseMap : this._default; @@ -371,6 +424,15 @@ export class Skybox { this._globalDSManager.update(); } } + + protected _updateSubModes () { + if (this._model) { + const subModels = this._model.subModels; + for (let i = 0; i < subModels.length; i++) { + subModels[i].update(); + } + } + } } legacyCC.Skybox = Skybox; diff --git a/cocos/core/scene-graph/scene-globals.jsb.ts b/cocos/core/scene-graph/scene-globals.jsb.ts index c2177c6920..d512665a21 100644 --- a/cocos/core/scene-graph/scene-globals.jsb.ts +++ b/cocos/core/scene-graph/scene-globals.jsb.ts @@ -402,6 +402,10 @@ serializable(SkyboxInfoProto, '_enabled'); serializable(SkyboxInfoProto, '_useHDR'); type(Material)(SkyboxInfoProto, '_editableMaterial'); serializable(SkyboxInfoProto, '_editableMaterial'); +type(TextureCube)(SkyboxInfoProto, '_reflectionHDR'); +serializable(SkyboxInfoProto, '_reflectionHDR'); +type(TextureCube)(SkyboxInfoProto, '_reflectionLDR'); +serializable(SkyboxInfoProto, '_reflectionLDR'); const skyboxEnabledDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfoProto, 'enabled'); tooltip('i18n:skybox.enabled')(SkyboxInfoProto, 'enabled', skyboxEnabledDescriptor); editable(SkyboxInfoProto, 'enabled', skyboxEnabledDescriptor); diff --git a/cocos/core/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts index 0a0b30aa24..ce702c8f45 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -1,3 +1,4 @@ +/* eslint-disable func-names */ /* Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -343,9 +344,6 @@ export class SkyboxInfo { // Switch UI to and from LDR/HDR textures depends on HDR state if (this._resource) { - this.envmap = this._resource.envmap; - this.diffuseMap = this._resource.diffuseMap; - if (this.envLightingType === EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION) { if (this.diffuseMap === null) { this.envLightingType = EnvironmentLightingType.AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION; @@ -356,7 +354,10 @@ export class SkyboxInfo { } } - if (this._resource) { this._resource.useHDR = this._useHDR; } + if (this._resource) { + this._resource.useHDR = this._useHDR; + this._resource.updateMaterialRenderInfo(); + } } get useHDR () { (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR = this._useHDR; @@ -374,8 +375,10 @@ export class SkyboxInfo { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { this._envmapHDR = val; + this._reflectionHDR = null; } else { this._envmapLDR = val; + this._reflectionLDR = null; } if (!val) { if (isHDR) { @@ -392,6 +395,7 @@ export class SkyboxInfo { if (this._resource) { this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR); this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); + this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR); this._resource.useDiffuseMap = this.applyDiffuseMap; this._resource.envmap = val; } @@ -440,6 +444,40 @@ export class SkyboxInfo { } } + /** + * @en Convolutional map using environmental reflections + * @zh 使用环境反射卷积图 + */ + @visible(function (this : SkyboxInfo) { + if (this._resource?.reflectionMap) { + return true; + } + return false; + }) + @editable + @readOnly + @type(TextureCube) + @displayOrder(100) + set reflectionMap (val: TextureCube | null) { + const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; + if (isHDR) { + this._reflectionHDR = val; + } else { + this._reflectionLDR = val; + } + if (this._resource) { + this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR); + } + } + get reflectionMap () { + const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; + if (isHDR) { + return this._reflectionHDR; + } else { + return this._reflectionLDR; + } + } + /** * @en Use custom skybox material * @zh 使用自定义的天空盒材质 @@ -479,6 +517,12 @@ export class SkyboxInfo { @serializable @type(Material) protected _editableMaterial: Material | null = null; + @serializable + @type(TextureCube) + protected _reflectionHDR: TextureCube | null = null; + @serializable + @type(TextureCube) + protected _reflectionLDR: TextureCube | null = null; protected _resource: Skybox | null = null; @@ -494,6 +538,7 @@ export class SkyboxInfo { this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR); this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); this._resource.setSkyboxMaterial(this._editableMaterial); + this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR); this._resource.activate(); // update global DS first } } diff --git a/editor/assets/effects/pipeline/skybox.effect b/editor/assets/effects/pipeline/skybox.effect index 0d74301934..239893f61c 100644 --- a/editor/assets/effects/pipeline/skybox.effect +++ b/editor/assets/effects/pipeline/skybox.effect @@ -3,6 +3,8 @@ CCEffect %{ - passes: - vert: sky-vs:vert frag: sky-fs:frag + properties: &props + environmentMap: { value: grey } priority: max - 10 rasterizerState: cullMode: none @@ -57,11 +59,21 @@ CCProgram sky-fs %{ in mediump vec4 viewDir; - vec4 frag () { + vec3 getEnvironment(samplerCube cubeMap) + { #if USE_RGBE_CUBEMAP - vec3 c = unpackRGBE(fragTextureLod(cc_environment, viewDir.xyz, 0.0)); + vec3 c = unpackRGBE(fragTextureLod(cubeMap, viewDir.xyz, 0.0)); #else - vec3 c = SRGBToLinear(fragTextureLod(cc_environment, viewDir.xyz, 0.0).rgb); + vec3 c = SRGBToLinear(fragTextureLod(cubeMap, viewDir.xyz, 0.0).rgb); + #endif + return c; + } + uniform samplerCube environmentMap; + vec4 frag () { + #if USE_REFLECTION_CUBEMAP + vec3 c = getEnvironment(environmentMap); + #else + vec3 c = getEnvironment(cc_environment); #endif return CCFragOutput(vec4(c * cc_ambientSky.w, 1.0)); } diff --git a/editor/assets/effects/surfaces/sky.effect b/editor/assets/effects/surfaces/sky.effect index 49e05e217d..aad126744a 100644 --- a/editor/assets/effects/surfaces/sky.effect +++ b/editor/assets/effects/surfaces/sky.effect @@ -6,6 +6,8 @@ CCEffect %{ passes: - vert: sky-vs frag: sky-fs + properties: &props + environmentMap: { value: grey } priority : max - 10 rasterizerState : cullMode : none @@ -25,18 +27,32 @@ CCProgram surface-vertex %{ }% CCProgram surface-fragment %{ + + uniform samplerCube environmentMap; + + vec3 getEnvironment(samplerCube cubeMap) + { + vec3 c = vec3(1.0); + vec3 normal = normalize(FSInput_worldNormal); + #if USE_RGBE_CUBEMAP + c *= unpackRGBE(fragTextureLod(cubeMap, normal.xyz, 0.0)); + #else + c *= SRGBToLinear(fragTextureLod(cubeMap, normal.xyz, 0.0).rgb); + #endif + return c; + } + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY vec4 SurfacesFragmentModifyBaseColorAndTransparency() { - vec3 c = vec3(1.0); - #if CC_USE_IBL - vec3 normal = normalize(FSInput_worldNormal); - #if USE_RGBE_CUBEMAP - c *= unpackRGBE(fragTextureLod(cc_environment, normal.xyz, 0.0)); - #else - c *= SRGBToLinear(fragTextureLod(cc_environment, normal.xyz, 0.0).rgb); + vec3 c = vec3(1.0); + #if CC_USE_IBL + #if USE_REFLECTION_CUBEMAP + c = getEnvironment(environmentMap); + #else + c = getEnvironment(cc_environment); + #endif #endif - #endif return vec4(c * cc_ambientSky.w, 1.0); } }% diff --git a/native/cocos/scene/Skybox.cpp b/native/cocos/scene/Skybox.cpp index fccfd909be..c0a1664f45 100644 --- a/native/cocos/scene/Skybox.cpp +++ b/native/cocos/scene/Skybox.cpp @@ -91,6 +91,7 @@ void SkyboxInfo::setUseHDR(bool val) { if (_resource) { setEnvmap(_resource->getEnvmap()); setDiffuseMap(_resource->getDiffuseMap()); + setReflectionMap(_resource->getReflectionMap()); if (_envLightingType == EnvironmentLightingType::DIFFUSEMAP_WITH_REFLECTION) { auto *diffuseMap = getDiffuseMap(); @@ -117,8 +118,10 @@ void SkyboxInfo::setEnvmap(TextureCube *val) { const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); if (isHDR) { _envmapHDR = val; + _reflectionHDR = nullptr; } else { _envmapLDR = val; + _reflectionLDR = nullptr; } if (!val) { @@ -136,6 +139,7 @@ void SkyboxInfo::setEnvmap(TextureCube *val) { if (_resource) { _resource->setEnvMaps(_envmapHDR, _envmapLDR); _resource->setDiffuseMaps(_diffuseMapHDR, _diffuseMapLDR); + _resource->setReflectionMaps(_reflectionHDR, _reflectionLDR); _resource->setUseDiffuseMap(isApplyDiffuseMap()); _resource->setEnvmap(val); } @@ -164,6 +168,19 @@ TextureCube *SkyboxInfo::getDiffuseMap() const { return isHDR ? _diffuseMapHDR : _diffuseMapLDR; } +void SkyboxInfo::setReflectionMap(TextureCube *val) { + const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); + if (isHDR) { + _reflectionHDR = val; + } else { + _reflectionLDR = val; + } + + if (_resource) { + _resource->setReflectionMaps(_reflectionHDR, _reflectionLDR); + } +} + void SkyboxInfo::activate(Skybox *resource) { _resource = resource; // weak reference Root::getInstance()->getPipeline()->getPipelineSceneData()->setHDR(_useHDR); @@ -172,6 +189,7 @@ void SkyboxInfo::activate(Skybox *resource) { setEnvLightingType(this->_envLightingType); _resource->setEnvMaps(_envmapHDR, _envmapLDR); _resource->setDiffuseMaps(_diffuseMapHDR, _diffuseMapLDR); + _resource->setReflectionMaps(_reflectionHDR, _reflectionLDR); _resource->setSkyboxMaterial(_editableMaterial); _resource->activate(); // update global DS first } @@ -197,6 +215,10 @@ bool Skybox::isRGBE() const { } bool Skybox::isUsingConvolutionMap() const { + auto *reflectionMap = getReflectionMap(); + if (reflectionMap) { + return reflectionMap->isUsingOfflineMipmaps(); + } auto *envmap = getEnvmap(); if (envmap) { return envmap->isUsingOfflineMipmaps(); @@ -248,6 +270,17 @@ void Skybox::setDiffuseMaps(TextureCube *diffuseMapHDR, TextureCube *diffuseMapL updatePipeline(); } +TextureCube *Skybox::getReflectionMap() const { + const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); + return isHDR ? _reflectionHDR : _reflectionLDR; +} +void Skybox::setReflectionMaps(TextureCube *reflectionHDR, TextureCube *reflectionLDR) { + _reflectionHDR = reflectionHDR; + _reflectionLDR = reflectionLDR; + updateGlobalBinding(); + updatePipeline(); +} + void Skybox::setSkyboxMaterial(Material *skyboxMat) { _editableMaterial = skyboxMat; } @@ -259,8 +292,9 @@ void Skybox::activate() { if (!_model) { _model = Root::getInstance()->createModel(); - _model->initLocalDescriptors(CC_INVALID_INDEX); - _model->initWorldBoundDescriptors(CC_INVALID_INDEX); + //The skybox material has added properties of 'environmentMap' that need local ubo + //_model->initLocalDescriptors(CC_INVALID_INDEX); + //_model->initWorldBoundDescriptors(CC_INVALID_INDEX); } auto *envmap = getEnvmap(); bool isRGBE = envmap != nullptr ? envmap->isRGBE : _default->isRGBE; @@ -314,7 +348,20 @@ void Skybox::setUseHDR(bool val) { } void Skybox::updatePipeline() const { - + if (isEnabled() && _material != nullptr) { + if (getReflectionMap()) { + _material->recompileShaders({{"USE_RGBE_CUBEMAP", isRGBE()}, {"USE_REFLECTION_CUBEMAP", true}}); + _material->setProperty("environmentMap", getEnvmap()); + } else { + _material->recompileShaders({{"USE_RGBE_CUBEMAP", isRGBE()}, {"USE_REFLECTION_CUBEMAP", false}}); + } + } + + if (_model != nullptr && _material != nullptr) { + _model->setSubModelMaterial(0, _material); + updateSubModes(); + } + Root *root = Root::getInstance(); auto *pipeline = root->getPipeline(); @@ -394,15 +441,24 @@ void Skybox::updatePipeline() const { void Skybox::updateGlobalBinding() { if (_globalDSManager != nullptr) { auto *device = Root::getInstance()->getDevice(); - auto *envmap = getEnvmap(); - if (!envmap) { - envmap = _default.get(); - } - if (envmap != nullptr) { - auto *texture = envmap->getGFXTexture(); - auto *sampler = device->getSampler(envmap->getSamplerInfo()); + + auto *convolutonMap = getReflectionMap(); + if (convolutonMap != nullptr) { + auto *texture = convolutonMap->getGFXTexture(); + auto *sampler = device->getSampler(convolutonMap->getSamplerInfo()); _globalDSManager->bindSampler(pipeline::ENVIRONMENT::BINDING, sampler); _globalDSManager->bindTexture(pipeline::ENVIRONMENT::BINDING, texture); + } else { + auto *envmap = getEnvmap(); + if (!envmap) { + envmap = _default.get(); + } + if (envmap != nullptr) { + auto *texture = envmap->getGFXTexture(); + auto *sampler = device->getSampler(envmap->getSamplerInfo()); + _globalDSManager->bindSampler(pipeline::ENVIRONMENT::BINDING, sampler); + _globalDSManager->bindTexture(pipeline::ENVIRONMENT::BINDING, texture); + } } auto *diffuseMap = getDiffuseMap(); @@ -411,7 +467,7 @@ void Skybox::updateGlobalBinding() { } if (diffuseMap != nullptr) { auto *texture = diffuseMap->getGFXTexture(); - auto *sampler = device->getSampler(envmap->getSamplerInfo()); + auto *sampler = device->getSampler(diffuseMap->getSamplerInfo()); _globalDSManager->bindSampler(pipeline::DIFFUSEMAP::BINDING, sampler); _globalDSManager->bindTexture(pipeline::DIFFUSEMAP::BINDING, texture); } @@ -419,5 +475,14 @@ void Skybox::updateGlobalBinding() { } } +void Skybox::updateSubModes() const { + if (_model) { + ccstd::vector> subModels = _model->_subModels; + for (auto& subModel : subModels) { + subModel->update(); + } + } +} + } // namespace scene } // namespace cc diff --git a/native/cocos/scene/Skybox.h b/native/cocos/scene/Skybox.h index 70f49dbc9e..282e21a7b6 100644 --- a/native/cocos/scene/Skybox.h +++ b/native/cocos/scene/Skybox.h @@ -163,6 +163,8 @@ public: void setDiffuseMap(TextureCube *val); TextureCube *getDiffuseMap() const; + void setReflectionMap(TextureCube *val); + void activate(Skybox *resource); // cjh JSB need to bind the property, so need to make it public @@ -180,6 +182,8 @@ public: // @serializable // @type(TextureCube) TextureCube *_diffuseMapLDR{nullptr}; + TextureCube *_reflectionHDR{nullptr}; + TextureCube *_reflectionLDR{nullptr}; // @serializable bool _enabled{false}; // @serializable @@ -200,6 +204,8 @@ public: void setDiffuseMaps(TextureCube *diffuseMapHDR, TextureCube *diffuseMapLDR); + void setReflectionMaps(TextureCube *reflectionHDR, TextureCube *reflectionLDR); + void activate(); inline Model *getModel() const { return _model.get(); } @@ -272,14 +278,19 @@ public: void setDiffuseMap(TextureCube *val); void setSkyboxMaterial(Material* skyboxMat); + TextureCube *getReflectionMap() const; + private: void updatePipeline() const; void updateGlobalBinding(); + void updateSubModes() const; IntrusivePtr _envmapLDR; IntrusivePtr _envmapHDR; IntrusivePtr _diffuseMapLDR; IntrusivePtr _diffuseMapHDR; + IntrusivePtr _reflectionHDR; + IntrusivePtr _reflectionLDR; pipeline::GlobalDSManager *_globalDSManager{nullptr}; IntrusivePtr _model; IntrusivePtr _mesh; diff --git a/native/tools/tojs/scene.ini b/native/tools/tojs/scene.ini index 29df408689..b895cd32fa 100644 --- a/native/tools/tojs/scene.ini +++ b/native/tools/tojs/scene.ini @@ -122,7 +122,7 @@ field = Ambient::[SUN_ILLUM SKY_ILLUM], Shadows::[MAX_FAR COEFFICIENT_OF_EXPANSION], ShadowsInfo::[_enabled _type _normal _distance _shadowColor _maxReceived _size], FogInfo::[_type _fogColor _isEnabled _fogDensity _fogStart _fogEnd _fogAtten _fogTop _fogRange _accurate], - SkyboxInfo::[_envLightingType _envmapHDR _envmapLDR _diffuseMapHDR _diffuseMapLDR _enabled _useHDR _editableMaterial], + SkyboxInfo::[_envLightingType _envmapHDR _envmapLDR _diffuseMapHDR _diffuseMapLDR _enabled _useHDR _editableMaterial _reflectionHDR _reflectionLDR], OctreeInfo::[_enabled _minPos _maxPos _depth], Node::[_siblingIndex _parent _active$ _id] From b3c750e03c73a2aa35024fb4836a9cbe126d9e99 Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Thu, 21 Jul 2022 19:29:59 +0800 Subject: [PATCH 070/111] [ci skip][AUTO]: Automated code generating update: 1908d69bf92de8833e2c837f42e9de15dece1758 (#12112) (#12135) Co-authored-by: cocos-robot --- native/cocos/bindings/auto/jsb_scene_auto.cpp | 123 ++++++++++++++++++ native/cocos/bindings/auto/jsb_scene_auto.h | 3 + 2 files changed, 126 insertions(+) diff --git a/native/cocos/bindings/auto/jsb_scene_auto.cpp b/native/cocos/bindings/auto/jsb_scene_auto.cpp index b99ada7f44..c4bc974cec 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.cpp +++ b/native/cocos/bindings/auto/jsb_scene_auto.cpp @@ -11129,6 +11129,26 @@ static bool js_scene_SkyboxInfo_setEnvmapForJS(se::State& s) // NOLINT(readabili } SE_BIND_FUNC_AS_PROP_SET(js_scene_SkyboxInfo_setEnvmapForJS) +static bool js_scene_SkyboxInfo_setReflectionMap(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setReflectionMap(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_scene_SkyboxInfo_setReflectionMap) + static bool js_scene_SkyboxInfo_setUseHDR(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -11281,6 +11301,62 @@ static bool js_scene_SkyboxInfo_set__diffuseMapLDR(se::State& s) // NOLINT(reada } SE_BIND_PROP_SET(js_scene_SkyboxInfo_set__diffuseMapLDR) +static bool js_scene_SkyboxInfo_get__reflectionHDR(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->_reflectionHDR, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->_reflectionHDR, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_scene_SkyboxInfo_get__reflectionHDR) + +static bool js_scene_SkyboxInfo_set__reflectionHDR(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->_reflectionHDR, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_scene_SkyboxInfo_set__reflectionHDR) + +static bool js_scene_SkyboxInfo_get__reflectionLDR(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->_reflectionLDR, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->_reflectionLDR, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_scene_SkyboxInfo_get__reflectionLDR) + +static bool js_scene_SkyboxInfo_set__reflectionLDR(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->_reflectionLDR, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_scene_SkyboxInfo_set__reflectionLDR) + static bool js_scene_SkyboxInfo_get__enabled(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -11420,6 +11496,8 @@ bool js_register_scene_SkyboxInfo(se::Object* obj) // NOLINT(readability-identif cls->defineProperty("_envmapLDR", _SE(js_scene_SkyboxInfo_get__envmapLDR), _SE(js_scene_SkyboxInfo_set__envmapLDR)); cls->defineProperty("_diffuseMapHDR", _SE(js_scene_SkyboxInfo_get__diffuseMapHDR), _SE(js_scene_SkyboxInfo_set__diffuseMapHDR)); cls->defineProperty("_diffuseMapLDR", _SE(js_scene_SkyboxInfo_get__diffuseMapLDR), _SE(js_scene_SkyboxInfo_set__diffuseMapLDR)); + cls->defineProperty("_reflectionHDR", _SE(js_scene_SkyboxInfo_get__reflectionHDR), _SE(js_scene_SkyboxInfo_set__reflectionHDR)); + cls->defineProperty("_reflectionLDR", _SE(js_scene_SkyboxInfo_get__reflectionLDR), _SE(js_scene_SkyboxInfo_set__reflectionLDR)); cls->defineProperty("_enabled", _SE(js_scene_SkyboxInfo_get__enabled), _SE(js_scene_SkyboxInfo_set__enabled)); cls->defineProperty("_useHDR", _SE(js_scene_SkyboxInfo_get__useHDR), _SE(js_scene_SkyboxInfo_set__useHDR)); cls->defineProperty("_envLightingType", _SE(js_scene_SkyboxInfo_get__envLightingType), _SE(js_scene_SkyboxInfo_set__envLightingType)); @@ -11433,6 +11511,7 @@ bool js_register_scene_SkyboxInfo(se::Object* obj) // NOLINT(readability-identif cls->defineProperty("envLightingType", _SE(js_scene_SkyboxInfo_getEnvLightingType_asGetter), _SE(js_scene_SkyboxInfo_setEnvLightingType_asSetter)); cls->defineProperty("diffuseMap", _SE(js_scene_SkyboxInfo_getDiffuseMap_asGetter), _SE(js_scene_SkyboxInfo_setDiffuseMap_asSetter)); cls->defineFunction("activate", _SE(js_scene_SkyboxInfo_activate)); + cls->defineFunction("setReflectionMap", _SE(js_scene_SkyboxInfo_setReflectionMap)); cls->defineFinalizeFunction(_SE(js_cc_scene_SkyboxInfo_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -11523,6 +11602,26 @@ static bool js_scene_Skybox_getModel(se::State& s) // NOLINT(readability-identif } SE_BIND_FUNC_AS_PROP_GET(js_scene_Skybox_getModel) +static bool js_scene_Skybox_getReflectionMap(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::TextureCube* result = cobj->getReflectionMap(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_scene_Skybox_getReflectionMap) + static bool js_scene_Skybox_initialize(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -11767,6 +11866,28 @@ static bool js_scene_Skybox_setEnvmap(se::State& s) // NOLINT(readability-identi } SE_BIND_FUNC_AS_PROP_SET(js_scene_Skybox_setEnvmap) +static bool js_scene_Skybox_setReflectionMaps(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + // SE_PRECONDITION2(cobj, false, "Invalid Native Object"); + if (nullptr == cobj) return true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + cobj->setReflectionMaps(arg0.value(), arg1.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_scene_Skybox_setReflectionMaps) + static bool js_scene_Skybox_setSkyboxMaterial(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -11879,10 +12000,12 @@ bool js_register_scene_Skybox(se::Object* obj) // NOLINT(readability-identifier- cls->defineProperty("envmap", _SE(js_scene_Skybox_getEnvmap_asGetter), _SE(js_scene_Skybox_setEnvmap_asSetter)); cls->defineProperty("diffuseMap", _SE(js_scene_Skybox_getDiffuseMap_asGetter), _SE(js_scene_Skybox_setDiffuseMap_asSetter)); cls->defineFunction("activate", _SE(js_scene_Skybox_activate)); + cls->defineFunction("getReflectionMap", _SE(js_scene_Skybox_getReflectionMap)); cls->defineFunction("initialize", _SE(js_scene_Skybox_initialize)); cls->defineFunction("isUsingConvolutionMap", _SE(js_scene_Skybox_isUsingConvolutionMap)); cls->defineFunction("setDiffuseMaps", _SE(js_scene_Skybox_setDiffuseMaps)); cls->defineFunction("setEnvMaps", _SE(js_scene_Skybox_setEnvMaps)); + cls->defineFunction("setReflectionMaps", _SE(js_scene_Skybox_setReflectionMaps)); cls->defineFunction("setSkyboxMaterial", _SE(js_scene_Skybox_setSkyboxMaterial)); cls->defineFinalizeFunction(_SE(js_cc_scene_Skybox_finalize)); cls->install(); diff --git a/native/cocos/bindings/auto/jsb_scene_auto.h b/native/cocos/bindings/auto/jsb_scene_auto.h index 7abe080276..bc65a8014a 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.h +++ b/native/cocos/bindings/auto/jsb_scene_auto.h @@ -429,6 +429,7 @@ extern se::Class * __jsb_cc_scene_SkyboxInfo_class; // NOLINT bool js_register_cc_scene_SkyboxInfo(se::Object *obj); // NOLINT SE_DECLARE_FUNC(js_scene_SkyboxInfo_activate); +SE_DECLARE_FUNC(js_scene_SkyboxInfo_setReflectionMap); SE_DECLARE_FUNC(js_scene_SkyboxInfo_SkyboxInfo); extern se::Object *__jsb_cc_scene_Skybox_proto; // NOLINT @@ -437,10 +438,12 @@ extern se::Class * __jsb_cc_scene_Skybox_class; // NOLINT bool js_register_cc_scene_Skybox(se::Object *obj); // NOLINT SE_DECLARE_FUNC(js_scene_Skybox_activate); +SE_DECLARE_FUNC(js_scene_Skybox_getReflectionMap); SE_DECLARE_FUNC(js_scene_Skybox_initialize); SE_DECLARE_FUNC(js_scene_Skybox_isUsingConvolutionMap); SE_DECLARE_FUNC(js_scene_Skybox_setDiffuseMaps); SE_DECLARE_FUNC(js_scene_Skybox_setEnvMaps); +SE_DECLARE_FUNC(js_scene_Skybox_setReflectionMaps); SE_DECLARE_FUNC(js_scene_Skybox_setSkyboxMaterial); SE_DECLARE_FUNC(js_scene_Skybox_Skybox); From 5977077c7b7936b7aa0069735e471650b30c4a15 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Thu, 21 Jul 2022 20:59:42 +0800 Subject: [PATCH 071/111] corret metal device limits. includes maxFragmentUniformVectors maxVertexUniformVectors maxUniformBufferBindings (#12127) --- native/cocos/renderer/gfx-metal/MTLDevice.mm | 9 ++++++--- native/cocos/renderer/gfx-metal/MTLUtils.h | 1 + native/cocos/renderer/gfx-metal/MTLUtils.mm | 16 ++++++++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index 59622144c8..40131d8405 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -23,12 +23,12 @@ THE SOFTWARE. ****************************************************************************/ +#import "MTLDevice.h" #import "MTLBuffer.h" #import "MTLCommandBuffer.h" #import "MTLConfig.h" #import "MTLDescriptorSet.h" #import "MTLDescriptorSetLayout.h" -#import "MTLDevice.h" #import "MTLFramebuffer.h" #import "MTLGPUObjects.h" #import "MTLInputAssembler.h" @@ -42,10 +42,11 @@ #import "MTLShader.h" #import "MTLSwapchain.h" #import "MTLTexture.h" +#import "base/Log.h" #import "cocos/bindings/event/CustomEventTypes.h" #import "cocos/bindings/event/EventDispatcher.h" #import "profiler/Profiler.h" -#import "base/Log.h" + namespace cc { namespace gfx { @@ -91,7 +92,9 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { _caps.maxColorRenderTargets = mu::getMaxColorRenderTarget(gpuFamily); _caps.uboOffsetAlignment = mu::getMinBufferOffsetAlignment(gpuFamily); _caps.maxComputeWorkGroupInvocations = mu::getMaxThreadsPerGroup(gpuFamily); - _caps.maxVertexUniformVectors = 255; //no explicit limit on vertex stage. + _caps.maxFragmentUniformVectors = 256; + _caps.maxVertexUniformVectors = 256; + _caps.maxUniformBufferBindings = mu::getMaxUniformBufferBindings(gpuFamily); _maxBufferBindingIndex = mu::getMaxEntriesInBufferArgumentTable(gpuFamily); _icbSuppored = mu::isIndirectCommandBufferSupported(MTLFeatureSet(_mtlFeatureSet)); _isSamplerDescriptorCompareFunctionSupported = mu::isSamplerDescriptorCompareFunctionSupported(gpuFamily); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.h b/native/cocos/renderer/gfx-metal/MTLUtils.h index f64e66fb77..49086ea2d4 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.h +++ b/native/cocos/renderer/gfx-metal/MTLUtils.h @@ -78,6 +78,7 @@ const uint8_t *convertRGB32FToRGBA32F(const uint8_t *source, uint32_t length); NSUInteger highestSupportedFeatureSet(id device); uint32_t getGPUFamily(MTLFeatureSet featureSet); uint32_t getMaxVertexAttributes(uint32_t family); +uint32_t getMaxUniformBufferBindings(uint32_t family); uint32_t getMaxEntriesInBufferArgumentTable(uint32_t family); uint32_t getMaxEntriesInTextureArgumentTable(uint32_t family); uint32_t getMaxEntriesInSamplerStateArgumentTable(uint32_t family); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index 846863812a..37f9793b73 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -1199,6 +1199,22 @@ uint32_t mu::getMaxVertexAttributes(uint32_t family) { } } +uint32_t mu::getMaxUniformBufferBindings(uint32_t family) { + switch (static_cast(family)) { + case GPUFamily::Apple1: + case GPUFamily::Apple2: + case GPUFamily::Apple3: + case GPUFamily::Apple4: + case GPUFamily::Apple5: + case GPUFamily::Apple6: + return 31; + case GPUFamily::Mac1: + case GPUFamily::Mac2: + return 14; + } +} + + uint32_t mu::getMaxEntriesInBufferArgumentTable(uint32_t family) { switch (static_cast(family)) { case GPUFamily::Apple1: From be279ac1ccbca3077e50b789dcddd87ebfc39b42 Mon Sep 17 00:00:00 2001 From: changhua <39176194+changhua0118@users.noreply.github.com> Date: Thu, 21 Jul 2022 21:13:14 +0800 Subject: [PATCH 072/111] fix huawei-agc can not find platformTemplate (#12079) --- scripts/native-pack-tool/source/index.ts | 2 ++ .../source/platforms/huawei-agc.ts | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 scripts/native-pack-tool/source/platforms/huawei-agc.ts diff --git a/scripts/native-pack-tool/source/index.ts b/scripts/native-pack-tool/source/index.ts index c9a39cf0a1..c94499657d 100644 --- a/scripts/native-pack-tool/source/index.ts +++ b/scripts/native-pack-tool/source/index.ts @@ -5,12 +5,14 @@ import { WindowsPackTool } from './platforms/windows'; import { AndroidPackTool } from './platforms/android'; import { OHOSPackTool } from './platforms/ohos'; import { IOSPackTool } from './platforms/ios'; +import { HuaweiAGCPackTool } from './platforms/huawei-agc'; nativePackToolMg.register('ios', new IOSPackTool()); nativePackToolMg.register('mac', new MacPackTool()); nativePackToolMg.register('windows', new WindowsPackTool()); nativePackToolMg.register('android', new AndroidPackTool()); nativePackToolMg.register('ohos', new OHOSPackTool()); +nativePackToolMg.register('huawei-agc', new HuaweiAGCPackTool()); export * from './base/manager'; export * from './base/default'; diff --git a/scripts/native-pack-tool/source/platforms/huawei-agc.ts b/scripts/native-pack-tool/source/platforms/huawei-agc.ts new file mode 100644 index 0000000000..4c546be39a --- /dev/null +++ b/scripts/native-pack-tool/source/platforms/huawei-agc.ts @@ -0,0 +1,26 @@ +import * as fs from 'fs-extra'; +import * as ps from 'path'; + +import { AndroidPackTool } from "./android"; + +export class HuaweiAGCPackTool extends AndroidPackTool { + /** + * 共用 android 平台的流程 + * copyPlatformTemplate 拷贝平台模板倒 native/engine 目录下时,重写为从 android 平台的模板拷贝 agc + */ + protected async copyPlatformTemplate() { + // 原生工程不重复拷贝 TODO 复用前需要做版本检测 + if (!fs.existsSync(this.paths.nativePrjDir)) { + // 拷贝 lite 仓库的 templates/android/build 文件到构建输出目录 + await fs.copy(ps.join(this.paths.nativeTemplateDirInCocos, 'android', 'build'), this.paths.nativePrjDir, { overwrite: false }); + } + // 原生工程不重复拷贝 TODO 复用前需要做版本检测 + if (!fs.existsSync(this.paths.platformTemplateDirInPrj)) { + // 拷贝 lite 仓库的 templates/android/template 文件到构建输出目录 + await fs.copy(ps.join(this.paths.nativeTemplateDirInCocos, 'android', 'template'), this.paths.platformTemplateDirInPrj, { overwrite: false }); + this.writeEngineVersion(); + } else { + this.validateNativeDir(); + } + } +} From e92e3fb6f63d0f4b314615eac535e6347de490fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Thu, 21 Jul 2022 21:19:38 +0800 Subject: [PATCH 073/111] [Optimize] optimize i18n text for editor (#12052) * optimize i18n text for editor * optimize prop name show in editor --- editor/i18n/en/assets.js | 46 +++++++------- editor/i18n/en/components.js | 2 +- editor/i18n/en/localization.js | 112 ++++++++++++++++----------------- editor/i18n/zh/assets.js | 56 ++++++++--------- editor/i18n/zh/localization.js | 106 +++++++++++++++---------------- 5 files changed, 161 insertions(+), 161 deletions(-) diff --git a/editor/i18n/en/assets.js b/editor/i18n/en/assets.js index ef48dcb1fe..b1bc0b4c48 100644 --- a/editor/i18n/en/assets.js +++ b/editor/i18n/en/assets.js @@ -15,12 +15,12 @@ module.exports = { save: 'Save', locate_asset: 'Locate in Assets Panel', 'label-atlas': { - SpriteFrameTip: 'SpriteFrame', + SpriteFrameTip: 'Sprite Frame', ItemWidthTip: 'Item Width', ItemHeightTip: 'Item Height', StartCharTip: 'Start Char', FontSizeTip: 'Font Size', - SpriteFrame: 'SpriteFrame', + SpriteFrame: 'Sprite Frame', ItemWidth: 'Item Width', ItemHeight: 'Item Height', StartChar: 'Start Char', @@ -58,9 +58,9 @@ module.exports = { loadPluginInWeb: 'Load In Web', loadPluginInEditor: 'Load In Editor', loadPluginInNative: 'Load In Native', - simulateGlobals: 'Simulate global variables', + simulateGlobals: 'Simulate Global Variables', executionScopeTip: 'Do not transpile or wrap this plugin script.', - executionScopeEnclosed: 'Simulate global variables', + executionScopeEnclosed: 'Simulate Global Variables', pluginTip: 'Import As Plugin', dependenciesTip: 'Dependencies', globalTip: 'Global', @@ -223,19 +223,19 @@ module.exports = { }, }, dumpMaterials: { - name: 'Dump materials', + name: 'Dump Materials', title: 'Whether to extract material assets out of embedded (sub)assets, so that the assets become editable.', }, materialDumpDir: { - name: 'Material dump directory', + name: 'Material Dump Directory', title: 'The directory to dump the materials.\nDefault to a direct sub-folder named `Materials_${model-file-base-name}` under current path.', }, useVertexColors: { - name: 'Use vertex colors', + name: 'Use Vertex Colors', title: 'Whether to use vertex colors. ', }, depthWriteInAlphaModeBlend: { - name: 'Depth-write if blending', + name: 'Depth-Write If Blending', title: 'Enable depth-write if the alpha mode is set to "BLEND". ', }, skipValidation: { @@ -248,7 +248,7 @@ module.exports = { ok: 'OK', }, ImageRemap: { - remapAs: 'Remap as', + remapAs: 'Remap As', original: 'Original', }, limitMaterialDumpDir: 'The extracted path needs to be scoped to the project path.', @@ -259,7 +259,7 @@ module.exports = { warn: 'Warning: Changing this property may break imported assets that have been using or referencing. ', }, disableMeshSplit: { - name: 'Disable mesh split', + name: 'Disable Mesh Split', title: 'Currently there is a joint-counting-based mesh splitting process during the
' + 'import pipeline to workaround the max uniform vector limit problem for real-time
' + @@ -283,36 +283,36 @@ module.exports = { name: 'Simplification', title: 'Simplification', si: { - name: 'Achieve the ratio R', - title: 'Achieve the ratio R', + name: 'Achieve The Ratio R', + title: 'Achieve The Ratio R', }, sa: { - name: 'Aggressively simplify', - title: 'Aggressively simplify', + name: 'Aggressively Simplify', + title: 'Aggressively Simplify', }, }, scene: { name: 'Scene', title: 'Scene', kn: { - name: 'Keep nodes transform', - title: 'Keep nodes transform', + name: 'Keep Nodes Transform', + title: 'Keep Nodes Transform', }, ke: { - name: 'Keep extras data', - title: 'Keep extras data', + name: 'Keep Extras Data', + title: 'Keep Extras Data', }, }, miscellaneous: { name: 'Miscellaneous', title: 'Miscellaneous', noq: { - name: 'Disable quantization', - title: 'Disable quantization', + name: 'Disable Quantization', + title: 'Disable Quantization', }, v: { - name: 'Verbose output', - title: 'Verbose output', + name: 'Verbose Output', + title: 'Verbose Output', }, }, // eslint-disable-next-line max-len @@ -406,7 +406,7 @@ module.exports = { paste_component_values: 'Paste Component Values', help_url: 'Help Document', - custom_script: 'Custom script', + custom_script: 'Custom Script', }, prefab: { diff --git a/editor/i18n/en/components.js b/editor/i18n/en/components.js index b4d0bcb53b..7b68a87dfc 100644 --- a/editor/i18n/en/components.js +++ b/editor/i18n/en/components.js @@ -22,7 +22,7 @@ module.exports = { 'When the new Prefab system is complete, it will be automatically migrated to the new Prefab system.', }, label: { - font_style_tooltip: "The style of the text, corresponding to the engine's isBold,isItalic,isUnderline", + font_style_tooltip: "The style of the text, corresponding to the engine's Bold, Italic, Underline", }, layer: { confirm_message: 'Do you want to set layer for all child objects as well?', diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 34b7cc869a..85d9a5c15c 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -170,7 +170,7 @@ module.exports = { }, sprite: { gray_scale: 'Whether turn on grayscale rendering mode', - sprite_frame: 'SpriteFrame image to use', + sprite_frame: 'Sprite Frame image to use', atlas: 'Atlas that the image belongs to', type: 'Rendering mode:\n - Simple: Modifying the size will stretch the image as a whole, which is suitable for sequence frame animation and normal images. \n' + @@ -224,7 +224,7 @@ module.exports = { hover_sprite: 'The sprite frame used when the button is in hovered over.', disabled_sprite: 'The sprite frame used when the button is in a disabled sate.', target: - "reference to the Sprite as target's background. When the state of the target changes the sprite's color or spriteFrame will be updated.", + "reference to the Sprite as target's background. When the state of the target changes the sprite's color or sprite frame will be updated.", click_events: 'By changing the number to 1 or more, you can set the receiver and the handler for each click event', }, canvas: { @@ -333,15 +333,15 @@ module.exports = { 'The turning velocity threshold for page turning\nWhen user swipes the PageView quickly, a velocity is calculated based on the swipe distance and time.\nIf the velocity is larger than the threshold, the page will be flipped', }, pageview_indicator: { - spriteFrame: 'The spriteFrame for each element', - direction: 'The location direction of PageViewIndicator', + spriteFrame: 'The sprite frame for each element', + direction: 'The location direction of page view indicator', cell_size: 'The cellSize for each element', spacing: 'The distance between each element', }, particleSystemRenderer: { renderMode: 'Particle render mode', - velocityScale: 'Lerp speed of particle along move direction when render mode is StrecthedBillboard', - lengthScale: 'Lerp length of particle along move direction when render mode is StrecthedBillboard', + velocityScale: 'Lerp speed of particle along move direction when render mode is Stretched Billboard', + lengthScale: 'Lerp length of particle along move direction when render mode is Stretched Billboard', mesh: 'Particle emit mesh', particleMaterial: 'Particle material', trailMaterial: 'Trail material of particle', @@ -354,7 +354,7 @@ module.exports = { color: 'Render color', }, rotationOvertimeModule: { - separateAxes: 'Set rotation of X, Y and Z respectively(not supported now)', + separateAxes: 'Set rotation of X, Y and Z respectively (not supported now)', x: 'Set rotation of X-axis', y: 'Set rotation of Y-axis', z: 'Set rotation of Z-axis', @@ -367,7 +367,7 @@ module.exports = { z: 'How particle size along Z-axis will change during its lifetime', }, textureAnimationModule: { - mode: 'Set mode of texture animation(support Grid only now)', + mode: 'Set mode of texture animation (support Grid only now)', numTilesX: 'Animation frames along X-axis', numTilesY: 'Animation frames along Y-axis', animation: 'Animation play mode', @@ -393,7 +393,7 @@ module.exports = { hover_sprite: 'The Sprite that is used when the Toggle is hovered over.', disabled_sprite: 'The Sprite that is used when the Toggle is in a disabled sate.', target: - "reference to the Sprite as Toggle's background. When the state of the button changes the sprite's color or spriteFrame will be updated.", + "reference to the Sprite as Toggle's background. When the state of the button changes the sprite's color or sprite frame will be updated.", isChecked: 'If this flag is true, the associated checkMark sprite component will be enabled, otherwise the checkMark will be disabled.', checkMark: 'The Sprite component displayed when Toggle is checked.', @@ -419,12 +419,12 @@ module.exports = { sphericalDirectionAmount: 'Lerp value between current emit direction and current move direction', randomPositionAmount: 'Random setting of particle move position(particle will appear beyond emit range)', radius: 'Radius of particle emitter', - radiusThickness: 'Radius thickness of particle emitter(invalid when emitter type is Box):\n - 0 emit from surface;\n - 1 emit from center;\n - 0 ~ 1 emit between center and surface', + radiusThickness: 'Radius thickness of particle emitter (invalid when emitter type is Box):\n - 0 emit from surface;\n - 1 emit from center;\n - 0 ~ 1 emit between center and surface', arcMode: 'Emit mode in the sector range', arcSpread: 'Space margin along arc', arcSpeed: 'Emit speed along arc', length: 'The axis length from the top section of the cone to the bottom', - boxThickness: 'Thickness of particle emitter(only valid when emitter type is Box)', + boxThickness: 'Thickness of particle emitter (only valid when emitter type is Box)', }, slider: { handle: 'The "handle" part of the slider', @@ -448,7 +448,7 @@ module.exports = { x: 'Velocity component along X-axis', y: 'Velocity component along Y-axis', z: 'Velocity component along Z-axis', - speedModifier: 'Speed ​​correction factor(CPU particle supported only)', + speedModifier: 'Speed ​​correction factor (CPU particle supported only)', space: 'Space where velocity calculated', }, widget: { @@ -461,10 +461,10 @@ module.exports = { align_h_center: 'Align to the horizontal midpoint of the target Node', align_v_center: 'Align to the vertical midpoint of the target Node', align_mode: 'Specifies the alignment mode of the Widget, which determines when the widget should refresh at runtime.', - top: 'Top edge postion in pixels. This can be a percentage and a positive or negative value', - bottom: 'Bottom edge postion in pixels. This can be a percentage and a positive or negative value', - left: 'Left edge postion in pixels. This can be a percentage and a positive or negative value', - right: 'Right edge postion in pixels. This can be a percentage and a positive or negative value', + top: 'Top edge position in pixels. This can be a percentage and a positive or negative value', + bottom: 'Bottom edge position in pixels. This can be a percentage and a positive or negative value', + left: 'Left edge position in pixels. This can be a percentage and a positive or negative value', + right: 'Right edge position in pixels. This can be a percentage and a positive or negative value', horizontal_center: 'Horizontal midpoint offset in pixels, This can be a percentage and a positive or negative value', vertical_center: 'Vertical midpoint offset in pixels, This can be a percentage and a positive or negative value', }, @@ -497,9 +497,9 @@ module.exports = { sync_tips: 'Synchronize the parameters in the File to Custom', }, editbox: { - string: 'The initial input text of EditBox.', - backgroundImage: 'The background image of EditBox.', - returnType: 'The keyboard return type of EditBox. This is useful for keyboard of mobile device.', + string: 'The initial input text of Edit Box.', + backgroundImage: 'The background image of Edit Box.', + returnType: 'The keyboard return type of Edit Box. This is useful for keyboard of mobile device.', input_flag: 'Specify the input flag: password or capitalize word. ', input_mode: 'Specify the input mode: multiline or single line.', font_size: 'The font size of input label.', @@ -524,7 +524,7 @@ module.exports = { clip: 'The local video clip', playOnAwake: 'Whether the video start playing automatically after loaded?', volume: 'The volume of the video.(0.0 ~ 1.0)', - mute: 'Mutes the VideoPlayer. Mute sets the volume=0, Un-Mute restore the original volume.', + mute: 'Mutes the VideoPlayer. Mute sets the volume = 0, Un-Mute restore the original volume.', playbackRate: 'The Video playback rate', loop: 'Whether the video should be played again at the end', keepAspectRatio: 'Whether keep the aspect ration of the original video.', @@ -543,16 +543,16 @@ module.exports = { horizontal_align: 'Horizontal alignment', vertical_align: 'Vertical alignment', font_size: 'Font size, in points', - font: 'Custom TTF font of RichText', - font_family:'Custom System font of RichText', + font: 'Custom TTF font of Rich Text', + font_family:'Custom System font of Rich Text', use_system_font: 'Using system font', cache_mode: 'The cache mode of label. This mode only supports system fonts.', max_width: 'The maximize width of RichText, pass 0 means not limit the maximize width.', line_height: 'Line height, in points', image_atlas: - 'The image atlas for the img tag. For each src value in the img tag, there should be a valid spriteFrame in the image atlas.', + 'The image atlas for the img tag. For each src value in the img tag, there should be a valid sprite frame in the image atlas.', handleTouchEvent: - 'Once checked, the RichText will block all input events (mouse and touch) within the bounding box of the node, preventing the input from penetrating into the underlying node.', + 'Once checked, the Rich Text will block all input events (mouse and touch) within the bounding box of the node, preventing the input from penetrating into the underlying node.', }, UICoordinateTracker: { target: 'Target node', @@ -610,8 +610,8 @@ module.exports = { preview: 'Play particle in edit mode', custom: 'If set custom to true, then use custom properties instead of read particle file', file: 'The plist file', - spriteFrame: 'SpriteFrame of Particle System', - texture: 'Texture of Particle System, readonly, please use spriteFrame to setup new texture', + spriteFrame: 'Sprite Frame of Particle System', + texture: 'Texture of Particle System, readonly, please use Sprite Frame to setup new texture', particleCount: 'Current quantity of particles that are being simulated', srcBlendFactor: 'Specify the source Blend Factor', dstBlendFactor: 'Specify the destination Blend Factor', @@ -640,7 +640,7 @@ module.exports = { rotationIsDir: 'Indicate whether the rotation of each particle equals to its direction. Only available in Gravity mode', startRadius: 'Starting radius and variation of the particles. Only available in Radius mode', endRadius: 'Ending radius and variation of the particles. Only available in Radius mode', - rotatePerS: 'Number of degress to rotate a particle around the source pos per second and variation. Only available in Radius mode', + rotatePerS: 'Number of degrees to rotate a particle around the source pos per second and variation. Only available in Radius mode', capacity: 'Maximum particle amount that the system can generate', scaleSpace: 'Scale space', startSize3D: 'Set start size of X, Y and Z respectively if true', @@ -656,11 +656,11 @@ module.exports = { startLifetime: 'Life time of the particle', duration: 'Particle duration', loop: 'Loop animation', - prewarm: 'Animation plays from the end state of last round(only valid when loop activated)', + prewarm: 'Animation plays from the end state of last round (only valid when loop activated)', simulationSpace: 'The particle space your calculation is done in', simulationSpeed: 'Update ratio of particles', playOnAwake: 'Play on awake', - gravityModifier: 'How much particles get affected by the gravity(only support on CPU)', + gravityModifier: 'How much particles get affected by the gravity (only support on CPU)', rateOverTime: 'Number of particles emitted per second', rateOverDistance: 'Number of particles emitted per unit distance', bursts: 'Emit a given number of particles at a certain point in time', @@ -669,14 +669,14 @@ module.exports = { sizeOvertimeModule: 'Particle size module', velocityOvertimeModule: 'Particle velocity module', forceOvertimeModule: 'Particle acceleration module', - limitVelocityOvertimeModule: 'Particle velocity limitation module(only support on CPU)', + limitVelocityOvertimeModule: 'Particle velocity limitation module (only support on CPU)', rotationOvertimeModule: 'Particle rotation module', textureAnimationModule: 'Texture animation module', - trailModule: 'Trail module(only support on CPU)', + trailModule: 'Trail module (only support on CPU)', renderer: 'Particle render module', - renderCulling: 'Whether to enable the particle culling feature. If enabled, a particle emitter bounding box will be generated, and the particle emitter will be culled if the bounding box is not in the visible range of the camera. Please refer to the cullingMode option below for the behavior settings after particle culling.', - cullingMode: 'Sets the behavior of the particle emitter after it has been culled. The available options include Pause, Pause and Catchup, and Always Simulate.\nWhen the Pause is selected, the particle will pause the simulation if the particle emitter bounding box is not in the camera\'s visible range. If it resumes visibility, the particle will continue simulating at the time of last pause.\nWhen the Pause and Catchup is selected, if the particle emitter bounding box is not in the camera\'s visible range, the particle will pause the simulation. If visible again, the particle will start simulating at the current time.\nWhen the Always Simulate is selected, the particle will keep simulating regardless of whether the particle emitter bounding box is in the camera\'s visible range, but will not render when it is not in the camera\'s visible range.', - alignSpace: 'Particle alignment space, the available options include View Space, World Space and Local Space.\nWhen the View Space is selected, the rotation direction of the particle mesh will follow the camera\'s view direction.\nWhen the World Space is selected, the direction of the particle mesh will use the world space rotation direction of the node where the particle emitter is located.\nWhen the Local Space is selected, the particle mesh will use the local space rotation direction of the node where the particle emitter is located.', + renderCulling: 'Whether to enable the particle culling feature. \nIf enabled, a particle emitter bounding box will be generated, and the particle emitter will be culled if the bounding box is not in the visible range of the camera. Please refer to the cullingMode option below for the behavior settings after particle culling.', + cullingMode: 'Sets the behavior of the particle emitter after it has been culled. \nThe available options include Pause, Pause and Catchup, and Always Simulate.\nWhen the Pause is selected, the particle will pause the simulation if the particle emitter bounding box is not in the camera\'s visible range. If it resumes visibility, the particle will continue simulating at the time of last pause.\nWhen the Pause and Catchup is selected, if the particle emitter bounding box is not in the camera\'s visible range, the particle will pause the simulation. If visible again, the particle will start simulating at the current time.\nWhen the Always Simulate is selected, the particle will keep simulating regardless of whether the particle emitter bounding box is in the camera\'s visible range, but will not render when it is not in the camera\'s visible range.', + alignSpace: 'Particle alignment space, the available options include View Space. \nWorld Space and Local Space.\nWhen the View Space is selected, the rotation direction of the particle mesh will follow the camera\'s view direction.\nWhen the World Space is selected, the direction of the particle mesh will use the world space rotation direction of the node where the particle emitter is located.\nWhen the Local Space is selected, the particle mesh will use the local space rotation direction of the node where the particle emitter is located.', aabbHalfX: 'Half width of the emitter bounding box', aabbHalfY: 'Half height of the emitter bounding box', aabbHalfZ: 'Half length of the emitter bounding box', @@ -687,7 +687,7 @@ module.exports = { spriteFrame: 'The mask image', inverted: 'The Reverse mask (Not supported Canvas Mode)', alphaThreshold: - 'The alpha threshold,The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold (Not supported Canvas Mode)', + 'The alpha threshold, The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold (Not supported Canvas Mode)', segements: 'The segements for ellipse mask', }, physics: { @@ -695,13 +695,13 @@ module.exports = { enabledContactListener: 'Should enabled contact listener. When a collision is trigger, the collision callback will only be called when enabled contact listener.', bullet: 'Is this a fast moving body that should be prevented from tunneling through other moving bodies?', - type: 'Rigidbody type : Static, Kinematic, Dynamic or Animated.', + type: 'Rigid body type : Static, Kinematic, Dynamic or Animated.', allowSleep: 'Set this flag to false if this body should never fall asleep. Note that this increases CPU usage.', gravityScale: 'Scale the gravity applied to this body.', linearDamping: - 'Linear damping is use to reduce the linear velocity. The damping parameter can be larger than 1, but the damping effect becomes sensitive to the time step when the damping parameter is large.', + 'Linear damping is use to reduce the linear velocity.\nThe damping parameter can be larger than 1, but the damping effect becomes sensitive to the time step when the damping parameter is large.', angularDamping: - 'Angular damping is use to reduce the angular velocity. The damping parameter can be larger than 1 but the damping effect becomes sensitive to the time step when the damping parameter is large.', + 'Angular damping is use to reduce the angular velocity.\nThe damping parameter can be larger than 1 but the damping effect becomes sensitive to the time step when the damping parameter is large.', linearVelocity: "The linear velocity of the body's origin in world co-ordinates", angularVelocity: 'The angular velocity of the body.', fixedRotation: 'Should this body be prevented from rotating?', @@ -712,31 +712,31 @@ module.exports = { sensor: 'A sensor collider collects contact information but never generates a collision response', friction: 'The friction coefficient, usually in the range [0,1].', restitution: 'The restitution (elasticity) usually in the range [0,1].', - anchor: 'The anchor of the rigidbody.', - connectedAnchor: 'The anchor of the connected rigidbody.', - connectedBody: 'The rigidbody to which the other end of the joint is attached.', + anchor: 'The anchor of the rigid body.', + connectedAnchor: 'The anchor of the connected rigid body.', + connectedBody: 'The rigid body to which the other end of the joint is attached.', collideConnected: 'Should the two rigid bodies connected with this joint collide with each other?', distance: 'The distance separating the two ends of the joint.', frequency: 'The spring frequency.', dampingRatio: 'The damping ratio.', - linearOffset: 'The linear offset from connected rigidbody to rigidbody.', - angularOffset: 'The angular offset from connected rigidbody to rigidbody.', - maxForce: 'The maximum force can be applied to rigidbody.', - maxTorque: 'The maximum torque can be applied to rigidbody.', + linearOffset: 'The linear offset from connected rigid body to rigid body.', + angularOffset: 'The angular offset from connected rigid body to rigid body.', + maxForce: 'The maximum force can be applied to rigid body.', + maxTorque: 'The maximum torque can be applied to rigid body.', correctionFactor: 'The position correction factor in the range [0,1].', - mouseRegion: "The node used to register touch evnet. If this is null, it will be the joint's node.", - target: 'The target point. The mouse joint will move choosed rigidbody to target point.', - localAxisA: 'The local joint axis relative to rigidbody.', + mouseRegion: "The node used to register touch event. If this is null, it will be the joint's node.", + target: 'The target point. The mouse joint will move chosen rigid body to target point.', + localAxisA: 'The local joint axis relative to rigid body.', enableLimit: 'Enable joint distance limit?', enableMotor: 'Enable joint motor?', lowerLimit: 'The lower joint limit.', upperLimit: 'The upper joint limit.', - maxMotorForce: 'The maxium force can be applied to rigidbody to rearch the target motor speed.', + maxMotorForce: 'The maximum force can be applied to rigid body to reach the target motor speed.', motorSpeed: 'The expected motor speed.', referenceAngle: 'The reference angle. An angle between bodies considered to be zero for the joint angle.', lowerAngle: 'The lower angle.', upperAngle: 'The upper angle.', - maxMotorTorque: 'The maxium torque can be applied to rigidbody to rearch the target motor speed.', + maxMotorTorque: 'The maximum torque can be applied to rigid body to reach the target motor speed.', maxLength: 'The max length.', offset: 'Position offset', size: 'Box size', @@ -747,11 +747,11 @@ module.exports = { }, block_input_events: { brief_help: - 'This component will block all input events, preventing the input from penetrating to other nodes below the screen, typically for the background of the top-level UI of the screen.', + 'This component will block all input events, \npreventing the input from penetrating to other nodes below the screen, \ntypically for the background of the top-level UI of the screen.', }, tiledtile: { - row: 'Specify the TiledTile horizontal coordinate,use map tile as the unit.', - column: 'Specify the TiledTile vertical coordinate,use map tile as the unit.', + row: 'Specify the TiledTile horizontal coordinate, use map tile as the unit.', + column: 'Specify the TiledTile vertical coordinate, use map tile as the unit.', gid: 'Specify the TiledTile gid.', layer: 'Specify which TiledLayer the TiledTile belong to.', }, @@ -900,8 +900,8 @@ module.exports = { description: "Spine Animation support.", }, dragon_bones: { - label: "DragonBones", - description: "DragonBones support.", + label: "Dragon Bones", + description: "Dragon Bones support.", }, animation: { label: "Basic Animation", @@ -969,7 +969,7 @@ module.exports = { plane_normal: 'The normal to the plane in the local coordinate system', plane_constant: 'The distance of the plane moving along the normal from the origin in the local coordinate system', mesh_mesh: 'Mesh resources used by collider', - mesh_convex: 'Whether to use convex hull approximation instead, the number of vertices should be less than 255, and the dynamics can be supported after turning on', + mesh_convex: 'Whether to use convex hull approximation instead, \nthe number of vertices should be less than 255, \nand the dynamics can be supported after turning on', terrain_terrain: 'Terrain resources used by collider', simplex_shapeType: 'Simplex type, point, line, triangle, tetrahedron', simplex_vertex0: 'Vertex 0 of the shape', diff --git a/editor/i18n/zh/assets.js b/editor/i18n/zh/assets.js index 83878c106b..600aaf4fb5 100644 --- a/editor/i18n/zh/assets.js +++ b/editor/i18n/zh/assets.js @@ -15,12 +15,12 @@ module.exports = { save: '保存', locate_asset: '资源面板上定位该资源', 'label-atlas': { - SpriteFrameTip: 'SpriteFrame', + SpriteFrameTip: 'Sprite Frame', ItemWidthTip: 'Item Width', ItemHeightTip: 'Item Height', StartCharTip: 'Start Char', FontSizeTip: 'Font Size', - SpriteFrame: 'SpriteFrame', + SpriteFrame: 'Sprite Frame', ItemWidth: 'Item Width', ItemHeight: 'Item Height', StartChar: 'Start Char', @@ -69,7 +69,7 @@ module.exports = { loadPluginInWebTip: 'Load In Web', loadPluginInEditorTip: 'Load In Editor', loadPluginInNativeTip: 'Load In Native', - simulateGlobalsTip: 'Simulate global variables', + simulateGlobalsTip: 'Simulate Global Variables', }, scene: { asyncLoadAssets: '异步加载', @@ -129,13 +129,13 @@ module.exports = { edit: 'Edit', editTip: '编辑', meshType: 'Mesh Type', - meshTypeTip: 'SpriteFrame 生成的网格类型', + meshTypeTip: 'Sprite Frame 生成的网格类型', pixelsToUnit: 'Pixels To Unit', - pixelsToUnitTip: 'SpriteFrame 像素对应世界空间内单位长度的比例尺', + pixelsToUnitTip: 'Sprite Frame 像素对应世界空间内单位长度的比例尺', pivotX: 'Pivot X', - pivotXTip: 'SpriteFrame 本地坐标系原点的 X 轴位置', + pivotXTip: 'Sprite Frame 本地坐标系原点的 X 轴位置', pivotY: 'Pivot Y', - pivotYTip: 'SpriteFrame 本地坐标系原点的 Y 轴位置', + pivotYTip: 'Sprite Frame 本地坐标系原点的 Y 轴位置', }, texture: { anisotropy: 'Anisotropy', @@ -151,7 +151,7 @@ module.exports = { wrapModeT: 'Wrap Mode T', wrapModeTTip: '像素对纹理在 T(V)方向上的映射模式', modeWarn: - '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 repeat 过滤模式,运行时会自动改为 clamp-to-edge 模式,这会使材质的 tilingOffset 等属性完全失效。', + '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 Repeat 过滤模式,运行时会自动改为 Clamp-To-Edge 模式,这会使材质的 Tiling Offset 等属性完全失效。', }, fbx: { browse: '更换贴图', @@ -237,7 +237,7 @@ module.exports = { }, depthWriteInAlphaModeBlend: { name: '混合模式下的深度写入', - title: '当 alpha 模式为 "BLEND" 时开启深度写入。', + title: '当 Alpha 模式为 "BLEND" 时开启深度写入。', }, skipValidation: { name: '跳过验证', @@ -245,7 +245,7 @@ module.exports = { }, }, addEvent: { - shouldSave: '新建的 clip 需要先提交修改后,才能添加/编辑事件', + shouldSave: '新建的 Clip 需要先提交修改后,才能添加/编辑事件', ok: '知道了', }, ImageRemap: { @@ -262,10 +262,10 @@ module.exports = { disableMeshSplit: { name: '是否禁用 Mesh 拆分', title: - '为了解决实时骨骼动画系统下 uniform vector 数量限制问题,
' + + '为了解决实时骨骼动画系统下 Uniform Vector 数量限制问题,
' + '目前在资源导入期会根据骨骼数量做拆分,这会对其他系统也产生影响。
' + '如果确定不会使用实时计算模式 (对应 SkeletalAnimation 组件的
' + - 'useBakedAnimation 选项未勾选时),可以勾选此项以提升性能。
' + + 'UseBakedAnimation 选项未勾选时),可以勾选此项以提升性能。
' + '但注意改变此选项会影响生成的 prefab 内容,需要对应更新场景中的引用。
' + '后续重构会移除此流程。', }, @@ -282,36 +282,36 @@ module.exports = { name: 'Simplification', title: 'Simplification', si: { - name: 'Achieve the ratio R', - title: 'Achieve the ratio R', + name: 'Achieve The Ratio R', + title: 'Achieve The Ratio R', }, sa: { - name: 'Aggressively simplify', - title: 'Aggressively simplify', + name: 'Aggressively Simplify', + title: 'Aggressively Simplify', }, }, scene: { name: 'Scene', title: 'Scene', kn: { - name: 'Keep nodes transform', - title: 'Keep nodes transform', + name: 'Keep Nodes Transform', + title: 'Keep Nodes Transform', }, ke: { - name: 'Keep extras data', - title: 'Keep extras data', + name: 'Keep Extras Data', + title: 'Keep Extras Data', }, }, miscellaneous: { name: 'Miscellaneous', title: 'Miscellaneous', noq: { - name: 'Disable quantization', - title: 'Disable quantization', + name: 'Disable Quantization', + title: 'Disable Quantization', }, v: { - name: 'Verbose output', - title: 'Verbose output', + name: 'Verbose Output', + title: 'Verbose Output', }, }, warn: '警告:优化后,网格资源的数量和名称会发生改变,这将会造成组件引用的资源丢失,请及时手动更新;(另外,对于模型资源中预生成的预制体,资源同步机制会自动更新)', @@ -349,11 +349,11 @@ module.exports = { wrapModeT: 'Wrap Mode T', wrapModeTTip: 'Wrap Mode T', modeWarn: - '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 repeat 过滤模式,运行时会自动改为 clamp-to-edge 模式,这会使材质的 tilingOffset 等属性完全失效。', + '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 Repeat 过滤模式,运行时会自动改为 Clamp-To-Edge 模式,这会使材质的 Tiling Offset 等属性完全失效。', }, material: { - 'fail-to-load-custom-inspector': 'material: 自定义 effect {effect} 的 inspector 加载失败', - 'illegal-inspector-url': "Inspector的路径不合法", + 'fail-to-load-custom-inspector': 'Material: 自定义 Effect {effect} 的 Inspector 加载失败', + 'illegal-inspector-url': "Inspector 的路径不合法", }, animationGraph: { edit: '编辑', @@ -362,7 +362,7 @@ module.exports = { importSkeleton: '导入骨骼', clearAllNodes: '清空', clearAllNodesWarn: '确定清空所有遮罩数据吗?', - illegalFbx: '导入骨骼失败:此 fbx 文件不含有 prefab 子资源。', + illegalFbx: '导入骨骼失败:此 FBX 文件不含有 Prefab 子资源。', nodeEnableTip: '是否启用该节点及其子孙节点
按住 Alt + 点击,只切换自身的状态。', }, multipleWarning: '不支持此类型资源的多选编辑', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 9fc10844e5..f4855446b4 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -102,7 +102,7 @@ module.exports = { saturation: '阴影饱和度,建议设置为 1.0。若需要减小方向光阴影的饱和程度,推荐通过增加环境光来实现,而不是调节该值。', pcf: '开启软阴影,目前支持 HARD(硬采样)、SOFT(4 倍采样)、SOFT_2X(9 倍采样)类型', bias: '增加深度偏移值(世界空间单位)可以有效消除阴影摩尔纹,但是过大的值可能造成漏光现象', - normalBias: '法线深度偏移值(世界空间单位),可以消除物体表面朝向平行于阳光方向的阴影摩尔纹,防止曲面出现锯齿状;但是过大的值可能会造成阴影位置偏差', + normalBias: '法线深度偏移值(世界空间单位),可以消除物体表面朝向平行于阳光方向的阴影摩尔纹,\n防止曲面出现锯齿状;但是过大的值可能会造成阴影位置偏差', shadowMapSize: '阴影贴图分辨率,目前支持 Low_256x256、Medium_512x512、High_1024x1024、Ultra_2048x2048 四种精度的纹理', fixedArea: '切换固定区域和 CSM 模式。固定区域是一种旧模式,我们并不推荐使用。勾选该项则开启 CSM 模式,该模式下阴影会跟随方向光节点的位置,在方向光包围盒附近分布,而非跟随相机。', near: '固定区域开始值', @@ -116,7 +116,7 @@ module.exports = { default_clip: '在勾选自动播放或调用 play() 时默认播放的动画 clip。', clips: '通过脚本可以访问并播放的 AnimationClip 列表', play_on_load: '是否在运行游戏后自动播放默认动画 clip。', - use_baked_animation: '是否使用预烘焙动画,默认启用,可以大幅提高运行效时率,但所有动画效果会被彻底固定,不支持任何形式的编辑', + use_baked_animation: '是否使用预烘焙动画,默认启用,可以大幅提高运行效时率,\n但所有动画效果会被彻底固定,不支持任何形式的编辑', sockets: '当前动画组件维护的挂点数组。要挂载自定义节点到受动画驱动的骨骼上,必须先在此注册挂点', }, audio: { @@ -168,25 +168,25 @@ module.exports = { sprite: { gray_scale: '是否开启灰度渲染模式', atlas: '图片资源所属的 Atlas 图集资源', - sprite_frame: '渲染 Sprite 使用的 SpriteFrame 图片资源', + sprite_frame: '渲染 Sprite 使用的 Sprite Frame 图片资源', type: '渲染模式:\n - 普通(Simple):修改尺寸会整体拉伸图像,适用于序列帧动画和普通图像 \n' + - '- 九宫格(Sliced):修改尺寸时四个角的区域不会拉伸,适用于 UI 按钮和面板背景 \n' + - '- 平铺(Tiled):修改尺寸时会不断平铺原始大小的图片 \n' + - '- 填充(Filled):设置一定的填充起始位置和方向,能够以一定比率剪裁显示图片', + '- 九宫格 Sliced 修改尺寸时四个角的区域不会拉伸,适用于 UI 按钮和面板背景 \n' + + '- 平铺 Tiled 修改尺寸时会不断平铺原始大小的图片 \n' + + '- 填充 Filled 设置一定的填充起始位置和方向,能够以一定比率剪裁显示图片', original_size: '是否使用图片资源的原始尺寸作为 Sprite 节点的 size', edit_button: '编辑', select_button: '选择', select_tooltip: '选择 Atlas 中的其他 SpriteFrame', edit_tooltip: '打开 Sprite 编辑器,设置九宫格等数据', - fill_type: '填充方向,可以选择横向(Horizontal),纵向(Vertical)和扇形(Radial)三种方向', + fill_type: '填充方向,可以选择横向 Horizontal,纵向 Vertical 和扇形 Radial 三种方向', fill_center: '扇形填充时,指定扇形的中心点,取值范围 0 ~ 1', fill_start: '填充起始位置,输入一个 0 ~ 1 之间的小数表示起始位置的百分比', fill_range: '填充总量,取值范围 0 ~ 1 指定显示图像范围的百分比', src_blend_factor: '混合显示两张图片时,源图片的取值模式', dst_blend_factor: '混合显示两张图片时,目标图片的取值模式', size_mode: - '指定 Sprite 所在节点的尺寸,CUSTOM 表示自定义尺寸,TRIMMED 表示取原始图片剪裁透明像素后的尺寸,RAW 表示取原始图片未剪裁的尺寸', + '指定 Sprite 所在节点的尺寸\nCUSTOM 表示自定义尺寸\nTRIMMED 表示取原始图片剪裁透明像素后的尺寸\nRAW 表示取原始图片未剪裁的尺寸', trim: '节点约束框内是否包括透明像素区域,勾选此项会去除节点约束框内的透明区域', }, UIOpacity: { @@ -214,7 +214,7 @@ module.exports = { duration: '按钮颜色变化或者缩放变化的过渡时间', zoom_scale: '当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale, zoomScale 可以为负数', auto_gray_effect: - '如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰', + '如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,\n会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰', normal_sprite: '普通状态的按钮背景图资源', pressed_sprite: '按下状态的按钮背景图资源', hover_sprite: '悬停状态的按钮背景图资源', @@ -223,10 +223,10 @@ module.exports = { click_events: '按钮点击事件的列表。先将数量改为1或更多,就可以为每个点击事件设置接受者和处理方法', }, canvas: { - camera: '2D渲染相机', + camera: '2D 渲染相机', align: '自动为 camera 计算参数', design_resolution: - '设计分辨率是游戏在设计时使用的分辨率参考,以像素为单位,通过下面的适配策略,可以在不同分辨率的设备上按照一定的方式对 Canvas 进行整体缩放来适配。', + '设计分辨率是游戏在设计时使用的分辨率参考,以像素为单位,通过下面的适配策略,\n可以在不同分辨率的设备上按照一定的方式对 Canvas 进行整体缩放来适配。', fit_height: '自动缩放 Canvas 使设计分辨率的高度充满设备屏幕的高度', fit_width: '自动缩放 Canvas 使设计分辨率的宽度充满设备屏幕的宽度', }, @@ -299,18 +299,18 @@ module.exports = { scrollbar: { handle: '作为当前滚动区域位置显示的滑块 Sprite', direction: 'ScrollBar的滚动方向', - auto_hide: '是否在没有滚动动作时自动隐藏 ScrollBar', - auto_hide_time: '没有滚动动作后经过多久会自动隐藏\n注意:只有当 “enableAutoHide” 为 true 时,才有效', + auto_hide: '是否在没有滚动动作时自动隐藏 Scroll Bar', + auto_hide_time: '没有滚动动作后经过多久会自动隐藏\n注意:只有当 Enable Auto Hide 为 true 时才有效', }, scrollview: { content: '包含可滚动展示内容的节点引用', horizontal: '是否开启水平滚动', vertical: '是否开启垂直滚动', inertia: '是否开启滚动惯性', - brake: '开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止', + brake: '开启惯性后,在用户停止触摸后滚动多快停止,0 表示永不停止,1 表示立刻停止', elastic: '是否允许滚动内容超过边界,并在停止触摸后回弹', - horizontal_bar: '水平滚动的 ScrollBar', - vertical_bar: '垂直滚动的 ScrollBar', + horizontal_bar: '水平滚动的滚动条', + vertical_bar: '垂直滚动的滚动条', bounceDuration: '回弹持续的时间,0 表示将立即反弹', scrollEvents: '滚动视图的事件回调函数', cancelInnerEvents: '滚动行为是否会取消子节点上注册的触摸事件', @@ -319,7 +319,7 @@ module.exports = { sizeMode: '页面视图中每个页面大小类型', direction: '页面视图滚动方向', scrollThreshold: '滚动临界值,默认单位百分比,当拖拽超出该数值时,松开会自动滚动下一页,小于时则还原', - pageTurningEventTiming: '设置 PageView 页面自动滚动动画结束的阈值,修改此值可以调整 PageView 事件的发送时机。', + pageTurningEventTiming: '设置 Page View 页面自动滚动动画结束的阈值,\n修改此值可以调整 Page View 事件的发送时机。', indicator: '页面视图指示器组件', pageTurningSpeed: '每个页面翻页时所需时间。单位:秒', pageEvents: '页面视图的事件回调函数', @@ -334,8 +334,8 @@ module.exports = { }, particleSystemRenderer: { renderMode: '设定粒子生成模式', - velocityScale: '在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按速度大小进行拉伸', - lengthScale: '在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按粒子大小进行拉伸', + velocityScale: '在粒子生成方式为 Stretched Billboard 时,对粒子在运动方向上按速度大小进行拉伸', + lengthScale: '在粒子生成方式为 Stretched Billboard 时,对粒子在运动方向上按粒子大小进行拉伸', mesh: '粒子发射的模型', particleMaterial: '粒子使用的材质', trailMaterial: '拖尾使用的材质', @@ -368,8 +368,8 @@ module.exports = { frameOverTime: '一个周期内动画播放的帧与时间变化曲线', startFrame: '从第几帧开始播放,时间为整个粒子系统的生命周期', cycleCount: '一个生命周期内播放循环的次数', - randomRow: '随机从动画贴图中选择一行以生成动画,\n此选项仅在动画播放方式为 SingleRow 时生效', - rowIndex: '从动画贴图中选择特定行以生成动画,\n此选项仅在动画播放方式为 SingleRow 时且禁用 randomRow 时可用', + randomRow: '随机从动画贴图中选择一行以生成动画,\n此选项仅在动画播放方式为 Single Row 时生效', + rowIndex: '从动画贴图中选择特定行以生成动画,\n此选项仅在动画播放方式为 Single Row 时且禁用 Random Row 时可用', }, toggle: { interactable: 'Toggle 是否可交互,这一项未选中时,Toggle 处在禁用状态', @@ -380,9 +380,9 @@ module.exports = { hover_color: '悬停状态的 Toggle 背景颜色', disabled_color: '禁用状态的 Toggle 背景颜色', duration: 'Toggle 颜色变化或者缩放变化的过渡时间', - zoom_scale: '当用户点击 Toggle 后,Toggle 会缩放到一个值,这个值等于 Toggle 原始 scale * zoomScale, zoomScale 可以为负数', + zoom_scale: '当用户点击 Toggle 后,Toggle 会缩放到一个值,\n这个值等于 Toggle 原始 scale * zoomScale, zoomScale 可以为负数', auto_gray_effect: - '如果这个标记为 true,当 toggle 的 interactable 属性为 false 的时候,会使用内置 shader 让 toggle 的 target 节点的 sprite 组件变灰', + '如果这个标记为 true,当 toggle 的 interactable 属性为 false 的时候,\n会使用内置 shader 让 toggle 的 target 节点的 sprite 组件变灰', normal_sprite: '普通状态的 Toggle 背景图资源', pressed_sprite: '按下状态的 Toggle 背景图资源', hover_sprite: '悬停状态的 Toggle 背景图资源', @@ -391,7 +391,7 @@ module.exports = { isChecked: '如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。', checkMark: 'Toggle 处于选中状态时显示的精灵图片', toggleGroup: - 'Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox,否则,Toggle 是一个 RadioButton。', + 'Toggle 所属的 Toggle Group,这个属性是可选的。\n如果这个属性为 null,则 Toggle 是一个 CheckBox,否则,Toggle 是一个 Radio Button。', check_events: 'Toggle 按钮的点击事件列表', }, toggle_group: { @@ -428,8 +428,8 @@ module.exports = { mode: 'Particle在每个粒子的运动轨迹上形成拖尾效果', lifeTime: '拖尾的生命周期', minParticleDistance: '粒子每生成一个拖尾节点所运行的最短距离', - space: '拖尾所在的坐标系,World在世界坐标系中运行,Local在本地坐标系中运行', - textureMode: '贴图在拖尾上的展开形式,Stretch贴图覆盖在整条拖尾上,Repeat贴图覆盖在一段拖尾上', + space: '拖尾所在的坐标系,\nWorld 在世界坐标系中运行,\nLocal 在本地坐标系中运行', + textureMode: '贴图在拖尾上的展开形式,\nStretch 贴图覆盖在整条拖尾上,\nRepeat 贴图覆盖在一段拖尾上', widthFromParticle: '拖尾宽度继承自粒子大小', widthRatio: '拖尾宽度,如果继承自粒子则是粒子大小的比例', colorFromParticle: '拖尾颜色是否继承自粒子', @@ -539,8 +539,8 @@ module.exports = { cache_mode: '文本缓存模式, 该模式只支持系统字体', max_width: '富文本的最大宽度, 传 0 的话意味着必须手动换行.', line_height: '字体行高, 单位是 point', - image_atlas: '对于 img 标签里面的 src 属性名称,都需要在 imageAtlas 里面找到一个有效的 spriteFrame,否则 img tag 会判定为无效', - handleTouchEvent: '选中此选项后,RichText 将阻止节点边界框中的所有输入事件(鼠标和触摸),从而防止输入事件穿透到底层节点', + image_atlas: '对于 img 标签里面的 src 属性名称,都需要在 image atlas 里面找到一个有效的 sprite frame,否则 img tag 会判定为无效', + handleTouchEvent: '选中此选项后,rich text 将阻止节点边界框中的所有输入事件(鼠标和触摸),从而防止输入事件穿透到底层节点', }, UICoordinateTracker: { target: '目标对象', @@ -564,12 +564,12 @@ module.exports = { premultipliedAlpha: '是否启用贴图预乘', }, dragon_bones: { - dragon_bones_asset: '骨骼信息数据,拖拽 DragonBones 导出的骨骼动画信息 json 资源到这里来开始使用', - dragon_bones_atlas_asset: 'Texture 信息数据,拖拽 DragonBones 导出的 Texture 信息 json 资源到这里来开始使用', + dragon_bones_asset: '骨骼信息数据,拖拽 Dragon Bones 导出的骨骼动画信息 json 资源到这里来开始使用', + dragon_bones_atlas_asset: 'Texture 信息数据,拖拽 Dragon Bones 导出的 Texture 信息 json 资源到这里来开始使用', armature_name: '当前的 Armature 名称', animation_name: '当前播放的动画名称', time_scale: '当前骨骼中所有动画的时间缩放率', - play_times: '播放默认动画的循环次数\n-1 表示使用配置文件中的默认值\n0 表示无限循环\n>0 表示循环次数', + play_times: '播放默认动画的循环次数\n - 1 表示使用配置文件中的默认值\n0 表示无限循环\n > 0 表示循环次数', debug_bones: '是否显示 bone 的 debug 信息', }, motionStreak: { @@ -595,7 +595,7 @@ module.exports = { custom: '是否自定义粒子属性', file: 'plist 格式的粒子配置文件', spriteFrame: '粒子贴图定义', - texture: '粒子贴图,只读属性,请使用 spriteFrame 属性来替换贴图', + texture: '粒子贴图,只读属性,请使用 sprite Frame 属性来替换贴图', particleCount: '当前播放的粒子数量', srcBlendFactor: '指定原图混合模式', dstBlendFactor: '指定目标的混合模式', @@ -627,15 +627,15 @@ module.exports = { rotatePerS: '粒子每秒围绕起始点的旋转角度及变化范围,只有在半径模式下可用', capacity: '粒子系统能生成的最大粒子数量', scaleSpace: '选择缩放坐标系', - startSize3D: '是否分别设置粒子X,Y和Z轴的初始大小', - startSizeX: 'X轴初始大小', - startSizeY: 'Y轴初始大小', - startSizeZ: 'Z轴初始大小', + startSize3D: '是否分别设置粒子 X, Y 和 Z 轴的初始大小', + startSizeX: 'X 轴初始大小', + startSizeY: 'Y 轴初始大小', + startSizeZ: 'Z 轴初始大小', startSpeed: '初始速度', - startRotation3D: '是否分别设置粒子X,Y和Z轴的初始旋转角度', - startRotationX: 'X轴初始旋转角度', - startRotationY: 'Y轴初始旋转角度', - startRotationZ: 'Z轴初始旋转角度', + startRotation3D: '是否分别设置粒子 X, Y 和 Z 轴的初始旋转角度', + startRotationX: 'X 轴初始旋转角度', + startRotationY: 'Y 轴初始旋转角度', + startRotationZ: 'Z 轴初始旋转角度', startDelay: '粒子系统开始运行后,延迟粒子发射的时间', startLifetime: '粒子生命周期', duration: '粒子系统运行时间', @@ -670,14 +670,14 @@ module.exports = { type: '遮罩类型', spriteFrame: '遮罩所需要的贴图', inverted: '反向遮罩(不支持 Canvas 模式)', - alphaThreshold: 'Alpha阈值,只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容(不支持 Canvas 模式)', + alphaThreshold: 'Alpha阈值,只有当模板的像素的 alpha 大于 alpha Threshold 时,才会绘制内容(不支持 Canvas 模式)', segements: '椭圆遮罩的曲线细分数', }, physics: { rigidbody: { enabledContactListener: '是否启用接触接听器。当 collider 产生碰撞时,只有开启了接触接听器才会调用相应的回调函数', bullet: '这个刚体是否是一个快速移动的刚体,并且需要禁止穿过其他快速移动的刚体', - type: '刚体类型: Static(静态), Kinematic(不受外力), Dynamic(动态)和 Animated(通过设置线性速度和角速度驱动)', + type: '刚体类型:\nStatic(静态), \nKinematic(不受外力), \nDynamic(动态)和 Animated(通过设置线性速度和角速度驱动)', allowSleep: '如果此刚体永远都不应该进入睡眠,那么设置这个属性为 false。需要注意这将使 CPU 占用率提高', gravityScale: '缩放应用在此刚体上的重力值', linearDamping: @@ -731,10 +731,10 @@ module.exports = { brief_help: '该组件将拦截所有输入事件,防止输入穿透到屏幕下方的其它节点,一般用于屏幕上层 UI 的背景。', }, tiledtile: { - row: '指定 TiledTile 的横向坐标,以地图块为单位', - column: '指定 TiledTile 的纵向坐标,以地图块为单位', - gid: '指定 TiledTile 的 gid 值', - layer: '指定 TiledTile 属于哪一个 TiledLayer', + row: '指定 Tiled Tile 的横向坐标,以地图块为单位', + column: '指定 Tiled Tile 的纵向坐标,以地图块为单位', + gid: '指定 Tiled Tile 的 gid 值', + layer: '指定 Tiled Tile 属于哪一个 Tiled Layer', }, INSPECTOR: { component: { @@ -881,8 +881,8 @@ module.exports = { description: "Spine 动画支持。", }, dragon_bones: { - label: "DragonBones", - description: "DragonBones 支持。", + label: "Dragon Bones", + description: "Dragon Bones 支持。", }, animation: { label: "基础动画功能", @@ -922,7 +922,7 @@ module.exports = { physics3d: { rigidbody: { group: '刚体分组', - type: '刚体类型:Static为静态, Kinematic为运动学(通过变换信息操控), Dynamic为动力学(通过物理数值操控)', + type: '刚体类型:\nStatic为静态, \nKinematic 为运动学(通过变换信息操控), \nDynamic 为动力学(通过物理数值操控)', mass: '刚体质量,需大于 0', allowSleep: '是否允许自动休眠', linearDamping: '线性阻尼,用于衰减线性速度,值越大,衰减越快', @@ -953,10 +953,10 @@ module.exports = { mesh_convex: '是否使用凸包近似代替,顶点数应小于255,开启后可以支持动力学', terrain_terrain: '所使用的地形资源', simplex_shapeType: '单纯形类型,点、线、三角形、四面体', - simplex_vertex0: '形状的顶点0', - simplex_vertex1: '形状的顶点1', - simplex_vertex2: '形状的顶点2', - simplex_vertex3: '形状的顶点3', + simplex_vertex0: '形状的顶点 0', + simplex_vertex1: '形状的顶点 1', + simplex_vertex2: '形状的顶点 2', + simplex_vertex3: '形状的顶点 3', }, constant_force:{ force: '在世界坐标系中,对刚体施加的力', From db0edcbd0c676829a24e42947458014badfcd6e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Thu, 21 Jul 2022 21:20:19 +0800 Subject: [PATCH 074/111] [Optimize] effect editing interface style (#12093) --- editor/inspector/assets/effect.js | 19 +++++++++++-------- editor/inspector/contributions/node.css | 3 +-- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/editor/inspector/assets/effect.js b/editor/inspector/assets/effect.js index 2a816699b8..84a9082e63 100644 --- a/editor/inspector/assets/effect.js +++ b/editor/inspector/assets/effect.js @@ -29,20 +29,20 @@ exports.style = ` } .asset-effect > .config > .description { text-align: center; - color: var(--color-normal-border-weakest); + color: var(--color-normal-fill-weakest); } .asset-effect > .config > .combinations { padding: 10px 0; } - .asset-effect > .config > .combinations .checktab { + .asset-effect > .config > .combinations .tab { line-height: 20px; margin-left: 5px; margin-right: 5px; min-width: 60px; } - .asset-effect > .config > .combinations .checktab[checked="true"] { - border-color: var(--color-focus-contrast-weakest); - background-color: var(--color-focus-fill-weaker); + .asset-effect > .config > .combinations .tab[checked="true"] { + background-color: var(--color-focus-fill-emphasis); + color: var(--color-focus-contrast-emphasis); } .asset-effect > .codes > * { margin-bottom: 8px; @@ -57,7 +57,9 @@ exports.style = ` text-align: center; cursor: pointer; display: inline-block; - background: var(--color-normal-fill-weakest); + background-color: var(--color-normal-fill-emphasis); + color: var(--color-default-contrast-emphasis); + border: calc(var(--size-normal-border) * 1px) solid var(--color-normal-border); } .asset-effect > .codes .tabs > .tab:first-child { border-top-left-radius: 4px; @@ -70,7 +72,8 @@ exports.style = ` border-left: 1px solid var(--color-normal-fill-emphasis); } .asset-effect > .codes .tabs > .tab[active="true"] { - background: var(--color-normal-fill-emphasis); + background-color: var(--color-normal-fill); + color: var(--color-focus-fill-emphasis); } .asset-effect > .codes ui-code { max-height: 400px; @@ -152,7 +155,7 @@ const Elements = { const button = document.createElement('ui-button'); content.appendChild(button); - button.setAttribute('class', 'checktab'); + button.setAttribute('class', 'tab'); button.setAttribute('checked', checked); panel.updateReadonly(button); button.innerText = name; diff --git a/editor/inspector/contributions/node.css b/editor/inspector/contributions/node.css index 9846d8146a..6a5e052b2e 100644 --- a/editor/inspector/contributions/node.css +++ b/editor/inspector/contributions/node.css @@ -9,8 +9,7 @@ display: flex; flex-direction: column; overflow: scroll; - padding-left: 10px; - padding-right: 2px; + padding-left: 6px; } .container[hoving] { From 4ae8aaf232ea1a5590680593adbf42a999bd18d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Thu, 21 Jul 2022 21:20:59 +0800 Subject: [PATCH 075/111] [Feature] skybox bake reflection convolution (#12128) * Bake Reflection Convolution * test bake reflection convolution pass (cherry picked from commit 5291a388520c6e76b6ce8fdb7356c2f4fbf9b715) --- editor/inspector/contributions/node.js | 82 ++++++++++++-------------- 1 file changed, 39 insertions(+), 43 deletions(-) diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index 7b4e38758d..450169d09c 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -255,16 +255,14 @@ exports.template = /* html*/`
- + + Reflection Convolution +
+ + + +
+
@@ -664,10 +662,8 @@ const Elements = { event.preventDefault(); }); - panel.$.sceneSkyboxReflectionBake.addEventListener('confirm', Elements.scene.skyboxReflectionConvolutionChange.bind(panel)); - panel.$.sceneSkyboxReflectionRemove.addEventListener('confirm', Elements.scene.skyboxReflectionConvolutionChange.bind(panel)); - panel.skyboxReflectionConvolutionWatchBind = Elements.scene.skyboxReflectionConvolutionWatch.bind(panel); - Editor.Message.addBroadcastListener('asset-db:asset-change', panel.skyboxReflectionConvolutionWatchBind); + panel.$.sceneSkyboxReflectionBake.addEventListener('confirm', Elements.scene.skyboxReflectionConvolutionBake.bind(panel)); + panel.$.sceneSkyboxReflectionRemove.addEventListener('confirm', Elements.scene.skyboxReflectionConvolutionRemove.bind(panel)); }, async update() { const panel = this; @@ -716,13 +712,7 @@ const Elements = { } } - const envMapData = panel.dump._globals.skybox.value['envmap']; - if (envMapData.value && envMapData.value.uuid) { - panel.$.sceneSkyboxReflection.removeAttribute('hidden'); - envMapData.meta = await Elements.scene.skyboxReflectionConvolution.call(panel); - } else { - panel.$.sceneSkyboxReflection.setAttribute('hidden', ''); - } + Elements.scene.skyboxReflectionConvolution.call(panel); // skyBox 逻辑 end panel.dump._globals.octree.displayName = 'Octree Scene Culling'; @@ -778,50 +768,56 @@ const Elements = { async skyboxReflectionConvolution() { const panel = this; - const meta = await Editor.Message.request('asset-db', 'query-asset-meta', panel.dump._globals.skybox.value['envmap'].value.uuid); panel.$.sceneSkyboxReflectionLoading.style.display = 'none'; - if (meta.userData.mipBakeMode !== 1) { + const reflectionMap = panel.dump._globals.skybox.value['reflectionMap']; + if (reflectionMap.value && reflectionMap.value.uuid) { panel.$.sceneSkyboxReflectionBake.style.display = 'none'; panel.$.sceneSkyboxReflectionRemove.style.display = 'inline-block'; - } else { panel.$.sceneSkyboxReflectionBake.style.display = 'inline-block'; panel.$.sceneSkyboxReflectionRemove.style.display = 'none'; - } - return meta; + // 在 bake 按钮显示的状态下,如果 envmap 都没有配置,那 bake 也不需要显示 + const envMapData = panel.dump._globals.skybox.value['envmap']; + if (envMapData.value && envMapData.value.uuid) { + panel.$.sceneSkyboxReflection.removeAttribute('hidden'); + } else { + panel.$.sceneSkyboxReflection.setAttribute('hidden', ''); + } + } }, - skyboxReflectionConvolutionChange(event) { + async skyboxReflectionConvolutionBake() { const panel = this; const envMapData = panel.dump._globals.skybox.value['envmap']; - if (!envMapData.meta) { + if (!envMapData.value || !envMapData.value.uuid) { return; } panel.$.sceneSkyboxReflectionLoading.style.display = 'inline-block'; panel.$.sceneSkyboxReflectionBake.style.display = 'none'; - panel.$.sceneSkyboxReflectionRemove.style.display = 'none'; - const mipBakeMode = event.target.getAttribute('mipBakeMode') || 0; - envMapData.meta.userData.mipBakeMode = parseInt(mipBakeMode); - Editor.Message.send('asset-db', 'save-asset-meta', envMapData.value.uuid, JSON.stringify(envMapData.meta)); + await Editor.Message.request('scene', 'execute-scene-script', { + name: 'inspector', + method: 'bakeReflectionConvolution', + args: [envMapData.value.uuid], + }); }, - async skyboxReflectionConvolutionWatch(uuid) { + skyboxReflectionConvolutionRemove() { const panel = this; - if (panel.dump && panel.dump._globals && panel.dump._globals.skybox) { - const envMapData = panel.dump._globals.skybox.value['envmap']; - if (envMapData.value && envMapData.value.uuid === uuid) { - envMapData.meta = await Elements.scene.skyboxReflectionConvolution.call(panel); - } + + const reflectionMap = panel.dump._globals.skybox.value['reflectionMap']; + if (reflectionMap.value && reflectionMap.value.uuid) { + const $skyProps = panel.$.sceneSkybox.querySelectorAll('ui-prop[type="dump"]'); + $skyProps.forEach(($prop) => { + if ($prop.dump.name === 'reflectionMap') { + $prop.dump.value.uuid = ''; + $prop.dispatch('change'); + } + }); } }, - close() { - const panel = this; - - Editor.Message.removeBroadcastListener('asset-db:asset-change', panel.skyboxReflectionConvolutionWatchBind); - }, }, node: { ready() { From 235d0e9017bee8cd4a2b7999661323b89e466fe0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 21 Jul 2022 22:36:46 +0800 Subject: [PATCH 076/111] Fix TextureCube binding. (#12133) --- cocos/core/assets/texture-cube.jsb.ts | 30 --------------------------- native/tools/tojs/assets.ini | 1 - 2 files changed, 31 deletions(-) diff --git a/cocos/core/assets/texture-cube.jsb.ts b/cocos/core/assets/texture-cube.jsb.ts index 03f64fa601..4b5f4d666a 100644 --- a/cocos/core/assets/texture-cube.jsb.ts +++ b/cocos/core/assets/texture-cube.jsb.ts @@ -84,15 +84,6 @@ textureCubeProto._ctor = function () { this._mipmapAtlas = null; }; -function _forEachFace (mipmap, callback: (face, faceIndex) => void) { - callback(mipmap.front, FaceIndex.front); - callback(mipmap.back, FaceIndex.back); - callback(mipmap.left, FaceIndex.left); - callback(mipmap.right, FaceIndex.right); - callback(mipmap.top, FaceIndex.top); - callback(mipmap.bottom, FaceIndex.bottom); -} - Object.defineProperty(textureCubeProto, 'mipmaps', { get () { return this._mipmaps; @@ -100,27 +91,6 @@ Object.defineProperty(textureCubeProto, 'mipmaps', { set (value) { this._mipmaps = value; this.setMipmaps(value); - this.mipmapLevel = this._mipmaps.length; - if (this._mipmaps.length > 0) { - const imageAsset = this._mipmaps[0].front; - this.reset({ - width: imageAsset.width, - height: imageAsset.height, - format: imageAsset.format, - mipmapLevel: this._mipmaps.length, - }); - this._mipmaps.forEach((mipmap, level) => { - _forEachFace(mipmap, (face, faceIndex) => { - this.assignImage(face, level, faceIndex); - }); - }); - } else { - this.reset({ - width: 0, - height: 0, - mipmapLevel: this._mipmaps.length, - }); - } } }); diff --git a/native/tools/tojs/assets.ini b/native/tools/tojs/assets.ini index 0086b01811..ff21097b94 100644 --- a/native/tools/tojs/assets.ini +++ b/native/tools/tojs/assets.ini @@ -105,7 +105,6 @@ getter_setter= Asset::[_uuid/getUuid/setUuid nativeUrl/getNativeUrl _nativeDep/g ImageAsset::[format url/getUrl?/setUrl?], BufferAsset::[_nativeAsset/getNativeAssetForJS/setNativeAssetForJS], TextureBase::[isCompressed/isCompressed _width:width/getWidth/setWidth _height:height/getHeight/setHeight], - TextureCube::[mipmapAtlas image mipmaps], SimpleTexture::[mipmapLevel/mipmapLevel], RenderTexture::[window], Mesh::[_hash:hash/getHash/setHash data:_data/getData jointBufferIndices/getJointBufferIndices maxPosition/getMaxPosition minPosition/getMinPosition renderingSubMeshes/getRenderingSubMeshes subMeshCount/getSubMeshCount _nativeAsset/getAssetData/setAssetData _allowDataAccess:allowDataAccess/isAllowDataAccess/setAllowDataAccess], From b770828434b44e9e0df86e3fa0d803f447b89015 Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Thu, 21 Jul 2022 22:48:33 +0800 Subject: [PATCH 077/111] [ci skip][AUTO]: Automated code generating update: 0ac2d02a48016a0c9f3d9f0aa8515582e50d88a1 (#12133) (#12138) Co-authored-by: cocos-robot --- .../cocos/bindings/auto/jsb_assets_auto.cpp | 21 +++++++++++-------- native/cocos/bindings/auto/jsb_assets_auto.h | 6 ++++++ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/native/cocos/bindings/auto/jsb_assets_auto.cpp b/native/cocos/bindings/auto/jsb_assets_auto.cpp index 7d8a6f69e3..791c0fe33a 100644 --- a/native/cocos/bindings/auto/jsb_assets_auto.cpp +++ b/native/cocos/bindings/auto/jsb_assets_auto.cpp @@ -15325,7 +15325,7 @@ static bool js_assets_TextureCube_getImage(se::State& s) // NOLINT(readability-i SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC_AS_PROP_GET(js_assets_TextureCube_getImage) +SE_BIND_FUNC(js_assets_TextureCube_getImage) static bool js_assets_TextureCube_getMipmapAtlas(se::State& s) // NOLINT(readability-identifier-naming) { @@ -15345,7 +15345,7 @@ static bool js_assets_TextureCube_getMipmapAtlas(se::State& s) // NOLINT(readabi SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC_AS_PROP_GET(js_assets_TextureCube_getMipmapAtlas) +SE_BIND_FUNC(js_assets_TextureCube_getMipmapAtlas) static bool js_assets_TextureCube_getMipmaps(se::State& s) // NOLINT(readability-identifier-naming) { @@ -15365,7 +15365,7 @@ static bool js_assets_TextureCube_getMipmaps(se::State& s) // NOLINT(readability SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC_AS_PROP_GET(js_assets_TextureCube_getMipmaps) +SE_BIND_FUNC(js_assets_TextureCube_getMipmaps) static bool js_assets_TextureCube_initialize(se::State& s) // NOLINT(readability-identifier-naming) { @@ -15437,7 +15437,7 @@ static bool js_assets_TextureCube_setImage(se::State& s) // NOLINT(readability-i SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } -SE_BIND_FUNC_AS_PROP_SET(js_assets_TextureCube_setImage) +SE_BIND_FUNC(js_assets_TextureCube_setImage) static bool js_assets_TextureCube_setMipmapAtlas(se::State& s) // NOLINT(readability-identifier-naming) { @@ -15457,7 +15457,7 @@ static bool js_assets_TextureCube_setMipmapAtlas(se::State& s) // NOLINT(readabi SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } -SE_BIND_FUNC_AS_PROP_SET(js_assets_TextureCube_setMipmapAtlas) +SE_BIND_FUNC(js_assets_TextureCube_setMipmapAtlas) static bool js_assets_TextureCube_setMipmapAtlasForJS(se::State& s) // NOLINT(readability-identifier-naming) { @@ -15497,7 +15497,7 @@ static bool js_assets_TextureCube_setMipmaps(se::State& s) // NOLINT(readability SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } -SE_BIND_FUNC_AS_PROP_SET(js_assets_TextureCube_setMipmaps) +SE_BIND_FUNC(js_assets_TextureCube_setMipmaps) static bool js_assets_TextureCube_setMipmapsForJS(se::State& s) // NOLINT(readability-identifier-naming) { @@ -15620,15 +15620,18 @@ bool js_register_assets_TextureCube(se::Object* obj) // NOLINT(readability-ident #endif cls->defineProperty("_mipmapMode", _SE(js_assets_TextureCube_get__mipmapMode), _SE(js_assets_TextureCube_set__mipmapMode)); cls->defineProperty("isRGBE", _SE(js_assets_TextureCube_get_isRGBE), _SE(js_assets_TextureCube_set_isRGBE)); - cls->defineProperty("mipmapAtlas", _SE(js_assets_TextureCube_getMipmapAtlas_asGetter), _SE(js_assets_TextureCube_setMipmapAtlas_asSetter)); - cls->defineProperty("image", _SE(js_assets_TextureCube_getImage_asGetter), _SE(js_assets_TextureCube_setImage_asSetter)); - cls->defineProperty("mipmaps", _SE(js_assets_TextureCube_getMipmaps_asGetter), _SE(js_assets_TextureCube_setMipmaps_asSetter)); cls->defineFunction("getGfxTextureCreateInfo", _SE(js_assets_TextureCube_getGfxTextureCreateInfo)); cls->defineFunction("getGfxTextureViewCreateInfo", _SE(js_assets_TextureCube_getGfxTextureViewCreateInfo)); + cls->defineFunction("getImage", _SE(js_assets_TextureCube_getImage)); + cls->defineFunction("getMipmapAtlas", _SE(js_assets_TextureCube_getMipmapAtlas)); + cls->defineFunction("getMipmaps", _SE(js_assets_TextureCube_getMipmaps)); cls->defineFunction("initialize", _SE(js_assets_TextureCube_initialize)); cls->defineFunction("releaseTexture", _SE(js_assets_TextureCube_releaseTexture)); cls->defineFunction("reset", _SE(js_assets_TextureCube_reset)); + cls->defineFunction("setImage", _SE(js_assets_TextureCube_setImage)); + cls->defineFunction("setMipmapAtlas", _SE(js_assets_TextureCube_setMipmapAtlas)); cls->defineFunction("setMipmapAtlasForJS", _SE(js_assets_TextureCube_setMipmapAtlasForJS)); + cls->defineFunction("setMipmaps", _SE(js_assets_TextureCube_setMipmaps)); cls->defineFunction("setMipmapsForJS", _SE(js_assets_TextureCube_setMipmapsForJS)); cls->defineStaticFunction("fromTexture2DArray", _SE(js_assets_TextureCube_fromTexture2DArray_static)); cls->defineFinalizeFunction(_SE(js_cc_TextureCube_finalize)); diff --git a/native/cocos/bindings/auto/jsb_assets_auto.h b/native/cocos/bindings/auto/jsb_assets_auto.h index 82059e6399..e44498c9d0 100644 --- a/native/cocos/bindings/auto/jsb_assets_auto.h +++ b/native/cocos/bindings/auto/jsb_assets_auto.h @@ -585,10 +585,16 @@ bool js_register_cc_TextureCube(se::Object *obj); // NOLINT SE_DECLARE_FUNC(js_assets_TextureCube_getGfxTextureCreateInfo); SE_DECLARE_FUNC(js_assets_TextureCube_getGfxTextureViewCreateInfo); +SE_DECLARE_FUNC(js_assets_TextureCube_getImage); +SE_DECLARE_FUNC(js_assets_TextureCube_getMipmapAtlas); +SE_DECLARE_FUNC(js_assets_TextureCube_getMipmaps); SE_DECLARE_FUNC(js_assets_TextureCube_initialize); SE_DECLARE_FUNC(js_assets_TextureCube_releaseTexture); SE_DECLARE_FUNC(js_assets_TextureCube_reset); +SE_DECLARE_FUNC(js_assets_TextureCube_setImage); +SE_DECLARE_FUNC(js_assets_TextureCube_setMipmapAtlas); SE_DECLARE_FUNC(js_assets_TextureCube_setMipmapAtlasForJS); +SE_DECLARE_FUNC(js_assets_TextureCube_setMipmaps); SE_DECLARE_FUNC(js_assets_TextureCube_setMipmapsForJS); SE_DECLARE_FUNC(js_assets_TextureCube_fromTexture2DArray); SE_DECLARE_FUNC(js_assets_TextureCube_TextureCube); From 629d788596fed8a0f19daed4a035fa5634c5fa1d Mon Sep 17 00:00:00 2001 From: Santy-Wang Date: Thu, 21 Jul 2022 23:05:53 +0800 Subject: [PATCH 078/111] Output friendly information about effect name (#12137) * Output friendly information about effect name * Apply suggestions from code review Co-authored-by: pandamicro --- EngineErrorMap.md | 6 ++++- cc.config.json | 4 ++-- cocos/core/assets/effect-asset.ts | 28 ++++++++++++++++++++++ native/cocos/core/assets/EffectAsset.cpp | 30 ++++++++++++++++++++++++ native/cocos/core/builtin/DebugInfos.cpp | 1 + 5 files changed, 66 insertions(+), 3 deletions(-) diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 3269cafad4..b707f1cf3d 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -3286,4 +3286,8 @@ The native folder may be generated from older versions, please refer https://doc ### 16003 -'%s' is removed since v%s, please use '%s' instead. \ No newline at end of file +'%s' is removed since v%s, please use '%s' instead. + +### 16101 + +The effect('%s') you are looking for does not exist, please confirm the effect name in the editor. NOTE: Since 3.6, the name of the built-in effect has been changed to its name in the editor, please check it out. More information please refer to https://docs.cocos.com/creator/manual/en/shader/effect-inspector.html \ No newline at end of file diff --git a/cc.config.json b/cc.config.json index b7a4593140..77dc2c8ec8 100644 --- a/cc.config.json +++ b/cc.config.json @@ -7,7 +7,8 @@ "970b0598-bcb0-4714-91fb-2e81440dccd8", "bcd64cc6-2dd9-43f6-abbe-66318d332032", "d930590d-bb92-4cc8-8bd1-23cd027f9edf", - "a3cd009f-0ab0-420d-9278-b9fdab939bbc" + "a3cd009f-0ab0-420d-9278-b9fdab939bbc", + "9361fd90-ba52-4f84-aa93-6e878fd576ca" ]}, "gfx-webgl": { "modules": [ "gfx-webgl" ] }, "gfx-webgl2": { "modules": [ "gfx-webgl2" ] }, @@ -15,7 +16,6 @@ "modules": [ "3d" ], "dependentAssets": [ "1baf0fc9-befa-459c-8bdd-af1a450a0319", - "9361fd90-ba52-4f84-aa93-6e878fd576ca", "511d2633-09a7-4bdd-ac42-f778032124b3", "5d45aa00-e064-4938-b314-4265f0c2258c", "28d6d6b8-3f66-4a73-9795-17a0852ba2d4", diff --git a/cocos/core/assets/effect-asset.ts b/cocos/core/assets/effect-asset.ts index 1f4438c0ce..4f020585f0 100644 --- a/cocos/core/assets/effect-asset.ts +++ b/cocos/core/assets/effect-asset.ts @@ -33,6 +33,7 @@ import { MacroRecord } from '../renderer/core/pass-utils'; import { programLib } from '../renderer/core/program-lib'; import { Asset } from './asset'; import { legacyCC } from '../global-exports'; +import { warnID } from '../platform/debug'; export declare namespace EffectAsset { export interface IPropertyInfo { @@ -163,6 +164,30 @@ export declare namespace EffectAsset { } } +const legacyBuiltinEffectNames = [ + 'planar-shadow', + 'skybox', + 'deferred-lighting', + 'bloom', + 'post-process', + 'profiler', + 'splash-screen', + 'standard', + 'unlit', + 'sprite', + 'particle', + 'particle-gpu', + 'particle-trail', + 'billboard', + 'terrain', + 'graphics', + 'clear-stencil', + 'spine', + 'occlusion-query', + 'geometry-renderer', + 'debug-renderer', +]; + /** * @en Effect asset is the base template for instantiating material, all effects should be unique globally. * All effects are managed in a static map of EffectAsset. @@ -211,6 +236,9 @@ export class EffectAsset extends Asset { return EffectAsset._effects[n]; } } + if (legacyBuiltinEffectNames.includes(name)) { + warnID(16101, name); + } return null; } diff --git a/native/cocos/core/assets/EffectAsset.cpp b/native/cocos/core/assets/EffectAsset.cpp index 0e5cdf907c..895a38a7e5 100644 --- a/native/cocos/core/assets/EffectAsset.cpp +++ b/native/cocos/core/assets/EffectAsset.cpp @@ -28,6 +28,7 @@ #include "core/Root.h" #include "engine/BaseEngine.h" #include "renderer/core/ProgramLib.h" +#include "core/platform/Debug.h" namespace cc { @@ -132,6 +133,35 @@ EffectAsset *EffectAsset::get(const ccstd::string &name) { return iter->second; } } + static ccstd::vector legacyBuiltinEffectNames{ + "planar-shadow", + "skybox", + "deferred-lighting", + "bloom", + "post-process", + "profiler", + "splash-screen", + "standard", + "unlit", + "sprite", + "particle", + "particle-gpu", + "particle-trail", + "billboard", + "terrain", + "graphics", + "clear-stencil", + "spine", + "occlusion-query", + "geometry-renderer", + "debug-renderer" + }; + for (auto &legacyName : legacyBuiltinEffectNames) { + if (name == legacyName) { + debug::warnID(16101, name); + } + } + return nullptr; } diff --git a/native/cocos/core/builtin/DebugInfos.cpp b/native/cocos/core/builtin/DebugInfos.cpp index 7ad38a21d3..fe37b0cdf0 100644 --- a/native/cocos/core/builtin/DebugInfos.cpp +++ b/native/cocos/core/builtin/DebugInfos.cpp @@ -451,6 +451,7 @@ ccstd::unordered_map debugInfos = { { 16001, "'%s' is deprecated since v%s, please use '%s' instead." }, { 16002, "'%s' is removed since v%s." }, { 16003, "'%s' is removed since v%s, please use '%s' instead." }, +{ 16101, "The effect('%s') you are looking for does not exist, please confirm the effect name in the editor. NOTE: Since 3.6, the name of the built-in effect has been changed to its name in the editor, please check it out. More information please refer to https://docs.cocos.com/creator/manual/en/shader/effect-inspector.html" }, }; }//namespace cc From 8dfcbabeb0ecb80db3849a548acc173c578e95eb Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Thu, 21 Jul 2022 23:21:23 +0800 Subject: [PATCH 079/111] [V3.6.0 gfx] auto barrier added (#12118) auto barrier added. Co-authored-by: Zeqiang Li --- cocos/core/gfx/base/define.ts | 414 ++++--- native/CMakeLists.txt | 2 + .../cocos/renderer/frame-graph/DevicePass.cpp | 103 +- .../cocos/renderer/frame-graph/DevicePass.h | 9 +- .../frame-graph/DevicePassResourceTable.cpp | 28 +- .../renderer/frame-graph/ImmutableState.cpp | 341 ++++++ .../renderer/frame-graph/ImmutableState.h | 85 ++ .../cocos/renderer/frame-graph/PassNode.cpp | 4 + native/cocos/renderer/frame-graph/PassNode.h | 10 + .../renderer/frame-graph/PassNodeBuilder.h | 5 + .../cocos/renderer/gfx-base/GFXDef-common.h | 28 +- native/cocos/renderer/gfx-base/GFXDevice.h | 4 + .../renderer/gfx-gles3/GLES3Commands.cpp | 67 +- .../renderer/gfx-gles3/GLES3GPUObjects.h | 4 +- .../renderer/gfx-gles3/GLES3RenderPass.cpp | 1 + .../renderer/gfx-vulkan/VKCommandBuffer.cpp | 40 +- .../cocos/renderer/gfx-vulkan/VKCommands.cpp | 78 +- .../pipeline/custom/FGDispatcherTypes.cpp | 8 +- .../pipeline/custom/FGDispatcherTypes.h | 76 +- .../pipeline/custom/FrameGraphDispatcher.cpp | 1011 +++++++++++------ .../renderer/pipeline/custom/test/test.h | 928 ++++++++++++++- .../src/complicated_barrier_case.cpp | 293 +++++ .../unit-test/src/simple_barrier_test.cpp | 83 ++ .../src/simple_closed_barrier_test.cpp | 176 +++ native/tools/tojs/gfx.ini | 2 +- 25 files changed, 3147 insertions(+), 653 deletions(-) create mode 100644 native/cocos/renderer/frame-graph/ImmutableState.cpp create mode 100644 native/cocos/renderer/frame-graph/ImmutableState.h create mode 100644 native/tests/unit-test/src/complicated_barrier_case.cpp create mode 100644 native/tests/unit-test/src/simple_barrier_test.cpp create mode 100644 native/tests/unit-test/src/simple_closed_barrier_test.cpp diff --git a/cocos/core/gfx/base/define.ts b/cocos/core/gfx/base/define.ts index 69d9da2964..5a6e18a55f 100644 --- a/cocos/core/gfx/base/define.ts +++ b/cocos/core/gfx/base/define.ts @@ -32,6 +32,8 @@ import { DescriptorSetLayout } from './descriptor-set-layout'; import { Sampler } from './states/sampler'; import { GeneralBarrier } from './states/general-barrier'; +import { TextureBarrier } from './states/texture-barrier'; +import { BufferBarrier } from './states/buffer-barrier'; import { GCObject } from '../../data/gc-object'; interface ICopyable { copy (info: ICopyable): ICopyable; } @@ -679,6 +681,15 @@ export enum BarrierType { SPLIT_END, } +export enum PassType { + RASTER, + COMPUTE, + COPY, + MOVE, + RAYTRACE, + PRESENT, +} + export type BufferUsage = BufferUsageBit; export type BufferFlags = BufferFlagBit; export type MemoryAccess = MemoryAccessBit; @@ -763,6 +774,19 @@ export class DeviceCaps { } } +export class DeviceOptions { + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + + constructor ( + public enableBarrierDeduce: boolean = true, + ) {} + + public copy (info: Readonly) { + this.enableBarrierDeduce = info.enableBarrierDeduce; + return this; + } +} + export class Offset { declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object @@ -1535,13 +1559,25 @@ export class SubpassDependency { constructor ( public srcSubpass: number = 0, public dstSubpass: number = 0, - public barrier: GeneralBarrier = null!, + public generalBarrier: GeneralBarrier = null!, + public bufferBarriers: BufferBarrier = null!, + public buffers: Buffer = null!, + public bufferBarrierCount: number = 0, + public textureBarriers: TextureBarrier = null!, + public textures: Texture = null!, + public textureBarrierCount: number = 0, ) {} public copy (info: Readonly) { this.srcSubpass = info.srcSubpass; this.dstSubpass = info.dstSubpass; - this.barrier = info.barrier; + this.generalBarrier = info.generalBarrier; + this.bufferBarriers = info.bufferBarriers; + this.buffers = info.buffers; + this.bufferBarrierCount = info.bufferBarrierCount; + this.textureBarriers = info.textureBarriers; + this.textures = info.textures; + this.textureBarrierCount = info.textureBarrierCount; return this; } } @@ -2086,95 +2122,95 @@ export function FormatSize (format: Format, width: number, height: number, depth return (width * height * depth * FormatInfos[format].size); } else { switch (format) { - case Format.BC1: - case Format.BC1_ALPHA: - case Format.BC1_SRGB: - case Format.BC1_SRGB_ALPHA: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; - case Format.BC2: - case Format.BC2_SRGB: - case Format.BC3: - case Format.BC3_SRGB: - case Format.BC4: - case Format.BC4_SNORM: - case Format.BC6H_SF16: - case Format.BC6H_UF16: - case Format.BC7: - case Format.BC7_SRGB: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; - case Format.BC5: - case Format.BC5_SNORM: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth; + case Format.BC1: + case Format.BC1_ALPHA: + case Format.BC1_SRGB: + case Format.BC1_SRGB_ALPHA: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case Format.BC2: + case Format.BC2_SRGB: + case Format.BC3: + case Format.BC3_SRGB: + case Format.BC4: + case Format.BC4_SNORM: + case Format.BC6H_SF16: + case Format.BC6H_UF16: + case Format.BC7: + case Format.BC7_SRGB: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + case Format.BC5: + case Format.BC5_SNORM: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth; - case Format.ETC_RGB8: - case Format.ETC2_RGB8: - case Format.ETC2_SRGB8: - case Format.ETC2_RGB8_A1: - case Format.EAC_R11: - case Format.EAC_R11SN: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; - case Format.ETC2_RGBA8: - case Format.ETC2_SRGB8_A1: - case Format.EAC_RG11: - case Format.EAC_RG11SN: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + case Format.ETC_RGB8: + case Format.ETC2_RGB8: + case Format.ETC2_SRGB8: + case Format.ETC2_RGB8_A1: + case Format.EAC_R11: + case Format.EAC_R11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case Format.ETC2_RGBA8: + case Format.ETC2_SRGB8_A1: + case Format.EAC_RG11: + case Format.EAC_RG11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; - case Format.PVRTC_RGB2: - case Format.PVRTC_RGBA2: - case Format.PVRTC2_2BPP: - return Math.ceil(width / 8) * Math.ceil(height / 4) * 8 * depth; + case Format.PVRTC_RGB2: + case Format.PVRTC_RGBA2: + case Format.PVRTC2_2BPP: + return Math.ceil(width / 8) * Math.ceil(height / 4) * 8 * depth; - case Format.PVRTC_RGB4: - case Format.PVRTC_RGBA4: - case Format.PVRTC2_4BPP: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case Format.PVRTC_RGB4: + case Format.PVRTC_RGBA4: + case Format.PVRTC2_4BPP: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; - case Format.ASTC_RGBA_4X4: - case Format.ASTC_SRGBA_4X4: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; - case Format.ASTC_RGBA_5X4: - case Format.ASTC_SRGBA_5X4: - return Math.ceil(width / 5) * Math.ceil(height / 4) * 16 * depth; - case Format.ASTC_RGBA_5X5: - case Format.ASTC_SRGBA_5X5: - return Math.ceil(width / 5) * Math.ceil(height / 5) * 16 * depth; - case Format.ASTC_RGBA_6X5: - case Format.ASTC_SRGBA_6X5: - return Math.ceil(width / 6) * Math.ceil(height / 5) * 16 * depth; - case Format.ASTC_RGBA_6X6: - case Format.ASTC_SRGBA_6X6: - return Math.ceil(width / 6) * Math.ceil(height / 6) * 16 * depth; - case Format.ASTC_RGBA_8X5: - case Format.ASTC_SRGBA_8X5: - return Math.ceil(width / 8) * Math.ceil(height / 5) * 16 * depth; - case Format.ASTC_RGBA_8X6: - case Format.ASTC_SRGBA_8X6: - return Math.ceil(width / 8) * Math.ceil(height / 6) * 16 * depth; - case Format.ASTC_RGBA_8X8: - case Format.ASTC_SRGBA_8X8: - return Math.ceil(width / 8) * Math.ceil(height / 8) * 16 * depth; - case Format.ASTC_RGBA_10X5: - case Format.ASTC_SRGBA_10X5: - return Math.ceil(width / 10) * Math.ceil(height / 5) * 16 * depth; - case Format.ASTC_RGBA_10X6: - case Format.ASTC_SRGBA_10X6: - return Math.ceil(width / 10) * Math.ceil(height / 6) * 16 * depth; - case Format.ASTC_RGBA_10X8: - case Format.ASTC_SRGBA_10X8: - return Math.ceil(width / 10) * Math.ceil(height / 8) * 16 * depth; - case Format.ASTC_RGBA_10X10: - case Format.ASTC_SRGBA_10X10: - return Math.ceil(width / 10) * Math.ceil(height / 10) * 16 * depth; - case Format.ASTC_RGBA_12X10: - case Format.ASTC_SRGBA_12X10: - return Math.ceil(width / 12) * Math.ceil(height / 10) * 16 * depth; - case Format.ASTC_RGBA_12X12: - case Format.ASTC_SRGBA_12X12: - return Math.ceil(width / 12) * Math.ceil(height / 12) * 16 * depth; + case Format.ASTC_RGBA_4X4: + case Format.ASTC_SRGBA_4X4: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + case Format.ASTC_RGBA_5X4: + case Format.ASTC_SRGBA_5X4: + return Math.ceil(width / 5) * Math.ceil(height / 4) * 16 * depth; + case Format.ASTC_RGBA_5X5: + case Format.ASTC_SRGBA_5X5: + return Math.ceil(width / 5) * Math.ceil(height / 5) * 16 * depth; + case Format.ASTC_RGBA_6X5: + case Format.ASTC_SRGBA_6X5: + return Math.ceil(width / 6) * Math.ceil(height / 5) * 16 * depth; + case Format.ASTC_RGBA_6X6: + case Format.ASTC_SRGBA_6X6: + return Math.ceil(width / 6) * Math.ceil(height / 6) * 16 * depth; + case Format.ASTC_RGBA_8X5: + case Format.ASTC_SRGBA_8X5: + return Math.ceil(width / 8) * Math.ceil(height / 5) * 16 * depth; + case Format.ASTC_RGBA_8X6: + case Format.ASTC_SRGBA_8X6: + return Math.ceil(width / 8) * Math.ceil(height / 6) * 16 * depth; + case Format.ASTC_RGBA_8X8: + case Format.ASTC_SRGBA_8X8: + return Math.ceil(width / 8) * Math.ceil(height / 8) * 16 * depth; + case Format.ASTC_RGBA_10X5: + case Format.ASTC_SRGBA_10X5: + return Math.ceil(width / 10) * Math.ceil(height / 5) * 16 * depth; + case Format.ASTC_RGBA_10X6: + case Format.ASTC_SRGBA_10X6: + return Math.ceil(width / 10) * Math.ceil(height / 6) * 16 * depth; + case Format.ASTC_RGBA_10X8: + case Format.ASTC_SRGBA_10X8: + return Math.ceil(width / 10) * Math.ceil(height / 8) * 16 * depth; + case Format.ASTC_RGBA_10X10: + case Format.ASTC_SRGBA_10X10: + return Math.ceil(width / 10) * Math.ceil(height / 10) * 16 * depth; + case Format.ASTC_RGBA_12X10: + case Format.ASTC_SRGBA_12X10: + return Math.ceil(width / 12) * Math.ceil(height / 10) * 16 * depth; + case Format.ASTC_RGBA_12X12: + case Format.ASTC_SRGBA_12X12: + return Math.ceil(width / 12) * Math.ceil(height / 12) * 16 * depth; - default: { - return 0; - } + default: { + return 0; + } } } } @@ -2253,30 +2289,30 @@ export function getTypedArrayConstructor (info: FormatInfo): TypedArrayConstruct } const stride = info.size / info.count; switch (info.type) { - case FormatType.UNORM: - case FormatType.UINT: { - switch (stride) { - case 1: return Uint8Array; - case 2: return Uint16Array; - case 4: return Uint32Array; - default: - return Uint8Array; + case FormatType.UNORM: + case FormatType.UINT: { + switch (stride) { + case 1: return Uint8Array; + case 2: return Uint16Array; + case 4: return Uint32Array; + default: + return Uint8Array; + } } - } - case FormatType.SNORM: - case FormatType.INT: { - switch (stride) { - case 1: return Int8Array; - case 2: return Int16Array; - case 4: return Int32Array; - default: - return Int8Array; + case FormatType.SNORM: + case FormatType.INT: { + switch (stride) { + case 1: return Int8Array; + case 2: return Int16Array; + case 4: return Int32Array; + default: + return Int8Array; + } } - } - case FormatType.FLOAT: { - return Float32Array; - } - default: + case FormatType.FLOAT: { + return Float32Array; + } + default: } return Float32Array; } @@ -2286,93 +2322,93 @@ export interface FormatAlignment { height: number, // default 1 } -export function formatAlignment (format: Format) : FormatAlignment { +export function formatAlignment (format: Format): FormatAlignment { switch (format) { - case Format.BC1: - case Format.BC1_ALPHA: - case Format.BC1_SRGB: - case Format.BC1_SRGB_ALPHA: - case Format.BC2: - case Format.BC2_SRGB: - case Format.BC3: - case Format.BC3_SRGB: - case Format.BC4: - case Format.BC4_SNORM: - case Format.BC6H_SF16: - case Format.BC6H_UF16: - case Format.BC7: - case Format.BC7_SRGB: - case Format.BC5: - case Format.BC5_SNORM: - case Format.ETC_RGB8: - case Format.ETC2_RGB8: - case Format.ETC2_SRGB8: - case Format.ETC2_RGB8_A1: - case Format.EAC_R11: - case Format.EAC_R11SN: - case Format.ETC2_RGBA8: - case Format.ETC2_SRGB8_A1: - case Format.EAC_RG11: - case Format.EAC_RG11SN: - return { width: 4, height: 4 }; + case Format.BC1: + case Format.BC1_ALPHA: + case Format.BC1_SRGB: + case Format.BC1_SRGB_ALPHA: + case Format.BC2: + case Format.BC2_SRGB: + case Format.BC3: + case Format.BC3_SRGB: + case Format.BC4: + case Format.BC4_SNORM: + case Format.BC6H_SF16: + case Format.BC6H_UF16: + case Format.BC7: + case Format.BC7_SRGB: + case Format.BC5: + case Format.BC5_SNORM: + case Format.ETC_RGB8: + case Format.ETC2_RGB8: + case Format.ETC2_SRGB8: + case Format.ETC2_RGB8_A1: + case Format.EAC_R11: + case Format.EAC_R11SN: + case Format.ETC2_RGBA8: + case Format.ETC2_SRGB8_A1: + case Format.EAC_RG11: + case Format.EAC_RG11SN: + return { width: 4, height: 4 }; - case Format.PVRTC_RGB2: - case Format.PVRTC_RGBA2: - case Format.PVRTC2_2BPP: - return { width: 8, height: 4 }; + case Format.PVRTC_RGB2: + case Format.PVRTC_RGBA2: + case Format.PVRTC2_2BPP: + return { width: 8, height: 4 }; - case Format.PVRTC_RGB4: - case Format.PVRTC_RGBA4: - case Format.PVRTC2_4BPP: - return { width: 4, height: 4 }; + case Format.PVRTC_RGB4: + case Format.PVRTC_RGBA4: + case Format.PVRTC2_4BPP: + return { width: 4, height: 4 }; - case Format.ASTC_RGBA_4X4: - case Format.ASTC_SRGBA_4X4: - return { width: 4, height: 4 }; - case Format.ASTC_RGBA_5X4: - case Format.ASTC_SRGBA_5X4: - return { width: 5, height: 4 }; - case Format.ASTC_RGBA_5X5: - case Format.ASTC_SRGBA_5X5: - return { width: 5, height: 5 }; - case Format.ASTC_RGBA_6X5: - case Format.ASTC_SRGBA_6X5: - return { width: 6, height: 5 }; - case Format.ASTC_RGBA_6X6: - case Format.ASTC_SRGBA_6X6: - return { width: 6, height: 6 }; - case Format.ASTC_RGBA_8X5: - case Format.ASTC_SRGBA_8X5: - return { width: 8, height: 5 }; - case Format.ASTC_RGBA_8X6: - case Format.ASTC_SRGBA_8X6: - return { width: 8, height: 6 }; - case Format.ASTC_RGBA_8X8: - case Format.ASTC_SRGBA_8X8: - return { width: 8, height: 8 }; - case Format.ASTC_RGBA_10X5: - case Format.ASTC_SRGBA_10X5: - return { width: 10, height: 5 }; - case Format.ASTC_RGBA_10X6: - case Format.ASTC_SRGBA_10X6: - return { width: 10, height: 6 }; - case Format.ASTC_RGBA_10X8: - case Format.ASTC_SRGBA_10X8: - return { width: 10, height: 8 }; - case Format.ASTC_RGBA_10X10: - case Format.ASTC_SRGBA_10X10: - return { width: 10, height: 10 }; - case Format.ASTC_RGBA_12X10: - case Format.ASTC_SRGBA_12X10: - return { width: 12, height: 10 }; - case Format.ASTC_RGBA_12X12: - case Format.ASTC_SRGBA_12X12: - return { width: 12, height: 12 }; - default: - return { width: 1, height: 1 }; + case Format.ASTC_RGBA_4X4: + case Format.ASTC_SRGBA_4X4: + return { width: 4, height: 4 }; + case Format.ASTC_RGBA_5X4: + case Format.ASTC_SRGBA_5X4: + return { width: 5, height: 4 }; + case Format.ASTC_RGBA_5X5: + case Format.ASTC_SRGBA_5X5: + return { width: 5, height: 5 }; + case Format.ASTC_RGBA_6X5: + case Format.ASTC_SRGBA_6X5: + return { width: 6, height: 5 }; + case Format.ASTC_RGBA_6X6: + case Format.ASTC_SRGBA_6X6: + return { width: 6, height: 6 }; + case Format.ASTC_RGBA_8X5: + case Format.ASTC_SRGBA_8X5: + return { width: 8, height: 5 }; + case Format.ASTC_RGBA_8X6: + case Format.ASTC_SRGBA_8X6: + return { width: 8, height: 6 }; + case Format.ASTC_RGBA_8X8: + case Format.ASTC_SRGBA_8X8: + return { width: 8, height: 8 }; + case Format.ASTC_RGBA_10X5: + case Format.ASTC_SRGBA_10X5: + return { width: 10, height: 5 }; + case Format.ASTC_RGBA_10X6: + case Format.ASTC_SRGBA_10X6: + return { width: 10, height: 6 }; + case Format.ASTC_RGBA_10X8: + case Format.ASTC_SRGBA_10X8: + return { width: 10, height: 8 }; + case Format.ASTC_RGBA_10X10: + case Format.ASTC_SRGBA_10X10: + return { width: 10, height: 10 }; + case Format.ASTC_RGBA_12X10: + case Format.ASTC_SRGBA_12X10: + return { width: 12, height: 10 }; + case Format.ASTC_RGBA_12X12: + case Format.ASTC_SRGBA_12X12: + return { width: 12, height: 12 }; + default: + return { width: 1, height: 1 }; } } -export function alignTo (size: number, alignment: number) : number { +export function alignTo (size: number, alignment: number): number { return Math.ceil(size / alignment) * alignment; } diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index da68cc29e2..68f0e13619 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1627,6 +1627,8 @@ cocos_source_files( cocos/renderer/frame-graph/ResourceNode.h cocos/renderer/frame-graph/VirtualResource.cpp cocos/renderer/frame-graph/VirtualResource.h + cocos/renderer/frame-graph/ImmutableState.h + cocos/renderer/frame-graph/ImmutableState.cpp ) ##### physics diff --git a/native/cocos/renderer/frame-graph/DevicePass.cpp b/native/cocos/renderer/frame-graph/DevicePass.cpp index 5d0619bb0b..b25ae908ab 100644 --- a/native/cocos/renderer/frame-graph/DevicePass.cpp +++ b/native/cocos/renderer/frame-graph/DevicePass.cpp @@ -29,7 +29,6 @@ #include "FrameGraph.h" #include "PassNode.h" #include "ResourceNode.h" - #include "base/Utils.h" #include "gfx-base/GFXCommandBuffer.h" #include "gfx-base/GFXDef-common.h" @@ -42,10 +41,23 @@ namespace framegraph { DevicePass::DevicePass(const FrameGraph &graph, ccstd::vector const &subpassNodes) { ccstd::vector attachments; + uint32_t index = 0; for (const PassNode *passNode : subpassNodes) { append(graph, passNode, &attachments); + _barriers.push_back(std::cref(passNode->getBarriers())); + _subpasses.back().barrierID = index++; } + auto* device = gfx::Device::getInstance(); + // _enableAutoBarrier: auto barrier in framegraph + // barrierDeduce: deduce barrier gfx internally + // to avoid redundant instructions, either inside or outside + auto opts = device->getOptions(); + opts.enableBarrierDeduce = !gfx::ENABLE_GRAPH_AUTO_BARRIER; + device->setOptions(opts); + + CC_ASSERT(gfx::ENABLE_GRAPH_AUTO_BARRIER ^ gfx::Device::getInstance()->getOptions().enableBarrierDeduce); + // Important Notice: // here attchment index has changed. // _attachments is flattened previously, and it is spliced into two parts here: @@ -111,8 +123,93 @@ DevicePass::DevicePass(const FrameGraph &graph, ccstd::vector const } } +void DevicePass::passDependency(gfx::RenderPassInfo &rpInfo) { + if constexpr (gfx::ENABLE_GRAPH_AUTO_BARRIER) { + uint32_t index = 0; + + thread_local gfx::BufferBarrierList bufferBarriers; + thread_local gfx::TextureBarrierList textureBarriers; + thread_local gfx::BufferList buffers; + thread_local gfx::TextureList textures; + + bufferBarriers.clear(); + textureBarriers.clear(); + buffers.clear(); + textures.clear(); + + uint32_t lastBufferIndex{0}; + uint32_t lastTextureIndex{0}; + + auto mergeToDependency = [&](uint32_t barrierID, uint32_t subpassIndex){ + for (const auto &frontBarrier : _barriers[barrierID].get().frontBarriers) { + const auto &res = getBarrier(frontBarrier, &_resourceTable); + if (frontBarrier.resourceType == ResourceType::BUFFER) { + bufferBarriers.emplace_back(static_cast(res.first)); + buffers.emplace_back(static_cast(res.second)); + } else if (frontBarrier.resourceType == ResourceType::TEXTURE) { + textureBarriers.emplace_back(static_cast(res.first)); + textures.emplace_back(static_cast(res.second)); + } else { + CC_ASSERT(false); + } + } + + lastBufferIndex = static_cast(buffers.size()); + lastTextureIndex = static_cast(textures.size()); + + rpInfo.dependencies.emplace_back(gfx::SubpassDependency{ + subpassIndex > 1 ? subpassIndex - 1 : gfx::SUBPASS_EXTERNAL, + subpassIndex, + nullptr, + bufferBarriers.data() + lastBufferIndex, + buffers.data() + lastBufferIndex, + static_cast(buffers.size() - lastBufferIndex + 1), + textureBarriers.data() + lastTextureIndex, + textures.data() + lastTextureIndex, + static_cast(textures.size() - lastTextureIndex + 1)}); + + for (const auto &rearBarrier : _barriers[barrierID].get().rearBarriers) { + const auto &res = getBarrier(rearBarrier, &_resourceTable); + if (rearBarrier.resourceType == ResourceType::BUFFER) { + bufferBarriers.emplace_back(static_cast(res.first)); + buffers.emplace_back(static_cast(res.second)); + } else if (rearBarrier.resourceType == ResourceType::TEXTURE) { + textureBarriers.emplace_back(static_cast(res.first)); + textures.emplace_back(static_cast(res.second)); + } else { + CC_ASSERT(false); + } + } + + }; + + if(!_subpasses.empty()) { + for (const auto &subpass : _subpasses) { + mergeToDependency(subpass.barrierID, index); + ++index; + } + } else { + mergeToDependency(0, 0); + } + + if (textureBarriers.size() > lastTextureIndex || bufferBarriers.size() > lastBufferIndex) { + rpInfo.dependencies.emplace_back(gfx::SubpassDependency{ + _subpasses.empty() ? 0 : static_cast(_subpasses.size() - 1), + gfx::SUBPASS_EXTERNAL, + nullptr, + bufferBarriers.data() + lastBufferIndex, + buffers.data() + lastBufferIndex, + static_cast(buffers.size() - lastBufferIndex + 1), + textureBarriers.data() + lastTextureIndex, + textures.data() + lastTextureIndex, + static_cast(textures.size() - lastTextureIndex + 1)}); + } + } +} + void DevicePass::execute() { - auto *cmdBuff = gfx::Device::getInstance()->getCommandBuffer(); + auto *device = gfx::Device::getInstance(); + auto *cmdBuff = device->getCommandBuffer(); begin(cmdBuff); @@ -312,6 +409,8 @@ void DevicePass::begin(gfx::CommandBuffer *cmdBuff) { rpInfo.subpasses.emplace_back(subpass.desc); } + passDependency(rpInfo); + _renderPass = RenderPass(rpInfo); _renderPass.createTransient(); _resourceTable._renderPass = _renderPass.get(); diff --git a/native/cocos/renderer/frame-graph/DevicePass.h b/native/cocos/renderer/frame-graph/DevicePass.h index b7555b9199..e3c29dbbde 100644 --- a/native/cocos/renderer/frame-graph/DevicePass.h +++ b/native/cocos/renderer/frame-graph/DevicePass.h @@ -25,7 +25,9 @@ #pragma once +#include #include "CallbackPass.h" +#include "ImmutableState.h" #include "RenderTargetAttachment.h" #include "base/std/container/string.h" #include "gfx-base/GFXDef.h" @@ -54,8 +56,9 @@ private: }; struct Subpass final { - ccstd::vector logicPasses{}; gfx::SubpassInfo desc; + ccstd::vector logicPasses{}; + uint32_t barrierID{0xFFFFFFFF}; }; struct Attachment final { @@ -70,6 +73,8 @@ private: void next(gfx::CommandBuffer *cmdBuff) noexcept; void end(gfx::CommandBuffer *cmdBuff); + void passDependency(gfx::RenderPassInfo& rpInfo); + ccstd::vector _subpasses{}; ccstd::vector _attachments{}; uint16_t _usedRenderTargetSlotMask{0}; @@ -81,6 +86,8 @@ private: gfx::Rect _curScissor; RenderPass _renderPass; Framebuffer _fbo; + + std::vector> _barriers; }; } // namespace framegraph diff --git a/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp b/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp index 9605e4cbc6..26535645ff 100644 --- a/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp +++ b/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp @@ -51,8 +51,8 @@ void DevicePassResourceTable::extract(const FrameGraph &graph, void DevicePassResourceTable::extract(const FrameGraph &graph, ccstd::vector const &from, ResourceDictionary &to, - bool ignoreRenderTarget, - ccstd::vector const &renderTargets) noexcept { + bool /*ignoreRenderTarget*/, + ccstd::vector const &/*renderTargets*/) noexcept { std::for_each(from.cbegin(), from.cend(), [&](const Handle handle) { if (to.find(handle) != to.cend()) { return; @@ -66,19 +66,19 @@ void DevicePassResourceTable::extract(const FrameGraph &graph, return; } - if (ignoreRenderTarget) { - bool const isRenderTarget = - std::find_if( - renderTargets.cbegin(), - renderTargets.cend(), - [&deviceResource](const gfx::Texture *const x) { - return deviceResource == x; - }) != renderTargets.cend(); + //if (ignoreRenderTarget) { + // bool const isRenderTarget = + // std::find_if( + // renderTargets.cbegin(), + // renderTargets.cend(), + // [&deviceResource](const gfx::Texture *const x) { + // return deviceResource == x; + // }) != renderTargets.cend(); - if (isRenderTarget) { - return; - } - } + // if (isRenderTarget) { + // return; + // } + //} to[handle] = deviceResource; }); diff --git a/native/cocos/renderer/frame-graph/ImmutableState.cpp b/native/cocos/renderer/frame-graph/ImmutableState.cpp new file mode 100644 index 0000000000..ccd9324e95 --- /dev/null +++ b/native/cocos/renderer/frame-graph/ImmutableState.cpp @@ -0,0 +1,341 @@ + +/**************************************************************************** + Copyright (c) 2021-2022 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. +****************************************************************************/ + +#include "ImmutableState.h" +#include +#include "DevicePassResourceTable.h" +#include "gfx-base/GFXDef-common.h" +#include "pipeline/custom/GslUtils.h" + +namespace cc { +namespace framegraph { + +using gfx::AccessFlags; +using gfx::BufferUsage; +using gfx::hasFlag; +using gfx::MemoryAccess; +using gfx::MemoryUsage; +using gfx::PassType; +using gfx::ShaderStageFlags; +using gfx::TextureUsage; + +namespace { +enum class CommonUsage : uint32_t { + NONE = 0, + COPY_SRC = 1 << 0, + COPY_DST = 1 << 1, + ROM = 1 << 2, // sampled or UNIFORM + STORAGE = 1 << 3, + IB_OR_CA = 1 << 4, + VB_OR_DS = 1 << 5, + INDIRECT_OR_INPUT = 1 << 6, +}; +CC_ENUM_BITWISE_OPERATORS(CommonUsage); + +struct AccessElem { + uint32_t mask{0xFFFFFFFF}; + uint32_t key{0xFFFFFFFF}; + AccessFlags access{AccessFlags::NONE}; +}; + +// 23 and above :reserved +// 21 ~ 22: MemoryAccess +// 19 ~ 20: MemoryUsage +// 13 ~ 18: PassType +// 11 ~ 12: ResourceType +// 9 ~ 10: ShaderStageFlags +// 0 ~ 8: CommonUsage +constexpr uint32_t IGNORE_MEMACCESS = 0b0011111111111111111111; +constexpr uint32_t IGNORE_MEMUSAGE = 0b1100111111111111111111; +constexpr uint32_t IGNORE_PASSTYPE = 0b1111000000111111111111; +constexpr uint32_t IGNORE_RESTYPE = 0b1111111111001111111111; +constexpr uint32_t IGNORE_SHADERSTAGE = 0b1111111111110011111111; +constexpr uint32_t IGNORE_CMNUSAGE = 0b1111111111111100000000; +constexpr uint32_t IGNORE_NONE = 0xFFFFFFFF; + +constexpr uint32_t CARE_MEMACCESS = ~IGNORE_MEMACCESS; +constexpr uint32_t CARE_MEMUSAGE = ~IGNORE_MEMUSAGE; +constexpr uint32_t CARE_PASSTYPE = ~IGNORE_PASSTYPE; +constexpr uint32_t CARE_RESTYPE = ~IGNORE_RESTYPE; +constexpr uint32_t CARE_SHADERSTAGE = ~IGNORE_SHADERSTAGE; +constexpr uint32_t CARE_CMNUSAGE = ~IGNORE_CMNUSAGE; +constexpr uint32_t CARE_NONE = ~IGNORE_NONE; + +#define OPERABLE(val) static_cast::type>(val) + +constexpr auto ACCESS_READ = OPERABLE(MemoryAccess::READ_ONLY) << 20; +constexpr auto ACCESS_WRITE = OPERABLE(MemoryAccess::WRITE_ONLY) << 20; +constexpr auto MEM_DEVICE = OPERABLE(MemoryUsage::DEVICE) << 18; +constexpr auto MEM_HOST = OPERABLE(MemoryUsage::HOST) << 18; +constexpr auto PASS_RASTER = 1 << (OPERABLE(PassType::RASTER) + 12); +constexpr auto PASS_COMPUTE = 1 << (OPERABLE(PassType::COMPUTE) + 12); +constexpr auto PASS_COPY = 1 << (OPERABLE(PassType::COPY) + 12); +constexpr auto PASS_MOVE = 1 << (OPERABLE(PassType::MOVE) + 12); +constexpr auto PASS_RAYTRACE = 1 << (OPERABLE(PassType::RAYTRACE) + 12); +constexpr auto PASS_PRESENT = 1 << (OPERABLE(PassType::PRESENT) + 12); +constexpr auto RES_BUFFER = 1 << (OPERABLE(ResourceType::BUFFER) + 10); +constexpr auto RES_TEXTURE = 1 << (OPERABLE(ResourceType::TEXTURE) + 10); +constexpr auto SHADERSTAGE_VERT = 1 << 8; +constexpr auto SHADERSTAGE_FRAG = 1 << 9; +constexpr auto CMN_COPY_SRC = OPERABLE(CommonUsage::COPY_SRC); +constexpr auto CMN_COPY_DST = OPERABLE(CommonUsage::COPY_DST); +constexpr auto CMN_ROM = OPERABLE(CommonUsage::ROM); +constexpr auto CMN_STORAGE = OPERABLE(CommonUsage::STORAGE); +constexpr auto CMN_IB_OR_CA = OPERABLE(CommonUsage::IB_OR_CA); +constexpr auto CMN_VB_OR_DS = OPERABLE(CommonUsage::VB_OR_DS); +constexpr auto CMN_INDIRECT_OR_INPUT = OPERABLE(CommonUsage::INDIRECT_OR_INPUT); + +std::vector accessMap = { + {CARE_MEMACCESS, + 0x0, + AccessFlags::NONE}, + + {CARE_MEMUSAGE, + 0x0, + AccessFlags::NONE}, + + {IGNORE_PASSTYPE & IGNORE_SHADERSTAGE, + ACCESS_READ | MEM_DEVICE | RES_BUFFER | CMN_INDIRECT_OR_INPUT, + AccessFlags::INDIRECT_BUFFER}, + + {IGNORE_SHADERSTAGE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_BUFFER | CMN_IB_OR_CA, + AccessFlags::INDEX_BUFFER}, // buffer usage indicates what it is, so shader stage ignored. + + {IGNORE_SHADERSTAGE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_BUFFER | CMN_VB_OR_DS, + AccessFlags::VERTEX_BUFFER}, // ditto + + {IGNORE_NONE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_BUFFER | SHADERSTAGE_VERT | CMN_ROM, + AccessFlags::VERTEX_SHADER_READ_UNIFORM_BUFFER}, + + {IGNORE_NONE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_VERT | CMN_ROM, + AccessFlags::VERTEX_SHADER_READ_TEXTURE}, + + {IGNORE_RESTYPE & IGNORE_CMNUSAGE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | SHADERSTAGE_VERT, + AccessFlags::VERTEX_SHADER_READ_OTHER}, + + {IGNORE_NONE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_BUFFER | SHADERSTAGE_FRAG | CMN_ROM, + AccessFlags::FRAGMENT_SHADER_READ_UNIFORM_BUFFER}, + + {IGNORE_NONE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_ROM, + AccessFlags::FRAGMENT_SHADER_READ_TEXTURE}, + + {IGNORE_NONE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA | CMN_INDIRECT_OR_INPUT, + AccessFlags::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT}, + + {IGNORE_NONE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_VB_OR_DS | CMN_INDIRECT_OR_INPUT, + AccessFlags::FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT}, + + {IGNORE_NONE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | SHADERSTAGE_FRAG, + AccessFlags::FRAGMENT_SHADER_READ_OTHER}, + + {IGNORE_NONE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA, + AccessFlags::COLOR_ATTACHMENT_READ}, + + {IGNORE_NONE, + ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_VB_OR_DS, + AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ}, + + {IGNORE_PASSTYPE & IGNORE_SHADERSTAGE, + ACCESS_READ | MEM_DEVICE | RES_BUFFER | CMN_ROM, + AccessFlags::COMPUTE_SHADER_READ_UNIFORM_BUFFER}, + + {IGNORE_PASSTYPE & IGNORE_SHADERSTAGE, + ACCESS_READ | MEM_DEVICE | RES_TEXTURE | CMN_ROM, + AccessFlags::COMPUTE_SHADER_READ_TEXTURE}, + + {CARE_MEMACCESS | CARE_MEMUSAGE, + ACCESS_READ | MEM_DEVICE, + AccessFlags::COMPUTE_SHADER_READ_OTHER}, + + {CARE_MEMACCESS | CARE_MEMUSAGE | CARE_PASSTYPE, + ACCESS_READ | MEM_DEVICE | PASS_COMPUTE, + AccessFlags::TRANSFER_READ}, + + {CARE_MEMACCESS | CARE_MEMUSAGE, + ACCESS_READ | MEM_HOST, + AccessFlags::HOST_READ}, + + {CARE_MEMACCESS | CARE_MEMUSAGE | CARE_PASSTYPE, + ACCESS_READ | MEM_DEVICE | PASS_PRESENT, + AccessFlags::PRESENT}, + + {IGNORE_RESTYPE & IGNORE_CMNUSAGE, + ACCESS_WRITE | MEM_DEVICE | PASS_RASTER | SHADERSTAGE_VERT, + AccessFlags::VERTEX_SHADER_WRITE}, + + {IGNORE_RESTYPE & IGNORE_CMNUSAGE, + ACCESS_WRITE | MEM_DEVICE | PASS_RASTER | SHADERSTAGE_FRAG, + AccessFlags::FRAGMENT_SHADER_WRITE}, + + {IGNORE_NONE, + ACCESS_WRITE | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA, + AccessFlags::COLOR_ATTACHMENT_WRITE}, + + {IGNORE_NONE, + ACCESS_WRITE | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_VB_OR_DS, + AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE}, + + {CARE_MEMACCESS | CARE_MEMUSAGE, + ACCESS_WRITE | MEM_DEVICE, + AccessFlags::COMPUTE_SHADER_WRITE}, + + {CARE_MEMACCESS | CARE_MEMUSAGE | CARE_PASSTYPE, + ACCESS_WRITE | MEM_DEVICE | PASS_COPY, + AccessFlags::TRANSFER_WRITE}, + + {CARE_MEMACCESS | CARE_MEMUSAGE, + ACCESS_WRITE | MEM_HOST, + AccessFlags::HOST_WRITE}, +}; +} // namespace + +std::pair getBarrier(const ResourceBarrier& barrierInfo, const DevicePassResourceTable* dictPtr) noexcept { + std::pair res; + + const auto& dict = *dictPtr; + if (barrierInfo.resourceType == ResourceType::BUFFER) { + gfx::Buffer* gfxBuffer{nullptr}; + if (hasFlag(barrierInfo.endStatus.access, MemoryAccess::WRITE_ONLY)) { + gfxBuffer = dict.getWrite(static_cast(barrierInfo.handle)); + } else { + gfxBuffer = dict.getRead(static_cast(barrierInfo.handle)); + } + gfx::BufferBarrierInfo info; + + auto getGFXAccess = [&gfxBuffer](const AccessStatus& status) { + auto usage = gfxBuffer->getUsage(); + auto memUsage = gfxBuffer->getMemUsage(); + + uint32_t info = 0xFFFFFFFF; + info &= (OPERABLE(status.access) << 20 | IGNORE_MEMACCESS); + info &= (OPERABLE(memUsage) << 18 | IGNORE_MEMUSAGE); + info &= (1 << (OPERABLE(status.passType) + 12) | IGNORE_PASSTYPE); + info &= (1 << (OPERABLE(ResourceType::BUFFER) + 10) | IGNORE_RESTYPE); + switch (status.visibility) { + case ShaderStageFlags::NONE: + info &= IGNORE_SHADERSTAGE; + break; + case ShaderStageFlags::VERTEX: + info &= ((1 << 8) | IGNORE_SHADERSTAGE); + break; + case ShaderStageFlags::FRAGMENT: + info &= ((1 << 9) | IGNORE_SHADERSTAGE); + break; + default: + info |= ((0b11 << 8) | IGNORE_SHADERSTAGE); + } + info &= OPERABLE(usage) | IGNORE_CMNUSAGE; + + AccessFlags flags{AccessFlags::NONE}; + for (const auto& elem : accessMap) { + auto testFlag = info & elem.mask; + //hasKey + if ((testFlag & elem.key) == elem.key) { + flags |= elem.access; + } + } + return flags; + }; + + info.prevAccesses = getGFXAccess(barrierInfo.beginStatus); + info.nextAccesses = getGFXAccess(barrierInfo.endStatus); + info.offset = static_cast(barrierInfo.bufferRange.base); + info.size = static_cast(barrierInfo.bufferRange.len); + info.type = barrierInfo.barrierType; + + res.first = gfx::Device::getInstance()->getBufferBarrier(info); + res.second = gfxBuffer; + } else if (barrierInfo.resourceType == ResourceType::TEXTURE) { + gfx::Texture* gfxTexture{nullptr}; + if (hasFlag(barrierInfo.beginStatus.access, MemoryAccess::WRITE_ONLY)) { + gfxTexture = dict.getWrite(static_cast(barrierInfo.handle)); + } else { + gfxTexture = dict.getRead(static_cast(barrierInfo.handle)); + } + gfx::TextureBarrierInfo info; + + auto getGFXAccess = [&gfxTexture](const AccessStatus& status) { + auto usage = gfxTexture->getInfo().usage; + + uint32_t info = 0xFFFFFFFF; + info &= (OPERABLE(status.access) << 20 | IGNORE_MEMACCESS); + info &= MEM_DEVICE; + info &= (1 << (OPERABLE(status.passType) + 12) | IGNORE_PASSTYPE); + info &= (1 << (OPERABLE(ResourceType::BUFFER) + 10) | IGNORE_RESTYPE); + switch (status.visibility) { + case ShaderStageFlags::NONE: + info &= IGNORE_SHADERSTAGE; + break; + case ShaderStageFlags::VERTEX: + info &= ((1 << 8) | IGNORE_SHADERSTAGE); + break; + case ShaderStageFlags::FRAGMENT: + info &= ((1 << 9) | IGNORE_SHADERSTAGE); + break; + default: + info |= ((0b11 << 8) | IGNORE_SHADERSTAGE); + } + info &= OPERABLE(usage) | IGNORE_CMNUSAGE; + + AccessFlags flags{AccessFlags::NONE}; + for (const auto& elem : accessMap) { + auto testFlag = info & elem.mask; + //hasKey + if ((testFlag & elem.key) == elem.key) { + flags |= elem.access; + } + } + return flags; + }; + + info.type = barrierInfo.barrierType; + info.prevAccesses = getGFXAccess(barrierInfo.beginStatus); + info.nextAccesses = getGFXAccess(barrierInfo.endStatus); + info.baseMipLevel = static_cast(barrierInfo.mipRange.base); + info.levelCount = static_cast(barrierInfo.mipRange.len); + info.baseSlice = static_cast(barrierInfo.layerRange.base); + info.sliceCount = static_cast(barrierInfo.layerRange.len); + + res.first = gfx::Device::getInstance()->getTextureBarrier(info); + res.second = gfxTexture; + } + + return res; +} + +} // namespace framegraph +} // namespace cc diff --git a/native/cocos/renderer/frame-graph/ImmutableState.h b/native/cocos/renderer/frame-graph/ImmutableState.h new file mode 100644 index 0000000000..a608e293af --- /dev/null +++ b/native/cocos/renderer/frame-graph/ImmutableState.h @@ -0,0 +1,85 @@ + +/**************************************************************************** + Copyright (c) 2021-2022 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. +****************************************************************************/ + +#pragma once + +#include "frame-graph/Resource.h" +#include "gfx-base/GFXDef-common.h" + +namespace cc { +namespace framegraph { + +class DevicePassResourceTable; + +struct Range { + size_t base{0}; + size_t len{0}; +}; + +struct AccessStatus { + gfx::PassType passType{gfx::PassType::RASTER}; + gfx::ShaderStageFlagBit visibility{gfx::ShaderStageFlagBit::NONE}; + gfx::MemoryAccessBit access{gfx::MemoryAccessBit::NONE}; +}; + +enum class ResourceType : uint32_t { + UNKNOWN, + BUFFER, + TEXTURE, +}; + +struct ResourceBarrier { + ResourceType resourceType{ResourceType::UNKNOWN}; + gfx::BarrierType barrierType{gfx::BarrierType::FULL}; + + Handle handle; + + AccessStatus beginStatus; + AccessStatus endStatus; + Range layerRange; + + union { + Range mipRange; + Range bufferRange; + }; +}; + +struct PassBarrierPair { + ccstd::vector frontBarriers; + ccstd::vector rearBarriers; +}; + +using BarriersList = std::vector; + +struct PassBarriers { + PassBarrierPair blockBarrier; + BarriersList subpassBarriers; +}; + +std::pair getBarrier(const ResourceBarrier& barrierInfo, const DevicePassResourceTable* dict) noexcept; + +} // namespace framegraph +} // namespace cc diff --git a/native/cocos/renderer/frame-graph/PassNode.cpp b/native/cocos/renderer/frame-graph/PassNode.cpp index d8511e5dae..2b4f8756f0 100644 --- a/native/cocos/renderer/frame-graph/PassNode.cpp +++ b/native/cocos/renderer/frame-graph/PassNode.cpp @@ -184,5 +184,9 @@ Handle PassNode::getWriteResourceNodeHandle(const FrameGraph &graph, const Virtu return it == _writes.end() ? Handle{} : *it; } +void PassNode::setBarrier(const PassBarrierPair &barrier) { + _barriers = barrier; +} + } // namespace framegraph } // namespace cc diff --git a/native/cocos/renderer/frame-graph/PassNode.h b/native/cocos/renderer/frame-graph/PassNode.h index e4e7ee0c42..51e90bfedd 100644 --- a/native/cocos/renderer/frame-graph/PassNode.h +++ b/native/cocos/renderer/frame-graph/PassNode.h @@ -28,6 +28,7 @@ #include #include "CallbackPass.h" #include "Handle.h" +#include "ImmutableState.h" #include "PassInsertPointManager.h" #include "RenderTargetAttachment.h" #include "VirtualResource.h" @@ -50,9 +51,12 @@ public: Handle read(FrameGraph &graph, const Handle &input); Handle write(FrameGraph &graph, const Handle &output); void createRenderTargetAttachment(RenderTargetAttachment &&attachment); + void setBarrier(const PassBarrierPair &barrier); + inline void sideEffect(); inline void subpass(bool end, bool clearActionIgnorable); inline void setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor); + inline const PassBarrierPair &getBarriers() const; private: bool canMerge(const FrameGraph &graph, const PassNode &passNode) const; @@ -88,6 +92,8 @@ private: gfx::Viewport _viewport; gfx::Rect _scissor; + PassBarrierPair _barriers; + friend class FrameGraph; friend class DevicePass; friend class DevicePassResourceTable; @@ -95,6 +101,10 @@ private: ////////////////////////////////////////////////////////////////////////// +const PassBarrierPair &PassNode::getBarriers() const { + return _barriers; +} + void PassNode::sideEffect() { _sideEffect = true; } diff --git a/native/cocos/renderer/frame-graph/PassNodeBuilder.h b/native/cocos/renderer/frame-graph/PassNodeBuilder.h index 31298e82f4..2aebdee70c 100644 --- a/native/cocos/renderer/frame-graph/PassNodeBuilder.h +++ b/native/cocos/renderer/frame-graph/PassNodeBuilder.h @@ -55,6 +55,7 @@ public: inline void subpass(bool end = false, bool clearActionIgnorable = true) const noexcept; inline void setViewport(const gfx::Rect &scissor) noexcept; inline void setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) noexcept; + inline void setBarrier(const PassBarrierPair &barrier); void writeToBlackboard(const StringHandle &name, const Handle &handle) const noexcept; Handle readFromBlackboard(const StringHandle &name) const noexcept; @@ -95,5 +96,9 @@ void PassNodeBuilder::setViewport(const gfx::Viewport &viewport, const gfx::Rect _passNode.setViewport(viewport, scissor); } +void PassNodeBuilder::setBarrier(const PassBarrierPair &barrier) { + _passNode.setBarrier(barrier); +} + } // namespace framegraph } // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index a15a65f406..792c72a977 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -106,6 +106,9 @@ using TextureList = ccstd::vector; using SamplerList = ccstd::vector; using DescriptorSetLayoutList = ccstd::vector; +// make sure you have FILLED GRAPHs before enable this! +static constexpr bool ENABLE_GRAPH_AUTO_BARRIER{false}; + /** * @en Graphics object type * @zh 图形API对象的类型 @@ -793,6 +796,16 @@ enum class BarrierType : uint32_t { }; CC_ENUM_BITWISE_OPERATORS(BarrierType); +enum class PassType : uint32_t { + RASTER, + COMPUTE, + COPY, + MOVE, + RAYTRACE, + PRESENT, +}; +CC_ENUM_CONVERSION_OPERATOR(PassType); + #define EXPOSE_COPY_FN(type) \ type ©(const type &rhs) { \ *this = rhs; \ @@ -837,6 +850,13 @@ struct DeviceCaps { EXPOSE_COPY_FN(DeviceCaps) }; +struct DeviceOptions { + // whether deduce barrier in gfx internally. + // if you wanna do the barrier thing by yourself + // on the top of gfx layer, set it to false. + bool enableBarrierDeduce{true}; +}; + struct Offset { int32_t x{0}; int32_t y{0}; @@ -1289,7 +1309,13 @@ using SubpassInfoList = ccstd::vector; struct ALIGNAS(8) SubpassDependency { uint32_t srcSubpass{0}; uint32_t dstSubpass{0}; - GeneralBarrier *barrier{nullptr}; + GeneralBarrier *generalBarrier{nullptr}; + BufferBarrier **bufferBarriers{nullptr}; + Buffer **buffers{nullptr}; + uint32_t bufferBarrierCount{0}; + TextureBarrier **textureBarriers{nullptr}; + Texture **textures{nullptr}; + uint32_t textureBarrierCount{0}; #if CC_CPU_ARCH == CC_CPU_ARCH_32 uint32_t _padding{0}; #endif diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index ff575db63d..f1140378b2 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -118,6 +118,9 @@ public: template void registerOnAcquireCallback(ExecuteMethod &&execute); + inline void setOptions(const DeviceOptions &opts) { _options = opts; } + inline const DeviceOptions &getOptions() const { return _options; } + protected: static Device *instance; @@ -163,6 +166,7 @@ protected: API _api{API::UNKNOWN}; DeviceCaps _caps; BindingMappingInfo _bindingMappingInfo; + DeviceOptions _options; bool _multithreadedCommandRecording{true}; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 2e057a3257..0d944b8240 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -1377,13 +1377,62 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * gpuRenderPass->statistics[i].storeSubpass != SUBPASS_EXTERNAL); } - // should deduce this from subpass & attachment access infos - gpuRenderPass->barriers.resize(gpuRenderPass->subpasses.size() + 1); + ccstd::unordered_map> resRecord; + // if barrier deduce enabled: should deduce this from subpass & attachment access infos + if constexpr (ENABLE_GRAPH_AUTO_BARRIER) { + gpuRenderPass->subpassBarriers.resize(gpuRenderPass->dependencies.size()); + for (size_t i = 0; i < gpuRenderPass->subpassBarriers.size(); ++i) { + auto &barrier = gpuRenderPass->subpassBarriers[i]; + const auto &dependency = gpuRenderPass->dependencies[i]; + if (dependency.generalBarrier) { + barrier.prevAccesses = dependency.generalBarrier->getInfo().prevAccesses; + barrier.nextAccesses = dependency.generalBarrier->getInfo().nextAccesses; + completeBarrier(&barrier); + completeBarrier(&gpuRenderPass->blockBarrier); + } + + if (dependency.bufferBarrierCount) { + for (size_t index = 0; index < dependency.bufferBarrierCount; ++index) { + barrier.prevAccesses = dependency.bufferBarriers[index]->getInfo().prevAccesses; + barrier.nextAccesses = dependency.bufferBarriers[index]->getInfo().nextAccesses; + completeBarrier(&barrier); + auto iter = resRecord.find(dependency.buffers[index]); + if (iter == resRecord.end()) { + resRecord.insert({dependency.buffers[index], std::pair(barrier.glBarriers, barrier.glBarriersByRegion)}); + } else { + iter->second = std::pair(barrier.glBarriers, barrier.glBarriersByRegion); + } + } + } + + if (dependency.textureBarrierCount) { + for (size_t index = 0; index < dependency.textureBarrierCount; ++index) { + barrier.prevAccesses = dependency.textureBarriers[index]->getInfo().prevAccesses; + barrier.nextAccesses = dependency.textureBarriers[index]->getInfo().nextAccesses; + completeBarrier(&barrier); + auto iter = resRecord.find(dependency.textures[index]); + if (iter == resRecord.end()) { + resRecord.insert({dependency.textures[index], std::pair(barrier.glBarriers, barrier.glBarriersByRegion)}); + } else { + iter->second = std::pair(barrier.glBarriers, barrier.glBarriersByRegion); + } + } + } + } + + for (const auto &pair : resRecord) { + const auto &barrier = pair.second; + gpuRenderPass->blockBarrier.glBarriers |= barrier.first; + gpuRenderPass->blockBarrier.glBarriersByRegion |= barrier.second; + } + } else { + gpuRenderPass->subpassBarriers.resize(gpuRenderPass->subpasses.size() + 1); + } } void cmdFuncGLES3DestroyRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass *gpuRenderPass) { gpuRenderPass->statistics.clear(); - gpuRenderPass->barriers.clear(); + gpuRenderPass->subpassBarriers.clear(); } void cmdFuncGLES3CreateInputAssembler(GLES3Device *device, GLES3GPUInputAssembler *gpuInputAssembler) { @@ -1979,7 +2028,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, GLES3 uint32_t glAttachmentIndex = 0U; if (gpuFramebuffer->usesFBF) { if (subpassIdx == 0) { - cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->barriers[0].glBarriers, gpuRenderPass->barriers[0].glBarriersByRegion); + cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->blockBarrier.glBarriers, gpuRenderPass->blockBarrier.glBarriersByRegion); for (const auto attachmentIndex : gpuFramebuffer->uberColorAttachmentIndices) { performLoadOp(attachmentIndex, glAttachmentIndex++); @@ -1987,7 +2036,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, GLES3 performDepthStencilLoadOp(gpuFramebuffer->uberDepthStencil, false); } } else { - cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->barriers[subpassIdx].glBarriers, gpuRenderPass->barriers[subpassIdx].glBarriersByRegion); + cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->subpassBarriers[subpassIdx].glBarriers, gpuRenderPass->subpassBarriers[subpassIdx].glBarriersByRegion); for (const auto attachmentIndex : gpuRenderPass->subpasses[subpassIdx].colors) { if (gpuRenderPass->statistics[attachmentIndex].loadSubpass != subpassIdx) continue; @@ -2139,9 +2188,7 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { region.srcExtent.height = region.dstExtent.height = blitSrc->height; cmdFuncGLES3BlitTexture(device, blitSrc, blitDst, ®ion, 1, Filter::POINT); } - - cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->barriers.back().glBarriers, gpuRenderPass->barriers.back().glBarriersByRegion); - } else if (gpuFramebuffer->usesFBF) { + } else { if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_EXT) { GL_CHECK(glFramebufferFetchBarrierEXT()); } else if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { @@ -2157,8 +2204,8 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { bool skipStore = subpass.depthStencil == INVALID_BINDING || gpuRenderPass->statistics[subpass.depthStencil].storeSubpass != gfxStateCache.subpassIdx; performDepthStencilStoreOp(subpass.depthStencil, skipStore); - - cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->barriers.back().glBarriers, gpuRenderPass->barriers.back().glBarriersByRegion); + + cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->subpassBarriers.back().glBarriers, gpuRenderPass->subpassBarriers.back().glBarriersByRegion); } } diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index bd86c08d93..729e862ec9 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -325,10 +325,12 @@ struct GLES3GPURenderPass { ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; SubpassInfoList subpasses; + SubpassDependencyList dependencies; ccstd::vector statistics; // per attachment - ccstd::vector barriers; // per subpass + ccstd::vector subpassBarriers; // per subpass + GLES3GPUGeneralBarrier blockBarrier; }; class GLES3GPUFramebufferCacheMap; diff --git a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp index 52d8cfdde8..d2663ac1f2 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp @@ -46,6 +46,7 @@ void GLES3RenderPass::doInit(const RenderPassInfo & /*info*/) { _gpuRenderPass->colorAttachments = _colorAttachments; _gpuRenderPass->depthStencilAttachment = _depthStencilAttachment; _gpuRenderPass->subpasses = _subpasses; + _gpuRenderPass->dependencies = _dependencies; // assign a dummy subpass if not specified uint32_t colorCount = utils::toUint(_gpuRenderPass->colorAttachments.size()); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index 921d194022..7dd277bf4b 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -122,17 +122,23 @@ void CCVKCommandBuffer::end() { void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const * /*secondaryCBs*/, uint32_t secondaryCBCount) { + CCVKDevice *device = CCVKDevice::getInstance(); + if constexpr (!ENABLE_GRAPH_AUTO_BARRIER) { #if BARRIER_DEDUCTION_LEVEL >= BARRIER_DEDUCTION_LEVEL_BASIC - // guard against RAW hazard - VkMemoryBarrier vkBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - vkBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - vkBarrier.dstAccessMask = VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT; - vkCmdPipelineBarrier(_gpuCommandBuffer->vkCommandBuffer, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - 0, 1, &vkBarrier, 0, nullptr, 0, nullptr); + // guard against RAW hazard + VkMemoryBarrier vkBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + vkBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + vkBarrier.dstAccessMask = VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT; + vkCmdPipelineBarrier(_gpuCommandBuffer->vkCommandBuffer, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + 0, 1, &vkBarrier, 0, nullptr, 0, nullptr); #endif - + } else { + const auto& frontBarrier = renderPass->getDependencies().front(); + pipelineBarrier(frontBarrier.generalBarrier, frontBarrier.bufferBarriers, frontBarrier.buffers, frontBarrier.bufferBarrierCount, frontBarrier.textureBarriers, frontBarrier.textures, frontBarrier.textureBarrierCount); + } + _curGPUFBO = static_cast(fbo)->gpuFBO(); _curGPURenderPass = static_cast(renderPass)->gpuRenderPass(); VkFramebuffer framebuffer{_curGPUFBO->vkFramebuffer}; @@ -184,7 +190,8 @@ void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo void CCVKCommandBuffer::endRenderPass() { vkCmdEndRenderPass(_gpuCommandBuffer->vkCommandBuffer); - CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + auto* device = CCVKDevice::getInstance(); + CCVKGPUDevice *gpuDevice = device->gpuDevice(); size_t colorAttachmentCount = _curGPURenderPass->colorAttachments.size(); for (size_t i = 0U; i < colorAttachmentCount; ++i) { _curGPUFBO->gpuColorViews[i]->gpuTexture->currentAccessTypes = _curGPURenderPass->getBarrier(i, gpuDevice)->nextAccesses; @@ -196,12 +203,17 @@ void CCVKCommandBuffer::endRenderPass() { _curGPUFBO = nullptr; + if constexpr (!ENABLE_GRAPH_AUTO_BARRIER) { #if BARRIER_DEDUCTION_LEVEL >= BARRIER_DEDUCTION_LEVEL_BASIC - // guard against WAR hazard - vkCmdPipelineBarrier(_gpuCommandBuffer->vkCommandBuffer, - VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 0, nullptr); + // guard against WAR hazard + vkCmdPipelineBarrier(_gpuCommandBuffer->vkCommandBuffer, + VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 0, nullptr); #endif + } else { + const auto& rearBarrier = _curGPURenderPass->dependencies.back(); + pipelineBarrier(rearBarrier.generalBarrier, rearBarrier.bufferBarriers, rearBarrier.buffers, rearBarrier.bufferBarrierCount, rearBarrier.textureBarriers, rearBarrier.textures, rearBarrier.textureBarrierCount); + } } void CCVKCommandBuffer::bindPipelineState(PipelineState *pso) { diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index 958e9020c9..0f7d6ff297 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -23,6 +23,7 @@ THE SOFTWARE. ****************************************************************************/ +#include #include #include #include "VKStd.h" @@ -34,7 +35,9 @@ #include "VKDevice.h" #include "VKGPUObjects.h" #include "gfx-base/GFXDef.h" +#include "states/VKBufferBarrier.h" #include "states/VKGeneralBarrier.h" +#include "states/VKTextureBarrier.h" #include "gfx-base/SPIRVUtils.h" @@ -553,40 +556,73 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende size_t dependencyCount = gpuRenderPass->dependencies.size(); dependencyManager.clear(); - if (dependencyCount) { - offset = 0U; - VkImageLayout imageLayout{VK_IMAGE_LAYOUT_UNDEFINED}; - bool hasWriteAccess{false}; + bool manuallyDeduce = true; + if constexpr(ENABLE_GRAPH_AUTO_BARRIER) { + // single pass front and rear cost 2 slot. + manuallyDeduce = dependencyCount <= 2; + } else { + manuallyDeduce = dependencyCount == 0; + } + if (!manuallyDeduce) { + // offset = 0U; + ccstd::unordered_set subpassExternalFilter; for (uint32_t i = 0U; i < dependencyCount; ++i) { const auto &dependency{gpuRenderPass->dependencies[i]}; - const auto *gpuBarrier{static_cast(dependency.barrier)->gpuBarrier()}; - VkSubpassDependency2 vkDependency{VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2}; vkDependency.srcSubpass = dependency.srcSubpass; vkDependency.dstSubpass = dependency.dstSubpass; vkDependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - thsvsGetAccessInfo( - utils::toUint(gpuBarrier->prevAccesses.size()), - gpuBarrier->prevAccesses.data(), - &vkDependency.srcStageMask, - &vkDependency.srcAccessMask, - &imageLayout, &hasWriteAccess); + auto addStageAccessMask = [&vkDependency](const auto *barrier) { + VkPipelineStageFlags srcStageMask; + VkAccessFlags srcAccessMask; + VkPipelineStageFlags dstStageMask; + VkAccessFlags dstAccessMask; + VkImageLayout imageLayout{VK_IMAGE_LAYOUT_UNDEFINED}; + bool hasWriteAccess{false}; + const auto *gpuBarrier{barrier->gpuBarrier()}; + thsvsGetAccessInfo( + utils::toUint(gpuBarrier->prevAccesses.size()), + gpuBarrier->prevAccesses.data(), + &srcStageMask, + &srcAccessMask, + &imageLayout, &hasWriteAccess); - offset += gpuBarrier->prevAccesses.size(); + // offset += gpuBarrier->prevAccesses.size(); - thsvsGetAccessInfo( - utils::toUint(gpuBarrier->nextAccesses.size()), - gpuBarrier->nextAccesses.data(), - &vkDependency.dstStageMask, - &vkDependency.dstAccessMask, - &imageLayout, &hasWriteAccess); + thsvsGetAccessInfo( + utils::toUint(gpuBarrier->nextAccesses.size()), + gpuBarrier->nextAccesses.data(), + &dstStageMask, + &dstAccessMask, + &imageLayout, &hasWriteAccess); - dependencyManager.append(vkDependency); + // offset += gpuBarrier->nextAccesses.size(); + vkDependency.srcStageMask |= srcStageMask; + vkDependency.srcAccessMask |= srcAccessMask; + vkDependency.dstStageMask |= dstStageMask; + vkDependency.dstAccessMask |= dstAccessMask; + dependencyManager.append(vkDependency); + }; - offset += gpuBarrier->nextAccesses.size(); + if (dependency.generalBarrier) { + addStageAccessMask(static_cast(dependency.generalBarrier)); + } + + if (dependency.textureBarriers) { + for (size_t index = 0; index < dependency.textureBarrierCount; ++index) { + addStageAccessMask(static_cast(dependency.textureBarriers[index])); + } + } + + if (dependency.bufferBarriers) { + for (size_t index = 0; index < dependency.bufferBarrierCount; ++index) { + addStageAccessMask(static_cast(dependency.bufferBarriers[index])); + } + } } + } else { // try to deduce dependencies if not specified diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp index 9836126897..8a6427f74a 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp @@ -42,7 +42,8 @@ ResourceAccessGraph::ResourceAccessGraph(const allocator_type& alloc) noexcept passIndex(alloc), resourceNames(alloc), resourceIndex(alloc), - externalPasses(alloc) {} + externalPasses(alloc), + accessRecord(alloc) {} // ContinuousContainer void ResourceAccessGraph::reserve(vertices_size_type sz) { @@ -63,8 +64,9 @@ ResourceAccessGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& all : outEdges(rhs.outEdges, alloc), inEdges(rhs.inEdges, alloc) {} -FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, RenderGraph& graphIn, LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept // NOLINT -: resourceGraph(resourceGraphIn), +FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, RenderGraph& graphIn, LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept +: resourceAccessGraph(alloc), + resourceGraph(resourceGraphIn), graph(graphIn), layoutGraph(layoutGraphIn), scratch(scratchIn), diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index 2a5b25c969..0ced03718e 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -34,6 +34,7 @@ #include #include #include +#include #include "cocos/base/std/container/string.h" #include "cocos/base/std/container/vector.h" #include "cocos/renderer/pipeline/custom/GraphTypes.h" @@ -46,30 +47,37 @@ namespace cc { namespace render { -enum class PassType { - RASTER, - COMPUTE, - COPY, - MOVE, - RAYTRACE, - PRESENT, -}; - struct NullTag {}; -struct Range { - uint32_t mipLevels{0xFFFFFFFF}; - uint32_t numSlices{0xFFFFFFFF}; - uint32_t mostDetailedMip{0xFFFFFFFF}; - uint32_t firstSlice{0xFFFFFFFF}; - uint32_t planeSlice{0xFFFFFFFF}; +struct BufferRange { + uint32_t offset{0}; + uint32_t size{0}; }; +inline bool operator<(const BufferRange& lhs, const BufferRange& rhs) noexcept { + return std::forward_as_tuple(lhs.offset, lhs.size) < + std::forward_as_tuple(rhs.offset, rhs.size); +} + +struct TextureRange { + uint32_t firstSlice{0}; + uint32_t numSlices{1}; + uint32_t mipLevel{0}; + uint32_t levelCount{1}; +}; + +inline bool operator<(const TextureRange& lhs, const TextureRange& rhs) noexcept { + return std::forward_as_tuple(lhs.firstSlice, lhs.numSlices, lhs.mipLevel, lhs.levelCount) < + std::forward_as_tuple(rhs.firstSlice, rhs.numSlices, rhs.mipLevel, rhs.levelCount); +} + +using Range = ccstd::variant; + struct AccessStatus { uint32_t vertID{0xFFFFFFFF}; gfx::ShaderStageFlagBit visibility{gfx::ShaderStageFlagBit::NONE}; gfx::MemoryAccessBit access{gfx::MemoryAccessBit::NONE}; - PassType passType{PassType::RASTER}; + gfx::PassType passType{gfx::PassType::RASTER}; Range range; }; @@ -79,8 +87,8 @@ struct ResourceTransition { }; struct ResourceAccessNode { - std::vector attachemntStatus; - uint32_t circuitFlag; + std::vector attachemntStatus; + struct ResourceAccessNode* nextSubpass{nullptr}; }; struct ResourceAccessGraph { @@ -167,6 +175,20 @@ struct ResourceAccessGraph { using edge_iterator = impl::DirectedEdgeIterator; using edges_size_type = uint32_t; + ~ResourceAccessGraph() { + for (auto& node : access) { + auto* resNode = node.nextSubpass; + node.nextSubpass = nullptr; + while(resNode) { + auto* oldResNode = resNode; + resNode = resNode->nextSubpass; + oldResNode->nextSubpass = nullptr; + delete oldResNode; + } + } + } + + // ContinuousContainer void reserve(vertices_size_type sz); @@ -207,6 +229,7 @@ struct ResourceAccessGraph { PmrUnorderedStringMap resourceIndex; RenderGraph::vertex_descriptor presentPassID{0xFFFFFFFF}; ccstd::pmr::vector externalPasses; + PmrFlatMap accessRecord; }; struct EmptyGraph { @@ -298,19 +321,25 @@ struct EmptyGraph { struct Barrier { RenderGraph::vertex_descriptor resourceID{0xFFFFFFFF}; + gfx::BarrierType type{gfx::BarrierType::FULL}; AccessStatus beginStatus; AccessStatus endStatus; }; -struct BarrierNode { +struct BarrierPair { std::vector frontBarriers; std::vector rearBarriers; }; +struct BarrierNode { + BarrierPair blockBarrier; + std::vector subpassBarriers; +}; + struct FrameGraphDispatcher { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT - return {resourceGraph.get_allocator().resource()}; + return {resourceAccessGraph.get_allocator().resource()}; } FrameGraphDispatcher(ResourceGraph& resourceGraphIn, RenderGraph& graphIn, LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept; @@ -319,6 +348,8 @@ struct FrameGraphDispatcher { FrameGraphDispatcher& operator=(FrameGraphDispatcher&& rhs) = delete; FrameGraphDispatcher& operator=(FrameGraphDispatcher const& rhs) = delete; + using BarrierMap = FlatMap; + void enablePassReorder(bool enable); // how much paralell-execution weights during pass reorder, @@ -330,6 +361,11 @@ struct FrameGraphDispatcher { void run(); + inline const BarrierMap& getBarriers() const { return barrierMap; } + + BarrierMap barrierMap; + + ResourceAccessGraph resourceAccessGraph; ResourceGraph& resourceGraph; RenderGraph& graph; LayoutGraphData& layoutGraph; diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index 44d4b829a2..e17655c3d4 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -23,13 +23,14 @@ THE SOFTWARE. ****************************************************************************/ #ifdef __clang__ -#pragma clang diagnostic ignored "-Wshorten-64-to-32" + #pragma clang diagnostic ignored "-Wshorten-64-to-32" #endif #include #include #include #include #include +#include #include #include #include "FGDispatcherGraphs.h" @@ -45,6 +46,7 @@ #include "boost/lexical_cast.hpp" #include "gfx-base/GFXDef-common.h" #include "gfx-base/GFXDef.h" +#include "gfx-base/GFXDevice.h" #include "math/Vec2.h" #include "pipeline/custom/GslUtils.h" #include "pipeline/custom/RenderCommonFwd.h" @@ -54,19 +56,18 @@ namespace cc { namespace render { -void passReorder(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag); -void memoryAliasing(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag); -void buildBarriers(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag); +void passReorder(FrameGraphDispatcher &fgDispatcher); +void memoryAliasing(FrameGraphDispatcher &fgDispatcher); +void buildBarriers(FrameGraphDispatcher &fgDispatcher); void FrameGraphDispatcher::run() { - ResourceAccessGraph rag(this->scratch); if (_enablePassReorder) { - passReorder(*this, rag); + passReorder(*this); } if (_enableMemoryAliasing) { - memoryAliasing(*this, rag); + memoryAliasing(*this); } - buildBarriers(*this, rag); + buildBarriers(*this); } void FrameGraphDispatcher::enablePassReorder(bool enable) { @@ -87,7 +88,8 @@ void FrameGraphDispatcher::setParalellWeight(float paralellExecWeight) { using PmrString = ccstd::pmr::string; using RAG = ResourceAccessGraph; using LGD = LayoutGraphData; -using BarrierMap = FlatMap; +using gfx::PassType; +using BarrierMap = FrameGraphDispatcher::BarrierMap; using AccessVertex = ResourceAccessGraph::vertex_descriptor; using InputStatusTuple = std::tuple; using ResourceHandle = ResourceGraph::vertex_descriptor; @@ -96,8 +98,26 @@ using EdgeList = std::pair; using CloseCircuit = std::pair; using CloseCircuits = std::vector; using EmptyVert = EmptyGraph::vertex_descriptor; -using EmptyVerts = std::vector; -using ScoreMap = std::map>; +using EmptyVerts = std::vector; +using EmptyEdge = EmptyGraph::edge_descriptor; +using EmptyEdges = std::vector; +using ScoreMap = std::map>; +using RasterViewsMap = PmrTransparentMap; +using ComputeViewsMap = PmrTransparentMap>; + +struct Graphs { + const ResourceGraph &resourceGraph; + const LayoutGraphData &layoutGraphData; + ResourceAccessGraph &resourceAccessGraph; + EmptyGraph &relationGraph; +}; + +struct ViewStatus { + const PmrString &name; + const PassType passType; + const gfx::ShaderStageFlagBit visibility; + const gfx::MemoryAccessBit access; +}; auto defaultAccess = gfx::MemoryAccessBit::NONE; auto defaultVisibility = gfx::ShaderStageFlagBit::NONE; @@ -133,18 +153,22 @@ gfx::MemoryAccessBit toGfxAccess(AccessType type) { }; // AccessStatus.vertID : in resourceNode it's resource ID; in barrierNode it's pass ID. -AccessVertex dependencyCheck(RAG &rag, AccessTable &accessRecord, AccessVertex curVertID, const InputStatusTuple &status); +AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ViewStatus &status); gfx::ShaderStageFlagBit getVisibilityByDescName(const LGD &lgd, uint32_t passID, const PmrString &slotName); -void addAccessNode(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, InputStatusTuple status, const Range &range); -void processRasterPass(RAG &rag, EmptyGraph &relationGraph, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const RasterPass &pass); -void processComputePass(RAG &rag, EmptyGraph &relationGraph, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const ComputePass &pass); -void processCopyPass(RAG &rag, EmptyGraph &relationGraph, const LGD & /*lgd*/, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const CopyPass &pass); -void processRaytracePass(RAG &rag, EmptyGraph &relationGraph, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const RaytracePass &pass); -void processPresentPass(RAG &rag, EmptyGraph &relationGraph, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const PresentPass &pass); +void addAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status); +void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status); +void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass); +void processComputePass(const Graphs &graphs, uint32_t passID, const ComputePass &pass); +void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass); +void processRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass); +void processPresentPass(const Graphs &graphs, uint32_t passID, const PresentPass &pass); // execution order BUT NOT LOGICALLY -bool isPassExecAdjecent(uint32_t passL, uint32_t passR) { return (passL ^ passR) == 1; } +bool isPassExecAdjecent(uint32_t passLID, uint32_t passRID) { + return std::abs(static_cast(passLID) - static_cast(passRID)) <= 1; +} + bool isStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs); template bool tryAddEdge(uint32_t srcVertex, uint32_t dstVertex, Graph &graph); @@ -154,11 +178,11 @@ inline EmptyGraph::vertex_descriptor add_vertex(EmptyGraph &g) { // NOLINT } // status of resource access -void buildAccessGraph(const RenderGraph &renderGraph, const LayoutGraphData &lgd, const ResourceGraph &rescGragh, ResourceAccessGraph &rag, EmptyGraph &relationGraph) { +void buildAccessGraph(const RenderGraph &renderGraph, const Graphs &graphs) { // what we need: // - pass dependency // - pass attachment access - AccessTable accessRecord; + //AccessTable accessRecord; size_t numPasses = 1; numPasses += renderGraph.rasterPasses.size(); @@ -167,11 +191,13 @@ void buildAccessGraph(const RenderGraph &renderGraph, const LayoutGraphData &lgd numPasses += renderGraph.movePasses.size(); numPasses += renderGraph.raytracePasses.size(); - rag.reserve(static_cast(numPasses)); - rag.resourceNames.reserve(128); - rag.resourceIndex.reserve(128); + const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - auto startID = add_vertex(rag, INVALID_ID); + resourceAccessGraph.reserve(static_cast(numPasses)); + resourceAccessGraph.resourceNames.reserve(128); + resourceAccessGraph.resourceIndex.reserve(128); + + auto startID = add_vertex(resourceAccessGraph, INVALID_ID); CC_EXPECTS(startID == EXPECT_START_ID); add_vertex(relationGraph); @@ -180,19 +206,19 @@ void buildAccessGraph(const RenderGraph &renderGraph, const LayoutGraphData &lgd visitObject( passID, renderGraph, [&](const RasterPass &pass) { - processRasterPass(rag, relationGraph, lgd, rescGragh, accessRecord, passID, pass); + processRasterPass(graphs, passID, pass); }, [&](const ComputePass &pass) { - processComputePass(rag, relationGraph, lgd, rescGragh, accessRecord, passID, pass); + processComputePass(graphs, passID, pass); }, [&](const CopyPass &pass) { - processCopyPass(rag, relationGraph, lgd, rescGragh, accessRecord, passID, pass); + processCopyPass(graphs, passID, pass); }, [&](const RaytracePass &pass) { - processRaytracePass(rag, relationGraph, lgd, rescGragh, accessRecord, passID, pass); + processRaytracePass(graphs, passID, pass); }, [&](const PresentPass &pass) { - processPresentPass(rag, relationGraph, lgd, rescGragh, accessRecord, passID, pass); + processPresentPass(graphs, passID, pass); }, [&](const auto & /*pass*/) { // do nothing @@ -200,9 +226,9 @@ void buildAccessGraph(const RenderGraph &renderGraph, const LayoutGraphData &lgd } // make leaf node closed walk for pass reorder - for (auto pass : rag.externalPasses) { - if (out_degree(pass, rag) == 0) { - add_edge(pass, rag.presentPassID, rag); + for (auto pass : resourceAccessGraph.externalPasses) { + if (out_degree(pass, resourceAccessGraph) == 0) { + add_edge(pass, resourceAccessGraph.presentPassID, resourceAccessGraph); } } } @@ -213,64 +239,104 @@ struct BarrierVisitor : public boost::bfs_visitor<> { using Edge = ResourceAccessGraph::edge_descriptor; using Graph = ResourceAccessGraph; - explicit BarrierVisitor(const ResourceGraph &rg, BarrierMap &barriers, ExternalResMap &extMap, ResourceNames &externalNames) - : barrierMap(barriers), resourceGraph(rg), externalMap(extMap), externalResNames(externalNames) { + explicit BarrierVisitor(const ResourceGraph &rg, BarrierMap &barriers, ExternalResMap &extMap, ResourceNames &externalNames, const AccessTable& accessRecordIn) + : barrierMap(barriers), resourceGraph(rg), externalMap(extMap), externalResNames(externalNames), accessRecord(accessRecordIn) { } - void discover_vertex(Vertex u, const Graph &g) { + struct AccessNodeInfo { + const std::vector &status; + std::vector &edgeBarriers; // need to barrier front or back + const Vertex &vertID; + }; + + void processVertex(Vertex u, const Graph &g) { + const ResourceAccessNode &access = get(ResourceAccessGraph::AccessNode, g, u); + + if (barrierMap.find(u) == barrierMap.end()) { + barrierMap.emplace(u, BarrierNode{{}, {}}); + } + + const auto *srcAccess = &access; + + auto *dstAccess = access.nextSubpass; + auto &blockBarrier = barrierMap[u].blockBarrier; + auto &barriers = barrierMap[u].subpassBarriers; + if (!barriers.empty()) { + return; + } + uint32_t subpassIndex = 1; + bool isAdjacent = true; // subpass always adjacent to each other + if (dstAccess) { + // subpass at least two passes inside. + // the very first pass becomes attachment status collection of all subpass + CC_ASSERT(dstAccess->nextSubpass); + srcAccess = dstAccess; + dstAccess = dstAccess->nextSubpass; + barriers.emplace_back(); + } + while (dstAccess) { + barriers.emplace_back(); + CC_ASSERT(barriers.size() == subpassIndex + 1); + // 2 barriers at least when subpass exist + std::vector &srcRearBarriers = barriers[subpassIndex - 1].rearBarriers; + std::vector &dstFrontBarriers = barriers[subpassIndex].frontBarriers; + + AccessNodeInfo from = {srcAccess->attachemntStatus, srcRearBarriers, u}; + AccessNodeInfo to = {dstAccess->attachemntStatus, dstFrontBarriers, u}; + fillBarrier(from, to, isAdjacent); + + srcAccess = dstAccess; + dstAccess = dstAccess->nextSubpass; + } + + // last vertex front block barrier + if(!out_degree(u, g)) { + auto &rearBarriers = barrierMap[u].blockBarrier.rearBarriers; + auto &frontBarriers = barrierMap[u].blockBarrier.frontBarriers; + for (const auto &barriers : barrierMap[u].subpassBarriers) { + for (const auto &barrier : barriers.frontBarriers) { + auto resID = barrier.resourceID; + auto findBarrierByResID = [resID](const Barrier &barrier) { + return barrier.resourceID == resID; + }; + auto resFinalPassID = accessRecord.at(resID).currStatus.vertID; + auto firstMeetIter = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID); + auto innerResIter = std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID); + + if (firstMeetIter == frontBarriers.end() && innerResIter == rearBarriers.end() && resFinalPassID >= u) { + frontBarriers.emplace_back(barrier); + } + } + } + } } - void batchBarriers(Edge e, const Graph &g) { - // what we get: - // - beginAccess: not NONE, endAccess: not NONE ===> full barrier - // - beginAccess: not NONE, endAccess: NONE ===> split begin barrier - // - beginAccess: NONE, endAccess: not NONE ===> split end barrier - - Vertex from = source(e, g); - Vertex to = target(e, g); - - bool isAdjacent = isPassExecAdjecent(from, to); - - const ResourceAccessNode &fromAccess = get(ResourceAccessGraph::AccessNode, g, from); - const ResourceAccessNode &toAccess = get(ResourceAccessGraph::AccessNode, g, to); - + void fillBarrier(const AccessNodeInfo &from, const AccessNodeInfo &to, bool isAdjacent) { + const auto &[srcStatus, srcRearBarriers, srcVert] = from; + const auto &[dstStatus, dstFrontBarriers, dstVert] = to; std::vector commonResources; - const std::vector &fromStatus = fromAccess.attachemntStatus; - const std::vector &toStatus = toAccess.attachemntStatus; - - std::set_intersection(fromStatus.begin(), fromStatus.end(), - toStatus.begin(), toStatus.end(), + std::set_intersection(srcStatus.begin(), srcStatus.end(), + dstStatus.begin(), dstStatus.end(), std::back_inserter(commonResources), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); - if (commonResources.empty()) { // this edge is a logic edge added during pass reorder, // no real dependency between this two vertices. return; } - if (barrierMap.find(from) == barrierMap.end()) { - barrierMap.emplace(from, BarrierNode{}); - } - if (barrierMap.find(to) == barrierMap.end()) { - barrierMap.emplace(to, BarrierNode{}); - } - - std::vector &srcRearBarriers = barrierMap[from].rearBarriers; - std::vector &dstFrontBarriers = barrierMap[to].frontBarriers; - // NOLINTNEXTLINE for (uint32_t i = 0; i < commonResources.size(); ++i) { - const uint32_t resourceID = commonResources[i].vertID; + uint32_t resourceID = commonResources[i].vertID; auto findAccessByID = [resourceID](const AccessStatus &resAccess) { return resAccess.vertID == resourceID; }; - auto fromIter = std::find_if(fromStatus.begin(), fromStatus.end(), findAccessByID); - auto toIter = std::find_if(toStatus.begin(), toStatus.end(), findAccessByID); + auto fromIter = std::find_if(srcStatus.begin(), srcStatus.end(), findAccessByID); + auto toIter = std::find_if(dstStatus.begin(), dstStatus.end(), findAccessByID); // can't happen - CC_ASSERT(fromIter != fromStatus.end()); - CC_ASSERT(toIter != toStatus.end()); + CC_ASSERT(fromIter != srcStatus.end()); + CC_ASSERT(toIter != dstStatus.end()); if (!isStatusDependent(*fromIter, *toIter)) { continue; @@ -278,137 +344,149 @@ struct BarrierVisitor : public boost::bfs_visitor<> { auto findBarrierNodeByResID = [resourceID](const Barrier &barrier) { return resourceID == barrier.resourceID; }; - auto srcBarrierIter = std::find_if(srcRearBarriers.begin(), srcRearBarriers.end(), findBarrierNodeByResID); - auto dstBarrierIter = std::find_if(dstFrontBarriers.begin(), dstFrontBarriers.end(), findBarrierNodeByResID); + auto srcBarrierIter = srcRearBarriers.empty() ? srcRearBarriers.end() : std::find_if(srcRearBarriers.begin(), srcRearBarriers.end(), findBarrierNodeByResID); + auto dstBarrierIter = dstFrontBarriers.empty() ? dstFrontBarriers.end() : std::find_if(dstFrontBarriers.begin(), dstFrontBarriers.end(), findBarrierNodeByResID); if (srcBarrierIter == srcRearBarriers.end()) { srcRearBarriers.emplace_back(Barrier{ resourceID, + isAdjacent ? gfx::BarrierType::FULL : gfx::BarrierType::SPLIT_BEGIN, { - from, + srcVert, (*fromIter).visibility, (*fromIter).access, (*fromIter).passType, (*fromIter).range, }, { - to, - isAdjacent ? (*toIter).visibility : defaultVisibility, - isAdjacent ? (*toIter).access : defaultAccess, + isAdjacent ? srcVert : dstVert, + (*toIter).visibility, + (*toIter).access, (*toIter).passType, (*toIter).range, }, }); - + srcBarrierIter = std::prev(srcRearBarriers.end()); } else { if (isAdjacent) { - (*srcBarrierIter).beginStatus.vertID = from; + (*srcBarrierIter).type = gfx::BarrierType::FULL; + + (*srcBarrierIter).beginStatus.vertID = srcVert; (*srcBarrierIter).beginStatus.visibility = (*fromIter).visibility; (*srcBarrierIter).beginStatus.access = (*fromIter).access; (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; (*srcBarrierIter).beginStatus.range = (*fromIter).range; - (*srcBarrierIter).endStatus.vertID = to; + (*srcBarrierIter).endStatus.vertID = dstVert; (*srcBarrierIter).endStatus.visibility = (*toIter).visibility; (*srcBarrierIter).endStatus.access = (*toIter).access; (*srcBarrierIter).endStatus.passType = (*toIter).passType; (*srcBarrierIter).endStatus.range = (*toIter).range; } else { - if (from > (*srcBarrierIter).beginStatus.vertID) { + if (srcVert >= (*srcBarrierIter).beginStatus.vertID) { uint32_t siblingPass = (*srcBarrierIter).beginStatus.vertID; - (*srcBarrierIter).beginStatus.vertID = from; + (*srcBarrierIter).beginStatus.vertID = srcVert; (*srcBarrierIter).beginStatus.visibility = (*fromIter).visibility; (*srcBarrierIter).beginStatus.access = (*fromIter).access; (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; (*srcBarrierIter).beginStatus.range = (*fromIter).range; - auto siblingIter = std::find_if(barrierMap[siblingPass].rearBarriers.begin(), barrierMap[siblingPass].rearBarriers.end(), - [resourceID](const Barrier &barrier) { - return resourceID == barrier.resourceID; - }); - CC_ASSERT(siblingIter != barrierMap[siblingPass].rearBarriers.end()); - barrierMap[siblingPass].rearBarriers.erase(siblingIter); + // + if (srcVert > (*srcBarrierIter).beginStatus.vertID) { + auto &siblingPassBarrier = barrierMap[siblingPass].blockBarrier.rearBarriers; + auto siblingIter = std::find_if(siblingPassBarrier.begin(), siblingPassBarrier.end(), + [resourceID](const Barrier &barrier) { + return resourceID == barrier.resourceID; + }); + CC_ASSERT(siblingIter != siblingPassBarrier.end()); + siblingPassBarrier.erase(siblingIter); + } } } } - if (dstBarrierIter == dstFrontBarriers.end()) { - // if isAdjacent, full barrier already in src rear barriers. - if (!isAdjacent) { - dstFrontBarriers.emplace_back(Barrier{ - resourceID, - { - from, - defaultVisibility, - defaultAccess, - (*fromIter).passType, - (*fromIter).range, - }, - { - to, // next use of resc varies between resources - (*toIter).visibility, - (*toIter).access, - (*toIter).passType, - (*toIter).range, - }, - }); - } - } else { - if (isAdjacent) { - // adjacent, barrier should be commit at fromPass, and remove this iter from dstBarriers - (*srcBarrierIter).beginStatus.vertID = from; - (*srcBarrierIter).beginStatus.visibility = (*fromIter).visibility; - (*srcBarrierIter).beginStatus.access = (*fromIter).access; - (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; - (*srcBarrierIter).beginStatus.range = (*fromIter).range; - - (*srcBarrierIter).endStatus.vertID = to; - (*srcBarrierIter).endStatus.visibility = (*toIter).visibility; - (*srcBarrierIter).endStatus.access = (*toIter).access; - (*srcBarrierIter).endStatus.passType = (*toIter).passType; - (*srcBarrierIter).endStatus.range = (*toIter).range; - - dstFrontBarriers.erase(dstBarrierIter); + if ((*srcBarrierIter).type == gfx::BarrierType::SPLIT_BEGIN) { + if (dstBarrierIter == dstFrontBarriers.end()) { + // if isAdjacent, full barrier already in src rear barriers. + if (!isAdjacent) { + dstFrontBarriers.emplace_back(Barrier{ + resourceID, + gfx::BarrierType::SPLIT_END, + { + srcVert, + (*fromIter).visibility, + (*fromIter).access, + (*fromIter).passType, + (*fromIter).range, + }, + { + dstVert, // next use of resc varies between resources + (*toIter).visibility, + (*toIter).access, + (*toIter).passType, + (*toIter).range, + }, + }); + } } else { - // logic but not exec adjacent - // and more adjacent(further from src) than another pass which hold a use of resourceID - // replace previous one + if (isAdjacent) { + // adjacent, barrier should be commit at fromPass, and remove this iter from dstBarriers + (*srcBarrierIter).type = gfx::BarrierType::FULL; - // 1 --> 2 --> 3 - // ↓ - // 4 --> 5 --> 6 + (*srcBarrierIter).beginStatus.vertID = srcVert; + (*srcBarrierIter).beginStatus.visibility = (*fromIter).visibility; + (*srcBarrierIter).beginStatus.access = (*fromIter).access; + (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; + (*srcBarrierIter).beginStatus.range = (*fromIter).range; - // [if] real pass order: 1 - 2 - 4 - 5 - 3 - 6 + (*srcBarrierIter).endStatus.vertID = dstVert; + (*srcBarrierIter).endStatus.visibility = (*toIter).visibility; + (*srcBarrierIter).endStatus.access = (*toIter).access; + (*srcBarrierIter).endStatus.passType = (*toIter).passType; + (*srcBarrierIter).endStatus.range = (*toIter).range; - // 2 and 5 read from ResA, 6 writes to ResA - // 5 and 6 logically adjacent but not adjacent in execution order. - // barrier for ResA between 2 - 6 can be totally replace by 5 - 6 - if (to < (*dstBarrierIter).endStatus.vertID) { - uint32_t siblingPass = (*dstBarrierIter).endStatus.vertID; - (*dstBarrierIter).endStatus.vertID = to; - (*dstBarrierIter).endStatus.visibility = (*toIter).visibility; - (*dstBarrierIter).endStatus.access = (*toIter).access; - (*dstBarrierIter).endStatus.passType = (*toIter).passType; - (*dstBarrierIter).endStatus.range = (*toIter).range; + dstFrontBarriers.erase(dstBarrierIter); + } else { + // logic but not exec adjacent + // and more adjacent(further from src) than another pass which hold a use of resourceID + // replace previous one - // remove the further redundant barrier - auto siblingIter = std::find_if(barrierMap[siblingPass].frontBarriers.begin(), barrierMap[siblingPass].frontBarriers.end(), - [resourceID](const Barrier &barrier) { - return resourceID == barrier.resourceID; - }); - CC_ASSERT(siblingIter != barrierMap[siblingPass].frontBarriers.end()); - barrierMap[siblingPass].frontBarriers.erase(siblingIter); + // 1 --> 2 --> 3 + // ↓ + // 4 --> 5 --> 6 + + // [if] real pass order: 1 - 2 - 4 - 5 - 3 - 6 + + // 2 and 5 read from ResA, 6 writes to ResA + // 5 and 6 logically adjacent but not adjacent in execution order. + // barrier for ResA between 2 - 6 can be totally replace by 5 - 6 + if (dstVert <= (*dstBarrierIter).endStatus.vertID) { + uint32_t siblingPass = (*dstBarrierIter).endStatus.vertID; + (*dstBarrierIter).endStatus.vertID = dstVert; + (*dstBarrierIter).endStatus.visibility = (*toIter).visibility; + (*dstBarrierIter).endStatus.access = (*toIter).access; + (*dstBarrierIter).endStatus.passType = (*toIter).passType; + (*dstBarrierIter).endStatus.range = (*toIter).range; + + // remove the further redundant barrier + auto &siblingPassBarrier = barrierMap[siblingPass].blockBarrier.frontBarriers; + auto siblingIter = std::find_if(siblingPassBarrier.begin(), siblingPassBarrier.end(), + [resourceID](const Barrier &barrier) { + return resourceID == barrier.resourceID; + }); + CC_ASSERT(siblingIter != siblingPassBarrier.end()); + siblingPassBarrier.erase(siblingIter); + } } } } } //----------------------------------------------check external---------------------------------------------- - auto barrierExternalRes = [&](const AccessStatus &rescAccess, bool isFrom) { uint32_t rescID = rescAccess.vertID; bool externalRes = get(get(ResourceGraph::Traits, resourceGraph), rescID).hasSideEffects(); - Vertex vert = isFrom ? from : to; + Vertex vert = isFrom ? from.vertID : to.vertID; if (externalRes) { const PmrString &resName = get(ResourceGraph::Name, resourceGraph, rescID); auto iter = externalMap.find(resName); @@ -444,9 +522,10 @@ struct BarrierVisitor : public boost::bfs_visitor<> { }; if (isStatusDependent(externalMap[resName].lastStatus, externalMap[resName].currStatus)) { - barrierMap[vert].frontBarriers.emplace_back(Barrier{ + barrierMap[vert].blockBarrier.frontBarriers.emplace_back(Barrier{ rescID, - (*iter).second.currStatus, + gfx::BarrierType::SPLIT_END, + externalMap[resName].lastStatus, externalMap[resName].currStatus, }); } @@ -455,7 +534,6 @@ struct BarrierVisitor : public boost::bfs_visitor<> { } else { if ((*iter).second.currStatus.vertID < vert) { //[pass: vert] is later access than in iter. - externalMap[resName].lastStatus = externalMap[resName].currStatus; externalMap[resName].currStatus = { INVALID_ID, rescAccess.visibility, @@ -468,27 +546,104 @@ struct BarrierVisitor : public boost::bfs_visitor<> { } }; - for (const AccessStatus &rescAccess : fromAccess.attachemntStatus) { + for (const AccessStatus &rescAccess : srcStatus) { barrierExternalRes(rescAccess, true); } - for (const AccessStatus &rescAccess : toAccess.attachemntStatus) { + for (const AccessStatus &rescAccess : dstStatus) { barrierExternalRes(rescAccess, false); } //--------------------------------------------------------------------------------------------------------- } void examine_edge(Edge e, const Graph &g) { - batchBarriers(e, g); + Vertex from = source(e, g); + Vertex to = target(e, g); + + processVertex(from, g); + processVertex(to, g); + + // hasSubpass ? fromAccess is a single node with all attachment status stored in 'attachmentStatus' + // : fromAccess is head of chain of subpasses, which stores all attachment status in 'attachmentStatus' + const ResourceAccessNode &fromAccess = get(ResourceAccessGraph::AccessNode, g, from); + const ResourceAccessNode &toAccess = get(ResourceAccessGraph::AccessNode, g, to); + + bool isAdjacent = isPassExecAdjecent(from, to); + std::vector commonResources; + + const auto *srcHead = &fromAccess; + const auto *dstHead = &toAccess; + + uint32_t srcSubpassIndex = 0; + bool srcHasSubpass = srcHead->nextSubpass; + bool dstHasSubpass = dstHead->nextSubpass; + srcHead = srcHasSubpass ? srcHead->nextSubpass : srcHead; + + while (srcHead) { + const std::vector &fromStatus = srcHead->attachemntStatus; + std::vector &srcRearBarriers = srcHasSubpass ? barrierMap[from].subpassBarriers[srcSubpassIndex].rearBarriers : barrierMap[from].blockBarrier.rearBarriers; + uint32_t dstSubpassIndex = 0; + dstHead = &toAccess; + bool dstHasSubpass = dstHead->nextSubpass; + dstHead = dstHasSubpass ? toAccess.nextSubpass : &toAccess; + while (dstHead) { + const std::vector &toStatus = dstHead->attachemntStatus; + std::vector &dstFrontBarriers = dstHasSubpass ? barrierMap[to].subpassBarriers[dstSubpassIndex].frontBarriers : barrierMap[to].blockBarrier.frontBarriers; + AccessNodeInfo fromInfo = {fromStatus, srcRearBarriers, from}; + AccessNodeInfo toInfo = {toStatus, dstFrontBarriers, to}; + bool isExecAdjacent = isAdjacent && (!srcHead->nextSubpass && !dstSubpassIndex); + fillBarrier(fromInfo, toInfo, isAdjacent); + dstHead = dstHead->nextSubpass; + ++dstSubpassIndex; + } + srcHead = srcHead->nextSubpass; + ++srcSubpassIndex; + } + + auto &rearBarriers = barrierMap[from].blockBarrier.rearBarriers; + auto &frontBarriers = barrierMap[from].blockBarrier.frontBarriers; + for (const auto &barriers : barrierMap[from].subpassBarriers) { + for (const auto &barrier : barriers.rearBarriers) { + auto resID = barrier.resourceID; + auto findBarrierByResID = [resID](const Barrier &barrier) { + return barrier.resourceID == resID; + }; + auto iter = std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID); + auto resFinalPassID = accessRecord.at(resID).currStatus.vertID; + + if(resFinalPassID > from) { + if (iter == rearBarriers.end()) { + rearBarriers.emplace_back(barrier); + } else { + (*iter) = barrier; + } + } + } + + for (const auto &barrier : barriers.frontBarriers) { + auto resID = barrier.resourceID; + auto findBarrierByResID = [resID](const Barrier &barrier) { + return barrier.resourceID == resID; + }; + auto resFinalPassID = accessRecord.at(resID).currStatus.vertID; + auto firstMeetIter = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID); + auto innerResIter = std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID); + + if (firstMeetIter == frontBarriers.end() && innerResIter == rearBarriers.end() && resFinalPassID > from) { + frontBarriers.emplace_back(barrier); + } + } + } } + const AccessTable& accessRecord; BarrierMap &barrierMap; const ResourceGraph &resourceGraph; ExternalResMap &externalMap; // last frame to curr frame status transition ResourceNames &externalResNames; // first meet in this frame }; -void buildBarriers(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag) { +void buildBarriers(FrameGraphDispatcher &fgDispatcher) { { auto *scratch = fgDispatcher.scratch; const auto &graph = fgDispatcher.graph; @@ -496,20 +651,22 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag) const auto &resourceGraph = fgDispatcher.resourceGraph; auto &relationGraph = fgDispatcher.relationGraph; auto &externalResMap = fgDispatcher.externalResMap; + auto &rag = fgDispatcher.resourceAccessGraph; // record resource current in-access and out-access for every single node if (!fgDispatcher._accessGraphBuilt) { - buildAccessGraph(graph, layoutGraph, resourceGraph, rag, relationGraph); + const Graphs graphs{resourceGraph, layoutGraph, rag, relationGraph}; + buildAccessGraph(graph, graphs); fgDispatcher._accessGraphBuilt = true; } // found pass id in this map ? barriers you should commit when run into this pass // : or no extra barrier needed. - BarrierMap batchedBarriers; + BarrierMap &batchedBarriers = fgDispatcher.barrierMap; ResourceNames namesSet; { // _externalResNames records external resource between frames - BarrierVisitor visitor(resourceGraph, batchedBarriers, externalResMap, namesSet); + BarrierVisitor visitor(resourceGraph, batchedBarriers, externalResMap, namesSet, rag.accessRecord); auto colors = rag.colors(scratch); boost::queue q; @@ -520,6 +677,46 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag) visitor, get(colors, rag)); } + + // external res barrier for next frame + for (const auto &externalPair : externalResMap) { + const auto &transition = externalPair.second; + auto resID = resourceGraph.valueIndex.at(externalPair.first); + auto passID = transition.currStatus.vertID; + if (batchedBarriers.find(passID) == batchedBarriers.end()) { + batchedBarriers.emplace(passID, BarrierNode{}); + } + + Barrier nextFrameResBarrier{ + resID, + gfx::BarrierType::SPLIT_BEGIN, + externalResMap[externalPair.first].currStatus, + {}}; + + bool hasSubpass = !batchedBarriers[passID].subpassBarriers.empty(); + + if (hasSubpass) { + auto &subpassBarriers = batchedBarriers[passID].subpassBarriers; + for (int i = static_cast(subpassBarriers.size()) - 1; i >= 0; --i) { + auto findBarrierByResID = [resID](const Barrier &barrier) { + return barrier.resourceID == resID; + }; + + const auto &frontBarriers = subpassBarriers[i].frontBarriers; + auto &rearBarriers = subpassBarriers[i].rearBarriers; + auto found = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID) != frontBarriers.end() || + std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID) != rearBarriers.end(); + if (found) { + // put into rear barriers in order not to stuck + rearBarriers.push_back({}); + break; + } + } + } else { + auto &rearBarriers = batchedBarriers[passID].blockBarrier.rearBarriers; + rearBarriers.emplace_back(nextFrameResBarrier); + } + } } } #pragma endregion BUILD_BARRIERS @@ -629,18 +826,20 @@ private: CloseCircuits &_circuits; }; -auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, EmptyVert vert, bool backward) { +auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, EmptyVert vert, bool forward) { + // forward: + // -- true: how much resource this pass writes to, which has an effect of later passes; + // -- false: how much resource this pass reads from, which is dependent from former passes. const ResourceAccessNode &accessNode = get(RAG::AccessNode, rag, static_cast(vert)); int64_t score = 0; bool forceAdjacent = false; - // how much corelation to last pass for (const auto &resc : accessNode.attachemntStatus) { int64_t eval = 0; auto rescID = resc.vertID; const ResourceDesc &desc = get(ResourceGraph::Desc, rescGraph, rescID); const ResourceTraits &traits = get(ResourceGraph::Traits, rescGraph, rescID); - gfx::MemoryAccessBit filter = backward ? gfx::MemoryAccessBit::WRITE_ONLY : gfx::MemoryAccessBit::READ_ONLY; + gfx::MemoryAccessBit filter = forward ? gfx::MemoryAccessBit::WRITE_ONLY : gfx::MemoryAccessBit::READ_ONLY; if (resc.access == filter) { continue; } @@ -656,12 +855,9 @@ auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, EmptyVert break; } - if (traits.residency == ResourceResidency::MANAGED) { - eval *= 2; // metal on macOS holds a copy of memory on CPU side in this mode. - score += eval; - } else if (traits.residency == ResourceResidency::MEMORYLESS) { + if (traits.residency == ResourceResidency::MEMORYLESS) { forceAdjacent = true; - score = backward ? std::numeric_limits::lowest() : std::numeric_limits::max(); + score = forward ? std::numeric_limits::lowest() : std::numeric_limits::max(); break; } } @@ -672,8 +868,8 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGr assert(lhsVerts.size() >= 2); assert(rhsVerts.size() >= 2); - auto evaluate = [&rag, &rescGraph](EmptyVert vert, bool backward) { - return evaluateHeaviness(rag, rescGraph, vert, backward); + auto evaluate = [&rag, &rescGraph](EmptyVert vert, bool forward) { + return evaluateHeaviness(rag, rescGraph, vert, forward); }; if (lhsVerts.size() == 2 || rhsVerts.size() == 2) { @@ -689,20 +885,19 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGr // fist and last pass in this circuit don't get involved in reorder. auto firstLhsNode = lhsVerts[1]; auto lastLhsNode = lhsVerts[lhsVerts.size() - 2]; - // back to front - const auto &backLhsStatus = evaluate(firstLhsNode, true); - bool lhsAdjacentToStart = std::get<0>(backLhsStatus); - const auto &frontLhsStatus = evaluate(lastLhsNode, false); - bool lhsAdjacentToEnd = std::get<0>(frontLhsStatus); + + const auto &lhsBackwardStatus = evaluate(firstLhsNode, false); + bool lhsAdjacentToStart = std::get<0>(lhsBackwardStatus); + const auto &lhsForwardStatus = evaluate(lastLhsNode, true); + bool lhsAdjacentToEnd = std::get<0>(lhsForwardStatus); auto firstRhsNode = rhsVerts[1]; auto lastRhsNode = rhsVerts[rhsVerts.size() - 2]; - const auto &backRhsStatus = evaluate(firstRhsNode, true); - bool rhsAdjacentToStart = std::get<0>(backRhsStatus); - int64_t rhsBackScore = std::get<1>(backRhsStatus); - const auto &frontRhsStatus = evaluate(lastRhsNode, false); - bool rhsAdjacentToEnd = std::get<0>(frontRhsStatus); + const auto &rhsBackwardStatus = evaluate(firstRhsNode, true); + bool rhsAdjacentToStart = std::get<0>(rhsBackwardStatus); + const auto &rhsForwardStatus = evaluate(lastRhsNode, false); + bool rhsAdjacentToEnd = std::get<0>(rhsForwardStatus); if (lhsAdjacentToStart || rhsAdjacentToEnd || lhsAdjacentToEnd || rhsAdjacentToStart) { const EmptyVerts *formerPath = &lhsVerts; @@ -713,63 +908,112 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGr remove_edge((*latterPath)[0], (*latterPath)[1], relationGraph); remove_edge((*formerPath)[formerPath->size() - 2], (*formerPath)[formerPath->size() - 1], relationGraph); - // remove_edge(rhsVerts[0], rhsVerts[1], relationGraph); - // remove_edge(rhsVerts[rhsVerts.size() - 2], rhsVerts[rhsVerts.size() - 1], relationGraph); tryAddEdge((*formerPath)[formerPath->size() - 2], (*latterPath)[1], relationGraph); } assert(lhsVerts.size() >= 3 && rhsVerts.size() >= 3); - int64_t score = std::numeric_limits::lowest(); - std::vector candidateSections; - EmptyVerts section; - for (size_t i = 1; i < lhsVerts.size() - 1; ++i) { + constexpr int64_t score = std::numeric_limits::lowest(); + ccstd::vector> candidateSections; + std::queue lhsSection; + for (size_t i = 1; i < lhsVerts.size(); ++i) { auto tryE = edge(lhsVerts[i], lhsVerts[i - 1], relationGraphTc); auto tryRE = edge(lhsVerts[i - 1], lhsVerts[i], relationGraphTc); if (!tryE.second && !tryRE.second) { remove_edge(lhsVerts[i - 1], lhsVerts[i], relationGraph); - candidateSections.push_back(section); - section.clear(); + candidateSections.emplace_back(lhsSection); + std::queue clearQ; + lhsSection.swap(clearQ); } - section.push_back(lhsVerts[i]); + auto e = edge(lhsVerts[i], lhsVerts[i - 1], relationGraph); + // verts comes in order, so either real edge exist or logic edge is added. + CC_ASSERT(e.second); + + lhsSection.emplace(e.first); } if (candidateSections.empty()) { + // if this one is a tight edge(no logic edge, dependent from one to its next), + // keep this whole chain as a candidate. remove_edge(lhsVerts[0], lhsVerts[1], relationGraph); remove_edge(lhsVerts[lhsVerts.size() - 2], lhsVerts[lhsVerts.size() - 1], relationGraph); - candidateSections.push_back(section); + candidateSections.emplace_back(std::move(lhsSection)); } - section.clear(); - for (size_t i = 1; i < rhsVerts.size() - 1; ++i) { + std::queue rhsSection; + for (size_t i = 1; i < rhsVerts.size(); ++i) { auto tryE = edge(rhsVerts[i], rhsVerts[i - 1], relationGraphTc); auto tryRE = edge(rhsVerts[i - 1], rhsVerts[i], relationGraphTc); if (!tryE.second && !tryRE.second) { remove_edge(rhsVerts[i - 1], rhsVerts[i], relationGraph); - candidateSections.push_back(section); - section.clear(); + candidateSections.emplace_back(rhsSection); + std::queue clearQ; + rhsSection.swap(clearQ); } - section.push_back(rhsVerts[i]); + auto e = edge(rhsVerts[i], rhsVerts[i - 1], relationGraph); + // verts comes in order, so either real edge exist or logic edge is added. + CC_ASSERT(e.second); + rhsSection.emplace(e.first); } + + // lhs verts already put in. if (candidateSections.size() == 1) { remove_edge(rhsVerts[0], rhsVerts[1], relationGraph); remove_edge(rhsVerts[rhsVerts.size() - 2], rhsVerts[rhsVerts.size() - 1], relationGraph); - candidateSections.emplace_back(std::move(section)); + candidateSections.emplace_back(std::move(rhsSection)); } assert(candidateSections.size() >= 2); - std::sort(candidateSections.begin(), candidateSections.end(), [evaluate](const EmptyVerts &lhs, const EmptyVerts &rhs) { - const auto lhsFrontStats = evaluate(lhs.back(), true); - const auto lhsBackStats = evaluate(lhs.front(), false); - const auto rhsFrontStats = evaluate(rhs.back(), true); - const auto rhsBackStats = evaluate(rhs.front(), false); - return std::get<1>(lhsBackStats) - std::get<1>(lhsFrontStats) < std::get<1>(rhsBackStats) - std::get<1>(rhsFrontStats); - }); - tryAddEdge(lhsVerts[0], candidateSections[0][0], relationGraph); - for (size_t i = 0; i < candidateSections.size() - 1; ++i) { - tryAddEdge(candidateSections[i].back(), candidateSections[i + 1].front(), relationGraph); + ScoreMap scMap; + auto tailVert = lhsVerts[0]; + while (!candidateSections.empty()) { + int64_t lightest = std::numeric_limits::max(); + uint32_t index = 0; + for (size_t i = 0; i < candidateSections.size(); ++i) { + auto e = candidateSections[i].front(); + auto srcVert = source(e, relationGraph); + auto dstVert = target(e, relationGraph); + int64_t srcBackwardScore = 0; + int64_t dstForwardScore = 0; + if (scMap.find(srcVert) == scMap.end()) { + auto res = evaluate(srcVert, false); + srcBackwardScore = std::get<1>(res); + res = evaluate(srcVert, true); + auto srcForwardScore = std::get<1>(res); + scMap.emplace(srcVert, std::pair(srcBackwardScore, srcForwardScore)); + } else { + srcBackwardScore = std::get<0>(scMap.at(srcVert)); + } + if (scMap.find(dstForwardScore) == scMap.end()) { + auto res = evaluate(dstVert, false); + dstForwardScore = std::get<1>(res); + res = evaluate(dstVert, true); + auto dstBackwardScore = std::get<1>(res); + scMap.emplace(dstVert, std::pair(dstBackwardScore, dstForwardScore)); + } else { + dstForwardScore = std::get<1>(scMap.at(dstVert)); + } + + auto score = dstForwardScore - srcBackwardScore; + if (lightest > score) { + lightest = score; + index = i; + } + } + auto e = candidateSections[index].front(); + candidateSections[index].pop(); + if (candidateSections[index].empty()) { + auto iter = candidateSections.begin(); + std::advance(iter, index); + candidateSections.erase(iter); + } + auto srcVert = source(e, relationGraph); + auto dstVert = target(e, relationGraph); + tryAddEdge(tailVert, srcVert, relationGraph); + tailVert = dstVert; } - tryAddEdge(candidateSections.back().back(), lhsVerts.back(), relationGraph); + + tryAddEdge(tailVert, lhsVerts.back(), relationGraph); } } @@ -874,15 +1118,17 @@ void applyRelation(RelationGraph &relationGraph, const TargetGraph &targetGraph) } } -void passReorder(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag) { +void passReorder(FrameGraphDispatcher &fgDispatcher) { auto *scratch = fgDispatcher.scratch; const auto &graph = fgDispatcher.graph; const auto &layoutGraph = fgDispatcher.layoutGraph; const auto &resourceGraph = fgDispatcher.resourceGraph; auto &relationGraph = fgDispatcher.relationGraph; + auto &rag = fgDispatcher.resourceAccessGraph; if (!fgDispatcher._accessGraphBuilt) { - buildAccessGraph(graph, layoutGraph, resourceGraph, rag, relationGraph); + const Graphs graphs{resourceGraph, layoutGraph, rag, relationGraph}; + buildAccessGraph(graph, graphs); fgDispatcher._accessGraphBuilt = true; } @@ -930,34 +1176,34 @@ void passReorder(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag) { std::vector candidateBuffer; uint32_t coloredVerts = 0; while (coloredVerts < relationGraph.vertices.size()) { - // decreasing order + // decreasing order, pop back from vector, push into queue, then it's ascending order. std::sort(candidates.begin(), candidates.end(), [&](EmptyVert lhsVert, EmptyVert rhsVert) { - int64_t lhsFrontScore{0}; - int64_t rhsFrontScore{0}; - int64_t lhsBackScore{0}; - int64_t rhsBackScore{0}; + int64_t lhsForwardScore{0}; + int64_t rhsForwardScore{0}; + int64_t lhsBackwardScore{0}; + int64_t rhsBackwardScore{0}; if (scoreMap.find(lhsVert) == scoreMap.end()) { - const auto &frontLhsStats = evaluateHeaviness(rag, resourceGraph, lhsVert, false); - lhsFrontScore = get<1>(frontLhsStats); - const auto &backLhsStats = evaluateHeaviness(rag, resourceGraph, lhsVert, true); - lhsBackScore = get<1>(backLhsStats); - scoreMap.emplace(lhsVert, std::pair{lhsBackScore, lhsFrontScore}); + const auto &lhsForwardStatus = evaluateHeaviness(rag, resourceGraph, lhsVert, true); + lhsForwardScore = get<1>(lhsForwardStatus); + const auto &lhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, lhsVert, false); + lhsBackwardScore = get<1>(lhsBackwardStatus); + scoreMap.emplace(lhsVert, std::pair{lhsBackwardScore, lhsForwardScore}); } else { - lhsBackScore = scoreMap[lhsVert].first; - lhsFrontScore = scoreMap[lhsVert].second; + lhsBackwardScore = scoreMap[lhsVert].first; + lhsForwardScore = scoreMap[lhsVert].second; } if (scoreMap.find(rhsVert) == scoreMap.end()) { - const auto &frontRhsStats = evaluateHeaviness(rag, resourceGraph, rhsVert, false); - rhsFrontScore = get<1>(frontRhsStats); - const auto &backRhsStats = evaluateHeaviness(rag, resourceGraph, rhsVert, true); - rhsBackScore = get<1>(backRhsStats); - scoreMap.emplace(rhsVert, std::pair{rhsBackScore, rhsFrontScore}); + const auto &rhsForwardStatus = evaluateHeaviness(rag, resourceGraph, rhsVert, true); + rhsForwardScore = get<1>(rhsForwardStatus); + const auto &rhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, rhsVert, false); + rhsBackwardScore = get<1>(rhsBackwardStatus); + scoreMap.emplace(rhsVert, std::pair{rhsBackwardScore, rhsForwardScore}); } else { - rhsBackScore = scoreMap[rhsVert].first; - rhsFrontScore = scoreMap[rhsVert].second; + rhsBackwardScore = scoreMap[rhsVert].first; + rhsForwardScore = scoreMap[rhsVert].second; } - return lhsBackScore - lhsFrontScore > rhsBackScore - rhsFrontScore; + return lhsBackwardScore - lhsForwardScore > rhsBackwardScore - rhsForwardScore; }); const auto vert = candidates.back(); @@ -1009,7 +1255,7 @@ void passReorder(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag) { #pragma endregion PASS_REORDER -void memoryAliasing(FrameGraphDispatcher &fgDispatcher, ResourceAccessGraph &rag) { +void memoryAliasing(FrameGraphDispatcher &fgDispatcher) { } #pragma region assisstantFuncDefinition @@ -1035,18 +1281,15 @@ bool isStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs) { return res; } -void addAccessNode(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, InputStatusTuple status, const Range &range) { - // std::tie(passType, rescName, visibility, access) ; - PassType passType = std::get<0>(status); - const PmrString &rescName = std::get<1>(status); - gfx::ShaderStageFlagBit visibility = std::get<2>(status); - gfx::MemoryAccessBit access = std::get<3>(status); +void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status, const Range &range) { + const auto &[name, passType, visibility, access] = status; - CC_EXPECTS(rg.valueIndex.find(rescName) != rg.valueIndex.end()); - uint32_t rescID = rg.valueIndex.at(rescName); - if (std::find(rag.resourceNames.begin(), rag.resourceNames.end(), rescName) == rag.resourceNames.end()) { - rag.resourceIndex.emplace(rescName, rescID); - rag.resourceNames.emplace_back(rescName); + uint32_t rescID = rg.valueIndex.at(name); + + CC_EXPECTS(rg.valueIndex.find(name) != rg.valueIndex.end()); + if (std::find(rag.resourceNames.begin(), rag.resourceNames.end(), name) == rag.resourceNames.end()) { + rag.resourceIndex.emplace(name, rescID); + rag.resourceNames.emplace_back(name); } node.attachemntStatus.emplace_back(AccessStatus{ @@ -1058,15 +1301,39 @@ void addAccessNode(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, }); } -AccessVertex dependencyCheck(RAG &rag, AccessTable &accessRecord, AccessVertex curVertID, const InputStatusTuple &status) { - PassType passType = std::get<0>(status); - const PmrString &rescName = std::get<1>(status); - gfx::ShaderStageFlagBit visibility = std::get<2>(status); - gfx::MemoryAccessBit access = std::get<3>(status); +void addAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status) { + const auto &[name, passType, visibility, access] = status; + uint32_t rescID = rg.valueIndex.at(name); + const auto &resourceDesc = get(ResourceGraph::Desc, rg, rescID); + Range range; + if (resourceDesc.dimension == ResourceDimension::BUFFER) { + range = BufferRange{0, resourceDesc.depthOrArraySize}; + } else { + range = TextureRange{0, 1, 0, resourceDesc.mipLevels}; + } + + CC_EXPECTS(rg.valueIndex.find(name) != rg.valueIndex.end()); + if (std::find(rag.resourceNames.begin(), rag.resourceNames.end(), name) == rag.resourceNames.end()) { + rag.resourceIndex.emplace(name, rescID); + rag.resourceNames.emplace_back(name); + } + + node.attachemntStatus.emplace_back(AccessStatus{ + rescID, + visibility, + access, + passType, + range, + }); +} + +AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ViewStatus &viewStatus) { + const auto &[name, passType, visibility, access] = viewStatus; + auto &accessRecord = rag.accessRecord; AccessVertex lastVertID = INVALID_ID; - CC_EXPECTS(rag.resourceIndex.find(rescName) != rag.resourceIndex.end()); - auto resourceID = rag.resourceIndex[rescName]; + CC_EXPECTS(rag.resourceIndex.find(name) != rag.resourceIndex.end()); + auto resourceID = rag.resourceIndex[name]; auto iter = accessRecord.find(resourceID); if (iter == accessRecord.end()) { accessRecord.emplace( @@ -1076,7 +1343,8 @@ AccessVertex dependencyCheck(RAG &rag, AccessTable &accessRecord, AccessVertex c {curVertID, visibility, access, passType, Range{}}}); } else { ResourceTransition &trans = iter->second; - if (access == gfx::MemoryAccessBit::READ_ONLY && trans.currStatus.access == gfx::MemoryAccessBit::READ_ONLY) { + if (access == gfx::MemoryAccessBit::READ_ONLY && trans.currStatus.access == gfx::MemoryAccessBit::READ_ONLY && + trans.currStatus.passType == passType && trans.currStatus.visibility == visibility) { // current READ, no WRITE before in this frame, it's expected to be external. bool dirtyExternalRes = trans.lastStatus.vertID == INVALID_ID; if (!dirtyExternalRes) { @@ -1087,7 +1355,8 @@ AccessVertex dependencyCheck(RAG &rag, AccessTable &accessRecord, AccessVertex c rag.externalPasses.emplace_back(curVertID); } else { bool needTransition = (trans.currStatus.access != access) || (trans.currStatus.passType != passType) || (trans.currStatus.visibility != visibility); - if (needTransition) { + // avoid subpass self depends + if (needTransition && trans.currStatus.vertID != curVertID) { trans.lastStatus = trans.currStatus; trans.currStatus = {curVertID, visibility, access, passType, Range{}}; tryAddEdge(trans.lastStatus.vertID, curVertID, rag); @@ -1101,7 +1370,6 @@ AccessVertex dependencyCheck(RAG &rag, AccessTable &accessRecord, AccessVertex c gfx::ShaderStageFlagBit getVisibilityByDescName(const LGD &lgd, uint32_t passID, const PmrString &slotName) { auto vis = gfx::ShaderStageFlagBit::NONE; - const auto &layout = get(LGD::Layout, lgd, passID); bool found = false; auto compare = [](const PmrString &name, const uint32_t slot) { @@ -1120,162 +1388,211 @@ gfx::ShaderStageFlagBit getVisibilityByDescName(const LGD &lgd, uint32_t passID, return visIter->second; }; -void processRasterPass(RAG &rag, EmptyGraph &relationGraph, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const RasterPass &pass) { - auto rlgVertID = add_vertex(relationGraph); - - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); +bool checkRasterViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, PassType passType, ResourceAccessNode &node, const RasterViewsMap &rasterViews) { + const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; bool dependent = false; - for (const auto &pair : pass.rasterViews) { + + for (const auto &pair : rasterViews) { const auto &rasterView = pair.second; - gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); + gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(layoutGraphData, passID, pair.first); auto access = toGfxAccess(rasterView.accessType); - addAccessNode(rag, rescGraph, node, InputStatusTuple{PassType::RASTER, rasterView.slotName, visibility, access}, Range{}); - auto lastVertId = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::RASTER, rasterView.slotName, visibility, access}); - if (lastVertId != INVALID_ID) { - tryAddEdge(lastVertId, vertID, rag); - tryAddEdge(lastVertId, rlgVertID, relationGraph); + ViewStatus viewStatus{rasterView.slotName, passType, visibility, access}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); + auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, viewStatus); + if (lastVertId != INVALID_ID && lastVertId != vertID) { + tryAddEdge(lastVertId, vertID, resourceAccessGraph); + tryAddEdge(lastVertId, vertID, relationGraph); dependent = true; } } - for (const auto &pair : pass.computeViews) { - const auto &values = pair.second; - gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); - for (const auto &computeView : values) { - auto access = toGfxAccess(computeView.accessType); - addAccessNode(rag, rescGraph, node, InputStatusTuple{PassType::COMPUTE, computeView.name, visibility, access}, Range{}); - auto lastVertId = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::COMPUTE, computeView.name, visibility, access}); - if (lastVertId != INVALID_ID) { - tryAddEdge(lastVertId, vertID, rag); - tryAddEdge(lastVertId, rlgVertID, relationGraph); - dependent = true; - } - } - } - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, rag); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); - } + // sort for vector intersection std::sort(node.attachemntStatus.begin(), node.attachemntStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); + + return dependent; } -void processComputePass(RAG &rag, EmptyGraph &relationGraph, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const ComputePass &pass) { - auto rlgVertID = add_vertex(relationGraph); - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); +bool checkComputeViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, PassType passType, ResourceAccessNode &node, const ComputeViewsMap &computeViews) { + const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; bool dependent = false; - for (const auto &pair : pass.computeViews) { + + for (const auto &pair : computeViews) { const auto &values = pair.second; - gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); for (const auto &computeView : values) { + gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(layoutGraphData, passID, computeView.name); auto access = toGfxAccess(computeView.accessType); - addAccessNode(rag, rescGraph, node, InputStatusTuple{PassType::COMPUTE, computeView.name, visibility, access}, Range{}); - auto lastVertId = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::COMPUTE, computeView.name, visibility, access}); + ViewStatus viewStatus{computeView.name, passType, visibility, access}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); + auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, viewStatus); if (lastVertId != INVALID_ID) { - tryAddEdge(lastVertId, vertID, rag); - tryAddEdge(lastVertId, rlgVertID, relationGraph); + tryAddEdge(lastVertId, vertID, resourceAccessGraph); + tryAddEdge(lastVertId, vertID, relationGraph); dependent = true; } } } - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, rag); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); - } + + // sort for vector intersection std::sort(node.attachemntStatus.begin(), node.attachemntStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); + + return dependent; } -void processCopyPass(RAG &rag, EmptyGraph &relationGraph, const LGD & /*lgd*/, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const CopyPass &pass) { +void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass) { + const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + auto rlgVertID = add_vertex(relationGraph); - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); + auto vertID = add_vertex(resourceAccessGraph, passID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); + const auto &subpasses = get(SubpassGraph::Subpass, pass.subpassGraph); + bool hasSubpass = !subpasses.container->empty(); + bool dependent = false; + if (hasSubpass) { + auto *lastNode = &node; + for(const auto &subpass : (*subpasses.container)) { + lastNode->nextSubpass = new ResourceAccessNode; + auto *head = lastNode->nextSubpass; + + dependent |= checkRasterViews(graphs, vertID, passID, PassType::RASTER, *head, subpass.rasterViews); + dependent |= checkComputeViews(graphs, vertID, passID, PassType::RASTER, *head, subpass.computeViews); + + for (const auto &attachment : head->attachemntStatus) { + auto resID = attachment.vertID; + auto findByResID = [resID](const AccessStatus &status) { + return status.vertID == resID; + }; + + auto iter = std::find_if(node.attachemntStatus.begin(), node.attachemntStatus.end(), findByResID); + if (iter == node.attachemntStatus.end()) { + node.attachemntStatus.emplace_back(attachment); + } else { + (*iter) = attachment; + } + } + lastNode = head; + } + } else { + dependent |= checkRasterViews(graphs, vertID, passID, PassType::RASTER, node, pass.rasterViews); + dependent |= checkComputeViews(graphs, vertID, passID, PassType::RASTER, node, pass.computeViews); + } + + if (!dependent) { + tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); + tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); + } +} + +void processComputePass(const Graphs &graphs, uint32_t passID, const ComputePass &pass) { + const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + auto rlgVertID = add_vertex(relationGraph); + auto vertID = add_vertex(resourceAccessGraph, passID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); + bool dependent = checkComputeViews(graphs, vertID, passID, PassType::COMPUTE, node, pass.computeViews); + + if (!dependent) { + tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); + tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); + } +} + +void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass) { + const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + + auto rlgVertID = add_vertex(relationGraph); + auto vertID = add_vertex(resourceAccessGraph, passID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); bool dependent = false; for (const auto &pair : pass.copyPairs) { auto sourceRange = Range{ - pair.mipLevels, - pair.numSlices, - pair.sourceMostDetailedMip, - pair.sourceFirstSlice, - pair.sourcePlaneSlice, - }; + TextureRange{ + pair.sourceFirstSlice, + pair.sourcePlaneSlice, + pair.mipLevels, + pair.numSlices, + }}; auto targetRange = Range{ - pair.mipLevels, - pair.numSlices, - pair.targetMostDetailedMip, - pair.targetFirstSlice, - pair.targetPlaneSlice, - }; - addAccessNode(rag, rescGraph, node, InputStatusTuple{PassType::COPY, pair.source, defaultVisibility, gfx::MemoryAccessBit::READ_ONLY}, sourceRange); - addAccessNode(rag, rescGraph, node, InputStatusTuple{PassType::COPY, pair.target, defaultVisibility, gfx::MemoryAccessBit::WRITE_ONLY}, targetRange); - uint32_t lastVertSrc = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::COPY, pair.source, defaultVisibility, gfx::MemoryAccessBit::READ_ONLY}); + TextureRange{ + pair.targetFirstSlice, + pair.targetPlaneSlice, + pair.mipLevels, + pair.numSlices, + }}; + + ViewStatus srcViewStatus{pair.source, PassType::COPY, defaultVisibility, gfx::MemoryAccessBit::READ_ONLY}; + addCopyAccessStatus(resourceAccessGraph, resourceGraph, node, srcViewStatus, sourceRange); + ViewStatus dstViewStatus{pair.target, PassType::COPY, defaultVisibility, gfx::MemoryAccessBit::WRITE_ONLY}; + addCopyAccessStatus(resourceAccessGraph, resourceGraph, node, dstViewStatus, targetRange); + + uint32_t lastVertSrc = dependencyCheck(resourceAccessGraph, vertID, srcViewStatus); if (lastVertSrc != INVALID_ID) { - tryAddEdge(lastVertSrc, vertID, rag); + tryAddEdge(lastVertSrc, vertID, resourceAccessGraph); tryAddEdge(lastVertSrc, rlgVertID, relationGraph); dependent = true; } - uint32_t lastVertDst = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::COPY, pair.source, defaultVisibility, gfx::MemoryAccessBit::WRITE_ONLY}); + uint32_t lastVertDst = dependencyCheck(resourceAccessGraph, vertID, dstViewStatus); if (lastVertDst != INVALID_ID) { - tryAddEdge(lastVertDst, vertID, rag); + tryAddEdge(lastVertDst, vertID, resourceAccessGraph); tryAddEdge(lastVertDst, rlgVertID, relationGraph); dependent = true; } } if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, rag); + tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); } std::sort(node.attachemntStatus.begin(), node.attachemntStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); } -void processRaytracePass(RAG &rag, EmptyGraph &relationGraph, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const RaytracePass &pass) { +void processRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass) { + const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + auto rlgVertID = add_vertex(relationGraph); - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); - bool dependent = false; - for (const auto &pair : pass.computeViews) { - const auto &values = pair.second; - gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); - for (const auto &computeView : values) { - auto access = toGfxAccess(computeView.accessType); - addAccessNode(rag, rescGraph, node, InputStatusTuple{PassType::COMPUTE, computeView.name, visibility, access}, Range{}); - auto lastVertId = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::COMPUTE, computeView.name, visibility, access}); - if (lastVertId != INVALID_ID) { - tryAddEdge(lastVertId, vertID, rag); - tryAddEdge(lastVertId, rlgVertID, relationGraph); - dependent = true; - } - } - } + auto vertID = add_vertex(resourceAccessGraph, passID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); + bool dependent = checkComputeViews(graphs, vertID, passID, PassType::RAYTRACE, node, pass.computeViews); + if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, rag); + tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); } - std::sort(node.attachemntStatus.begin(), node.attachemntStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); } -void processPresentPass(RAG &rag, EmptyGraph &relationGraph, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const PresentPass &pass) { +void processPresentPass(const Graphs &graphs, uint32_t passID, const PresentPass &pass) { + const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + auto rlgVertID = add_vertex(relationGraph); - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); + auto vertID = add_vertex(resourceAccessGraph, passID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); bool dependent = false; for (const auto &pair : pass.presents) { - gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); - auto lastVertId = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::PRESENT, pair.first, visibility, gfx::MemoryAccessBit::WRITE_ONLY}); - addAccessNode(rag, rescGraph, node, InputStatusTuple{PassType::PRESENT, pair.first, defaultVisibility, gfx::MemoryAccessBit::WRITE_ONLY}, Range{}); + gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(layoutGraphData, passID, pair.first); + ViewStatus viewStatus{pair.first, PassType::PRESENT, visibility, gfx::MemoryAccessBit::READ_ONLY}; + + auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, viewStatus); + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); if (lastVertId != INVALID_ID) { - tryAddEdge(lastVertId, vertID, rag); + tryAddEdge(lastVertId, vertID, resourceAccessGraph); tryAddEdge(lastVertId, rlgVertID, relationGraph); dependent = true; } } if (!dependent) { // LOG("~~~~~~~~~~ Found an empty pipeline! ~~~~~~~~~~"); - tryAddEdge(EXPECT_START_ID, vertID, rag); + tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); } - rag.presentPassID = vertID; + resourceAccessGraph.presentPassID = vertID; std::sort(node.attachemntStatus.begin(), node.attachemntStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); } diff --git a/native/cocos/renderer/pipeline/custom/test/test.h b/native/cocos/renderer/pipeline/custom/test/test.h index e833cfa4d8..b32a9a9166 100644 --- a/native/cocos/renderer/pipeline/custom/test/test.h +++ b/native/cocos/renderer/pipeline/custom/test/test.h @@ -23,34 +23,50 @@ ****************************************************************************/ #include +#include #include +#include #include #include #include +#include "../../Enum.h" #include "../FGDispatcherTypes.h" #include "../LayoutGraphGraphs.h" #include "../NativePipelineTypes.h" +#include "../Range.h" #include "../RenderGraphGraphs.h" #include "../RenderGraphTypes.h" +#include "GFXDeviceManager.h" +#include "cocos/base/std/container/vector.h" +#include "frame-graph/FrameGraph.h" #include "gfx-base/GFXDef-common.h" +#include "gfx-base/GFXDevice.h" namespace cc { namespace render { using ccstd::pmr::string; -using std::map; +using gfx::PassType; using std::pair; using std::vector; using ViewInfo = vector>>>>; -using ResourceInfo = vector>; +using ResourceInfo = vector>; using LayoutUnit = std::tuple; using LayoutInfo = vector>; +using framegraph::PassBarrierPair; +using framegraph::ResourceBarrier; +using RasterViews = PmrTransparentMap; +using ComputeViews = PmrTransparentMap>; +using BarrierMap = FrameGraphDispatcher::BarrierMap; -void testData(const ViewInfo &rasterData, const ResourceInfo &rescInfo, const LayoutInfo &layoutInfo, RenderGraph &renderGraph, ResourceGraph &rescGraph, LayoutGraphData &layoutGraphData) { +static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescInfo, const LayoutInfo &layoutInfo, RenderGraph &renderGraph, ResourceGraph &rescGraph, LayoutGraphData &layoutGraphData) { for (const auto &resc : rescInfo) { string name = std::get<0>(resc); auto rescVertexID = add_vertex(rescGraph, ManagedTag{}, name.c_str()); + rescGraph.descs[rescVertexID] = std::get<1>(resc); + rescGraph.traits[rescVertexID] = std::get<2>(resc); + rescGraph.states[rescVertexID] = std::get<3>(resc); } const auto &mem_resource = layoutGraphData.get_allocator(); @@ -75,6 +91,54 @@ void testData(const ViewInfo &rasterData, const ResourceInfo &rescInfo, const La } } + std::set nameSet; + auto addRasterNode = [&](const vector>> &subpasses, uint32_t count, uint32_t passID) { + const ccstd::string name = "pass" + std::to_string(passID); + const auto vertexID = add_vertex(renderGraph, RasterTag{}, name.c_str()); + auto &raster = get(RasterTag{}, vertexID, renderGraph); + auto &subpassGraph = raster.subpassGraph; + + bool hasSubpass = count > 1; + + RasterSubpass *subpass = nullptr; + + for (size_t j = 0; j < count; ++j) { + assert(subpasses[j].size() == 2); // inputs and outputs + const auto &attachments = subpasses[j]; + bool isOutput = false; + + RasterSubpass *subpass = nullptr; + if (hasSubpass) { + const ccstd::string subpassName = "subpass" + std::to_string(passID); + auto subpassVertexID = add_vertex(subpassGraph, subpassName.c_str()); + subpass = &get(SubpassGraph::Subpass, subpassGraph, subpassVertexID); + } + + for (size_t k = 0; k < attachments.size(); ++k) { + for (size_t l = 0; l < attachments[k].size(); ++l) { + const auto &inputsOrOutputs = attachments[k]; + const auto &viewName = inputsOrOutputs[l]; + bool firstMeet = nameSet.find(viewName.c_str()) == nameSet.end(); + if (firstMeet) { + nameSet.emplace(viewName); + } + + auto &rasterViews = hasSubpass ? (*subpass).rasterViews : raster.rasterViews; + rasterViews.emplace(viewName.c_str(), RasterView{ + viewName.c_str(), + isOutput ? AccessType::WRITE : AccessType::READ, + AttachmentType::RENDER_TARGET, + firstMeet ? gfx::LoadOp::CLEAR : gfx::LoadOp::LOAD, + gfx::StoreOp::STORE, + gfx::ClearFlagBit::ALL, + gfx::Color({1.0, 0.0, 0.0, 1.0}), + }); + } + isOutput = true; + } + } + }; + uint32_t passCount = 0; for (size_t i = 0; i < rasterData.size(); ++i) { const auto &pass = rasterData[i]; @@ -82,42 +146,848 @@ void testData(const ViewInfo &rasterData, const ResourceInfo &rescInfo, const La case PassType::RASTER: { // const string name = pass.first; const auto &subpasses = pass.second; - for (size_t j = 0; j < subpasses.size(); ++j) { - const ccstd::string name = "pass" + std::to_string(passCount++); - const auto vertexID = add_vertex(renderGraph, RasterTag{}, name.c_str()); - assert(subpasses[j].size() == 2); // inputs and outputs - const auto &attachments = subpasses[j]; - auto &raster = get(RasterTag{}, vertexID, renderGraph); - bool isOutput = false; + addRasterNode(subpasses, subpasses.size(), passCount++); + break; + } + case PassType::COMPUTE: { + // const string name = pass.first; + const auto &subpasses = pass.second; - for (size_t k = 0; k < attachments.size(); ++k) { - for (size_t l = 0; l < attachments[k].size(); ++l) { - const auto &inputsOrOutputs = attachments[k]; - const auto &viewName = inputsOrOutputs[l]; - raster.rasterViews.emplace(viewName.c_str(), RasterView{ - viewName.c_str(), - isOutput ? AccessType::WRITE : AccessType::READ, - AttachmentType::RENDER_TARGET, - gfx::LoadOp::CLEAR, - gfx::StoreOp::STORE, - gfx::ClearFlagBit::ALL, - gfx::Color({1.0, 0.0, 0.0, 1.0}), - }); - } - isOutput = true; - } + const ccstd::string name = "pass" + std::to_string(passCount++); + const auto vertexID = add_vertex(renderGraph, ComputeTag{}, name.c_str()); + + assert(subpasses.back().size() == 2); // inputs and outputs + auto &computePass = get(ComputeTag{}, vertexID, renderGraph); + const auto &inputsAndOutputs = subpasses.back(); + const auto &inputs = inputsAndOutputs.front(); + const auto &outputs = inputsAndOutputs.back(); + + std::vector views(2); + ComputeView &src = views.front(); + src.name = inputs.front(); + src.accessType = AccessType::READ; + ComputeView &dst = views.back(); + dst.name = outputs.front(); + dst.accessType = AccessType::WRITE; + + computePass.computeViews.emplace(name, ccstd::pmr::vector{}); + computePass.computeViews.at(name.c_str()).emplace_back(); + computePass.computeViews.at(name.c_str()).emplace_back(); + computePass.computeViews.at(name.c_str()).front().name = inputs.front(); + computePass.computeViews.at(name.c_str()).front().accessType = AccessType::READ; + computePass.computeViews.at(name.c_str()).back().name = outputs.front(); + computePass.computeViews.at(name.c_str()).back().accessType = AccessType::WRITE; + + break; + } + case PassType::PRESENT: { + // const string name = pass.first; + const auto &subpasses = pass.second; + // addRasterNode(subpasses, subpasses.size() - 1, passCount++); + + const ccstd::string name = "pass" + std::to_string(passCount++); + const auto vertexID = add_vertex(renderGraph, PresentTag{}, name.c_str()); + assert(subpasses.back().size() == 2); // inputs and outputs + assert(subpasses.back()[1].empty()); // present pass no output + auto &presentPass = get(PresentTag{}, vertexID, renderGraph); + const auto &resName = subpasses.back()[0].back(); + if (presentPass.presents.find(resName.c_str()) == presentPass.presents.end()) { + // ? + presentPass.presents.emplace(resName.c_str(), Present{0, 0}); } + break; + } + case PassType::COPY: { + // const string name = pass.first; + const auto &subpasses = pass.second; + + const ccstd::string name = "pass" + std::to_string(passCount++); + const auto vertexID = add_vertex(renderGraph, CopyTag{}, name.c_str()); + assert(subpasses.back().size() == 2); // inputs and outputs + auto ©Pass = get(CopyTag{}, vertexID, renderGraph); + const auto &inputsAndOutputs = subpasses.back(); + const auto &inputs = inputsAndOutputs.front(); + const auto &outputs = inputsAndOutputs.back(); + copyPass.copyPairs.emplace_back(CopyPair{ + inputs.front().c_str(), + outputs.front().c_str(), + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0}); + + break; } } } - FrameGraphDispatcher fgDispatcher(rescGraph, renderGraph, layoutGraphData, layoutGraphData.resource(), layoutGraphData.resource()); + /* FrameGraphDispatcher fgDispatcher(rescGraph, renderGraph, layoutGraphData, layoutGraphData.resource(), layoutGraphData.resource()); fgDispatcher.enableMemoryAliasing(true); fgDispatcher.enablePassReorder(true); fgDispatcher.setParalellWeight(0.4); - fgDispatcher.run(); + fgDispatcher.run(); */ } +static void fillBarriers(const ResourceGraph &resourceGraph, const BarrierPair &barrierInfo, framegraph::PassNodeBuilder &builder, PassBarrierPair &barriers) { + auto doFill = [&builder, &resourceGraph](const std::vector &edgeInfo, std::vector &edgeBarriers) { + for (const auto &resBarrier : edgeInfo) { + const auto &name = get(ResourceGraph::Name, resourceGraph, resBarrier.resourceID); + const auto &desc = get(ResourceGraph::Desc, resourceGraph, resBarrier.resourceID); + auto type = desc.dimension == ResourceDimension::BUFFER ? cc::framegraph::ResourceType::BUFFER : cc::framegraph::ResourceType::TEXTURE; + framegraph::Range layerRange; + framegraph::Range mipRange; + if (type == framegraph::ResourceType::BUFFER) { + auto bufferRange = ccstd::get(resBarrier.beginStatus.range); + layerRange = {0, 0}; + mipRange = {bufferRange.offset, bufferRange.size}; + } else { + auto textureRange = ccstd::get(resBarrier.beginStatus.range); + layerRange = {textureRange.firstSlice, textureRange.numSlices}; + mipRange = {textureRange.mipLevel, textureRange.levelCount}; + } + + edgeBarriers.emplace_back(cc::framegraph::ResourceBarrier{ + type, + resBarrier.type, + builder.readFromBlackboard(framegraph::FrameGraph::stringToHandle(name.c_str())), + {resBarrier.beginStatus.passType, + resBarrier.beginStatus.visibility, + resBarrier.beginStatus.access}, + {resBarrier.endStatus.passType, + resBarrier.endStatus.visibility, + resBarrier.endStatus.access}, + layerRange, + mipRange, + }); + } + }; + + doFill(barrierInfo.frontBarriers, barriers.frontBarriers); + doFill(barrierInfo.rearBarriers, barriers.rearBarriers); +} + +struct TestRenderData { + ccstd::vector> outputTexes; +}; + +struct FrameGraphPassInfo { + framegraph::FrameGraph &frameGraph; + const RenderGraph &renderGraph; + const ResourceGraph &resourceGraph; + const RasterViews &rasterViews; + const ComputeViews &computeViews; + const BarrierMap &barrierMap; + uint32_t passID{0}; + bool isSubpass{false}; + bool subpassEnd{false}; +}; + +static void addPassToFrameGraph(const FrameGraphPassInfo &info) { + const auto &rasterViews = info.rasterViews; + const auto &passID = info.passID; + auto &barrierMap = info.barrierMap; + const auto &renderGraph = info.renderGraph; + const auto &resourceGraph = info.resourceGraph; + auto &frameGraph = info.frameGraph; + bool isSupass = info.isSubpass; + bool subpassEnd = info.subpassEnd; + + auto forwardSetup = [&](framegraph::PassNodeBuilder &builder, TestRenderData &data) { + if (isSupass) { + builder.subpass(subpassEnd); + } + + auto goThroughRasterViews = [&](const RasterViews &views) { + for (const auto &view : views) { + const auto handle = framegraph::FrameGraph::stringToHandle(view.second.slotName.c_str()); + auto typedHandle = builder.readFromBlackboard(handle); + data.outputTexes.emplace_back(); + auto &lastTex = data.outputTexes.back(); + framegraph::Texture::Descriptor colorTexInfo; + colorTexInfo.format = gfx::Format::RGBA8; + + // if (rasterView.second.accessType == AccessType::READ) { + colorTexInfo.usage = gfx::TextureUsage::INPUT_ATTACHMENT | gfx::TextureUsage::COLOR_ATTACHMENT; + //} + lastTex.first = view.second.accessType; + lastTex.second = static_cast(typedHandle); + + if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { + colorTexInfo.width = 960; + colorTexInfo.height = 640; + + lastTex.second = builder.create(handle, colorTexInfo); + } + + framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; + colorAttachmentInfo.usage = view.second.attachmentType == AttachmentType::RENDER_TARGET ? framegraph::RenderTargetAttachment::Usage::COLOR : framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; + colorAttachmentInfo.clearColor = view.second.clearColor; + colorAttachmentInfo.loadOp = view.second.loadOp; + if (view.second.accessType == AccessType::WRITE) { + lastTex.second = builder.write(lastTex.second, colorAttachmentInfo); + builder.writeToBlackboard(handle, lastTex.second); + colorAttachmentInfo.beginAccesses = colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE; + } else { + colorAttachmentInfo.beginAccesses = colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::COLOR_ATTACHMENT_READ; + auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); + builder.writeToBlackboard(handle, res); + } + } + }; + + auto goThroughComputeViews = [&](const ComputeViews &views) { + for (const auto &pair : views) { + for (const auto &view : pair.second) { + const auto handle = framegraph::FrameGraph::stringToHandle(view.name.c_str()); + auto typedHandle = builder.readFromBlackboard(handle); + data.outputTexes.emplace_back(); + auto &lastTex = data.outputTexes.back(); + framegraph::Texture::Descriptor colorTexInfo; + colorTexInfo.format = gfx::Format::RGBA8; + + // if (rasterView.second.accessType == AccessType::READ) { + colorTexInfo.usage = gfx::TextureUsage::INPUT_ATTACHMENT | gfx::TextureUsage::COLOR_ATTACHMENT; + //} + lastTex.first = view.accessType; + lastTex.second = static_cast(typedHandle); + + if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { + colorTexInfo.width = 960; + colorTexInfo.height = 640; + + lastTex.second = builder.create(handle, colorTexInfo); + } + + framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; + + if (view.accessType == AccessType::WRITE) { + lastTex.second = builder.write(lastTex.second); + builder.writeToBlackboard(handle, lastTex.second); + } else { + auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); + builder.writeToBlackboard(handle, res); + } + } + } + }; + + goThroughRasterViews(info.rasterViews); + goThroughComputeViews(info.computeViews); + + builder.setViewport({0U, 640U, 0U, 960U, 0.0F, 1.0F}, {0U, 0U, 960U, 640U}); + + if (barrierMap.find(passID + 1) == barrierMap.end()) { + return; + } + const auto &barrier = barrierMap.at(passID + 1); + PassBarrierPair barrierPairs; + fillBarriers(resourceGraph, barrier.blockBarrier, builder, barrierPairs); + builder.setBarrier(barrierPairs); + }; + + auto forwardExec = [](const TestRenderData &data, + const framegraph::DevicePassResourceTable &table) { + /*for(const auto& pair: data.outputTexes) { + if(pair.first == AccessType::WRITE) { + table.getWrite(pair.second); + } + if(pair.first == AccessType::READ) { + table.getRead(pair.second); + } + if(pair.first == AccessType::READ_WRITE) { + table.getRead(pair.second); + table.getWrite(pair.second); + } + }*/ + }; + + auto passHandle = framegraph::FrameGraph::stringToHandle(get(RenderGraph::Name, renderGraph, passID).c_str()); + + string presentHandle; + + for (const auto &view : rasterViews) { + // write or read_write + if (view.second.accessType != AccessType::READ) { + presentHandle = view.first; + break; + } + } + + frameGraph.addPass(static_cast(ForwardInsertPoint::IP_FORWARD), passHandle, forwardSetup, forwardExec); +} + +static void runTestGraph(const RenderGraph &renderGraph, const ResourceGraph &resourceGraph, const LayoutGraphData &layoutGraphData, const FrameGraphDispatcher &fgDispatcher) { + const auto &barriers = fgDispatcher.getBarriers(); + + framegraph::FrameGraph framegraph; + + auto *device = gfx::Device::getInstance(); + if (!device) { + device = gfx::DeviceManager::create(); + } + + for (const auto passID : makeRange(vertices(renderGraph))) { + visitObject( + passID, renderGraph, + [&](const RasterPass &pass) { + // TestRenderData tmpData; + const auto &subpasses = get(SubpassGraph::Subpass, pass.subpassGraph); + uint32_t count = 0; + for (const auto &subpass : *subpasses.container) { + FrameGraphPassInfo info = { + framegraph, + renderGraph, + resourceGraph, + subpass.rasterViews, + subpass.computeViews, + fgDispatcher.getBarriers(), + passID, + true, + count < subpasses.container->size() - 1}; + addPassToFrameGraph(info); + ++count; + }; + if ((*subpasses.container).empty()) { + FrameGraphPassInfo info = { + framegraph, + renderGraph, + resourceGraph, + pass.rasterViews, + pass.computeViews, + fgDispatcher.getBarriers(), + passID, + false, + false}; + addPassToFrameGraph(info); + ++count; + } + }, + [&](const ComputePass &pass) { + // TestRenderData tmpData; + FrameGraphPassInfo info = { + framegraph, + renderGraph, + resourceGraph, + {}, + pass.computeViews, + fgDispatcher.getBarriers(), + passID, + false, + false}; + addPassToFrameGraph(info); + }, + [&](const CopyPass &pass) { + auto forwardSetup = [&](framegraph::PassNodeBuilder &builder, TestRenderData &data) { + for (const auto &pair : pass.copyPairs) { + for (size_t i = 0; i < 2; ++i) { + bool write = (i % 2 == 0); + const auto handle = framegraph::FrameGraph::stringToHandle(write ? pair.target.c_str() : pair.source.c_str()); + auto typedHandle = builder.readFromBlackboard(handle); + data.outputTexes.emplace_back(); + auto &lastTex = data.outputTexes.back(); + framegraph::Texture::Descriptor colorTexInfo; + colorTexInfo.format = gfx::Format::RGBA8; + colorTexInfo.usage = write ? gfx::TextureUsage::TRANSFER_DST : gfx::TextureUsage::TRANSFER_SRC; + + lastTex.second = static_cast(typedHandle); + + if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { + colorTexInfo.width = 960; + colorTexInfo.height = 640; + + lastTex.second = builder.create(handle, colorTexInfo); + } + + if (write) { + lastTex.second = builder.write(lastTex.second); + builder.writeToBlackboard(handle, lastTex.second); + } else { + auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); + builder.writeToBlackboard(handle, res); + } + } + } + }; + + auto forwardExec = [](const TestRenderData &data, + const framegraph::DevicePassResourceTable &table) { + }; + + auto passHandle = framegraph::FrameGraph::stringToHandle(get(RenderGraph::Name, renderGraph, passID).c_str()); + framegraph.addPass(static_cast(ForwardInsertPoint::IP_FORWARD), passHandle, forwardSetup, forwardExec); + }, + [&](const RaytracePass &pass) {}, + [&](const PresentPass &pass) { + auto forwardSetup = [&](framegraph::PassNodeBuilder &builder, TestRenderData &data) { + for (const auto &pair : pass.presents) { + auto *externalRes = gfx::Device::getInstance()->createTexture(gfx::TextureInfo{ + gfx::TextureType::TEX2D, + gfx::TextureUsageBit::COLOR_ATTACHMENT, + gfx::Format::RGBA8, + 960, + 640, + }); + + const auto handle = framegraph::FrameGraph::stringToHandle(pair.first.c_str()); + auto typedHandle = builder.readFromBlackboard(handle); + data.outputTexes.emplace_back(); + auto &lastTex = data.outputTexes.back(); + framegraph::Texture::Descriptor colorTexInfo; + colorTexInfo.format = gfx::Format::RGBA8; + colorTexInfo.usage = gfx::TextureUsage::SAMPLED; + + lastTex.second = static_cast(typedHandle); + + if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { + colorTexInfo.width = 960; + colorTexInfo.height = 640; + + lastTex.second = builder.create(handle, colorTexInfo); + } + + auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); + builder.writeToBlackboard(handle, res); + + framegraph.presentFromBlackboard(framegraph::FrameGraph::stringToHandle(pair.first.c_str()), externalRes, false); + } + }; + + auto forwardExec = [](const TestRenderData &data, + const framegraph::DevicePassResourceTable &table) { + }; + auto passHandle = framegraph::FrameGraph::stringToHandle(get(RenderGraph::Name, renderGraph, passID).c_str()); + framegraph.addPass(static_cast(ForwardInsertPoint::IP_FORWARD), passHandle, forwardSetup, forwardExec); + }, + [&](const auto & /*pass*/) {}); + } + framegraph.compile(); + framegraph.execute(); + framegraph.reset(); +} + +#define TEST_CASE_DEFINE \ + using namespace cc::render; \ + using cc::gfx::AccessFlagBit; \ + using cc::gfx::BarrierType; \ + using cc::gfx::Format; \ + using cc::gfx::MemoryAccessBit; \ + using cc::gfx::SampleCount; \ + using cc::gfx::ShaderStageFlagBit; \ + using cc::gfx::TextureFlagBit; \ + ResourceInfo resources = { \ + {"0", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"1", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"2", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"3", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"4", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"5", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"6", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"7", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"8", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"9", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"10", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"11", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"12", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"13", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"14", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"15", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"16", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"17", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"18", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"19", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"20", \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + }; + +#define TEST_CASE_1 \ + TEST_CASE_DEFINE \ + \ + ViewInfo rasterData = { \ + { \ + PassType::RASTER, \ + { \ + {{}, {"0", "1", "2"}}, \ + {{"0", "1", "2"}, {"3"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"3"}, {"5"}}, \ + }, \ + }, \ + { \ + PassType::PRESENT, \ + { \ + {{"5"}, {}}, \ + }, \ + }, \ + }; \ + \ + LayoutInfo layoutInfo = { \ + { \ + {"0", 0, cc::gfx::ShaderStageFlagBit::VERTEX}, \ + {"1", 1, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"2", 2, cc::gfx::ShaderStageFlagBit::VERTEX}, \ + {"3", 3, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"3", 3, cc::gfx::ShaderStageFlagBit::VERTEX}, \ + {"5", 5, cc::gfx::ShaderStageFlagBit::VERTEX}, \ + }, \ + { \ + {"5", 5, cc::gfx::ShaderStageFlagBit::COMPUTE /*whatever*/}, \ + }}; + +#define TEST_CASE_2 \ + TEST_CASE_DEFINE \ + \ + ViewInfo rasterData = { \ + { \ + PassType::RASTER, \ + { \ + {{}, {"0", "1"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"0"}, {"2", "3"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"1"}, {"4", "5"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"3", "5"}, {"6"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"2", "4", "6"}, {"7"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{}, {"8"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"0", "8"}, {"9"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"7", "9"}, {"10"}}, \ + }, \ + }, \ + { \ + PassType::PRESENT, \ + { \ + {{"10"}, {}}, \ + }, \ + }, \ + }; \ + \ + LayoutInfo layoutInfo = { \ + { \ + {"0", 0, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"1", 1, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"0", 0, cc::gfx::ShaderStageFlagBit::VERTEX}, \ + {"2", 2, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"3", 3, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"4", 4, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"5", 5, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"1", 1, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"3", 3, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"5", 5, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"6", 6, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"2", 2, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"4", 4, cc::gfx::ShaderStageFlagBit::VERTEX}, \ + {"6", 6, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"7", 7, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"8", 8, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"0", 0, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"8", 8, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"9", 9, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"7", 7, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"9", 9, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"10", 10, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"10", 10, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + }; + +#define TEST_CASE_3 \ + TEST_CASE_DEFINE \ + \ + ViewInfo rasterData = { \ + { \ + PassType::RASTER, \ + { \ + {{}, {"0"}}, \ + {{"0"}, {"1"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"1"}, {"2"}}, \ + {{"2"}, {"3"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"3"}, {"4"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"4"}, {"5"}}, \ + {{"5"}, {"6"}}, \ + }, \ + }, \ + { \ + PassType::COMPUTE, \ + { \ + {{"3"}, {"7"}}, \ + }, \ + }, \ + { \ + PassType::COPY, \ + { \ + {{"7"}, {"8"}}, \ + }, \ + }, \ + { \ + PassType::COMPUTE, \ + { \ + {{"1"}, {"9"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"1"}, {"14"}}, \ + }, \ + }, \ + { \ + PassType::COMPUTE, \ + { \ + {{"14"}, {"15"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"15", "9"}, {"10"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"1"}, {"16"}}, \ + }, \ + }, \ + { \ + PassType::COPY, \ + { \ + {{"16"}, {"17"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"8", "10", "17"}, {"11"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"11", "5", "6"}, {"12"}}, \ + }, \ + }, \ + { \ + PassType::RASTER, \ + { \ + {{"12"}, {"13"}}, \ + }, \ + }, \ + { \ + PassType::PRESENT, \ + { \ + {{"13"}, {}}, \ + }, \ + }, \ + }; \ + \ + LayoutInfo layoutInfo = { \ + { \ + {"0", 0, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"1", 1, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"1", 1, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"2", 2, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"3", 3, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"3", 3, cc::gfx::ShaderStageFlagBit::VERTEX}, \ + {"4", 4, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"4", 4, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"5", 5, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"6", 6, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"3", 3, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"7", 7, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"7", 7, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"8", 8, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"1", 1, cc::gfx::ShaderStageFlagBit::VERTEX}, \ + {"9", 9, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"1", 1, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"14", 14, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"14", 14, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"15", 15, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"15", 15, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"9", 9, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"10", 10, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"1", 1, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"16", 16, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"16", 16, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"17", 17, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"8", 8, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"10", 10, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"17", 17, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"11", 11, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"5", 5, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"6", 6, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"11", 11, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"12", 12, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"12", 12, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + {"13", 13, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + { \ + {"13", 13, cc::gfx::ShaderStageFlagBit::FRAGMENT}, \ + }, \ + }; + +/* void testCase1() { boost::container::pmr::memory_resource *resource = boost::container::pmr::get_default_resource(); RenderGraph renderGraph(resource); @@ -692,6 +1562,6 @@ void testCase4() { testData(data, resources, layoutInfo, renderGraph, rescGraph, layoutGraph); // for(const auto* camera : cameras) {} } - +*/ } // namespace render } // namespace cc diff --git a/native/tests/unit-test/src/complicated_barrier_case.cpp b/native/tests/unit-test/src/complicated_barrier_case.cpp new file mode 100644 index 0000000000..3f6078c24c --- /dev/null +++ b/native/tests/unit-test/src/complicated_barrier_case.cpp @@ -0,0 +1,293 @@ +/**************************************************************************** +Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +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. +****************************************************************************/ +#include "cocos/renderer/pipeline/custom/test/test.h" +#include "gfx-base/GFXDef-common.h" +#include "gtest/gtest.h" +#include "utils.h" + +TEST(complicatedBarrierTest, test12) { + + // simple graph + TEST_CASE_3; + + boost::container::pmr::memory_resource* resource = boost::container::pmr::get_default_resource(); + RenderGraph renderGraph(resource); + ResourceGraph rescGraph(resource); + LayoutGraphData layoutGraphData(resource); + + fillTestGraph(rasterData, resources, layoutInfo, renderGraph, rescGraph, layoutGraphData); + + FrameGraphDispatcher fgDispatcher(rescGraph, renderGraph, layoutGraphData, resource, resource); + fgDispatcher.run(); + + auto findBarrierByResID = [](const std::vector& barriers, uint32_t resID){ + return std::find_if(std::begin(barriers), std::end(barriers), [resID](const Barrier& barrier){ + return barrier.resourceID == resID; + }); + }; + + const auto& barrierMap = fgDispatcher.getBarriers(); + const auto& rag = fgDispatcher.resourceAccessGraph; + ExpectEq(rag.vertices.size() == 17, true); + + // head + const auto& head = barrierMap.at(0); + ExpectEq(head.blockBarrier.frontBarriers.empty(), true); + ExpectEq(head.blockBarrier.rearBarriers.empty(), true); + ExpectEq(head.subpassBarriers.empty(), true); + + // 1st node + const auto& node1 = barrierMap.at(1); + ExpectEq(node1.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node1.blockBarrier.rearBarriers.size() == 1, true); + ExpectEq(node1.subpassBarriers.empty(), false); + + //block barrier: what comes in and what comes out, no matter how many subpasses inside. + ExpectEq(node1.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node1.blockBarrier.rearBarriers[0].resourceID == 1, true); + ExpectEq(node1.blockBarrier.rearBarriers[0].beginStatus.vertID == 1, true); + ExpectEq(node1.blockBarrier.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(node1.blockBarrier.rearBarriers[0].endStatus.vertID == 1, true); + ExpectEq(node1.blockBarrier.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); + + //subpass barrier: like normal pass + const auto& node1subpass = node1.subpassBarriers; + ExpectEq(node1subpass[0].frontBarriers.empty(), true); + ExpectEq(node1subpass[0].rearBarriers.size() == 1, true); + const auto& node1subpassres0 = node1subpass[0].rearBarriers[0]; + ExpectEq(node1subpassres0.type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node1subpassres0.resourceID == 0, true); + ExpectEq(node1subpassres0.beginStatus.vertID == 1, true); + ExpectEq(node1subpassres0.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(node1subpassres0.beginStatus.passType == PassType::RASTER, true); + ExpectEq(node1subpassres0.endStatus.vertID == 1, true);; + ExpectEq(node1subpassres0.endStatus.access == MemoryAccessBit::READ_ONLY, true); + ExpectEq(node1subpassres0.endStatus.passType == PassType::RASTER, true); + + ExpectEq(node1subpass[1].frontBarriers.empty(), true); + const auto& node1subpassres1 = node1subpass[1].rearBarriers[0]; + ExpectEq(node1subpassres1.type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node1subpassres1.resourceID == 1, true); + ExpectEq(node1subpassres1.beginStatus.vertID == 1, true); + ExpectEq(node1subpassres1.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(node1subpassres1.beginStatus.passType == PassType::RASTER, true); + ExpectEq(node1subpassres1.endStatus.vertID == 1, true);; + ExpectEq(node1subpassres1.endStatus.access == MemoryAccessBit::READ_ONLY, true); + ExpectEq(node1subpassres1.endStatus.passType == PassType::RASTER, true); + + //node2 + const auto& node2 = barrierMap.at(2); + ExpectEq(node2.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node2.blockBarrier.rearBarriers.size() == 2, true); + ExpectEq(node2.subpassBarriers.size() == 2, true); + + const auto& node2blockRear = node2.blockBarrier.rearBarriers; + auto iter3in2 = findBarrierByResID(node2blockRear, 3); + const auto& res3in2 = (*iter3in2); + ExpectEq(res3in2.resourceID == 3, true); + ExpectEq(res3in2.type == cc::gfx::BarrierType::FULL, true); + ExpectEq(res3in2.beginStatus.vertID == 2, true); + ExpectEq(res3in2.beginStatus.passType == PassType::RASTER, true); + ExpectEq(res3in2.endStatus.vertID == 2, true); + ExpectEq(res3in2.endStatus.passType == PassType::RASTER, true); + + const auto& node2subpass = node2.subpassBarriers; + ExpectEq(node2subpass.empty(), false); + ExpectEq(node2subpass[0].frontBarriers.empty(), true); + ExpectEq(node2subpass[0].rearBarriers.empty(), false); + + const auto& node2subpassRes2 = node2subpass[0].rearBarriers[0]; + ExpectEq(node2subpassRes2.type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node2subpassRes2.resourceID == 2, true); + ExpectEq(node2subpassRes2.beginStatus.vertID == 2, true); + ExpectEq(node2subpassRes2.beginStatus.passType == PassType::RASTER, true); + ExpectEq(node2subpassRes2.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(node2subpassRes2.endStatus.vertID == 2, true); + ExpectEq(node2subpassRes2.endStatus.access == MemoryAccessBit::READ_ONLY, true); + + //node3 + const auto& node3 = barrierMap.at(3); + ExpectEq(node3.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node3.blockBarrier.rearBarriers.size() == 2, true); + ExpectEq(node3.subpassBarriers.empty(), true); + + const auto& node3block = node3.blockBarrier; + ExpectEq(node3block.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node3block.rearBarriers[0].resourceID == 4, true); + ExpectEq(node3block.rearBarriers[0].beginStatus.vertID == 3, true); + ExpectEq(node3block.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(node3block.rearBarriers[0].endStatus.vertID == 3, true); + ExpectEq(node3block.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); + + //node4 + const auto& node4 = barrierMap.at(4); + ExpectEq(node4.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node4.blockBarrier.rearBarriers.size() == 2, true); + ExpectEq(node4.subpassBarriers.empty(), false); + + const auto& node4block = node4.blockBarrier; + auto iter5in4 = findBarrierByResID(node4block.rearBarriers, 5); + ExpectEq(iter5in4 != node4block.rearBarriers.end(), true); + ExpectEq((*iter5in4).type == cc::gfx::BarrierType::FULL, true); + ExpectEq((*iter5in4).resourceID == 5, true); + ExpectEq((*iter5in4).beginStatus.vertID == 4, true); + ExpectEq((*iter5in4).endStatus.vertID == 4, true); + + auto iter6in4 = findBarrierByResID(node4block.rearBarriers, 6); + ExpectEq(iter6in4 != node4block.rearBarriers.end(), true); + ExpectEq((*iter6in4).type == cc::gfx::BarrierType::SPLIT_BEGIN, true); + ExpectEq((*iter6in4).resourceID == 6, true); + ExpectEq((*iter6in4).beginStatus.vertID == 4, true); + ExpectEq((*iter6in4).endStatus.vertID == 14, true); + + const auto& node4subpass0 = node4.subpassBarriers[0]; + ExpectEq(node4subpass0.frontBarriers.empty(), true); + ExpectEq(node4subpass0.rearBarriers.size() == 1, true); + ExpectEq(node4subpass0.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node4subpass0.rearBarriers[0].resourceID == 5, true); + ExpectEq(node4subpass0.rearBarriers[0].beginStatus.vertID == 4, true); + ExpectEq(node4subpass0.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(node4subpass0.rearBarriers[0].endStatus.vertID == 4, true); + ExpectEq(node4subpass0.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); + + const auto& node4subpass1 = node4.subpassBarriers[1]; + ExpectEq(node4subpass1.frontBarriers.empty(), true); + ExpectEq(node4subpass1.rearBarriers.size() == 1, true); + ExpectEq(node4subpass1.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); + ExpectEq(node4subpass1.rearBarriers[0].resourceID == 6, true); + ExpectEq(node4subpass1.rearBarriers[0].beginStatus.vertID == 4, true); + ExpectEq(node4subpass1.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(node4subpass1.rearBarriers[0].endStatus.vertID == 14, true); + ExpectEq(node4subpass1.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); + + const auto& node5 = barrierMap.at(5); + ExpectEq(node5.blockBarrier.frontBarriers.empty(), false); + ExpectEq(node5.blockBarrier.rearBarriers.size() == 1, true); + ExpectEq(node5.subpassBarriers.empty(), true); + + auto iter7in5 = findBarrierByResID(node5.blockBarrier.rearBarriers, 7); + const auto& res7in5 = (*iter7in5); + ExpectEq(res7in5.type == cc::gfx::BarrierType::FULL, true); + ExpectEq(res7in5.resourceID == 7, true); + ExpectEq(res7in5.beginStatus.vertID == 5, true); + ExpectEq(res7in5.endStatus.vertID == 5, true); + ExpectEq(res7in5.beginStatus.passType == PassType::COMPUTE, true); + ExpectEq(res7in5.endStatus.passType == PassType::COPY, true); + ExpectEq(res7in5.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(res7in5.endStatus.access == MemoryAccessBit::READ_ONLY, true); + + const auto& node6 = barrierMap.at(6); + ExpectEq(node6.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node6.blockBarrier.rearBarriers.size() == 1, true); + ExpectEq(node6.subpassBarriers.empty(), true); + + auto iter8in6 = findBarrierByResID(node6.blockBarrier.rearBarriers, 8); + const auto& res8in6 = (*iter8in6); + ExpectEq(res8in6.type == cc::gfx::BarrierType::SPLIT_BEGIN, true); + ExpectEq(res8in6.resourceID == 8, true); + ExpectEq(res8in6.beginStatus.vertID == 6, true); + ExpectEq(res8in6.endStatus.vertID == 13, true); + ExpectEq(res8in6.beginStatus.passType == PassType::COPY, true); + ExpectEq(res8in6.endStatus.passType == PassType::RASTER, true); + ExpectEq(res8in6.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(res8in6.endStatus.access == MemoryAccessBit::READ_ONLY, true); + + // node7 + const auto& node7 = barrierMap.at(7); + ExpectEq(node7.blockBarrier.frontBarriers.empty(), false); + ExpectEq(node7.blockBarrier.rearBarriers.empty(), false); + ExpectEq(node7.subpassBarriers.empty(), true); + + auto iter9in7 = findBarrierByResID(node7.blockBarrier.rearBarriers, 9); + const auto& res9in7 = (*iter9in7); + ExpectEq(res9in7.type == cc::gfx::BarrierType::SPLIT_BEGIN, true); + ExpectEq(res9in7.resourceID == 9, true); + ExpectEq(res9in7.beginStatus.vertID == 7, true); + ExpectEq(res9in7.endStatus.vertID == 10, true); + ExpectEq(res9in7.beginStatus.passType == PassType::COMPUTE, true); + ExpectEq(res9in7.endStatus.passType == PassType::RASTER, true); + + //node8: almost the same as node7 + //node9: almost the same as node8 + //node10: ditto + //node11: ditto + //node12: ditto + + //node13 + const auto& node13 = barrierMap.at(13); + ExpectEq(node13.blockBarrier.frontBarriers.size() == 2, true); + ExpectEq(node13.blockBarrier.rearBarriers.size() == 1, true); + ExpectEq(node13.subpassBarriers.empty(), true); + + auto iter8in13 = findBarrierByResID(node13.blockBarrier.frontBarriers, 8); + const auto& res8in13 = (*iter8in13); + ExpectEq(res8in13.type == cc::gfx::BarrierType::SPLIT_END, true); + ExpectEq(res8in13.resourceID == 8, true); + ExpectEq(res8in13.beginStatus.vertID == 6, true); + ExpectEq(res8in13.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(res8in13.beginStatus.passType == PassType::COPY, true); + ExpectEq(res8in13.endStatus.vertID == 13, true); + ExpectEq(res8in13.endStatus.access == MemoryAccessBit::READ_ONLY, true); + ExpectEq(res8in13.endStatus.passType == PassType::RASTER, true); + + auto iter10in13 = findBarrierByResID(node13.blockBarrier.frontBarriers, 10); + const auto& res10in13 = (*iter10in13); + ExpectEq(res10in13.type == cc::gfx::BarrierType::SPLIT_END, true); + ExpectEq(res10in13.resourceID == 10, true); + ExpectEq(res10in13.beginStatus.vertID == 10, true); + ExpectEq(res10in13.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(res10in13.beginStatus.passType == PassType::RASTER, true); + ExpectEq(res10in13.endStatus.vertID == 13, true); + ExpectEq(res10in13.endStatus.access == MemoryAccessBit::READ_ONLY, true); + ExpectEq(res10in13.endStatus.passType == PassType::RASTER, true); + + auto iter11in13 = findBarrierByResID(node13.blockBarrier.rearBarriers, 11); + const auto& res11in13 = (*iter11in13); + ExpectEq(res11in13.type == cc::gfx::BarrierType::FULL, true); + ExpectEq(res11in13.resourceID == 11, true); + ExpectEq(res11in13.beginStatus.vertID == 13, true); + ExpectEq(res11in13.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(res11in13.beginStatus.passType == PassType::RASTER, true); + ExpectEq(res11in13.endStatus.vertID == 13, true); + ExpectEq(res11in13.endStatus.access == MemoryAccessBit::READ_ONLY, true); + ExpectEq(res11in13.endStatus.passType == PassType::RASTER, true); + + //node14: almost the same as 13 + + //node15: ditto + const auto& node15 = barrierMap.at(15); + const auto& theone = node15.blockBarrier.rearBarriers.front(); + ExpectEq(theone.resourceID == 13, true); + ExpectEq(theone.type == cc::gfx::BarrierType::FULL, true); + ExpectEq(theone.endStatus.vertID == 15, true); + ExpectEq(theone.endStatus.passType == PassType::PRESENT, true); + + //node16 + const auto& node16 = barrierMap.at(16); + ExpectEq(node16.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node16.blockBarrier.rearBarriers.empty(), true); + ExpectEq(node16.subpassBarriers.empty(), true); + + //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); +} diff --git a/native/tests/unit-test/src/simple_barrier_test.cpp b/native/tests/unit-test/src/simple_barrier_test.cpp new file mode 100644 index 0000000000..d672b027fc --- /dev/null +++ b/native/tests/unit-test/src/simple_barrier_test.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** +Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +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. +****************************************************************************/ +#include "cocos/renderer/pipeline/custom/test/test.h" +#include "gfx-base/GFXDef-common.h" +#include "gtest/gtest.h" +#include "utils.h" + +TEST(barrierTest, test10) { + + // simple graph + TEST_CASE_1; + + boost::container::pmr::memory_resource* resource = boost::container::pmr::get_default_resource(); + RenderGraph renderGraph(resource); + ResourceGraph rescGraph(resource); + LayoutGraphData layoutGraphData(resource); + + fillTestGraph(rasterData, resources, layoutInfo, renderGraph, rescGraph, layoutGraphData); + + FrameGraphDispatcher fgDispatcher(rescGraph, renderGraph, layoutGraphData, resource, resource); + fgDispatcher.run(); + + const auto& barrierMap = fgDispatcher.getBarriers(); + const auto& rag = fgDispatcher.resourceAccessGraph; + ExpectEq(rag.vertices.size() == 4, true); + + // head + const auto& head = barrierMap.at(0); + ExpectEq(head.blockBarrier.frontBarriers.empty(), true); + ExpectEq(head.blockBarrier.rearBarriers.empty(), true); + + // 1st node + const auto& node1 = barrierMap.at(1); + ExpectEq(node1.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node1.blockBarrier.rearBarriers.size() == 1, true); + + ExpectEq(node1.subpassBarriers[0].frontBarriers.empty(), true); + ExpectEq(node1.subpassBarriers[0].rearBarriers.size() == 3, true); + + ExpectEq(node1.subpassBarriers[1].frontBarriers.empty(), true); + ExpectEq(node1.subpassBarriers[1].rearBarriers.size() == 1, true); + + const auto& barrier = node1.blockBarrier.rearBarriers[0]; + ExpectEq(barrier.type == BarrierType::FULL, true); + ExpectEq(barrier.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + //resID 3 + ExpectEq(barrier.beginStatus.visibility == std::get<2>(layoutInfo[0][3]), true); + + + //// 2nd node + const auto& node2 = barrierMap.at(2); + ExpectEq(node2.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node2.blockBarrier.rearBarriers.size() == 1, true); + + const auto& node2RearBarrier0 = node2.blockBarrier.rearBarriers.back(); + ExpectEq(node2RearBarrier0.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + ExpectEq(node2RearBarrier0.beginStatus.visibility == ShaderStageFlagBit::VERTEX, true); + ExpectEq(node2RearBarrier0.endStatus.access == MemoryAccessBit::READ_ONLY, true); + //endstatus: whatever it was, it's COLOR_ATTACHMENT_OPTIMAL + + //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); +} diff --git a/native/tests/unit-test/src/simple_closed_barrier_test.cpp b/native/tests/unit-test/src/simple_closed_barrier_test.cpp new file mode 100644 index 0000000000..a45b775514 --- /dev/null +++ b/native/tests/unit-test/src/simple_closed_barrier_test.cpp @@ -0,0 +1,176 @@ +/**************************************************************************** +Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +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. +****************************************************************************/ +#include "cocos/renderer/pipeline/custom/test/test.h" +#include "gfx-base/GFXDef-common.h" +#include "gtest/gtest.h" +#include "utils.h" + +TEST(simpleClosedBarrierTest, test11) { + + // simple graph + TEST_CASE_2; + + boost::container::pmr::memory_resource* resource = boost::container::pmr::get_default_resource(); + RenderGraph renderGraph(resource); + ResourceGraph rescGraph(resource); + LayoutGraphData layoutGraphData(resource); + + fillTestGraph(rasterData, resources, layoutInfo, renderGraph, rescGraph, layoutGraphData); + + FrameGraphDispatcher fgDispatcher(rescGraph, renderGraph, layoutGraphData, resource, resource); + fgDispatcher.run(); + + const auto& barrierMap = fgDispatcher.getBarriers(); + const auto& rag = fgDispatcher.resourceAccessGraph; + ExpectEq(rag.vertices.size() == 10, true); + + // head + const auto& head = barrierMap.at(0); + ExpectEq(head.blockBarrier.frontBarriers.empty(), true); + ExpectEq(head.blockBarrier.rearBarriers.empty(), true); + ExpectEq(head.subpassBarriers.empty(), true); + + // 1st node + const auto& node1 = barrierMap.at(1); + ExpectEq(node1.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node1.blockBarrier.rearBarriers.size() == 2, true); + ExpectEq(node1.subpassBarriers.empty(), true); + + ExpectEq(node1.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node1.blockBarrier.rearBarriers[0].endStatus.vertID == 1, true); + ExpectEq(node1.blockBarrier.rearBarriers[1].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); + ExpectEq(node1.blockBarrier.rearBarriers[1].endStatus.vertID == 3, true); + + const auto& node2 = barrierMap.at(2); + ExpectEq(node2.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node2.blockBarrier.rearBarriers.size() == 3, true); + ExpectEq(node2.subpassBarriers.empty(), true); + + // res3 + ExpectEq(node2.blockBarrier.rearBarriers[1].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); + ExpectEq(node2.blockBarrier.rearBarriers[1].beginStatus.vertID == 2, true); + ExpectEq(node2.blockBarrier.rearBarriers[1].endStatus.vertID == 5, true); + // res2 + ExpectEq(node2.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); + ExpectEq(node2.blockBarrier.rearBarriers[0].beginStatus.vertID == 2, true); + ExpectEq(node2.blockBarrier.rearBarriers[0].endStatus.vertID == 4, true); + + const auto& node3 = barrierMap.at(3); + ExpectEq(node3.blockBarrier.frontBarriers.size() == 1, true); + ExpectEq(node3.blockBarrier.rearBarriers.size() == 2, true); + ExpectEq(node3.subpassBarriers.empty(), true); + + ExpectEq(node3.blockBarrier.frontBarriers[0].type == cc::gfx::BarrierType::SPLIT_END, true); + ExpectEq(node3.blockBarrier.frontBarriers[0].beginStatus.vertID == 1, true); + ExpectEq(node3.blockBarrier.frontBarriers[0].endStatus.vertID == 3, true); + // res 5 + ExpectEq(node3.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node3.blockBarrier.rearBarriers[0].beginStatus.vertID == 3, true); + ExpectEq(node3.blockBarrier.rearBarriers[0].endStatus.vertID == 3, true); + // res 4 + ExpectEq(node3.blockBarrier.rearBarriers[1].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); + ExpectEq(node3.blockBarrier.rearBarriers[1].beginStatus.vertID == 3, true); + ExpectEq(node3.blockBarrier.rearBarriers[1].endStatus.vertID == 5, true); + + const auto& node4 = barrierMap.at(4); + ExpectEq(node4.blockBarrier.frontBarriers.size() == 1, true); + ExpectEq(node4.blockBarrier.rearBarriers.size() == 1, true); + ExpectEq(node4.subpassBarriers.empty(), true); + + ExpectEq(node4.blockBarrier.frontBarriers[0].resourceID == 3, true); + ExpectEq(node4.blockBarrier.frontBarriers[0].type == cc::gfx::BarrierType::SPLIT_END, true); + ExpectEq(node4.blockBarrier.frontBarriers[0].beginStatus.vertID == 2, true); + ExpectEq(node4.blockBarrier.frontBarriers[0].endStatus.vertID == 4, true); + + ExpectEq(node4.blockBarrier.rearBarriers[0].resourceID == 6, true); + ExpectEq(node4.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node4.blockBarrier.rearBarriers[0].beginStatus.vertID == 4, true); + ExpectEq(node4.blockBarrier.rearBarriers[0].endStatus.vertID == 4, true); + + const auto& node5 = barrierMap.at(5); + ExpectEq(node5.blockBarrier.frontBarriers.size() == 2, true); + ExpectEq(node5.blockBarrier.rearBarriers.size() == 1, true); + ExpectEq(node5.subpassBarriers.empty(), true); + + ExpectEq(node5.blockBarrier.frontBarriers[0].resourceID == 2, true); + ExpectEq(node5.blockBarrier.frontBarriers[0].type == cc::gfx::BarrierType::SPLIT_END, true); + ExpectEq(node5.blockBarrier.frontBarriers[0].beginStatus.vertID == 2, true); + ExpectEq(node5.blockBarrier.frontBarriers[0].endStatus.vertID == 5, true); + ExpectEq(node5.blockBarrier.frontBarriers[1].resourceID == 4, true); + ExpectEq(node5.blockBarrier.frontBarriers[1].type == cc::gfx::BarrierType::SPLIT_END, true); + ExpectEq(node5.blockBarrier.frontBarriers[1].beginStatus.vertID == 3, true); + ExpectEq(node5.blockBarrier.frontBarriers[1].endStatus.vertID == 5, true); + + ExpectEq(node5.blockBarrier.rearBarriers[0].resourceID == 7, true); + ExpectEq(node5.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); + ExpectEq(node5.blockBarrier.rearBarriers[0].beginStatus.vertID == 5, true); + ExpectEq(node5.blockBarrier.rearBarriers[0].endStatus.vertID == 8, true); + + const auto& node6 = barrierMap.at(6); + ExpectEq(node6.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node6.blockBarrier.rearBarriers.size() == 1, true); + ExpectEq(node6.subpassBarriers.empty(), true); + + ExpectEq(node6.blockBarrier.rearBarriers[0].resourceID == 8, true); + ExpectEq(node6.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node6.blockBarrier.rearBarriers[0].beginStatus.vertID == 6, true); + ExpectEq(node6.blockBarrier.rearBarriers[0].endStatus.vertID == 6, true); + + const auto& node7 = barrierMap.at(7); + ExpectEq(node7.subpassBarriers.empty(), true); + ExpectEq(node7.blockBarrier.frontBarriers.empty(), false); + ExpectEq(node7.blockBarrier.rearBarriers.size() == 1, true); + + ExpectEq(node7.blockBarrier.rearBarriers[0].resourceID == 9, true); + ExpectEq(node7.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node7.blockBarrier.rearBarriers[0].beginStatus.vertID == 7, true); + ExpectEq(node7.blockBarrier.rearBarriers[0].endStatus.vertID == 7, true); + + const auto& node8 = barrierMap.at(8); + ExpectEq(node8.subpassBarriers.empty(), true); + ExpectEq(node8.blockBarrier.frontBarriers.empty(), false); // size == 1 + ExpectEq(node8.blockBarrier.rearBarriers.size() == 1, true); + + ExpectEq(node8.blockBarrier.frontBarriers[0].resourceID == 7, true); + ExpectEq(node8.blockBarrier.frontBarriers[0].type == cc::gfx::BarrierType::SPLIT_END, true); + ExpectEq(node8.blockBarrier.frontBarriers[0].beginStatus.vertID == 5, true); + ExpectEq(node8.blockBarrier.frontBarriers[0].endStatus.vertID == 8, true); + + ExpectEq(node8.blockBarrier.rearBarriers[0].resourceID == 10, true); + ExpectEq(node8.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); + ExpectEq(node8.blockBarrier.rearBarriers[0].beginStatus.vertID == 8, true); + ExpectEq(node8.blockBarrier.rearBarriers[0].endStatus.vertID == 8, true); + + const auto& node9 = barrierMap.at(9); + ExpectEq(node9.subpassBarriers.empty(), true); + ExpectEq(node9.blockBarrier.frontBarriers.empty(), true); + ExpectEq(node9.blockBarrier.rearBarriers.empty(), true); + // const auto& node2RearBarrier0 = node2.blockBarrier.rearBarriers.back(); + // ExpectEq(node2RearBarrier0.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); + // ExpectEq(node2RearBarrier0.beginStatus.visibility == ShaderStageFlagBit::VERTEX, true); + // ExpectEq(node2RearBarrier0.endStatus.access == MemoryAccessBit::READ_ONLY, true); + //endstatus: whatever it was, it's COLOR_ATTACHMENT_OPTIMAL + + //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); +} diff --git a/native/tools/tojs/gfx.ini b/native/tools/tojs/gfx.ini index e40557355a..dd1b22a619 100644 --- a/native/tools/tojs/gfx.ini +++ b/native/tools/tojs/gfx.ini @@ -74,7 +74,7 @@ skip = Buffer::[Buffer initialize update], GeneralBarrier::[GeneralBarrier], TextureBarrier::[TextureBarrier], BufferBarrier::[BufferBarrier], - Device::[Device copyBuffersToTexture copyTextureToBuffers createBuffer createTexture getInstance], + Device::[Device copyBuffersToTexture copyTextureToBuffers createBuffer createTexture getInstance setOptions getOptions], DeviceManager::[addSurfaceEventListener isDetachDeviceThread getGFXName] skip_public_fields = *::[_.*] From 6ab59df008eb8f15a0fadba08c46bc70bcdc2cdd Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Thu, 21 Jul 2022 23:23:16 +0800 Subject: [PATCH 080/111] [v3.6.0 pipeline] add pipeline macro (#12136) * add pipeline macro --- cocos/core/pipeline/custom/index.ts | 7 +-- cocos/core/pipeline/custom/web-pipeline.ts | 50 ++++++++++++---------- cocos/core/platform/macro.ts | 11 +++++ cocos/core/root.ts | 5 ++- 4 files changed, 46 insertions(+), 27 deletions(-) diff --git a/cocos/core/pipeline/custom/index.ts b/cocos/core/pipeline/custom/index.ts index 0f77ca67f7..3028c2bc92 100644 --- a/cocos/core/pipeline/custom/index.ts +++ b/cocos/core/pipeline/custom/index.ts @@ -23,17 +23,18 @@ THE SOFTWARE. */ -import { legacyCC } from '../../global-exports'; import { Pipeline, PipelineBuilder } from './pipeline'; import { WebPipeline } from './web-pipeline'; import { buildDeferredLayout, buildForwardLayout } from './effect'; +import { macro } from '../../platform/macro'; let _pipeline: WebPipeline | null = null; export function createCustomPipeline (): Pipeline { - const root = legacyCC.director.root; const ppl = new WebPipeline(); - if (root.useDeferredPipeline) { + const pplName = macro.CUSTOM_PIPELINE_NAME; + ppl.setCustomPipelineName(pplName); + if (ppl.usesDeferredPipeline) { buildDeferredLayout(ppl); } else { buildForwardLayout(ppl); diff --git a/cocos/core/pipeline/custom/web-pipeline.ts b/cocos/core/pipeline/custom/web-pipeline.ts index 98f757e1b8..e3ef09902b 100644 --- a/cocos/core/pipeline/custom/web-pipeline.ts +++ b/cocos/core/pipeline/custom/web-pipeline.ts @@ -370,9 +370,6 @@ function isManaged (residency: ResourceResidency): boolean { } export class WebPipeline extends Pipeline { - public get device (): Device { - return this._device; - } public containsResource (name: string): boolean { return this._resourceGraph.contains(name); } @@ -390,19 +387,9 @@ export class WebPipeline extends Pipeline { public presentAll (): void { throw new Error('Method not implemented.'); } - public get lightingMode (): LightingMode { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return this._lightingMode; - } - public set lightingMode (mode: LightingMode) { - this._lightingMode = mode; - } public createSceneTransversal (camera: Camera, scene: RenderScene): SceneTransversal { throw new Error('Method not implemented.'); } - public get layoutGraphBuilder (): LayoutGraphBuilder { - return new WebLayoutGraphBuilder(this._device, this._layoutGraph); - } protected _generateConstantMacros (clusterEnabled: boolean) { let str = ''; str += `#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE ${this._device.getFormatFeatures(Format.RGBA32F) @@ -415,7 +402,12 @@ export class WebPipeline extends Pipeline { str += `#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES ${macro.ENABLE_WEBGL_HIGHP_STRUCT_VALUES ? 1 : 0}\n`; this._constantMacros = str; } - + public setCustomPipelineName (name: string) { + this._customPipelineName = name; + if (this._customPipelineName === 'Deferred') { + this._usesDeferredPipeline = true; + } + } public activate (swapchain: Swapchain): boolean { this._device = deviceManager.gfxDevice; this._globalDSManager = new GlobalDSManager(this._device); @@ -434,9 +426,8 @@ export class WebPipeline extends Pipeline { >= (WebPipeline.CSM_UNIFORM_VECTORS + WebPipeline.GLOBAL_UNIFORM_VECTORS); this.setMacroBool('CC_SUPPORT_CASCADED_SHADOW_MAP', this.pipelineSceneData.csmSupported); - const root = legacyCC.director.root; // enable the deferred pipeline - if (root.useDeferredPipeline) { + if (this.usesDeferredPipeline) { this.setMacroInt('CC_PIPELINE_TYPE', 1); } const shadowMapSampler = this._globalDSManager.pointSampler; @@ -457,6 +448,22 @@ export class WebPipeline extends Pipeline { this._pipelineSceneData?.destroy(); return true; } + public get device (): Device { + return this._device; + } + public get lightingMode (): LightingMode { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this._lightingMode; + } + public set lightingMode (mode: LightingMode) { + this._lightingMode = mode; + } + public get layoutGraphBuilder (): LayoutGraphBuilder { + return new WebLayoutGraphBuilder(this._device, this._layoutGraph); + } + public get usesDeferredPipeline (): boolean { + return this._usesDeferredPipeline; + } public get macros (): MacroRecord { return this._macros; } @@ -650,13 +657,10 @@ export class WebPipeline extends Pipeline { this.beginFrame(); if (this.builder) { this.builder.setup(cameras, this); + } else if (this.usesDeferredPipeline) { + this._deferred.setup(cameras, this); } else { - const root = legacyCC.director.root; - if (root.useDeferredPipeline) { - this._deferred.setup(cameras, this); - } else { - this._forward.setup(cameras, this); - } + this._forward.setup(cameras, this); } this.compile(); this.execute(); @@ -705,6 +709,7 @@ export class WebPipeline extends Pipeline { } public static MAX_BLOOM_FILTER_PASS_NUM = 6; + private _usesDeferredPipeline = false; private _device!: Device; private _globalDSManager!: GlobalDSManager; private readonly _macros: MacroRecord = {}; @@ -720,6 +725,7 @@ export class WebPipeline extends Pipeline { private _renderGraph: RenderGraph | null = null; private _compiler: Compiler | null = null; private _executor: Executor | null = null; + private _customPipelineName = ''; private _forward!: ForwardPipelineBuilder; private _deferred!: DeferredPipelineBuilder; public builder: PipelineBuilder | null = null; diff --git a/cocos/core/platform/macro.ts b/cocos/core/platform/macro.ts index 9d3e319b92..cfb92e4550 100644 --- a/cocos/core/platform/macro.ts +++ b/cocos/core/platform/macro.ts @@ -1071,6 +1071,16 @@ interface Macro { */ BATCHER2D_MEM_INCREMENT: number; + /** + * @zh 自定义渲染管线的名字(实验性) + * 引擎会根据名字创建对应的渲染管线(仅限Web平台)。如果名字为空,则不启用自定义渲染管线。 + * 目前仅支持'Forward', 'Deferred'两种。 + * @en The name of custom rendering pipeline (experimental) + * Engine will use the name to create the custom pipeline (Web only). If the name is empty, custom pipeline will be disabled. + * Currently only 'Forward' and 'Deferred' are supported. + */ + CUSTOM_PIPELINE_NAME: string; + /** * @internal */ @@ -1104,6 +1114,7 @@ const macro: Macro = { MAX_LABEL_CANVAS_POOL_SIZE: 20, ENABLE_WEBGL_HIGHP_STRUCT_VALUES: false, BATCHER2D_MEM_INCREMENT: 144, + CUSTOM_PIPELINE_NAME: '', init () { if (NATIVE || MINIGAME || RUNTIME_BASED) { this.CLEANUP_IMAGE_CACHE = true; diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 56377397aa..4a5e8a59bf 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -43,6 +43,7 @@ import { Batcher2D } from '../2d/renderer/batcher-2d'; import { IPipelineEvent } from './pipeline/pipeline-event'; import { settings, Settings } from './settings'; import { localDescriptorSetLayout_ResizeMaxJoints } from './pipeline/define'; +import { macro } from './platform/macro'; /** * @en Initialization information for the Root @@ -119,7 +120,7 @@ export class Root { * 启用自定义渲染管线 */ public get usesCustomPipeline (): boolean { - return this._usesCustomPipeline && !DEV && (HTML5 || TEST); + return this._usesCustomPipeline && macro.CUSTOM_PIPELINE_NAME !== ''; } /** @@ -248,7 +249,7 @@ export class Root { private _mainWindow: RenderWindow | null = null; private _curWindow: RenderWindow | null = null; private _tempWindow: RenderWindow | null = null; - private _usesCustomPipeline = false; + private _usesCustomPipeline = true; private _pipeline: PipelineRuntime | null = null; private _pipelineEvent: IPipelineEvent | null = null; private _classicPipeline: RenderPipeline | null = null; From a2a7c9fc8338272c16bc07df8fb5f333662bf707 Mon Sep 17 00:00:00 2001 From: zxx43 Date: Thu, 21 Jul 2022 23:29:47 +0800 Subject: [PATCH 081/111] V3.6.0 gpu particle fix (#11944) * fix gpu particles * fix gpu texture animation value error --- cocos/particle/animator/curve-range.ts | 6 +++--- cocos/particle/animator/gradient-range.ts | 4 ++-- cocos/particle/renderer/particle-system-renderer-gpu.ts | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos/particle/animator/curve-range.ts b/cocos/particle/animator/curve-range.ts index 88b93bdd89..1aad3808d7 100644 --- a/cocos/particle/animator/curve-range.ts +++ b/cocos/particle/animator/curve-range.ts @@ -316,7 +316,7 @@ export function packCurveRangeXY (samples: number, x: CurveRange, y: CurveRange, sum += value; average = sum / (j + 1); } - data[j * 4 + i] = average; + data[((h * samples) + j) * 4 + i] = average; } } } @@ -342,7 +342,7 @@ export function packCurveRangeXYZ (samples: number, x: CurveRange, y: CurveRange sum += value; average = sum / (j + 1); } - data[j * 4 + i] = average; + data[((h * samples) + j) * 4 + i] = average; } } } @@ -368,7 +368,7 @@ export function packCurveRangeXYZW (samples: number, x: CurveRange, y: CurveRang sum += value; average = sum / (j + 1); } - data[j * 4 + i] = average; + data[((h * samples) + j) * 4 + i] = average; } } } diff --git a/cocos/particle/animator/gradient-range.ts b/cocos/particle/animator/gradient-range.ts index 0770f58186..a19c8dbe05 100644 --- a/cocos/particle/animator/gradient-range.ts +++ b/cocos/particle/animator/gradient-range.ts @@ -140,7 +140,7 @@ export default class GradientRange { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onBeforeSerialize (props: any): any { + public _onBeforeSerialize (props: any) { return SerializableTable[this._mode]; } } @@ -174,7 +174,7 @@ function evaluateHeight (gr: GradientRange) { export function packGradientRange (samples: number, gr: GradientRange) { const height = evaluateHeight(gr); const data = new Uint8Array(samples * height * 4); - const interval = 1.0 / (samples - 1); + const interval = 1.0 / (samples); let offset = 0; for (let h = 0; h < height; h++) { diff --git a/cocos/particle/renderer/particle-system-renderer-gpu.ts b/cocos/particle/renderer/particle-system-renderer-gpu.ts index d8dd3d19fd..9255b25cd8 100644 --- a/cocos/particle/renderer/particle-system-renderer-gpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-gpu.ts @@ -457,7 +457,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this._defines[TEXTURE_ANIMATION_MODULE_ENABLE] = enable; if (enable) { if (this._animTexture) this._animTexture.destroy(); - this._animTexture = packCurveRangeXY(_sample_num, textureModule.startFrame, textureModule.frameOverTime); + this._animTexture = packCurveRangeXY(_sample_num, textureModule.startFrame, textureModule.frameOverTime, true); const handle = pass.getHandle('texture_animation_tex0'); const binding = Pass.getBindingFromHandle(handle); pass.bindSampler(binding, this._animTexture.getGFXSampler()!); From d871c1eb5dc153dc4fa99304ed49e480de32acba Mon Sep 17 00:00:00 2001 From: SijieWang Date: Thu, 21 Jul 2022 23:32:08 +0800 Subject: [PATCH 082/111] [Optimize] When MENU is specified, do not put it in the custom script (#12123) --- cocos/core/components/component.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/core/components/component.ts b/cocos/core/components/component.ts index ad0d2c63cb..6bd3d02b8a 100644 --- a/cocos/core/components/component.ts +++ b/cocos/core/components/component.ts @@ -748,7 +748,7 @@ value(Component, '_registerEditorProps', (cls, props) => { { const frame = RF.peek(); let menu = val; - if (frame) { + if (frame && !menu.includes('/')) { menu = `i18n:menu.custom_script/${menu}`; } From 810de3fe68e338da49c5f63e280511cfd39f52a9 Mon Sep 17 00:00:00 2001 From: PP Date: Thu, 21 Jul 2022 23:33:44 +0800 Subject: [PATCH 083/111] support number type of engine constant (#12012) * add constant type for number * support number type of build time constant * publish 4.3.11 * update test * support genCCEnvConstants && publish 4.3.12 * NET_MODE is public, SERVER_MODE is private * update deps * fix exportDynamicConstants * update test * publish 4.3.14 * update deps * support JIT is not dynamic * update lock --- cc.config.json | 36 +- cc.config.schema.json | 19 +- package-lock.json | 381 +++++++++--------- package.json | 2 +- scripts/build-engine/package-lock.json | 48 ++- scripts/build-engine/package.json | 6 +- scripts/build-engine/src/config-interface.ts | 9 +- scripts/build-engine/src/constant-manager.ts | 104 +++-- scripts/build-engine/src/index.ts | 2 +- .../constant-manager.test.ts.snap | 50 ++- .../tests/stats-query/cc.config.json | 46 ++- .../stats-query/constant-manager.test.ts | 2 + 12 files changed, 442 insertions(+), 263 deletions(-) diff --git a/cc.config.json b/cc.config.json index 77dc2c8ec8..412737ccc1 100644 --- a/cc.config.json +++ b/cc.config.json @@ -268,78 +268,91 @@ "constants": { "HTML5": { "comment": "Running in Web platform", + "type": "boolean", "value": false, "internal": false, "dynamic": true }, "NATIVE": { "comment": "Running in native platform (mobile app, desktop app, or simulator).", + "type": "boolean", "value": false, "internal": false, "dynamic": true }, "WECHAT": { "comment": "Running in the Wechat's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "BAIDU": { "comment": "Running in the baidu's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "XIAOMI": { "comment": "Running in the xiaomi's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "ALIPAY": { "comment": "Running in the alipay's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "BYTEDANCE": { "comment": "Running in the ByteDance's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "OPPO": { "comment": "Running in the oppo's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "VIVO": { "comment": "Running in the vivo's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "HUAWEI": { "comment": "Running in the huawei's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "COCOSPLAY": { "comment": "Running in the cocosplay.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "QTT": { "comment": "Running in the qtt's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "LINKSURE": { "comment": "Running in the linksure's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false @@ -347,6 +360,7 @@ "EDITOR": { "comment": "Running in the editor.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false, @@ -354,6 +368,7 @@ }, "PREVIEW": { "comment": "Preview in browser or simulator.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false, @@ -361,12 +376,14 @@ }, "BUILD": { "comment": "Running in published project.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "TEST": { "comment": "Running in the engine's unit test.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false, @@ -376,19 +393,22 @@ "DEBUG": { "comment": "Running debug mode.", + "type": "boolean", "value": true, "ccGlobal": true, "internal": false }, "SERVER_MODE": { "comment": "Running in the server mode.", + "type": "boolean", "value": false, - "internal": false + "internal": true }, "DEV": { "comment": "Running in the editor or preview.", + "type": "boolean", "value": "$EDITOR || $PREVIEW || $TEST", "ccGlobal": true, "internal": false, @@ -396,25 +416,28 @@ }, "MINIGAME": { "comment": "Running in mini game.", + "type": "boolean", "value": "$WECHAT || $BAIDU || $XIAOMI || $ALIPAY || $BYTEDANCE", "ccGlobal": true, "internal": false }, "RUNTIME_BASED": { "comment": "Running in runtime based environment.", + "type": "boolean", "value": "$OPPO || $VIVO || $HUAWEI || $COCOSPLAY || $QTT || $LINKSURE", "ccGlobal": true, "internal": false }, "SUPPORT_JIT": { "comment": "Support JIT.", + "type": "boolean", "value": "!($MINIGAME || $RUNTIME_BASED)", "ccGlobal": true, - "internal": false, - "dynamic": true + "internal": false }, "JSB": { "comment": "Running in environment where using JSB as the JavaScript interface binding scheme.", + "type": "boolean", "value": "$NATIVE", "ccGlobal": true, "internal": false, @@ -422,8 +445,15 @@ }, "NOT_PACK_PHYSX_LIBS": { "comment": "This is an internal constant to determine whether pack physx libs.", + "type": "boolean", "value": false, "internal": true + }, + "NET_MODE": { + "comment": "The network access mode.\n- 0 Client\n- 1 ListenServer\n- 2 HostServer", + "type": "number", + "value": 0, + "internal": false } } } diff --git a/cc.config.schema.json b/cc.config.schema.json index e2f0b72edf..2446166f91 100644 --- a/cc.config.schema.json +++ b/cc.config.schema.json @@ -38,7 +38,6 @@ "additionalProperties": { "type": "string" }, - "description": "Construct a type with a set of properties K of type T", "type": "object" }, "test": { @@ -62,6 +61,13 @@ ], "type": "object" }, + "ConstantTypeName": { + "enum": [ + "boolean", + "number" + ], + "type": "string" + }, "Feature": { "additionalProperties": false, "description": "An engine feature.", @@ -111,16 +117,22 @@ "description": "Whether exported to developer. If true, it's only exported to engine.", "type": "boolean" }, + "type": { + "$ref": "#/definitions/ConstantTypeName", + "description": "The type of the constant for generating consts.d.ts file." + }, "value": { - "description": "The default value of the constant. It can be a boolean or string. When it's a string type, the value is the result of eval().", + "description": "The default value of the constant. It can be a boolean, number or string. When it's a string type, the value is the result of eval().", "type": [ "boolean", - "string" + "string", + "number" ] } }, "required": [ "comment", + "type", "value", "internal" ], @@ -144,7 +156,6 @@ }, "type": "object" }, - "description": "Construct a type with a set of properties K of type T", "type": "object" } }, diff --git a/package-lock.json b/package-lock.json index 025d7f038b..9ffc6ecdef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1771,9 +1771,9 @@ } }, "@cocos/build-engine": { - "version": "4.3.10", - "resolved": "https://registry.npmjs.org/@cocos/build-engine/-/build-engine-4.3.10.tgz", - "integrity": "sha512-0UXMGivu+5S6tjBbEp2AjzfHSusRCi1+GU+27gDAM1hLTEMPhfjrJdPjxAHH7VuLDDIO27CNZEbtjNMYF0zIBQ==", + "version": "4.3.14", + "resolved": "https://registry.npmjs.org/@cocos/build-engine/-/build-engine-4.3.14.tgz", + "integrity": "sha512-YIeGAV/kqN0LHT2Sx09+D6jHmd66iWwwtGVeSUvvXSgGj/EK4FXlPV10a92T3VSKKR5A2sfpUC/RDCBKJSXpbQ==", "dev": true, "requires": { "@babel/core": "^7.13.10", @@ -1803,25 +1803,34 @@ }, "dependencies": { "ansi-regex": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", - "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", + "version": "5.0.1", + "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, - "cliui": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", - "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "string-width": "^3.1.0", - "strip-ansi": "^5.2.0", - "wrap-ansi": "^5.1.0" + "color-convert": "^2.0.1" + } + }, + "cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dev": true, + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" } }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { @@ -1830,19 +1839,23 @@ }, "color-name": { "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, - "emoji-regex": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", - "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", - "dev": true + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } }, "fs-extra": { "version": "8.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "resolved": "https://registry.npmmirror.com/fs-extra/-/fs-extra-8.1.0.tgz", "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", "dev": true, "requires": { @@ -1853,28 +1866,34 @@ }, "get-caller-file": { "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "resolved": "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, "is-core-module": { "version": "2.9.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.9.0.tgz", + "resolved": "https://registry.npmmirror.com/is-core-module/-/is-core-module-2.9.0.tgz", "integrity": "sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A==", "dev": true, "requires": { "has": "^1.0.3" } }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, "json5": { "version": "2.2.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", + "resolved": "https://registry.npmmirror.com/json5/-/json5-2.2.1.tgz", "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", "dev": true }, "locate-path": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { @@ -1883,7 +1902,7 @@ }, "p-locate": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { @@ -1892,30 +1911,30 @@ }, "path-exists": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true }, "require-main-filename": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/require-main-filename/-/require-main-filename-2.0.0.tgz", "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, "resolve": { - "version": "1.22.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.0.tgz", - "integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==", + "version": "1.22.1", + "resolved": "https://registry.npmmirror.com/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", "dev": true, "requires": { - "is-core-module": "^2.8.1", + "is-core-module": "^2.9.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" } }, "semver": { "version": "7.3.7", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", + "resolved": "https://registry.npmmirror.com/semver/-/semver-7.3.7.tgz", "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", "dev": true, "requires": { @@ -1923,93 +1942,51 @@ } }, "string-width": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "version": "4.2.3", + "resolved": "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "requires": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" } }, "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "version": "6.0.1", + "resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "requires": { - "ansi-regex": "^4.1.0" - } - }, - "tfig": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/tfig/-/tfig-3.2.5.tgz", - "integrity": "sha512-IGizsIrOow7IFCSqGWFEX+vjO7jI5dZg8ASkNUb0Vl/Q7Yl7VcwWcmgdCeTTLLJPt/k2/yYOPpGgVu/QB/2UhA==", - "dev": true, - "requires": { - "fs-extra": "^7.0.1", - "typescript": "^4.2.3", - "yargs": "^13.2.2" - }, - "dependencies": { - "fs-extra": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", - "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - } - }, - "yargs": { - "version": "13.3.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", - "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", - "dev": true, - "requires": { - "cliui": "^5.0.0", - "find-up": "^3.0.0", - "get-caller-file": "^2.0.1", - "require-directory": "^2.1.1", - "require-main-filename": "^2.0.0", - "set-blocking": "^2.0.0", - "string-width": "^3.0.0", - "which-module": "^2.0.0", - "y18n": "^4.0.0", - "yargs-parser": "^13.1.2" - } - } + "ansi-regex": "^5.0.1" } }, "which-module": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/which-module/-/which-module-2.0.0.tgz", "integrity": "sha512-B+enWhmw6cjfVC7kS8Pj9pCrKSc5txArRyaYGe088shv/FGWH+0Rjx/xPgtsWfsUtS27FkP697E4DDhgrgoc0Q==", "dev": true }, "wrap-ansi": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", - "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "version": "6.2.0", + "resolved": "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, "requires": { - "ansi-styles": "^3.2.0", - "string-width": "^3.0.0", - "strip-ansi": "^5.0.0" + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" } }, "y18n": { "version": "4.0.3", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "resolved": "https://registry.npmmirror.com/y18n/-/y18n-4.0.3.tgz", "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "dev": true }, "yargs": { "version": "15.4.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "resolved": "https://registry.npmmirror.com/yargs/-/yargs-15.4.1.tgz", "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", "dev": true, "requires": { @@ -2024,103 +2001,12 @@ "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true - }, - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "requires": { - "color-convert": "^2.0.1" - } - }, - "cliui": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", - "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", - "dev": true, - "requires": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^6.2.0" - } - }, - "emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "requires": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - } - }, - "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true - }, - "string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - } - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "requires": { - "ansi-regex": "^5.0.1" - } - }, - "wrap-ansi": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", - "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", - "dev": true, - "requires": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - } - }, - "yargs-parser": { - "version": "18.1.3", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", - "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", - "dev": true, - "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - } - } } }, "yargs-parser": { - "version": "13.1.2", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz", - "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", + "version": "18.1.3", + "resolved": "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", "dev": true, "requires": { "camelcase": "^5.0.0", @@ -18346,6 +18232,125 @@ "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", "dev": true }, + "tfig": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/tfig/-/tfig-3.2.5.tgz", + "integrity": "sha512-IGizsIrOow7IFCSqGWFEX+vjO7jI5dZg8ASkNUb0Vl/Q7Yl7VcwWcmgdCeTTLLJPt/k2/yYOPpGgVu/QB/2UhA==", + "dev": true, + "requires": { + "fs-extra": "^7.0.1", + "typescript": "^4.2.3", + "yargs": "^13.2.2" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", + "dev": true + }, + "cliui": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "dev": true, + "requires": { + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" + } + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true + }, + "require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha512-B+enWhmw6cjfVC7kS8Pj9pCrKSc5txArRyaYGe088shv/FGWH+0Rjx/xPgtsWfsUtS27FkP697E4DDhgrgoc0Q==", + "dev": true + }, + "wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + } + }, + "y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "dev": true + }, + "yargs": { + "version": "13.3.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", + "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", + "dev": true, + "requires": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.2" + } + }, + "yargs-parser": { + "version": "13.1.2", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz", + "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } + }, "throat": { "version": "6.0.1", "resolved": "https://registry.npmmirror.com/throat/-/throat-6.0.1.tgz", diff --git a/package.json b/package.json index 058b16ea20..a7b85a3d39 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,7 @@ "@babel/core": "^7.13.10", "@babel/preset-env": "7.8.7", "@cocos/babel-preset-cc": "2.2.0", - "@cocos/build-engine": "4.3.10", + "@cocos/build-engine": "4.3.14", "@types/fs-extra": "^5.0.4", "@types/jest": "^24.9.1", "@types/yargs": "^12.0.14", diff --git a/scripts/build-engine/package-lock.json b/scripts/build-engine/package-lock.json index bc866266ba..316ca036eb 100644 --- a/scripts/build-engine/package-lock.json +++ b/scripts/build-engine/package-lock.json @@ -1,6 +1,6 @@ { "name": "@cocos/build-engine", - "version": "4.3.10", + "version": "4.3.14", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -2544,6 +2544,12 @@ "pretty-format": "^27.0.0" } }, + "@types/json-schema": { + "version": "7.0.11", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/json-schema/-/json-schema-7.0.11.tgz", + "integrity": "sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==", + "dev": true + }, "@types/json5": { "version": "0.0.30", "resolved": "https://registry.npm.taobao.org/@types/json5/download/@types/json5-0.0.30.tgz", @@ -6117,6 +6123,12 @@ "resolved": "https://registry.npm.taobao.org/safe-buffer/download/safe-buffer-5.1.2.tgz", "integrity": "sha1-mR7GnSluAxN0fVm9/St0XDX4go0=" }, + "safe-stable-stringify": { + "version": "2.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/safe-stable-stringify/-/safe-stable-stringify-2.3.1.tgz", + "integrity": "sha512-kYBSfT+troD9cDA85VDnHZ1rpHC50O0g1e6WlGHVCz/g+JS+9WKLj+XwFYyR8UbrZN8ll9HUpDAAddY58MGisg==", + "dev": true + }, "semver": { "version": "7.3.2", "resolved": "https://registry.npm.taobao.org/semver/download/semver-7.3.2.tgz", @@ -6532,6 +6544,40 @@ } } }, + "ts-json-schema-generator": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/ts-json-schema-generator/-/ts-json-schema-generator-1.0.0.tgz", + "integrity": "sha512-F5VofsyMhNSXKII32NDS8/Ur8o2K3Sh5i/U2ke3UgCKf26ybgm2cZeT2x7VJPl1trML/9QLzz/82l0mvzmb3Vw==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.9", + "commander": "^9.0.0", + "glob": "^7.2.0", + "json5": "^2.2.0", + "safe-stable-stringify": "^2.3.1", + "typescript": "~4.6.2" + }, + "dependencies": { + "commander": { + "version": "9.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/commander/-/commander-9.3.0.tgz", + "integrity": "sha512-hv95iU5uXPbK83mjrJKuZyFM/LBAoCV/XhVGkS5Je6tl7sxr6A0ITMw5WoRV46/UaJ46Nllm3Xt7IaJhXTIkzw==", + "dev": true + }, + "json5": { + "version": "2.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/json5/-/json5-2.2.1.tgz", + "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", + "dev": true + }, + "typescript": { + "version": "4.6.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/typescript/-/typescript-4.6.4.tgz", + "integrity": "sha512-9ia/jWHIEbo49HfjrLGfKbZSuWo9iTMwXO+Ca3pRsSpbsMbc7/IU8NKdCZVRRBafVPGnoJeFL76ZOAA84I9fEg==", + "dev": true + } + } + }, "type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", diff --git a/scripts/build-engine/package.json b/scripts/build-engine/package.json index 4fd86128bf..834275d04d 100644 --- a/scripts/build-engine/package.json +++ b/scripts/build-engine/package.json @@ -1,6 +1,6 @@ { "name": "@cocos/build-engine", - "version": "4.3.10", + "version": "4.3.14", "description": "", "repository": { "type": "git", @@ -49,7 +49,8 @@ "@types/semver": "^7.3.4", "@types/yargs": "^15.0.4", "jest": "^28.1.1", - "ts-jest": "^28.0.4" + "ts-jest": "^28.0.4", + "ts-json-schema-generator": "~1.0.0" }, "peerDependencies": { "typescript": "^3.7.2" @@ -58,6 +59,7 @@ "build": "npx tsc", "clear": "node ./scripts/clear.mjs", "prepublishOnly": "npm run clear & npm run build", + "gen-config-json-schema": "npx ts-json-schema-generator -t Config -p ./src/config-interface.ts -o ./cc.config.schema.json", "test": "jest" }, "author": "", diff --git a/scripts/build-engine/src/config-interface.ts b/scripts/build-engine/src/config-interface.ts index 35bfe338df..9f19e7b333 100644 --- a/scripts/build-engine/src/config-interface.ts +++ b/scripts/build-engine/src/config-interface.ts @@ -66,6 +66,7 @@ export interface Context { buildTimeConstants?: Object; } +export type ConstantTypeName = 'boolean' | 'number'; export interface IConstantInfo { /** @@ -73,12 +74,16 @@ export interface IConstantInfo { * Which is used to generate the consts.d.ts file. */ readonly comment: string; + /** + * The type of the constant for generating consts.d.ts file. + */ + readonly type: ConstantTypeName; /** * The default value of the constant. - * It can be a boolean or string. + * It can be a boolean, number or string. * When it's a string type, the value is the result of eval(). */ - value: boolean | string, + value: boolean | string | number, /** * Whether exported to global as a `CC_XXXX` constant. * eg. WECHAT is exported to global.CC_WECHAT diff --git a/scripts/build-engine/src/constant-manager.ts b/scripts/build-engine/src/constant-manager.ts index 0eb635709d..c85e0b6960 100644 --- a/scripts/build-engine/src/constant-manager.ts +++ b/scripts/build-engine/src/constant-manager.ts @@ -6,15 +6,19 @@ export type ModeType = 'EDITOR' | 'PREVIEW' | 'BUILD' | 'TEST'; export type PlatformType = 'HTML5' | 'NATIVE' | 'WECHAT' | 'BAIDU' | 'XIAOMI' | 'ALIPAY' | 'BYTEDANCE' | 'OPPO' | 'VIVO' | 'HUAWEI' | 'COCOSPLAY' | 'QTT' | 'LINKSURE'; -export type FlagType = 'DEBUG' | 'SERVER_MODE'; +export type InternalFlagType = 'SERVER_MODE' | 'NOT_PACK_PHYSX_LIBS'; +export type PublicFlagType = 'DEBUG' | 'NET_MODE'; +export type FlagType = InternalFlagType | PublicFlagType; +export type ValueType = number | boolean; export interface ConstantOptions { mode: ModeType; platform: PlatformType; - flags: Partial>; + flags: Partial>; } +export type BuildTimeConstants = Record; +export type CCEnvConstants = Record; -export type BuildTimeConstants = Record export class ConstantManager { private _engineRoot: string; @@ -51,7 +55,7 @@ export class ConstantManager { console.warn(`Unknown platform: ${platform}`); } for (const key in flags) { - const value = flags[key as FlagType] as boolean; + const value = flags[key as FlagType]!; if (config[key]) { config[key].value = value; } else { @@ -71,7 +75,7 @@ export class ConstantManager { for (const key in config) { const info = config[key]; const value = info.value; - if (info.dynamic) { + if (info.dynamic || info.internal) { continue; } result += `export const ${key} = ${value};\n`; @@ -84,50 +88,36 @@ export class ConstantManager { return result; } - public genBuildTimeConstants ({ - mode, - platform, - flags, - }: ConstantOptions): BuildTimeConstants { + public genBuildTimeConstants (options: ConstantOptions): BuildTimeConstants { const config = this._getConfig(); - // update value - if (config[mode]) { - config[mode].value = true; - } else { - console.warn(`Unknown mode: ${mode}`); - } - if (config[platform]) { - config[platform].value = true; - } else { - console.warn(`Unknown platform: ${platform}`); - } - for (const key in flags) { - const value = flags[key as FlagType] as boolean; - if (config[key]) { - config[key].value = value; - } else { - console.warn(`Unknown flag: ${key}`); - } - } - - // eval value - for (const key in config) { - const info = config[key]; - if (typeof info.value === 'string') { - info.value = this._evalExpression(info.value, config); - } - } + this._applyOptionsToConfig(config, options); // generate json object - const jsonObj: Record = {}; + const jsonObj: Record = {}; for (const key in config) { const info = config[key]; - jsonObj[key] = info.value as boolean; + jsonObj[key] = info.value as ValueType; } return jsonObj as BuildTimeConstants; } + public genCCEnvConstants (options: ConstantOptions): CCEnvConstants { + const config = this._getConfig(); + + this._applyOptionsToConfig(config, options); + + // generate json object + const jsonObj: Record = {}; + for (const key in config) { + const info = config[key]; + if (!info.internal) { + jsonObj[key] = info.value as ValueType; + } + } + return jsonObj as CCEnvConstants; + } + public exportStaticConstants ({ mode, platform, @@ -152,7 +142,7 @@ export class ConstantManager { console.warn(`Unknown platform: ${platform}`); } for (const key in flags) { - const value = flags[key as FlagType] as boolean; + const value = flags[key as FlagType]!; if (config[key]) { config[key].value = value; } else { @@ -222,7 +212,7 @@ export class ConstantManager { result += `\t * ${comment}\n`; } result += '\t */\n'; - result += `\texport const ${name}: boolean;\n\n` + result += `\texport const ${name}: ${info.type};\n\n` return result; } //#endregion declaration @@ -284,5 +274,37 @@ export class ConstantManager { const evalFn = new Function('$', `return ${expression}`); return evalFn(config); } + + private _applyOptionsToConfig (config: IConstantConfig, options: ConstantOptions) { + const { mode, platform, flags } = options; + + // update value + if (config[mode]) { + config[mode].value = true; + } else { + console.warn(`Unknown mode: ${mode}`); + } + if (config[platform]) { + config[platform].value = true; + } else { + console.warn(`Unknown platform: ${platform}`); + } + for (const key in flags) { + const value = flags[key as FlagType]!; + if (config[key]) { + config[key].value = value; + } else { + console.warn(`Unknown flag: ${key}`); + } + } + + // eval value + for (const key in config) { + const info = config[key]; + if (typeof info.value === 'string') { + info.value = this._evalExpression(info.value, config); + } + } + } //#endregion utils } \ No newline at end of file diff --git a/scripts/build-engine/src/index.ts b/scripts/build-engine/src/index.ts index 23fa1930c4..9b7200dcbc 100644 --- a/scripts/build-engine/src/index.ts +++ b/scripts/build-engine/src/index.ts @@ -29,7 +29,7 @@ import { filePathToModuleRequest } from './utils'; import { assetRef as rpAssetRef, pathToAssetRefURL } from './rollup-plugins/asset-ref'; import { codeAsset } from './rollup-plugins/code-asset'; -export { ModeType, PlatformType, FlagType, ConstantOptions, BuildTimeConstants } from './constant-manager'; +export { ModeType, PlatformType, FlagType, ConstantOptions, BuildTimeConstants, CCEnvConstants } from './constant-manager'; export { StatsQuery }; export { ModuleOption, enumerateModuleOptionReps, parseModuleOption }; diff --git a/scripts/build-engine/tests/stats-query/__snapshots__/constant-manager.test.ts.snap b/scripts/build-engine/tests/stats-query/__snapshots__/constant-manager.test.ts.snap index 100a13aef0..951e598b21 100644 --- a/scripts/build-engine/tests/stats-query/__snapshots__/constant-manager.test.ts.snap +++ b/scripts/build-engine/tests/stats-query/__snapshots__/constant-manager.test.ts.snap @@ -62,14 +62,14 @@ tryDefineGlobal('CC_BUILD', true); export const DEBUG = true; tryDefineGlobal('CC_DEBUG', true); -export const SERVER_MODE = false; - export const MINIGAME = true; tryDefineGlobal('CC_MINIGAME', true); export const RUNTIME_BASED = false; tryDefineGlobal('CC_RUNTIME_BASED', false); +export const NET_MODE = 0; + " `; @@ -152,6 +152,10 @@ tryDefineGlobal('CC_SUPPORT_JIT', false); export const JSB = false; tryDefineGlobal('CC_JSB', false); +export const NOT_PACK_PHYSX_LIBS = false; + +export const NET_MODE = 0; + " `; @@ -188,17 +192,17 @@ exports[`generateCCEnv 1`] = ` export const ALIPAY: boolean; /** - * Running in the ByteDance's quick game. + * Running in the ByteDance's mini game. */ export const BYTEDANCE: boolean; /** - * Running in the oppo's mini game. + * Running in the oppo's quick game. */ export const OPPO: boolean; /** - * Running in the vivo's mini game. + * Running in the vivo's quick game. */ export const VIVO: boolean; @@ -247,11 +251,6 @@ exports[`generateCCEnv 1`] = ` */ export const DEBUG: boolean; - /** - * Running in the server mode. - */ - export const SERVER_MODE: boolean; - /** * Running in the editor or preview. */ @@ -273,10 +272,18 @@ exports[`generateCCEnv 1`] = ` export const SUPPORT_JIT: boolean; /** - * Running in native platform (mobile app, desktop app, or simulator). + * Running in environment where using JSB as the JavaScript interface binding scheme. */ export const JSB: boolean; + /** + * The network access mode. + * - 0 Client + * - 1 ListenServer + * - 2 HostServer + */ + export const NET_MODE: number; + } " `; @@ -314,17 +321,17 @@ exports[`generateInternalConstants 1`] = ` export const ALIPAY: boolean; /** - * Running in the ByteDance's quick game. + * Running in the ByteDance's mini game. */ export const BYTEDANCE: boolean; /** - * Running in the oppo's mini game. + * Running in the oppo's quick game. */ export const OPPO: boolean; /** - * Running in the vivo's mini game. + * Running in the vivo's quick game. */ export const VIVO: boolean; @@ -399,10 +406,23 @@ exports[`generateInternalConstants 1`] = ` export const SUPPORT_JIT: boolean; /** - * Running in native platform (mobile app, desktop app, or simulator). + * Running in environment where using JSB as the JavaScript interface binding scheme. */ export const JSB: boolean; + /** + * This is an internal constant to determine whether pack physx libs. + */ + export const NOT_PACK_PHYSX_LIBS: boolean; + + /** + * The network access mode. + * - 0 Client + * - 1 ListenServer + * - 2 HostServer + */ + export const NET_MODE: number; + } " `; diff --git a/scripts/build-engine/tests/stats-query/cc.config.json b/scripts/build-engine/tests/stats-query/cc.config.json index fe8403c92c..4a3f1448fe 100644 --- a/scripts/build-engine/tests/stats-query/cc.config.json +++ b/scripts/build-engine/tests/stats-query/cc.config.json @@ -168,78 +168,91 @@ "constants": { "HTML5": { "comment": "Running in Web platform", + "type": "boolean", "value": false, "internal": false, "dynamic": true }, "NATIVE": { "comment": "Running in native platform (mobile app, desktop app, or simulator).", + "type": "boolean", "value": false, "internal": false, "dynamic": true }, "WECHAT": { "comment": "Running in the Wechat's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "BAIDU": { "comment": "Running in the baidu's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "XIAOMI": { "comment": "Running in the xiaomi's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "ALIPAY": { "comment": "Running in the alipay's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "BYTEDANCE": { - "comment": "Running in the ByteDance's quick game.", + "comment": "Running in the ByteDance's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "OPPO": { - "comment": "Running in the oppo's mini game.", + "comment": "Running in the oppo's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "VIVO": { - "comment": "Running in the vivo's mini game.", + "comment": "Running in the vivo's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "HUAWEI": { "comment": "Running in the huawei's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "COCOSPLAY": { "comment": "Running in the cocosplay.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "QTT": { "comment": "Running in the qtt's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "LINKSURE": { "comment": "Running in the linksure's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false @@ -247,6 +260,7 @@ "EDITOR": { "comment": "Running in the editor.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false, @@ -254,6 +268,7 @@ }, "PREVIEW": { "comment": "Preview in browser or simulator.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false, @@ -261,12 +276,14 @@ }, "BUILD": { "comment": "Running in published project.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "TEST": { "comment": "Running in the engine's unit test.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false, @@ -276,19 +293,22 @@ "DEBUG": { "comment": "Running debug mode.", + "type": "boolean", "value": true, "ccGlobal": true, "internal": false }, "SERVER_MODE": { "comment": "Running in the server mode.", + "type": "boolean", "value": false, - "internal": false + "internal": true }, "DEV": { "comment": "Running in the editor or preview.", + "type": "boolean", "value": "$EDITOR || $PREVIEW || $TEST", "ccGlobal": true, "internal": false, @@ -296,29 +316,45 @@ }, "MINIGAME": { "comment": "Running in mini game.", + "type": "boolean", "value": "$WECHAT || $BAIDU || $XIAOMI || $ALIPAY || $BYTEDANCE", "ccGlobal": true, "internal": false }, "RUNTIME_BASED": { "comment": "Running in runtime based environment.", + "type": "boolean", "value": "$OPPO || $VIVO || $HUAWEI || $COCOSPLAY || $QTT || $LINKSURE", "ccGlobal": true, "internal": false }, "SUPPORT_JIT": { "comment": "Support JIT.", + "type": "boolean", "value": "!($MINIGAME || $RUNTIME_BASED)", "ccGlobal": true, "internal": false, "dynamic": true }, "JSB": { - "comment": "Running in native platform (mobile app, desktop app, or simulator).", + "comment": "Running in environment where using JSB as the JavaScript interface binding scheme.", + "type": "boolean", "value": "$NATIVE", "ccGlobal": true, "internal": false, "dynamic": true + }, + "NOT_PACK_PHYSX_LIBS": { + "comment": "This is an internal constant to determine whether pack physx libs.", + "type": "boolean", + "value": false, + "internal": true + }, + "NET_MODE": { + "comment": "The network access mode.\n- 0 Client\n- 1 ListenServer\n- 2 HostServer", + "type": "number", + "value": 0, + "internal": false } } } diff --git a/scripts/build-engine/tests/stats-query/constant-manager.test.ts b/scripts/build-engine/tests/stats-query/constant-manager.test.ts index d7e181b3e3..dff34518e6 100644 --- a/scripts/build-engine/tests/stats-query/constant-manager.test.ts +++ b/scripts/build-engine/tests/stats-query/constant-manager.test.ts @@ -48,6 +48,8 @@ test('genBuildTimeConstants', () => { "LINKSURE": false, "MINIGAME": false, "NATIVE": true, + "NET_MODE": 0, + "NOT_PACK_PHYSX_LIBS": false, "OPPO": false, "PREVIEW": false, "QTT": false, From 06fd96bf8c1687cf150af94d9ba4111cbef78cca Mon Sep 17 00:00:00 2001 From: changhua <39176194+changhua0118@users.noreply.github.com> Date: Thu, 21 Jul 2022 23:39:59 +0800 Subject: [PATCH 084/111] [Optimize] mipmaps on the inspector (#11938) * optimize mipmaps on the inspector pane * update i18n * update review Co-authored-by: SijieWang --- editor/i18n/en/assets.js | 30 +- editor/i18n/zh/assets.js | 31 +- editor/inspector/assets/erp-texture-cube.js | 421 ++++++++++++++------ editor/inspector/assets/image.js | 32 +- editor/inspector/assets/texture/texture.js | 355 +++++++++++++++-- 5 files changed, 691 insertions(+), 178 deletions(-) diff --git a/editor/i18n/en/assets.js b/editor/i18n/en/assets.js index b1bc0b4c48..a415a3a25a 100644 --- a/editor/i18n/en/assets.js +++ b/editor/i18n/en/assets.js @@ -32,17 +32,24 @@ module.exports = { }, erpTextureCube: { anisotropy: 'Anisotropy', + filterMode: 'Filter Mode', minFilter: 'Min Filter', magFilter: 'Mag Filter', + generateMipmaps: 'Generate Mipmaps', mipFilter: 'Mip Filter', + wrapMode: 'Wrap Mode', wrapModeS: 'Wrap Mode S', wrapModeT: 'Wrap Mode T', - anisotropyTip: 'Anisotropy', - minFilterTip: 'Min Filter', - magFilterTip: 'Mag Filter', - mipFilterTip: 'Mip Filter', - wrapModeSTip: 'Wrap Mode S', - wrapModeTTip: 'Wrap Mode T', + anisotropyTip: 'Maximum threshold for applying anisotropic filtering algorithms', + filterModeTip: 'Choose how Texture is filtered when apply 3d transformation', + minFilterTip: 'Minification filtering method', + magFilterTip: 'Magnification filtering method', + generateMipmapsTip: + 'Turn on this option to enable Mipmaps generation.Mipmaps are smaller versions of the original texture that are used to enhance performance and reduce rendering artifacts when objects are small in screen space', + mipFilterTip: 'Mip map filtering method', + wrapModeTip: 'Choose how Texture behaves when tiled. The default option is repeat', + wrapModeSTip: 'Texture addressing mode in S(U) direction', + wrapModeTTip: 'Texture addressing mode in T(V) direction', bakeReflectionConvolution: 'Bake Reflection Convolution', faceSize: { name: 'Face Size', @@ -138,19 +145,26 @@ module.exports = { }, texture: { anisotropy: 'Anisotropy', - anisotropyTip: 'Anisotropy', + anisotropyTip: 'Maximum threshold for applying anisotropic filtering algorithms', + filterMode: 'Filter Mode', + filterModeTip: 'Choose how Texture is filtered when apply 3d transformation', minfilter: 'Min Filter', minfilterTip: 'Minification filtering method', magfilter: 'Mag Filter', magfilterTip: 'Magnification filtering method', + generateMipmaps: 'Generate Mipmaps', + generateMipmapsTip: + 'Turn on this option to enable Mipmaps generation.Mipmaps are smaller versions of the original texture that are used to enhance performance and reduce rendering artifacts when objects are small in screen space', mipfilter: 'Mip Filter', mipfilterTip: 'Mip map filtering method', + wrapMode: 'Wrap Mode', + wrapModeTip: 'Choose how Texture behaves when tiled. The default option is repeat', wrapModeS: 'Wrap Mode S', wrapModeSTip: 'Texture addressing mode in S(U) direction', wrapModeT: 'Wrap Mode T', wrapModeTTip: 'Texture addressing mode in T(V) direction', modeWarn: - "Warning: WebGL 1.0 platform doesn't support 'repeat' filter for non-power-of-two textures(runtime fallback to 'clamp-to-edge'), effectively disabling features like the 'tilingOffset' property in many materials.", + "Warning: WebGL 1.0 platform doesn't support 'Repeat' filter for non-power-of-two textures(runtime fallback to 'Clamp'), effectively disabling features like the 'tilingOffset' property in many materials.", }, fbx: { browse: 'Change Target', diff --git a/editor/i18n/zh/assets.js b/editor/i18n/zh/assets.js index 600aaf4fb5..37a981c676 100644 --- a/editor/i18n/zh/assets.js +++ b/editor/i18n/zh/assets.js @@ -32,22 +32,28 @@ module.exports = { }, erpTextureCube: { anisotropy: 'Anisotropy', + filterMode: '过滤模式', minFilter: 'Min Filter', magFilter: 'Mag Filter', + generateMipmaps: '生成 Mipmaps', mipFilter: 'Mip Filter', + wrapMode: '拼接模式', wrapModeS: 'Wrap Mode S', wrapModeT: 'Wrap Mode T', - anisotropyTip: 'Anisotropy', - minFilterTip: 'Min Filter', - magFilterTip: 'Mag Filter', - mipFilterTip: 'Mip Filter', - wrapModeSTip: 'Wrap Mode S', - wrapModeTTip: 'Wrap Mode T', + anisotropyTip: '应用各向异性过滤算法的最大阈值', + filterModeTip: '选择贴图在应用三维图形变换时的过滤模式', + minFilterTip: '缩小贴图时采用的过滤算法', + magFilterTip: '放大贴图时采用的过滤算法', + generateMipmapsTip: + '勾选此选项以自动生成 Mipmaps。Mipmaps 是一系列缩小到不同尺寸的原贴图,在物体占屏幕空间小的时候使用以提升性能和减少闪烁', + mipFilterTip: '采用多级纹理时的过滤算法', + wrapModeTip: '选择在贴图小于填充空间时的填充方式,默认模式为循环', + wrapModeSTip: '像素对纹理在 S(U)方向上的映射模式', + wrapModeTTip: '像素对纹理在 T(V)方向上的映射模式', bakeReflectionConvolution: 'Bake Reflection Convolution', faceSize: { name: 'Face Size', - title: - '每个面的尺寸。如果未指定或指定为0,将使用默认尺寸——最接近贴图宽度 / 4 的2次幂。', + title: '每个面的尺寸。如果未指定或指定为0,将使用默认尺寸——最接近贴图宽度 / 4 的2次幂。', }, }, javascript: { @@ -140,18 +146,25 @@ module.exports = { texture: { anisotropy: 'Anisotropy', anisotropyTip: '应用各向异性过滤算法的最大阈值', + filterMode: '过滤模式', + filterModeTip: '选择贴图在应用三维图形变换时的过滤模式', minfilter: 'Min Filter', minfilterTip: '缩小贴图时采用的过滤算法', magfilter: 'Mag Filter', magfilterTip: '放大贴图时采用的过滤算法', + generateMipmaps: '生成 Mipmaps', + generateMipmapsTip: + '勾选此选项以自动生成 Mipmaps。Mipmaps 是一系列缩小到不同尺寸的原贴图,在物体占屏幕空间小的时候使用以提升性能和减少闪烁', mipfilter: 'Mip Filter', mipfilterTip: '采用多级纹理时的过滤算法', + wrapMode: '拼接模式', + wrapModeTip: '选择在贴图小于填充空间时的填充方式,默认模式为循环', wrapModeS: 'Wrap Mode S', wrapModeSTip: '像素对纹理在 S(U)方向上的映射模式', wrapModeT: 'Wrap Mode T', wrapModeTTip: '像素对纹理在 T(V)方向上的映射模式', modeWarn: - '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 Repeat 过滤模式,运行时会自动改为 Clamp-To-Edge 模式,这会使材质的 Tiling Offset 等属性完全失效。', + '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 Repeat 过滤模式,运行时会自动改为 Clamp 模式,这会使材质的 tilingOffset 等属性完全失效。', }, fbx: { browse: '更换贴图', diff --git a/editor/inspector/assets/erp-texture-cube.js b/editor/inspector/assets/erp-texture-cube.js index 97bcae6a8c..6ff0749a4a 100644 --- a/editor/inspector/assets/erp-texture-cube.js +++ b/editor/inspector/assets/erp-texture-cube.js @@ -1,108 +1,54 @@ -exports.template = /* html */` +exports.template = /* html */ `
- - - - + + - - - - + + - - - - - - - + + +
+ + + + + + + + + + + + +
+ + + + +
+
- - - - - - - + + +
+ + + + + + + + +
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
@@ -113,17 +59,28 @@ exports.style = ` .asset-erp-texture-cube ui-prop{ margin-top: 4px; } +.asset-erp-texture-cube #filterAdvancedSection, +.asset-erp-texture-cube #wrapAdvancedSection, +.asset-erp-texture-cube #generateMipmapsSection { + margin-left: 1.2em; + display: none; +} `; exports.$ = { anisotropy: '#anisotropy', faceSize: '#faceSize', + filterMode: '#filterMode', + filterAdvancedSection: '#filterAdvancedSection', minfilter: '#minfilter', magfilter: '#magfilter', + generateMipmaps: '#generateMipmaps', + generateMipmapsSection: '#generateMipmapsSection', mipfilter: '#mipfilter', + wrapMode: '#wrapMode', + wrapAdvancedSection: '#wrapAdvancedSection', wrapModeS: '#wrapModeS', wrapModeT: '#wrapModeT', - bakeReflectionConvo: '.bake-reflection-convo', mipBakeMode: '#mipBakeMode', }; @@ -148,6 +105,45 @@ exports.update = function(assetList, metaList) { } }; +const ModeMap = { + filter: { + 'Nearest (None)': { + minfilter: 'nearest', + magfilter: 'nearest', + mipfilter: 'none', + }, + Bilinear: { + minfilter: 'linear', + magfilter: 'linear', + mipfilter: 'none', + }, + 'Bilinear with Mipmaps': { + minfilter: 'linear', + magfilter: 'linear', + mipfilter: 'nearest', + }, + 'Trilinear with Mipmaps': { + minfilter: 'linear', + magfilter: 'linear', + mipfilter: 'linear', + }, + }, + wrap: { + Repeat: { + wrapModeS: 'repeat', + wrapModeT: 'repeat', + }, + Clamp: { + wrapModeS: 'clamp-to-edge', + wrapModeT: 'clamp-to-edge', + }, + Mirror: { + wrapModeS: 'mirrored-repeat', + wrapModeT: 'mirrored-repeat', + }, + }, +}; + const Elements = { anisotropy: { ready() { @@ -164,18 +160,64 @@ const Elements = { this.$.faceSize.addEventListener('change', this.dataChange.bind(this, 'faceSize')); }, update() { - this.$.faceSize.value = this.meta.userData.faceSize; this.updateInvalid(this.$.faceSize, 'faceSize'); this.updateReadonly(this.$.faceSize); }, }, + filterMode: { + ready() { + this.$.filterMode.addEventListener('change', this.dataChange.bind(this, 'filterMode')); + }, + update() { + let optionsHtml = ''; + // FilterMode 选项 + const types = Object.keys(ModeMap.filter).concat('Advanced'); + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.filterMode.innerHTML = optionsHtml; + + // 匹配 filterMode 值,没有匹配到组合,则为自定义 Advanced + let value = 'Advanced'; + for (const filterKey of Object.keys(ModeMap.filter)) { + const filterItem = ModeMap.filter[filterKey]; + let flag = true; + for (const key of Object.keys(filterItem)) { + if (this.meta.userData[key] !== filterItem[key]) { + flag = false; + break; + } + } + if (flag) { + value = filterKey; + break; + } + } + this.$.filterMode.value = value; + + // 更新时需要判断是否显示自定义项 + value === 'Advanced' + ? (this.$.filterAdvancedSection.style.display = 'block') + : (this.$.filterAdvancedSection.style.display = 'none'); + + this.updateInvalid(this.$.filterMode, 'filterMode'); + this.updateReadonly(this.$.filterMode); + }, + }, minfilter: { ready() { this.$.minfilter.addEventListener('change', this.dataChange.bind(this, 'minfilter')); }, update() { - this.$.minfilter.value = this.meta.userData.minfilter; + let optionsHtml = ''; + const types = ['nearest', 'linear']; + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.minfilter.innerHTML = optionsHtml; + + this.$.minfilter.value = this.meta.userData.minfilte || 'nearest'; this.updateInvalid(this.$.minfilter, 'minfilter'); this.updateReadonly(this.$.minfilter); }, @@ -185,27 +227,108 @@ const Elements = { this.$.magfilter.addEventListener('change', this.dataChange.bind(this, 'magfilter')); }, update() { - this.$.magfilter.value = this.meta.userData.magfilter; + let optionsHtml = ''; + const types = ['nearest', 'linear']; + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.magfilter.innerHTML = optionsHtml; + + this.$.magfilter.value = this.meta.userData.magfilter || 'nearest'; this.updateInvalid(this.$.magfilter, 'magfilter'); this.updateReadonly(this.$.magfilter); }, }, + generateMipmaps: { + ready() { + this.$.generateMipmaps.addEventListener('change', this.dataChange.bind(this, 'generateMipmaps')); + }, + update() { + this.$.generateMipmaps.value = this.meta.userData.mipfilter ? this.meta.userData.mipfilter !== 'none' : false; + + // 更新时判断是否显示 mipfilter 选项 + this.$.generateMipmaps.value + ? (this.$.generateMipmapsSection.style.display = 'block') + : (this.$.generateMipmapsSection.style.display = 'none'); + + this.updateInvalid(this.$.generateMipmaps, 'generateMipmaps'); + this.updateReadonly(this.$.generateMipmaps); + }, + }, mipfilter: { ready() { this.$.mipfilter.addEventListener('change', this.dataChange.bind(this, 'mipfilter')); }, update() { - this.$.mipfilter.value = this.meta.userData.mipfilter; + let optionsHtml = ''; + const types = ['nearest', 'linear']; + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.mipfilter.innerHTML = optionsHtml; + + this.$.mipfilter.value = this.meta.userData.mipfilter || 'nearest'; this.updateInvalid(this.$.mipfilter, 'mipfilter'); this.updateReadonly(this.$.mipfilter); }, }, + wrapMode: { + ready() { + this.$.wrapMode.addEventListener('change', this.dataChange.bind(this, 'wrapMode')); + }, + update() { + let optionsHtml = ''; + // WrapMode 选项 + const types = Object.keys(ModeMap.wrap).concat('Advanced'); + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.wrapMode.innerHTML = optionsHtml; + + // 匹配 wrapMode 值,没有匹配到组合,则为自定义 Advanced + let value = 'Advanced'; + for (const wrapKey of Object.keys(ModeMap.wrap)) { + const wrapItem = ModeMap.wrap[wrapKey]; + let flag = true; + for (const key of Object.keys(wrapItem)) { + if (this.meta.userData[key] !== wrapItem[key]) { + flag = false; + break; + } + } + if (flag) { + value = wrapKey; + break; + } + } + this.$.wrapMode.value = value; + + // 更新时需要判断是否显示自定义项 + value === 'Advanced' + ? (this.$.wrapAdvancedSection.style.display = 'block') + : (this.$.wrapAdvancedSection.style.display = 'none'); + + this.updateInvalid(this.$.wrapMode, 'wrapMode'); + this.updateReadonly(this.$.wrapMode); + }, + }, wrapModeS: { ready() { this.$.wrapModeS.addEventListener('change', this.dataChange.bind(this, 'wrapModeS')); }, update() { - this.$.wrapModeS.value = this.meta.userData.wrapModeS; + let optionsHtml = ''; + const types = { + Repeat: 'repeat', + Clamp: 'clamp-to-edge', + Mirror: 'mirrored-repeat', + }; + for (const type in types) { + optionsHtml += ``; + } + this.$.wrapModeS.innerHTML = optionsHtml; + + this.$.wrapModeS.value = this.meta.userData.wrapModeS || 'repeat'; this.updateInvalid(this.$.wrapModeS, 'wrapModeS'); this.updateReadonly(this.$.wrapModeS); }, @@ -215,7 +338,18 @@ const Elements = { this.$.wrapModeT.addEventListener('change', this.dataChange.bind(this, 'wrapModeT')); }, update() { - this.$.wrapModeT.value = this.meta.userData.wrapModeT; + let optionsHtml = ''; + const types = { + Repeat: 'repeat', + Clamp: 'clamp-to-edge', + Mirror: 'mirrored-repeat', + }; + for (const type in types) { + optionsHtml += ``; + } + this.$.wrapModeT.innerHTML = optionsHtml; + + this.$.wrapModeT.value = this.meta.userData.wrapModeT || 'repeat'; this.updateInvalid(this.$.wrapModeT, 'wrapModeT'); this.updateReadonly(this.$.wrapModeT); }, @@ -228,17 +362,46 @@ const Elements = { this.$.mipBakeMode.value = this.meta.userData.mipBakeMode === 2 ? true : false; this.updateInvalid(this.$.mipBakeMode, 'mipBakeMode'); this.updateReadonly(this.$.mipBakeMode); - this.updateBakeReflectionVisible(this.meta.userData.mipfilter === 'linear'); }, }, - }; exports.methods = { updateInvalid(element, prop) { - const invalid = this.metaList.some((meta) => { - return meta.userData[prop] !== this.meta.userData[prop]; - }); + let invalid; + // filterMode、 wrapMode 和 generateMipmaps 需要拆解进行判断 + switch (prop) { + case 'filterMode': + invalid = this.metaList.some((meta) => { + for (const key of Object.keys(ModeMap.filter.Bilinear)) { + if (meta.userData[key] !== this.meta.userData[key]) { + return true; + } + } + return false; + }); + break; + case 'wrapMode': + invalid = this.metaList.some((meta) => { + for (const key of Object.keys(ModeMap.wrap.Repeat)) { + if (meta.userData[key] !== this.meta.userData[key]) { + return true; + } + } + return false; + }); + break; + case 'generateMipmaps': + invalid = this.metaList.some((meta) => { + return meta.userData['mipfilter'] !== this.meta.userData['mipfilter']; + }); + break; + default: + invalid = this.metaList.some((meta) => { + return meta.userData[prop] !== this.meta.userData[prop]; + }); + break; + } element.invalid = invalid; }, updateReadonly(element) { @@ -248,20 +411,50 @@ exports.methods = { element.removeAttribute('disabled'); } }, - updateBakeReflectionVisible(show) { - this.$.bakeReflectionConvo.style.display = show ? 'block' : 'none'; - - }, dataChange(key, event) { let value = event.target.value; if (key === 'mipBakeMode') { value = event.target.value ? 2 : 1; } - if (key === 'mipfilter') { - this.updateBakeReflectionVisible(value === 'linear'); - } this.metaList.forEach((meta) => { - meta.userData[key] = value || undefined; + if (key === 'filterMode') { + if (ModeMap.filter[value]) { + const data = ModeMap.filter[value]; + for (const key of Object.keys(data)) { + meta.userData[key] = data[key]; + } + this.$.filterAdvancedSection.style.display = 'none'; + } else { + // 选择 advanced 显示自定义项 + this.$.filterAdvancedSection.style.display = 'block'; + } + } else if (key === 'generateMipmaps') { + if (!value) { + // 没勾选 生成 mipmaps,不显示 mipfilter 选项 + meta.userData.mipfilter = 'none'; + this.$.generateMipmapsSection.style.display = 'none'; + } else { + this.$.generateMipmapsSection.style.display = 'block'; + if (this.$.mipfilter.value === 'none') { + this.$.mipfilter.value = 'nearest'; + // TODO: 目前 ui-select 通过 .value 修改组件值后没有触发 change 事件,需要手动提交 + this.$.mipfilter.dispatch('change'); + } + } + } else if (key === 'wrapMode') { + if (ModeMap.wrap[value]) { + const data = ModeMap.wrap[value]; + for (const key of Object.keys(data)) { + meta.userData[key] = data[key]; + } + this.$.wrapAdvancedSection.style.display = 'none'; + } else { + // 选择 advanced 需要显示自定义项 + this.$.wrapAdvancedSection.style.display = 'block'; + } + } else { + meta.userData[key] = value || undefined; + } }); this.dispatch('change'); diff --git a/editor/inspector/assets/image.js b/editor/inspector/assets/image.js index 30d25adec8..2acf90eccc 100644 --- a/editor/inspector/assets/image.js +++ b/editor/inspector/assets/image.js @@ -73,6 +73,14 @@ const Elements = { const panel = this; panel.$.typeSelect.addEventListener('change', (event) => { + // metaList 时以以选中的第一个 asset 的类型进行处理 + let spriteFrameChange; + if (panel.meta.userData.type === 'sprite-frame') { + spriteFrameChange = 'spriteFrameToOthers'; + } else if (event.target.value === 'sprite-frame') { + spriteFrameChange = 'othersToSpriteFrame'; + } + panel.metaList.forEach((meta) => { meta.userData.type = event.target.value; }); @@ -81,7 +89,8 @@ const Elements = { // There are other properties whose updates depend on its changes attribute corresponds to the edit element Elements.isRGBE.update.call(panel); Elements.fixAlphaTransparencyArtifacts.update.call(panel); - panel.updatePanel(); + // imageAssets 类型有 spriteFrame 变化的话需要处理 mipmaps + panel.updatePanel(spriteFrameChange); }); }, update() { @@ -147,7 +156,6 @@ const Elements = { panel.$.fixAlphaTransparencyArtifactsCheckbox.addEventListener('change', (event) => { panel.metaList.forEach((meta) => { meta.userData.fixAlphaTransparencyArtifacts = event.target.value; - }); panel.dispatch('change'); }); @@ -169,7 +177,6 @@ const Elements = { } else { fixATAProp.style.display = 'none'; } - }, }, isRGBE: { @@ -260,7 +267,7 @@ exports.methods = { } }, - async _updatePanel($section, type) { + _updatePanel($section, type, spriteFrameChange) { const assetList = []; const metaList = []; @@ -306,6 +313,13 @@ exports.methods = { } if (subMeta.importer === imageImporter) { + if (spriteFrameChange === 'othersToSpriteFrame') { + // imageAsset 类型切换到 spriteFrame,禁用 mipmaps + subMeta.userData.mipfilter = 'none'; + } else if (spriteFrameChange === 'spriteFrameToOthers' && subMeta.userData.mipfilter === 'none') { + // imageAsset 类型从 spriteFrame 切换到其他,原来没启用的话 mipmaps 默认 nearest + subMeta.userData.mipfilter = 'nearest'; + } metaList.push(subMeta); break; } @@ -327,10 +341,14 @@ exports.methods = { $panel.update(assetList, metaList); }, - async updatePanel() { - this._updatePanel(this.$.panelSection, this.meta.userData.type); + /** + * 更新属性 panel + * @param {*} spriteFrameChange imageAsset 类型是否切换和 spriteFrame 是否有关 + */ + updatePanel(spriteFrameChange) { + this._updatePanel(this.$.panelSection, this.meta.userData.type, spriteFrameChange); if (this.meta.userData.type === 'sprite-frame') { - this._updatePanel(this.$.texturePanelSection, 'texture'); + this._updatePanel(this.$.texturePanelSection, 'texture', spriteFrameChange); } else { this.$.texturePanelSection.style.display = 'none'; } diff --git a/editor/inspector/assets/texture/texture.js b/editor/inspector/assets/texture/texture.js index fce26c1221..fff852696d 100644 --- a/editor/inspector/assets/texture/texture.js +++ b/editor/inspector/assets/texture/texture.js @@ -9,26 +9,44 @@ exports.template = ` - - + + - - - +
+ + + + + + + + + + + + +
+ + + + +
+
+ + + - - - - - - - - - - - - -