From 97b1c409417b233065959a4912856c685717afae Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Wed, 1 Feb 2023 17:46:34 +0800 Subject: [PATCH] [pipeline] add native pipeline ubo uploading (#14061) * merge v3.7.0-pipeline * pass done * fix const reference return type * add uniform block buiding * fix const cast * fix const * fix mtl const * integrating native program library * native pipeline workflow updated * adding ubo binding * Solve the problem of the version attribute of pass (#87) * ubo upload added * adding camera ubo * add constant name * update uniform buffer * adding execution resources * per pass ubo added * fix bugs * ubo added * fix render pass bug * bind set added * adding ubo uploading * shader binding overwrite added * shader binding overwrite added * add missing header * draw updated * ubo updated * fix main light ubo * pass ubo added * lint * fix custom pipeline window resize issue. (#88) * fix lint * fix assert * remove texture1d * fix constantMacros * lint * fixed: native custom pipeline graphics pipeline state leak. (#89) * lint * skybox added * skip subpass input binding rewrite (#90) * per pass descriptor set modified * adding blit * fix material * fix fg get usage (#91) * fix barrier fetch * fix ios bug * fix barrier * support cc builtin overwrite * try fix shadowMap * refactor resources * update blit * add render graph binding * fix shader bugs * fix blit * fix bugs * remove unnessary barriers * fix init * fix addCameraQuad * fix raster view order --------- Co-authored-by: GengineJS <476393671@qq.com> Co-authored-by: Zach Lee Co-authored-by: Zeqiang Li --- cocos/gfx/base/device.ts | 29 +- cocos/rendering/custom/define.ts | 13 +- cocos/rendering/custom/executor.ts | 14 +- cocos/rendering/custom/layout-graph-utils.ts | 15 + cocos/rendering/custom/types.ts | 3 + cocos/rendering/custom/web-pipeline.ts | 31 +- cocos/rendering/render-pipeline.ts | 2 +- .../effects/pipeline/deferred-lighting.effect | 77 +- .../effects/pipeline/post-process.effect | 4 +- native/CMakeLists.txt | 3 + native/cocos/core/assets/EffectAsset.h | 6 + native/cocos/renderer/core/PassInstance.cpp | 47 +- native/cocos/renderer/core/ProgramLib.cpp | 1 + native/cocos/renderer/core/ProgramUtils.cpp | 2 +- native/cocos/renderer/gfx-base/GFXDevice.cpp | 12 +- native/cocos/renderer/gfx-base/GFXDevice.h | 4 +- native/cocos/renderer/gfx-metal/MTLBuffer.mm | 27 +- .../renderer/pipeline/RenderPipeline.cpp | 29 +- .../cocos/renderer/pipeline/RenderPipeline.h | 2 +- .../pipeline/custom/FGDispatcherTypes.cpp | 2 +- .../pipeline/custom/FGDispatcherTypes.h | 4 +- .../pipeline/custom/FrameGraphDispatcher.cpp | 24 +- .../pipeline/custom/LayoutGraphTypes.cpp | 3 +- .../pipeline/custom/LayoutGraphTypes.h | 2 +- .../pipeline/custom/LayoutGraphUtils.cpp | 170 +++- .../pipeline/custom/LayoutGraphUtils.h | 14 +- .../pipeline/custom/NativeExecutor.cpp | 812 ++++++++++++++---- .../pipeline/custom/NativeLayoutGraph.cpp | 61 +- .../pipeline/custom/NativePipeline.cpp | 256 +++++- .../pipeline/custom/NativePipelineFwd.h | 9 +- .../pipeline/custom/NativePipelineTypes.cpp | 83 +- .../pipeline/custom/NativePipelineTypes.h | 257 +++++- .../renderer/pipeline/custom/NativePools.cpp | 149 ++++ .../pipeline/custom/NativeProgramLibrary.cpp | 288 ++++++- .../pipeline/custom/NativeRenderGraph.cpp | 740 ++++++++++++++-- .../pipeline/custom/NativeResourceGraph.cpp | 84 +- .../renderer/pipeline/custom/NativeUtils.cpp | 35 + .../renderer/pipeline/custom/NativeUtils.h | 13 + .../pipeline/custom/RenderCommonJsb.cpp | 7 + .../custom/RenderCommonSerialization.h | 2 + .../pipeline/custom/RenderCommonTypes.cpp | 6 +- .../pipeline/custom/RenderCommonTypes.h | 1 + .../pipeline/custom/RenderGraphTypes.h | 3 + native/cocos/scene/Ambient.cpp | 9 +- native/cocos/scene/Ambient.h | 11 +- native/cocos/scene/Pass.cpp | 46 +- native/cocos/scene/Pass.h | 2 + 47 files changed, 2759 insertions(+), 655 deletions(-) create mode 100644 native/cocos/renderer/pipeline/custom/NativePools.cpp create mode 100644 native/cocos/renderer/pipeline/custom/NativeUtils.cpp create mode 100644 native/cocos/renderer/pipeline/custom/NativeUtils.h diff --git a/cocos/gfx/base/device.ts b/cocos/gfx/base/device.ts index 7291fe2120..3ccf22f4c0 100644 --- a/cocos/gfx/base/device.ts +++ b/cocos/gfx/base/device.ts @@ -27,7 +27,8 @@ import { CommandBufferInfo, BufferInfo, BufferViewInfo, TextureInfo, TextureViewInfo, SamplerInfo, DescriptorSetInfo, ShaderInfo, InputAssemblerInfo, RenderPassInfo, FramebufferInfo, DescriptorSetLayoutInfo, PipelineLayoutInfo, QueueInfo, BufferTextureCopy, DeviceInfo, DeviceCaps, GeneralBarrierInfo, TextureBarrierInfo, BufferBarrierInfo, - SwapchainInfo, BindingMappingInfo, Format, FormatFeature, TextureType, TextureUsageBit, TextureFlagBit, Offset, Extent, SampleCount, TextureSubresLayers, + SwapchainInfo, BindingMappingInfo, Format, FormatFeature, TextureType, TextureUsageBit, + TextureFlagBit, Offset, Extent, SampleCount, TextureSubresLayers, } from './define'; import { Buffer } from './buffer'; import { CommandBuffer } from './command-buffer'; @@ -354,11 +355,10 @@ export abstract class Device { } export class DefaultResource { - private _texture2D : Texture | null = null; - private _texture3D : Texture | null = null; - private _textureCube : Texture | null = null; - private _texture1DArray : Texture | null = null; - private _texture2DArray : Texture | null = null; + private _texture2D: Texture | null = null; + private _texture3D: Texture | null = null; + private _textureCube: Texture | null = null; + private _texture2DArray: Texture | null = null; constructor (device: Device) { const bufferSize = 64; @@ -412,20 +412,6 @@ export class DefaultResource { const copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 2), new TextureSubresLayers(0, 0, 1)); device.copyBuffersToTexture([buffer], this._texture3D, [copyRegion]); } - if (device.capabilities.maxArrayTextureLayers >= 2) { - this._texture1DArray = device.createTexture(new TextureInfo( - TextureType.TEX1D_ARRAY, - TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, - Format.RGBA8, - 1, 1, - TextureFlagBit.NONE, - 2, - )); - const copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(1, 1, 1), new TextureSubresLayers(0, 0, 1)); - device.copyBuffersToTexture([buffer], this._texture1DArray, [copyRegion]); - copyRegion.texSubres.baseArrayLayer = 1; - device.copyBuffersToTexture([buffer], this._texture1DArray, [copyRegion]); - } if (device.capabilities.maxArrayTextureLayers >= 2) { this._texture2DArray = device.createTexture(new TextureInfo( TextureType.TEX2D_ARRAY, @@ -442,12 +428,11 @@ export class DefaultResource { } } - public getTexture (type : TextureType) { + public getTexture (type: TextureType) { switch (type) { case TextureType.TEX2D: return this._texture2D; case TextureType.TEX3D: return this._texture3D; case TextureType.CUBE: return this._textureCube; - case TextureType.TEX1D_ARRAY: return this._texture1DArray; case TextureType.TEX2D_ARRAY: return this._texture2DArray; default: return null; } diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index 039bd86048..62e8a05b17 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -545,6 +545,7 @@ export function buildForwardPass (camera: Camera, } if (!isOffScreen) { ppl.updateRenderWindow(forwardPassRTName, camera.window); + ppl.updateDepthStencil(forwardPassDSName, width, height); } else { ppl.updateRenderTarget(forwardPassRTName, width, height); ppl.updateDepthStencil(forwardPassDSName, width, height); @@ -554,13 +555,13 @@ export function buildForwardPass (camera: Camera, forwardPass.setViewport(new Viewport(area.x, area.y, width, height)); for (const dirShadowName of cameraInfo.mainLightShadowNames) { if (ppl.containsResource(dirShadowName)) { - const computeView = new ComputeView(); + const computeView = new ComputeView('cc_shadowMap'); forwardPass.addComputeView(dirShadowName, computeView); } } for (const spotShadowName of cameraInfo.spotLightShadowNames) { if (ppl.containsResource(spotShadowName)) { - const computeView = new ComputeView(); + const computeView = new ComputeView('cc_spotShadowMap'); forwardPass.addComputeView(spotShadowName, computeView); } } @@ -872,13 +873,13 @@ export function buildLightingPass (camera: Camera, ppl: Pipeline, gBuffer: GBuff lightingPass.setViewport(new Viewport(area.x, area.y, width, height)); for (const dirShadowName of cameraInfo.mainLightShadowNames) { if (ppl.containsResource(dirShadowName)) { - const computeView = new ComputeView(); + const computeView = new ComputeView('cc_shadowMap'); lightingPass.addComputeView(dirShadowName, computeView); } } for (const spotShadowName of cameraInfo.spotLightShadowNames) { if (ppl.containsResource(spotShadowName)) { - const computeView = new ComputeView(); + const computeView = new ComputeView('cc_spotShadowMap'); lightingPass.addComputeView(spotShadowName, computeView); } } @@ -916,8 +917,8 @@ export function buildLightingPass (camera: Camera, ppl: Pipeline, gBuffer: GBuff camera, lightingInfo.deferredLightingMaterial, 0, SceneFlags.VOLUMETRIC_LIGHTING, ); - lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), - SceneFlags.TRANSPARENT_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.GEOMETRY); + // lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), + // SceneFlags.TRANSPARENT_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.GEOMETRY); return { rtName: deferredLightingPassRTName, dsName: deferredLightingPassDS }; } diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 04ff84abf2..8799ff412a 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -65,6 +65,8 @@ import { VectorGraphColorMap } from './effect'; import { getDescBindingFromName, getDescriptorSetDataFromLayout, getRenderArea, mergeSrcToTargetDesc, updateGlobalDescBinding } from './define'; import { RenderReflectionProbeQueue } from '../render-reflection-probe-queue'; import { ReflectionProbeManager } from '../reflection-probe-manager'; +import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; +import { Texture2D } from '../../asset/assets/texture-2d'; class DeviceResource { protected _context: ExecutorContext; @@ -1047,9 +1049,14 @@ class DevicePreSceneTask extends WebSceneTask { const mainLight = graphScene.scene.camera.scene!.mainLight; const shadowFrameBufferMap = this.sceneData.shadowFrameBufferMap; if (mainLight && shadowFrameBufferMap.has(mainLight)) { + const shadowAttrID = context.layoutGraph.attributeIndex.get('cc_shadowMap'); + const defaultTex = builtinResMgr.get('default-texture').getGFXTexture()!; for (const [key, value] of data.textures) { - if (key === context.layoutGraph.attributeIndex.get('cc_shadowMap')) { - data.textures.set(key, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); + if (key === shadowAttrID) { + const tex = data.textures.get(shadowAttrID); + if (tex === defaultTex) { + data.textures.set(key, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); + } return; } } @@ -1521,7 +1528,8 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { } else { const passHash = pass.versionName; this.currPass = devicePasses.get(passHash); - if (!this.currPass || this.currPass.version !== pass.version) { + const currRasterPass = this.currPass ? this.currPass.rasterPassInfo.pass : null; + if (!this.currPass || currRasterPass.version !== pass.version) { this.currPass = new DeviceRenderPass(this.context, new RasterPassInfo(this.passID, pass)); devicePasses.set(passHash, this.currPass); } else { diff --git a/cocos/rendering/custom/layout-graph-utils.ts b/cocos/rendering/custom/layout-graph-utils.ts index a22afd1add..bd3e86c89e 100644 --- a/cocos/rendering/custom/layout-graph-utils.ts +++ b/cocos/rendering/custom/layout-graph-utils.ts @@ -1064,6 +1064,17 @@ export function getOrCreateDescriptorID (lg: LayoutGraphData, name: string): num return nameID; } +export function getOrCreateConstantID (lg: LayoutGraphData, name: string): number { + const nameID = lg.constantIndex.get(name); + if (nameID === undefined) { + const newID = lg.valueNames.length; + lg.constantIndex.set(name, newID); + lg.valueNames.push(name); + return newID; + } + return nameID; +} + // LayoutGraphData builder class LayoutGraphBuilder2 implements LayoutGraphBuilder { public constructor (lg: LayoutGraphData) { @@ -1156,6 +1167,10 @@ class LayoutGraphBuilder2 implements LayoutGraphBuilder { const layout = setData.descriptorSetLayoutData; const nameID = getOrCreateDescriptorID(g, name); layout.uniformBlocks.set(nameID, uniformBlock); + // register constant names + for (const member of uniformBlock.members) { + getOrCreateConstantID(g, member.name); + } } reserveDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void { if (block.capacity <= 0) { diff --git a/cocos/rendering/custom/types.ts b/cocos/rendering/custom/types.ts index 6e02f1b51c..7b61c4995e 100644 --- a/cocos/rendering/custom/types.ts +++ b/cocos/rendering/custom/types.ts @@ -280,6 +280,7 @@ export class RasterView { storeOp: StoreOp; clearFlags: ClearFlagBit; readonly clearColor: Color; + slotID = 0; } export enum ClearValueType { @@ -473,6 +474,7 @@ export function saveRasterView (ar: OutputArchive, v: RasterView) { ar.writeNumber(v.storeOp); ar.writeNumber(v.clearFlags); saveColor(ar, v.clearColor); + ar.writeNumber(v.slotID); } export function loadRasterView (ar: InputArchive, v: RasterView) { @@ -483,6 +485,7 @@ export function loadRasterView (ar: InputArchive, v: RasterView) { v.storeOp = ar.readNumber(); v.clearFlags = ar.readNumber(); loadColor(ar, v.clearColor); + v.slotID = ar.readNumber(); } export function saveComputeView (ar: OutputArchive, v: ComputeView) { diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index 6cbc6d012f..da55ffcedf 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -200,6 +200,20 @@ export class WebSetter { const num = this._lg.attributeIndex.get(name)!; this._data.samplers.set(num, sampler); } + public hasSampler (name: string): boolean { + const id = this._lg.attributeIndex.get(name); + if (id === undefined) { + return false; + } + return this._data.samplers.has(id); + } + public hasTexture (name: string): boolean { + const id = this._lg.attributeIndex.get(name); + if (id === undefined) { + return false; + } + return this._data.textures.has(id); + } // protected protected readonly _data: RenderData; @@ -515,11 +529,20 @@ function setTextureUBOView (setter: WebSetter, camera: Camera, cfg: Readonly('default-texture').getGFXTexture()!); - setter.setSampler('cc_spotShadowMap', pointSampler); - setter.setTexture('cc_spotShadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + if (!setter.hasSampler('cc_shadowMap')) { + setter.setSampler('cc_shadowMap', pointSampler); + } + if (!setter.hasTexture('cc_shadowMap')) { + setter.setTexture('cc_shadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + } + if (!setter.hasSampler('cc_spotShadowMap')) { + setter.setSampler('cc_spotShadowMap', pointSampler); + } + if (!setter.hasTexture('cc_spotShadowMap')) { + setter.setTexture('cc_spotShadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + } } function getFirstChildLayoutName (lg: LayoutGraphData, parentID: number): string { diff --git a/cocos/rendering/render-pipeline.ts b/cocos/rendering/render-pipeline.ts index 8cef2c0c9f..76e721d174 100644 --- a/cocos/rendering/render-pipeline.ts +++ b/cocos/rendering/render-pipeline.ts @@ -563,7 +563,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi this._pipelineRenderData!.bloom = null; } - private _genQuadVertexData (surfaceTransform: SurfaceTransform, renderArea: Rect) : Float32Array { + private _genQuadVertexData (surfaceTransform: SurfaceTransform, renderArea: Rect): Float32Array { const vbData = new Float32Array(4 * 4); const minX = renderArea.x / this._width; diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect b/editor/assets/effects/pipeline/deferred-lighting.effect index e6287ad97c..809a967af6 100644 --- a/editor/assets/effects/pipeline/deferred-lighting.effect +++ b/editor/assets/effects/pipeline/deferred-lighting.effect @@ -44,36 +44,16 @@ CCProgram lighting-fs %{ in vec2 v_uv; - #if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT - #pragma extension([GL_EXT_shader_framebuffer_fetch, __VERSION__ < 450, enable]) - #if __VERSION__ >= 450 - layout(binding = 0, input_attachment_index = 0) uniform subpassInput gbuffer_albedoMap; - layout(binding = 1, input_attachment_index = 1) uniform subpassInput gbuffer_normalMap; - layout(binding = 2, input_attachment_index = 2) uniform subpassInput gbuffer_emissiveMap; - layout(binding = 3, input_attachment_index = 3) uniform subpassInput depth_stencil; - #elif __VERSION__ >= 300 - layout(location = 0) inout vec4 gbuffer_albedoMap; - layout(location = 1) inout vec4 gbuffer_normalMap; - layout(location = 2) inout vec4 gbuffer_emissiveMap; - layout(binding = 3) uniform sampler2D depth_stencil; - #else - layout(binding = 3) uniform sampler2D depth_stencil; - #endif - #else - #pragma rate gbuffer_albedoMap pass - layout(binding = 0) uniform sampler2D gbuffer_albedoMap; - #pragma rate gbuffer_normalMap pass - layout(binding = 1) uniform sampler2D gbuffer_normalMap; - #pragma rate gbuffer_emissiveMap pass - layout(binding = 2) uniform sampler2D gbuffer_emissiveMap; - #pragma rate depth_stencil pass - layout(binding = 3) uniform sampler2D depth_stencil; - #endif - - #if !CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT || __VERSION__ >= 450 - layout(location = 0) out vec4 fragColor; - #endif + #pragma rate gbuffer_albedoMap pass + layout(binding = 0) uniform sampler2D gbuffer_albedoMap; + #pragma rate gbuffer_normalMap pass + layout(binding = 1) uniform sampler2D gbuffer_normalMap; + #pragma rate gbuffer_emissiveMap pass + layout(binding = 2) uniform sampler2D gbuffer_emissiveMap; + #pragma rate depth_stencil pass + layout(binding = 3) uniform sampler2D depth_stencil; + layout(location = 0) out vec4 fragColor; vec4 screen2WS(vec3 coord) { vec3 ndc = vec3( @@ -91,29 +71,10 @@ CCProgram lighting-fs %{ void main () { StandardSurface s; - #if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT - #if __VERSION__ >= 450 - vec4 albedoMap = subpassLoad(gbuffer_albedoMap); - vec4 normalMap = subpassLoad(gbuffer_normalMap); - vec4 emissiveMap = subpassLoad(gbuffer_emissiveMap); - float depth = subpassLoad(depth_stencil).x; - #elif __VERSION__ >= 300 - vec4 albedoMap = gbuffer_albedoMap; - vec4 normalMap = gbuffer_normalMap; - vec4 emissiveMap = gbuffer_emissiveMap; - float depth = texture(depth_stencil, v_uv).x; - #else - vec4 albedoMap = gl_LastFragData[0]; - vec4 normalMap = gl_LastFragData[1]; - vec4 emissiveMap = gl_LastFragData[2]; - float depth = texture(depth_stencil, v_uv).x; - #endif - #else - vec4 albedoMap = texture(gbuffer_albedoMap,v_uv); - vec4 normalMap = texture(gbuffer_normalMap,v_uv); - vec4 emissiveMap = texture(gbuffer_emissiveMap,v_uv); - float depth = texture(depth_stencil, v_uv).x; - #endif + vec4 albedoMap = texture(gbuffer_albedoMap,v_uv); + vec4 normalMap = texture(gbuffer_normalMap,v_uv); + vec4 emissiveMap = texture(gbuffer_emissiveMap,v_uv); + float depth = texture(depth_stencil, v_uv).x; s.albedo = albedoMap; vec3 position = screen2WS(vec3(gl_FragCoord.xy, depth)).xyz; @@ -140,16 +101,6 @@ CCProgram lighting-fs %{ CC_APPLY_FOG_BASE(color, fogFactor); color = CCFragOutput(color); - #if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT - #if __VERSION__ >= 450 - fragColor = color; - #elif __VERSION__ >= 300 - gbuffer_emissiveMap = color; - #else - gl_FragData[2] = color; - #endif - #else - fragColor = color; - #endif + fragColor = color; } }% diff --git a/editor/assets/effects/pipeline/post-process.effect b/editor/assets/effects/pipeline/post-process.effect index 5e99e8ee7a..302899d1f1 100644 --- a/editor/assets/effects/pipeline/post-process.effect +++ b/editor/assets/effects/pipeline/post-process.effect @@ -22,7 +22,7 @@ CCEffect %{ CCProgram post-process-vs %{ precision highp float; - #include + #include #include #include @@ -30,7 +30,7 @@ CCProgram post-process-vs %{ void main () { StandardVertInput In; - CCVertInput(In); + CCDecode(In); CC_HANDLE_GET_CLIP_FLIP(In.position.xy); gl_Position = In.position; gl_Position.y = gl_Position.y; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 571f55923a..f282d19cce 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1347,12 +1347,15 @@ cocos_source_files( cocos/renderer/pipeline/custom/NativePipelineGraphs.h cocos/renderer/pipeline/custom/NativePipelineTypes.cpp cocos/renderer/pipeline/custom/NativePipelineTypes.h + cocos/renderer/pipeline/custom/NativePools.cpp cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp cocos/renderer/pipeline/custom/NativeRenderGraph.cpp cocos/renderer/pipeline/custom/NativeRenderQueue.cpp cocos/renderer/pipeline/custom/NativeRenderingModule.cpp cocos/renderer/pipeline/custom/NativeTypes.cpp cocos/renderer/pipeline/custom/NativeTypes.h + cocos/renderer/pipeline/custom/NativeUtils.cpp + cocos/renderer/pipeline/custom/NativeUtils.h cocos/renderer/pipeline/custom/PrivateFwd.h cocos/renderer/pipeline/custom/PrivateTypes.cpp cocos/renderer/pipeline/custom/PrivateTypes.h diff --git a/native/cocos/core/assets/EffectAsset.h b/native/cocos/core/assets/EffectAsset.h index 03d0a7acc5..ac0bf92436 100644 --- a/native/cocos/core/assets/EffectAsset.h +++ b/native/cocos/core/assets/EffectAsset.h @@ -544,6 +544,12 @@ struct IShaderInfo { if (version == "glsl4") return &glsl4; return nullptr; } + IShaderSource *getSource(const ccstd::string &version) { + if (version == "glsl1") return &glsl1; + if (version == "glsl3") return &glsl3; + if (version == "glsl4") return &glsl4; + return nullptr; + } }; using IPreCompileInfoValueType = ccstd::variant, ccstd::vector, ccstd::vector>; diff --git a/native/cocos/renderer/core/PassInstance.cpp b/native/cocos/renderer/core/PassInstance.cpp index 4a8cce8739..8c4e157e8e 100644 --- a/native/cocos/renderer/core/PassInstance.cpp +++ b/native/cocos/renderer/core/PassInstance.cpp @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to @@ -22,16 +22,17 @@ THE SOFTWARE. ****************************************************************************/ -#include "renderer/core/PassInstance.h" -#include -#include "renderer/core/MaterialInstance.h" -#include "renderer/core/ProgramLib.h" -#include "renderer/pipeline/BatchedBuffer.h" -#include "renderer/pipeline/InstancedBuffer.h" +#include "cocos/renderer/core/PassInstance.h" +#include "cocos/renderer/core/MaterialInstance.h" +#include "cocos/renderer/core/ProgramLib.h" +#include "cocos/renderer/pipeline/BatchedBuffer.h" +#include "cocos/renderer/pipeline/InstancedBuffer.h" +#include "cocos/renderer/pipeline/custom/RenderingModule.h" namespace cc { -PassInstance::PassInstance(scene::Pass *parent, MaterialInstance *owner) : Super(parent->getRoot()), _parent(parent), _owner(owner) { +PassInstance::PassInstance(scene::Pass *parent, MaterialInstance *owner) +: Super(parent->getRoot()), _parent(parent), _owner(owner) { doInit(_parent->getPassInfoFull()); for (const auto &b : _shaderInfo->blocks) { scene::IBlockRef &block = _blocks[b.binding]; @@ -42,14 +43,30 @@ PassInstance::PassInstance(scene::Pass *parent, MaterialInstance *owner) : Super _rootBufferDirty = true; gfx::DescriptorSet *parentDescriptorSet = _parent->getDescriptorSet(); - for (const auto &samplerTexture : _shaderInfo->samplerTextures) { - for (uint32_t i = 0; i < samplerTexture.count; ++i) { - auto *sampler = parentDescriptorSet->getSampler(samplerTexture.binding, i); - auto *texture = parentDescriptorSet->getTexture(samplerTexture.binding, i); - _descriptorSet->bindSampler(samplerTexture.binding, sampler, i); - _descriptorSet->bindTexture(samplerTexture.binding, texture, i); + + auto *programLib = render::getProgramLibrary(); + if (programLib) { + const auto &set = _shaderInfo->descriptors.at( + static_cast(pipeline::SetIndex::MATERIAL)); + for (const auto &samplerTexture : set.samplerTextures) { + for (uint32_t i = 0; i < samplerTexture.count; ++i) { + auto *sampler = parentDescriptorSet->getSampler(samplerTexture.binding, i); + auto *texture = parentDescriptorSet->getTexture(samplerTexture.binding, i); + _descriptorSet->bindSampler(samplerTexture.binding, sampler, i); + _descriptorSet->bindTexture(samplerTexture.binding, texture, i); + } + } + } else { + for (const auto &samplerTexture : _shaderInfo->samplerTextures) { + for (uint32_t i = 0; i < samplerTexture.count; ++i) { + auto *sampler = parentDescriptorSet->getSampler(samplerTexture.binding, i); + auto *texture = parentDescriptorSet->getTexture(samplerTexture.binding, i); + _descriptorSet->bindSampler(samplerTexture.binding, sampler, i); + _descriptorSet->bindTexture(samplerTexture.binding, texture, i); + } } } + Super::tryCompile(); } diff --git a/native/cocos/renderer/core/ProgramLib.cpp b/native/cocos/renderer/core/ProgramLib.cpp index a35cdc9357..36097092d4 100644 --- a/native/cocos/renderer/core/ProgramLib.cpp +++ b/native/cocos/renderer/core/ProgramLib.cpp @@ -147,6 +147,7 @@ void IProgramInfo::copyFrom(const IShaderInfo &o) { buffers = o.buffers; images = o.images; subpassInputs = o.subpassInputs; + descriptors = o.descriptors; } ProgramLib::ProgramLib() { diff --git a/native/cocos/renderer/core/ProgramUtils.cpp b/native/cocos/renderer/core/ProgramUtils.cpp index 382f46d50a..d218d3fd55 100644 --- a/native/cocos/renderer/core/ProgramUtils.cpp +++ b/native/cocos/renderer/core/ProgramUtils.cpp @@ -248,7 +248,7 @@ ccstd::string getShaderInstanceName(const ccstd::string &name, const ccstd::vect return ret.str(); } -void addEffectDefaultProperties(EffectAsset& effect) { +void addEffectDefaultProperties(EffectAsset &effect) { for (auto &tech : effect._techniques) { for (auto &pass : tech.passes) { // grab default property declaration if there is none diff --git a/native/cocos/renderer/gfx-base/GFXDevice.cpp b/native/cocos/renderer/gfx-base/GFXDevice.cpp index 8a63f30b56..148d1ece8c 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.cpp +++ b/native/cocos/renderer/gfx-base/GFXDevice.cpp @@ -158,14 +158,6 @@ DefaultResource::DefaultResource(Device *device) { BufferTextureCopy region = {0, 0, 0, {0, 0, 0}, {2, 2, 2}, {0, 0, 1}}; device->copyBuffersToTexture(&bufferData, _texture3D, ®ion, 1); } - if (device->getCapabilities().maxArrayTextureLayers >= 2) { - _texture1DArray = device->createTexture({TextureType::TEX1D_ARRAY, TextureUsageBit::STORAGE | TextureUsageBit::SAMPLED, - Format::RGBA8, 1, 1, TextureFlagBit::NONE, 2}); - BufferTextureCopy region = {0, 0, 0, {0, 0, 0}, {1, 1, 1}, {0, 0, 1}}; - device->copyBuffersToTexture(&bufferData, _texture1DArray, ®ion, 1); - region.texSubres.baseArrayLayer = 1; - device->copyBuffersToTexture(&bufferData, _texture1DArray, ®ion, 1); - } if (device->getCapabilities().maxArrayTextureLayers >= 2) { _texture2DArray = device->createTexture({TextureType::TEX2D_ARRAY, TextureUsageBit::STORAGE | TextureUsageBit::SAMPLED, Format::RGBA8, 2, 2, TextureFlagBit::NONE, 2}); @@ -176,7 +168,7 @@ DefaultResource::DefaultResource(Device *device) { } } -const Texture *DefaultResource::getTexture(TextureType type) const { +Texture *DefaultResource::getTexture(TextureType type) const { switch (type) { case TextureType::TEX2D: return _texture2D; @@ -184,8 +176,6 @@ const Texture *DefaultResource::getTexture(TextureType type) const { return _textureCube; case TextureType::TEX3D: return _texture3D; - case TextureType::TEX1D_ARRAY: - return _texture1DArray; case TextureType::TEX2D_ARRAY: return _texture2DArray; default: diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index dffb018ee5..5c993f72fa 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -196,12 +196,10 @@ public: ~DefaultResource() = default; - const Texture *getTexture(TextureType type) const; + Texture *getTexture(TextureType type) const; private: - IntrusivePtr _texture1D; IntrusivePtr _texture2D; - IntrusivePtr _texture1DArray; IntrusivePtr _texture2DArray; IntrusivePtr _textureCube; IntrusivePtr _texture3D; diff --git a/native/cocos/renderer/gfx-metal/MTLBuffer.mm b/native/cocos/renderer/gfx-metal/MTLBuffer.mm index d9e618c290..ffbf228a86 100644 --- a/native/cocos/renderer/gfx-metal/MTLBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLBuffer.mm @@ -29,6 +29,7 @@ #include "MTLBuffer.h" #include "MTLCommandBuffer.h" #include "MTLDevice.h" +#include "MTLQueue.h" #include "MTLRenderCommandEncoder.h" #include "MTLUtils.h" #include "MTLGPUObjects.h" @@ -245,14 +246,26 @@ void CCMTLBuffer::update(const void *buffer, uint32_t size) { void CCMTLBuffer::updateMTLBuffer(const void *buffer, uint32_t /*offset*/, uint32_t size) { if (_gpuBuffer->mtlBuffer) { - CommandBuffer *cmdBuffer = CCMTLDevice::getInstance()->getCommandBuffer(); - cmdBuffer->begin(); - static_cast(cmdBuffer)->updateBuffer(this, buffer, size); -#if (CC_PLATFORM == CC_PLATFORM_MACOS) - if (_mtlResourceOptions == MTLResourceStorageModeManaged) { - [_gpuBuffer->mtlBuffer didModifyRange:NSMakeRange(0, _size)]; // Synchronize the managed buffer. + if(_gpuBuffer->mtlBuffer.storageMode == MTLStorageModeShared) { + memcpy(_gpuBuffer->mtlBuffer.contents, buffer, size); + } else { + auto* ccQueue = static_cast(CCMTLDevice::getInstance()->getQueue()); + id device = static_cast>(CCMTLDevice::getInstance()->getMTLDevice()); + id defaultQueue = ccQueue->gpuQueueObj()->mtlCommandQueue; + id cmdBuffer = [defaultQueue commandBuffer]; + id blit = [cmdBuffer blitCommandEncoder]; + id stagingbuffer = [device newBufferWithBytes:buffer length:size options:MTLStorageModeShared]; + [blit copyFromBuffer:stagingbuffer sourceOffset:0 toBuffer:_gpuBuffer->mtlBuffer destinationOffset:0 size:size]; + [blit endEncoding]; + [stagingbuffer release]; + [cmdBuffer commit]; + + #if (CC_PLATFORM == CC_PLATFORM_MACOS) + if (_mtlResourceOptions == MTLResourceStorageModeManaged) { + [_gpuBuffer->mtlBuffer didModifyRange:NSMakeRange(0, _size)]; // Synchronize the managed buffer. + } + #endif } -#endif } } diff --git a/native/cocos/renderer/pipeline/RenderPipeline.cpp b/native/cocos/renderer/pipeline/RenderPipeline.cpp index 21db853940..e3189d1f75 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.cpp +++ b/native/cocos/renderer/pipeline/RenderPipeline.cpp @@ -33,7 +33,6 @@ #include "PipelineStateManager.h" #include "PipelineUBO.h" #include "RenderFlow.h" -#include "RenderPipeline.h" #include "base/StringUtil.h" #include "base/std/hash/hash.h" #include "frame-graph/FrameGraph.h" @@ -42,6 +41,7 @@ #if CC_USE_DEBUG_RENDERER #include "profiler/DebugRenderer.h" #endif +#include "custom/NativeUtils.h" #include "scene/Camera.h" #include "scene/Skybox.h" @@ -291,31 +291,8 @@ void RenderPipeline::setShadingScale(float scale) { _pipelineSceneData->setShadingScale(scale); } -void RenderPipeline::genQuadVertexData(const Vec4 &viewport, float *vbData) { - auto minX = static_cast(viewport.x); - auto maxX = static_cast(viewport.x + viewport.z); - auto minY = static_cast(viewport.y); - auto maxY = static_cast(viewport.y + viewport.w); - if (_device->getCapabilities().screenSpaceSignY > 0) { - std::swap(minY, maxY); - } - int n = 0; - vbData[n++] = -1.0F; - vbData[n++] = -1.0F; - vbData[n++] = minX; // uv - vbData[n++] = maxY; - vbData[n++] = 1.0F; - vbData[n++] = -1.0F; - vbData[n++] = maxX; - vbData[n++] = maxY; - vbData[n++] = -1.0F; - vbData[n++] = 1.0F; - vbData[n++] = minX; - vbData[n++] = minY; - vbData[n++] = 1.0F; - vbData[n++] = 1.0F; - vbData[n++] = maxX; - vbData[n++] = minY; +void RenderPipeline::genQuadVertexData(const Vec4 &viewport, float vbData[16]) { + render::setupQuadVertexBuffer(*_device, viewport, vbData); } void RenderPipeline::generateConstantMacros() { diff --git a/native/cocos/renderer/pipeline/RenderPipeline.h b/native/cocos/renderer/pipeline/RenderPipeline.h index c8abdf8d03..5f2bdfba0b 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.h +++ b/native/cocos/renderer/pipeline/RenderPipeline.h @@ -110,7 +110,7 @@ public: gfx::Viewport getViewport(scene::Camera *camera); gfx::Rect getScissor(scene::Camera *camera); - void genQuadVertexData(const Vec4 &viewport, float *data); + void genQuadVertexData(const Vec4 &viewport, float data[16]); uint32_t getWidth() const { return _width; } uint32_t getHeight() const { return _height; } framegraph::FrameGraph &getFrameGraph() { return _fg; } diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp index dbfbd9323f..f8899fdc8c 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp @@ -89,7 +89,7 @@ RelationGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) : outEdges(rhs.outEdges, alloc), inEdges(rhs.inEdges, alloc) {} -FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept +FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept : resourceAccessGraph(alloc), resourceGraph(resourceGraphIn), graph(graphIn), diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index c528922111..2d085af91b 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -391,7 +391,7 @@ struct FrameGraphDispatcher { return {resourceAccessGraph.get_allocator().resource()}; } - FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept; + FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept; FrameGraphDispatcher(FrameGraphDispatcher&& rhs) = delete; FrameGraphDispatcher(FrameGraphDispatcher const& rhs) = delete; FrameGraphDispatcher& operator=(FrameGraphDispatcher&& rhs) = delete; @@ -417,7 +417,7 @@ struct FrameGraphDispatcher { ResourceAccessGraph resourceAccessGraph; ResourceGraph& resourceGraph; const RenderGraph& graph; - LayoutGraphData& layoutGraph; + const LayoutGraphData& layoutGraph; boost::container::pmr::memory_resource* scratch{nullptr}; PmrFlatMap externalResMap; RelationGraph relationGraph; diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index dfb096e9d0..4ed99709d9 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -809,6 +809,26 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { } }; + // remove unnecessary barriers + for (auto &&[nodeID, node] : batchedBarriers) { + auto removeUnnecessaryBarriers = [](std::vector &barriers) { + for (int32_t i = 0; i != barriers.size();) { + const auto &barrier = barriers[i]; + const auto &lhs = barrier.beginStatus; + const auto &rhs = barrier.endStatus; + if (std::forward_as_tuple(lhs.visibility, lhs.access, lhs.accessFlag) == + std::forward_as_tuple(rhs.visibility, rhs.access, rhs.accessFlag)) { + barriers.erase(barriers.begin() + i); + } else { + ++i; + } + } + }; + removeUnnecessaryBarriers(node.blockBarrier.frontBarriers); + removeUnnecessaryBarriers(node.blockBarrier.rearBarriers); + } + + // generate gfx barrier for (auto &passBarrierInfo : batchedBarriers) { auto &passBarrierNode = passBarrierInfo.second; genGFXBarrier(passBarrierNode.blockBarrier.frontBarriers); @@ -960,7 +980,7 @@ auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, ResourceA break; } } - return std::tie(forceAdjacent, score); + return std::make_tuple(forceAdjacent, score); }; void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, const RelationGraph &relationGraphTc, const RelationVerts &lhsVerts, const RelationVerts &rhsVerts) { @@ -1451,7 +1471,7 @@ auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAcce accesFlag = gfx::getAccessFlags(texUsage, memAccess, vis); } - return std::tie(vis, usage, accesFlag); + return std::make_tuple(vis, usage, accesFlag); } void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status, const Range &range) { diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp index b5387ff64c..6b6a4671a2 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp @@ -234,7 +234,6 @@ LayoutGraphData::LayoutGraphData(const allocator_type& alloc) noexcept constantIndex(alloc), shaderLayoutIndex(alloc), effects(alloc), - constantMacros(alloc), pathIndex(alloc) {} LayoutGraphData::LayoutGraphData(LayoutGraphData&& rhs, const allocator_type& alloc) @@ -249,7 +248,7 @@ LayoutGraphData::LayoutGraphData(LayoutGraphData&& rhs, const allocator_type& al constantIndex(std::move(rhs.constantIndex), alloc), shaderLayoutIndex(std::move(rhs.shaderLayoutIndex), alloc), effects(std::move(rhs.effects), alloc), - constantMacros(std::move(rhs.constantMacros), alloc), + constantMacros(std::move(rhs.constantMacros)), pathIndex(std::move(rhs.pathIndex), alloc) {} // ContinuousContainer diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h index 4ac2fca7f0..cf3911fe8a 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphTypes.h @@ -706,7 +706,7 @@ struct LayoutGraphData { PmrFlatMap constantIndex; PmrFlatMap shaderLayoutIndex; PmrFlatMap effects; - ccstd::pmr::string constantMacros; + ccstd::string constantMacros; // Path PmrTransparentMap pathIndex; }; diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp index 02ba74a11b..ba6d31bffa 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp @@ -26,13 +26,19 @@ #include "LayoutGraphUtils.h" #include #include +#include "LayoutGraphGraphs.h" +#include "LayoutGraphNames.h" +#include "LayoutGraphTypes.h" +#include "RenderCommonNames.h" +#include "RenderCommonTypes.h" #include "cocos/base/Log.h" +#include "cocos/base/StringUtil.h" #include "cocos/base/std/container/string.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" -#include "LayoutGraphTypes.h" -#include "LayoutGraphGraphs.h" -#include "RenderCommonTypes.h" +#include "details/DebugUtils.h" +#include "details/GslUtils.h" #include "details/Map.h" +#include "details/Range.h" namespace cc { @@ -243,8 +249,8 @@ void makeDescriptorSetLayoutData( // increate total capacity capacity += block.capacity; data.capacity += block.capacity; - if (index.descriptorType == DescriptorTypeOrder::UNIFORM_BUFFER - || index.descriptorType == DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER) { + if (index.descriptorType == DescriptorTypeOrder::UNIFORM_BUFFER || + index.descriptorType == DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER) { data.uniformBlockCapacity += block.capacity; } else if (index.descriptorType == DescriptorTypeOrder::SAMPLER_TEXTURE) { data.samplerTextureCapacity += block.capacity; @@ -275,16 +281,21 @@ void initializeDescriptorSetLayoutInfo( namespace { const ccstd::unordered_map DEFAULT_UNIFORM_COUNTS{ - {"cc_joints", pipeline::UBOSkinning::layout.members[0].count}, {"cc_lightPos", pipeline::UBOForwardLight::LIGHTS_PER_PASS}, {"cc_lightColor", pipeline::UBOForwardLight::LIGHTS_PER_PASS}, {"cc_lightSizeRangeAngle", pipeline::UBOForwardLight::LIGHTS_PER_PASS}, {"cc_lightDir", pipeline::UBOForwardLight::LIGHTS_PER_PASS}, }; +const TransparentSet DYNAMIC_UNIFORM_BLOCK{ + {"CCCamera"}, + {"CCForwardLight"}, + {"CCUILocal"}, +}; + } // namespace -uint32_t getSize(const ccstd::vector& blockMembers) { +uint32_t getUniformBlockSize(const ccstd::vector& blockMembers) { uint32_t prevSize = 0; for (const auto& m : blockMembers) { if (m.count) { @@ -296,11 +307,22 @@ uint32_t getSize(const ccstd::vector& blockMembers) { prevSize += getTypeSize(m.type) * iter->second; continue; } + if (m.name == "cc_joints") { + const auto sz = getTypeSize(m.type) * pipeline::UBOSkinning::layout.members[0].count; + CC_EXPECTS(sz == pipeline::UBOSkinning::size); + prevSize += sz; + continue; + } CC_LOG_ERROR("Invalid uniform count: %s", m.name.c_str()); } + CC_ENSURES(prevSize); return prevSize; } +bool isDynamicUniformBlock(std::string_view name) { + return DYNAMIC_UNIFORM_BLOCK.find(name) != DYNAMIC_UNIFORM_BLOCK.end(); +} + gfx::DescriptorSet* getOrCreatePerPassDescriptorSet( gfx::Device* device, LayoutGraphData& lg, LayoutGraphData::vertex_descriptor vertID) { @@ -321,6 +343,140 @@ gfx::DescriptorSet* getOrCreatePerPassDescriptorSet( return data.descriptorSet; } +void generateConstantMacros( + gfx::Device* device, + ccstd::string& constantMacros, + bool clusterEnabled) { + constantMacros = StringUtil::format( + R"( +#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE %d +#define CC_ENABLE_CLUSTERED_LIGHT_CULLING %d +#define CC_DEVICE_MAX_VERTEX_UNIFORM_VECTORS %d +#define CC_DEVICE_MAX_FRAGMENT_UNIFORM_VECTORS %d +#define CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT %d +#define CC_PLATFORM_ANDROID_AND_WEBGL 0 +#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES 0 + )", + hasAnyFlags(device->getFormatFeatures(gfx::Format::RGBA32F), + gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE), + clusterEnabled ? 1 : 0, + device->getCapabilities().maxVertexUniformVectors, + device->getCapabilities().maxFragmentUniformVectors, + device->hasFeature(gfx::Feature::INPUT_ATTACHMENT_BENEFIT)); +} + +namespace { + +ccstd::string getName(gfx::ShaderStageFlagBit stage) { + std::ostringstream oss; + int count = 0; + if (hasFlag(stage, gfx::ShaderStageFlagBit::VERTEX)) { + if (count++) { + oss << " | "; + } + oss << "Vertex"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::CONTROL)) { + if (count++) { + oss << " | "; + } + oss << "Control"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::EVALUATION)) { + if (count++) { + oss << " | "; + } + oss << "Evaluation"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::GEOMETRY)) { + if (count++) { + oss << " | "; + } + oss << "Geometry"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::FRAGMENT)) { + if (count++) { + oss << " | "; + } + oss << "Fragment"; + } + if (hasFlag(stage, gfx::ShaderStageFlagBit::COMPUTE)) { + if (count++) { + oss << " | "; + } + oss << "Compute"; + } + if (hasAllFlags(stage, gfx::ShaderStageFlagBit::ALL)) { + if (count++) { + oss << " | "; + } + oss << "All"; + } + return oss.str(); +} + +} // namespace + +void printLayoutGraphData( + const LayoutGraphData& lg, std::ostream& oss, + boost::container::pmr::memory_resource* scratch) { + ccstd::pmr::string space(scratch); + + oss << "\n"; + + for (const auto v : makeRange(vertices(lg))) { + if (parent(v, lg) != LayoutGraphData::null_vertex()) { + continue; + } + const auto& name = get(LayoutGraphData::Name, lg, v); + OSS << "\"" << name << "\": "; + + visit( + [&](auto tag) { + oss << getName(tag); + }, + tag(v, lg)); + + oss << " {\n"; + INDENT_BEG(); + const auto& info = get(LayoutGraphData::Layout, lg, v); + for (const auto& set : info.descriptorSets) { + OSS << "Set<" << getName(set.first) << "> {\n"; + { + INDENT(); + for (const auto& block : set.second.descriptorSetLayoutData.descriptorBlocks) { + OSS << "Block<" << getName(block.type) << ", " << getName(block.visibility) << "> {\n"; + { + INDENT(); + OSS << "capacity: " << block.capacity << ",\n"; + OSS << "count: " << block.descriptors.size() << ",\n"; + if (!block.descriptors.empty()) { + OSS << "Descriptors{ "; + int count = 0; + for (const auto& d : block.descriptors) { + if (count++) { + oss << ", "; + } + const auto& name = lg.valueNames.at(d.descriptorID.value); + oss << "\"" << name; + if (d.count != 1) { + oss << "[" << d.count << "]"; + } + oss << "\""; + } + oss << " }\n"; + } + } + OSS << "}\n"; + } + } + OSS << "}\n"; + } + INDENT_END(); + OSS << "}\n"; + } +} + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h index 3a06f524b6..c1c92b8dcf 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h @@ -24,6 +24,7 @@ #pragma once #include +#include #include "cocos/core/assets/EffectAsset.h" #include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" #include "cocos/renderer/pipeline/custom/RenderCommonTypes.h" @@ -48,12 +49,23 @@ void initializeDescriptorSetLayoutInfo( const DescriptorSetLayoutData& layoutData, gfx::DescriptorSetLayoutInfo& info); -uint32_t getSize(const ccstd::vector& blockMembers); +uint32_t getUniformBlockSize(const ccstd::vector& blockMembers); + +bool isDynamicUniformBlock(std::string_view name); gfx::DescriptorSet* getOrCreatePerPassDescriptorSet( gfx::Device* device, LayoutGraphData& lg, LayoutGraphData::vertex_descriptor vertID); +void generateConstantMacros( + gfx::Device* device, + ccstd::string& constantMacros, + bool clusterEnabled); + +void printLayoutGraphData( + const LayoutGraphData& lg, std::ostream& oss, + boost::container::pmr::memory_resource* scratch); + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index 1aa88ca77b..0434b5c917 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -24,20 +24,24 @@ #include #include -#include #include "FGDispatcherGraphs.h" #include "LayoutGraphGraphs.h" #include "LayoutGraphTypes.h" #include "LayoutGraphUtils.h" #include "NativePipelineFwd.h" #include "NativePipelineTypes.h" +#include "NativeUtils.h" +#include "PrivateTypes.h" #include "RenderGraphGraphs.h" #include "RenderGraphTypes.h" #include "RenderingModule.h" #include "cocos/renderer/gfx-base/GFXBarrier.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" +#include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" #include "cocos/renderer/gfx-base/GFXDevice.h" +#include "cocos/renderer/pipeline/Define.h" #include "cocos/renderer/pipeline/InstancedBuffer.h" +#include "cocos/renderer/pipeline/PipelineStateManager.h" #include "cocos/scene/Model.h" #include "cocos/scene/Octree.h" #include "cocos/scene/Pass.h" @@ -46,7 +50,6 @@ #include "details/GraphView.h" #include "details/GslUtils.h" #include "details/Range.h" -#include "pipeline/Define.h" namespace cc { @@ -75,8 +78,10 @@ struct RenderGraphVisitorContext { const scene::RenderScene*, ccstd::pmr::unordered_map>& sceneQueues; PipelineRuntime* ppl = nullptr; + ProgramLibrary* programLib = nullptr; boost::container::pmr::memory_resource* scratch = nullptr; gfx::RenderPass* currentPass = nullptr; + LayoutGraphData::vertex_descriptor currentPassLayoutID = LayoutGraphData::null_vertex(); }; void clear(gfx::RenderPassInfo& info) { @@ -111,6 +116,9 @@ uint32_t getRasterPassInputCount(const RasterPass& pass) { uint32_t getRasterPassOutputCount(const RasterPass& pass) { uint32_t numOutputs = 0; for (const auto& [name, view] : pass.rasterViews) { + if (view.attachmentType != AttachmentType::RENDER_TARGET) { + continue; + } if (view.accessType == AccessType::READ_WRITE || view.accessType == AccessType::WRITE) { ++numOutputs; } @@ -129,51 +137,65 @@ uint32_t getRasterPassPreserveCount(const RasterPass& pass) { } PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( - RenderGraphVisitorContext& ctx, const RasterPass& pass) { + RenderGraphVisitorContext& ctx, const RasterPass& pass, + boost::container::pmr::memory_resource* scratch) { auto& resg = ctx.resourceGraph; + PersistentRenderPassAndFramebuffer data(pass.get_allocator()); - gfx::RenderPassInfo rpInfo; - uint32_t numDepthStencil = 0; - rpInfo.colorAttachments.resize(pass.rasterViews.size()); - data.clearColors.resize(pass.rasterViews.size()); + gfx::RenderPassInfo rpInfo{}; + gfx::FramebufferInfo fbInfo{ data.renderPass, }; fbInfo.colorTextures.reserve(pass.rasterViews.size()); if (pass.subpassGraph.subpasses.empty()) { + const auto numInputs = getRasterPassInputCount(pass); + const auto numColors = getRasterPassOutputCount(pass); + + // persistent cache + data.clearColors.reserve(numColors); + + // render pass + rpInfo.colorAttachments.reserve(numColors); + auto& subpass = rpInfo.subpasses.emplace_back(); - subpass.inputs.resize(getRasterPassInputCount(pass)); - subpass.colors.resize(getRasterPassOutputCount(pass)); - subpass.resolves.resize(getRasterPassResolveCount(pass)); - subpass.preserves.resize(getRasterPassPreserveCount(pass)); + subpass.inputs.reserve(numInputs); + subpass.colors.reserve(numColors); + subpass.resolves.reserve(getRasterPassResolveCount(pass)); + subpass.preserves.reserve(getRasterPassPreserveCount(pass)); auto numTotalAttachments = static_cast(pass.rasterViews.size()); - uint32_t slot = 0; - uint32_t rtvCount = 0; + + PmrFlatMap viewIndex(scratch); + for (const auto& [name, view] : pass.rasterViews) { + viewIndex.emplace(view.slotID, name); + } + uint32_t dsvCount = 0; - for (const auto& pair : pass.rasterViews) { - const auto& name = pair.first; - const auto& view = pair.second; + for (const auto& [slotID, name] : viewIndex) { + const auto& view = pass.rasterViews.at(name); const auto resID = vertex(name, ctx.resourceGraph); const auto& desc = get(ResourceGraph::DescTag{}, ctx.resourceGraph, resID); if (view.attachmentType == AttachmentType::RENDER_TARGET) { // RenderTarget - auto& rtv = rpInfo.colorAttachments[slot]; - rtv.format = desc.format; - rtv.sampleCount = desc.sampleCount; - rtv.loadOp = view.loadOp; - rtv.storeOp = view.storeOp; - rtv.barrier = nullptr; - rtv.isGeneralLayout = hasFlag(desc.textureFlags, gfx::TextureFlags::GENERAL_LAYOUT); + auto slot = static_cast(rpInfo.colorAttachments.size()); + auto& rtv = rpInfo.colorAttachments.emplace_back( + gfx::ColorAttachment{ + desc.format, + desc.sampleCount, + view.loadOp, + view.storeOp, + nullptr, + hasFlag(desc.textureFlags, gfx::TextureFlags::GENERAL_LAYOUT), + }); if (view.accessType != AccessType::WRITE) { // Input auto inputSlot = getRasterViewPassInputSlot(view); - subpass.inputs[inputSlot] = slot; + subpass.inputs.emplace_back(slot); } if (view.accessType != AccessType::READ) { // Output - auto outputSlot = rtvCount++; - subpass.colors[outputSlot] = slot; + subpass.colors.emplace_back(slot); } - data.clearColors[slot] = view.clearColor; + data.clearColors.emplace_back(view.clearColor); auto resID = findVertex(name, resg); visitObject( @@ -187,6 +209,7 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( CC_EXPECTS(false); }, [&](const ManagedTexture& tex) { + CC_EXPECTS(tex.texture); fbInfo.colorTextures.emplace_back(tex.texture); }, [&](const IntrusivePtr& res) { @@ -203,10 +226,10 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( [&](const RenderSwapchain& sc) { fbInfo.colorTextures.emplace_back(sc.swapchain->getColorTexture()); }); - - ++slot; + CC_ENSURES(rpInfo.colorAttachments.size() == subpass.colors.size()); + CC_ENSURES(rpInfo.colorAttachments.size() == data.clearColors.size()); + CC_ENSURES(rpInfo.colorAttachments.size() == fbInfo.colorTextures.size()); } else { // DepthStencil - ++numDepthStencil; auto& dsv = rpInfo.depthStencilAttachment; CC_EXPECTS(desc.format != gfx::Format::UNKNOWN); dsv.format = desc.format; @@ -228,6 +251,7 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( visitObject( resID, resg, [&](const ManagedTexture& tex) { + CC_EXPECTS(tex.texture); CC_EXPECTS(!fbInfo.depthStencilTexture); fbInfo.depthStencilTexture = tex.texture.get(); }, @@ -240,23 +264,42 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( }); } } - CC_EXPECTS(numDepthStencil <= 1); - if (numDepthStencil) { - CC_EXPECTS(rpInfo.colorAttachments.back().format == gfx::Format::UNKNOWN); - rpInfo.colorAttachments.pop_back(); - data.clearColors.pop_back(); - } } else { CC_EXPECTS(false); } + data.renderPass = ctx.device->createRenderPass(rpInfo); - if (!data.framebuffer) { - fbInfo.renderPass = data.renderPass; - data.framebuffer = ctx.device->createFramebuffer(fbInfo); - } + fbInfo.renderPass = data.renderPass; + data.framebuffer = ctx.device->createFramebuffer(fbInfo); + data.hash = gfx::Framebuffer::computeHash(fbInfo); + return data; } +PersistentRenderPassAndFramebuffer& fetchOrCreateFramebuffer( + RenderGraphVisitorContext& ctx, const RasterPass& pass, + boost::container::pmr::memory_resource* scratch) { + auto iter = ctx.context.renderPasses.find(pass); + if (iter == ctx.context.renderPasses.end()) { + bool added = false; + std::tie(iter, added) = ctx.context.renderPasses.emplace( + pass, createPersistentRenderPassAndFramebuffer(ctx, pass, scratch)); + CC_ENSURES(added); + return iter->second; + } + + gfx::FramebufferInfo fbInfo{}; + fbInfo.renderPass = iter->second.renderPass; + fbInfo.colorTextures = iter->second.framebuffer->getColorTextures(); + fbInfo.depthStencilTexture = iter->second.framebuffer->getDepthStencilTexture(); + auto hash = gfx::Framebuffer::computeHash(fbInfo); + if (iter->second.hash != hash) { + iter->second.framebuffer = ctx.device->createFramebuffer(fbInfo); + iter->second.hash = hash; + } + return iter->second; +} + gfx::BufferBarrierInfo getBufferBarrier(const cc::render::Barrier& barrier) { gfx::MemoryUsage memUsage = gfx::MemoryUsage::DEVICE; @@ -280,42 +323,48 @@ gfx::BufferBarrierInfo getBufferBarrier(const cc::render::Barrier& barrier) { } std::pair getTextureBarrier( - const ResourceGraph& resg, ResourceGraph::vertex_descriptor resID, + ResourceGraph& resg, ResourceGraph::vertex_descriptor resID, const cc::render::Barrier& barrier) { - gfx::Texture* texture = nullptr; - visitObject( - resID, resg, - [&](const ManagedTexture& res) { - texture = res.texture.get(); - }, - [&](const IntrusivePtr& tex) { - texture = tex.get(); - }, - [&](const IntrusivePtr& fb) { - std::ignore = fb; - CC_EXPECTS(false); - }, - [&](const RenderSwapchain& sc) { - texture = sc.swapchain->getColorTexture(); - }, - [&](const auto& buffer) { - std::ignore = buffer; - CC_EXPECTS(false); - }); + gfx::Texture* texture = resg.getTexture(resID); + CC_ENSURES(texture); const auto& desc = get(ResourceGraph::DescTag{}, resg, resID); - const auto& beginUsage = get(barrier.beginStatus.usage); - const auto& endUsage = get(barrier.endStatus.usage); + + const bool isExternal = barrier.endStatus.vertID == ResourceAccessGraph::null_vertex(); + + const auto barrierType = isExternal ? gfx::BarrierType::FULL : barrier.type; + const auto beginUsage = get(barrier.beginStatus.usage); + const auto endUsage = [&]() { + if (!isExternal) { + return get(barrier.endStatus.usage); + } + return gfx::TextureUsage::NONE; + }(); auto beginAccesFlags = gfx::getAccessFlags( beginUsage, barrier.beginStatus.access, barrier.beginStatus.visibility); - auto endAccessFlags = gfx::getAccessFlags( - endUsage, - barrier.endStatus.access, - barrier.endStatus.visibility); + auto endAccessFlags = [&]() { + if (!isExternal) { + return gfx::getAccessFlags( + endUsage, + barrier.endStatus.access, + barrier.endStatus.visibility); + } + auto& states = get(ResourceGraph::States, resg, resID); + if (holds(resID, resg)) { + states.states = gfx::AccessFlagBit::PRESENT; + return states.states; + } + states.states = + gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | + gfx::AccessFlagBit::VERTEX_SHADER_READ_TEXTURE | + gfx::AccessFlagBit::COMPUTE_SHADER_READ_TEXTURE; + + return states.states; + }(); CC_ENSURES(beginAccesFlags != gfx::INVALID_ACCESS_FLAGS); CC_ENSURES(endAccessFlags != gfx::INVALID_ACCESS_FLAGS); @@ -328,7 +377,7 @@ std::pair getTextureBarrier( gfx::TextureBarrierInfo{ beginAccesFlags, endAccessFlags, - barrier.type, + barrierType, textureRange.mipLevel, textureRange.levelCount, textureRange.firstSlice, @@ -432,9 +481,327 @@ void updateGlobal( } } +void updateCpuUniformBuffer( + const LayoutGraphData& lg, + const RenderData& user, + const gfx::UniformBlock& uniformBlock, + bool bInit, + ccstd::pmr::vector& buffer) { + // calculate uniform block size + const auto bufferSize = uniformBlock.count * + getUniformBlockSize(uniformBlock.members); + // check pre-condition + CC_EXPECTS(buffer.size() == bufferSize); + + // reset buffer + if (bInit) { + std::fill(buffer.begin(), buffer.end(), 0); + } + + uint32_t offset = 0; + for (const auto& value : uniformBlock.members) { + CC_EXPECTS(value.count); + const auto typeSize = getTypeSize(value.type); + const auto totalSize = typeSize * value.count; + CC_ENSURES(typeSize); + CC_ENSURES(totalSize); + + const auto valueID = [&]() { + auto iter = lg.constantIndex.find(std::string_view{value.name}); + CC_EXPECTS(iter != lg.constantIndex.end()); + return iter->second.value; + }(); + + const auto iter2 = user.constants.find(valueID); + if (iter2 == user.constants.end() || iter2->second.empty()) { + if (bInit) { + if (value.type == gfx::Type::MAT4) { + // init matrix to identity + CC_EXPECTS(sizeof(Mat4) == typeSize); + const Mat4 id{}; + for (uint32_t i = 0; i != value.count; ++i) { + memcpy(buffer.data() + offset + i * typeSize, id.m, typeSize); + } + } + } + offset += totalSize; + continue; + } + const auto& source = iter2->second; + CC_EXPECTS(source.size() == totalSize); + CC_EXPECTS(offset + totalSize <= bufferSize); + memcpy(buffer.data() + offset, source.data(), + std::min(source.size(), totalSize)); // safe guard min + offset += totalSize; + } + CC_ENSURES(offset == bufferSize); +} + +void uploadUniformBuffer( + gfx::DescriptorSet* passSet, + uint32_t bindID, + UniformBlockResource& resource) { + auto* buffer = resource.bufferPool.allocateBuffer(); + CC_ENSURES(buffer); + buffer->update(resource.cpuBuffer.data(), + static_cast(resource.cpuBuffer.size())); + + CC_EXPECTS(passSet); + passSet->bindBuffer(bindID, buffer); +} + +void initPerPassDescriptorSet( + ResourceGraph& resg, + gfx::Device* device, + cc::gfx::CommandBuffer* cmdBuff, + const gfx::DefaultResource& defaultResource, + const LayoutGraphData& lg, + const PmrFlatMap& resourceIndex, + const DescriptorSetData& set, + const RenderData& user, + LayoutGraphNodeResource& node) { + // update per pass resources + const auto& data = set.descriptorSetLayoutData; + + gfx::DescriptorSet* passSet = node.descriptorSetPool.allocateDescriptorSet(); + for (const auto& block : data.descriptorBlocks) { + CC_EXPECTS(block.descriptors.size() == block.capacity); + auto bindID = block.offset; + switch (block.type) { + case DescriptorTypeOrder::UNIFORM_BUFFER: { + for (const auto& d : block.descriptors) { + // get uniform block + const auto& uniformBlock = data.uniformBlocks.at(d.descriptorID); + + auto& resource = node.uniformBuffers.at(d.descriptorID); + updateCpuUniformBuffer(lg, user, uniformBlock, true, resource.cpuBuffer); + CC_ENSURES(resource.bufferPool.bufferSize == resource.cpuBuffer.size()); + + // upload gfx buffer + uploadUniformBuffer(passSet, bindID, resource); + + // increase slot + // TODO(zhouzhenglong): here binding will be refactored in the future + // current implementation is incorrect, and we assume d.count == 1 + CC_EXPECTS(d.count == 1); + bindID += d.count; + } + break; + } + case DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::SAMPLER_TEXTURE: { + CC_EXPECTS(passSet); + for (const auto& d : block.descriptors) { + CC_EXPECTS(d.count == 1); + CC_EXPECTS(d.type >= gfx::Type::SAMPLER1D && + d.type <= gfx::Type::SAMPLER_CUBE); + + auto iter = resourceIndex.find(d.descriptorID); + if (iter != resourceIndex.end()) { + // render graph textures + auto* texture = resg.getTexture(iter->second); + CC_ENSURES(texture); + passSet->bindTexture(bindID, texture); + } else { + // user provided textures + auto iter = user.textures.find(d.descriptorID.value); + if (iter != user.textures.end()) { + passSet->bindTexture(bindID, iter->second.get()); + } else { + // default textures + gfx::TextureType type{}; + switch (d.type) { + case gfx::Type::SAMPLER1D: + type = gfx::TextureType::TEX1D; + break; + case gfx::Type::SAMPLER1D_ARRAY: + type = gfx::TextureType::TEX1D_ARRAY; + break; + case gfx::Type::SAMPLER2D: + type = gfx::TextureType::TEX2D; + break; + case gfx::Type::SAMPLER2D_ARRAY: + type = gfx::TextureType::TEX2D_ARRAY; + break; + case gfx::Type::SAMPLER3D: + type = gfx::TextureType::TEX3D; + break; + case gfx::Type::SAMPLER_CUBE: + type = gfx::TextureType::CUBE; + break; + default: + break; + } + passSet->bindTexture(bindID, defaultResource.getTexture(type)); + } + } + bindID += d.count; + } + break; + } + case DescriptorTypeOrder::SAMPLER: + for (const auto& d : block.descriptors) { + CC_EXPECTS(d.count == 1); + auto iter = user.samplers.find(d.descriptorID.value); + if (iter != user.samplers.end()) { + passSet->bindSampler(bindID, iter->second.get()); + } else { + gfx::SamplerInfo info{}; + auto* sampler = device->getSampler(info); + passSet->bindSampler(bindID, sampler); + } + bindID += d.count; + } + break; + case DescriptorTypeOrder::TEXTURE: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::STORAGE_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::DYNAMIC_STORAGE_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::STORAGE_IMAGE: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::INPUT_ATTACHMENT: + // not supported yet + CC_EXPECTS(false); + break; + default: + CC_EXPECTS(false); + break; + } + } + passSet->update(); + cmdBuff->bindDescriptorSet(static_cast(pipeline::SetIndex::GLOBAL), passSet); +} + +void updatePerPassDescriptorSet( + cc::gfx::CommandBuffer* cmdBuff, + const LayoutGraphData& lg, + const DescriptorSetData& set, + const RenderData& user, + LayoutGraphNodeResource& node) { + // update per pass resources + const auto& data = set.descriptorSetLayoutData; + + auto& prevSet = node.descriptorSetPool.getCurrentDescriptorSet(); + gfx::DescriptorSet* newSet = node.descriptorSetPool.allocateDescriptorSet(); + for (const auto& block : data.descriptorBlocks) { + CC_EXPECTS(block.descriptors.size() == block.capacity); + auto bindID = block.offset; + switch (block.type) { + case DescriptorTypeOrder::UNIFORM_BUFFER: { + for (const auto& d : block.descriptors) { + // get uniform block + const auto& uniformBlock = data.uniformBlocks.at(d.descriptorID); + + auto& resource = node.uniformBuffers.at(d.descriptorID); + updateCpuUniformBuffer(lg, user, uniformBlock, false, resource.cpuBuffer); + + // upload gfx buffer + uploadUniformBuffer(newSet, bindID, resource); + + // increase slot + // TODO(zhouzhenglong): here binding will be refactored in the future + // current implementation is incorrect, and we assume d.count == 1 + CC_EXPECTS(d.count == 1); + bindID += d.count; + } + break; + } + case DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::SAMPLER_TEXTURE: { + CC_EXPECTS(newSet); + for (const auto& d : block.descriptors) { + CC_EXPECTS(d.count == 1); + CC_EXPECTS(d.type >= gfx::Type::SAMPLER1D && + d.type <= gfx::Type::SAMPLER_CUBE); + auto iter = user.textures.find(d.descriptorID.value); + if (iter != user.textures.end()) { + newSet->bindTexture(bindID, iter->second.get()); + } else { + auto* prevTexture = prevSet.getTexture(bindID); + CC_ENSURES(prevTexture); + newSet->bindTexture(bindID, prevTexture); + } + bindID += d.count; + } + break; + } + case DescriptorTypeOrder::SAMPLER: + for (const auto& d : block.descriptors) { + CC_EXPECTS(d.count == 1); + auto iter = user.samplers.find(d.descriptorID.value); + if (iter != user.samplers.end()) { + newSet->bindSampler(bindID, iter->second.get()); + } else { + auto* prevSampler = prevSet.getSampler(bindID); + CC_ENSURES(prevSampler); + newSet->bindSampler(bindID, prevSampler); + } + bindID += d.count; + } + break; + case DescriptorTypeOrder::TEXTURE: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::STORAGE_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::DYNAMIC_STORAGE_BUFFER: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::STORAGE_IMAGE: + // not supported yet + CC_EXPECTS(false); + break; + case DescriptorTypeOrder::INPUT_ATTACHMENT: + // not supported yet + CC_EXPECTS(false); + break; + default: + CC_EXPECTS(false); + break; + } + } + newSet->update(); + cmdBuff->bindDescriptorSet(static_cast(pipeline::SetIndex::GLOBAL), newSet); +} + +void updateCameraUniformBufferAndDescriptorSet( + RenderGraphVisitorContext& ctx, RenderGraph::vertex_descriptor sceneID) { + // update states + CC_EXPECTS(ctx.currentPassLayoutID != LayoutGraphData::null_vertex()); + const auto& passLayoutID = ctx.currentPassLayoutID; + auto& layout = get(LayoutGraphData::Layout, ctx.lg, passLayoutID); + auto iter = layout.descriptorSets.find(UpdateFrequency::PER_PASS); + if (iter != layout.descriptorSets.end()) { + auto& set = iter->second; + auto& node = ctx.context.layoutGraphResources.at(passLayoutID); + const auto& user = get(RenderGraph::Data, ctx.g, sceneID); // notice: sceneID + updatePerPassDescriptorSet(ctx.cmdBuff, ctx.lg, set, user, node); + } +} + struct RenderGraphVisitor : boost::dfs_visitor<> { void submitBarriers(const std::vector& barriers) const { - const auto& resg = ctx.resourceGraph; + auto& resg = ctx.resourceGraph; auto sz = barriers.size(); ccstd::pmr::vector buffers(ctx.scratch); ccstd::pmr::vector bufferBarriers(ctx.scratch); @@ -477,15 +844,25 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { textureBarriers.data(), textures.data(), static_cast(textureBarriers.size())); } void frontBarriers(RenderGraph::vertex_descriptor vertID) const { - auto iter = ctx.barrierMap.find(vertID + 1); - if (iter != ctx.barrierMap.end()) { - submitBarriers(iter->second.blockBarrier.frontBarriers); + auto iter = ctx.fgd.resourceAccessGraph.passIndex.find(vertID); + if (iter == ctx.fgd.resourceAccessGraph.passIndex.end()) { + return; + } + const auto& nodeID = iter->second; + auto iter2 = ctx.barrierMap.find(nodeID); + if (iter2 != ctx.barrierMap.end()) { + submitBarriers(iter2->second.blockBarrier.frontBarriers); } } void rearBarriers(RenderGraph::vertex_descriptor vertID) const { - auto iter = ctx.barrierMap.find(vertID + 1); - if (iter != ctx.barrierMap.end()) { - submitBarriers(iter->second.blockBarrier.rearBarriers); + auto iter = ctx.fgd.resourceAccessGraph.passIndex.find(vertID); + if (iter == ctx.fgd.resourceAccessGraph.passIndex.end()) { + return; + } + const auto& nodeID = iter->second; + auto iter2 = ctx.barrierMap.find(nodeID); + if (iter2 != ctx.barrierMap.end()) { + submitBarriers(iter2->second.blockBarrier.rearBarriers); } } void begin(const RasterPass& pass, RenderGraph::vertex_descriptor vertID) const { @@ -499,16 +876,12 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { gfx::Rect scissor{0, 0, vp.width, vp.height}; // render pass + const auto& layoutName = get(RenderGraph::Layout, ctx.g, vertID); + const auto& layoutID = locate(LayoutGraphData::null_vertex(), layoutName, ctx.lg); { - auto iter = ctx.context.renderPasses.find(pass); - if (iter == ctx.context.renderPasses.end()) { - bool added = false; - std::tie(iter, added) = ctx.context.renderPasses.emplace( - pass, createPersistentRenderPassAndFramebuffer(ctx, pass)); - CC_ENSURES(added); - } - ++iter->second.refCount; - const auto& data = iter->second; + auto& res = fetchOrCreateFramebuffer(ctx, pass, ctx.scratch); + ++res.refCount; + const auto& data = res; auto* cmdBuff = ctx.cmdBuff; cmdBuff->beginRenderPass( @@ -518,76 +891,42 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { data.clearDepth, data.clearStencil); ctx.currentPass = data.renderPass.get(); + ctx.currentPassLayoutID = layoutID; + } + + // get layout + auto& layout = get(LayoutGraphData::Layout, ctx.lg, layoutID); + + // build pass resources + PmrFlatMap resourceIndex(ctx.scratch); + resourceIndex.reserve(pass.computeViews.size() * 2); + for (const auto& [resName, computeViews] : pass.computeViews) { + const auto resID = vertex(resName, ctx.resourceGraph); + for (const auto& computeView : computeViews) { + const auto& name = computeView.name; + CC_EXPECTS(!name.empty()); + const auto nameID = ctx.lg.attributeIndex.at(name); + resourceIndex.emplace(nameID, resID); + } } // update states - const auto& layoutName = get(RenderGraph::Layout, ctx.g, vertID); - const auto& layoutID = locate(LayoutGraphData::null_vertex(), layoutName, ctx.lg); - auto& layout = get(LayoutGraphData::Layout, ctx.lg, layoutID); auto iter = layout.descriptorSets.find(UpdateFrequency::PER_PASS); if (iter == layout.descriptorSets.end()) { return; } - - auto* passDescriptorSet = getOrCreatePerPassDescriptorSet( - ctx.device, ctx.lg, layoutID); - CC_ENSURES(passDescriptorSet); - auto& descriptorSet = *passDescriptorSet; - auto& set = iter->second; const auto& user = get(RenderGraph::Data, ctx.g, vertID); - const auto& data = set.descriptorSetLayoutData; - - for (const auto& block : data.descriptorBlocks) { - CC_EXPECTS(block.descriptors.size() == block.capacity); - auto bindID = block.offset; - switch (block.type) { - case DescriptorTypeOrder::UNIFORM_BUFFER: { - for (const auto& d : block.descriptors) { - const auto& uniformBlock = data.uniformBlocks.at(d.descriptorID); - } - - // auto* buffer = descriptorSet.getBuffer(bindID); - // if (!buffer) { - // gfx::BufferInfo info{ - // gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST, - // gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, - // static_cast(value.size()), - // static_cast(value.size())}; - // buffer = device.createBuffer(info); - // haveBuff = false; - // } - break; - } - case DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER: - break; - case DescriptorTypeOrder::SAMPLER_TEXTURE: - break; - case DescriptorTypeOrder::SAMPLER: - break; - case DescriptorTypeOrder::TEXTURE: - break; - case DescriptorTypeOrder::STORAGE_BUFFER: - break; - case DescriptorTypeOrder::DYNAMIC_STORAGE_BUFFER: - break; - case DescriptorTypeOrder::STORAGE_IMAGE: - break; - case DescriptorTypeOrder::INPUT_ATTACHMENT: - break; - } - } - - // passDescriptorSet->bindBuffer(); - - // cmdBuff->bindDescriptorSet( - // static_cast(pipeline::SetIndex::GLOBAL), passDescriptorSet); - - // auto offset = ctx.ppl->getPipelineUBO()->getCurrentCameraUBOOffset(); - // cmdBuff->bindDescriptorSet(pipeline::globalSet, ctx.getDescriptorSet(), 1, &offset); + auto& node = ctx.context.layoutGraphResources.at(layoutID); + initPerPassDescriptorSet( + ctx.resourceGraph, + ctx.device, ctx.cmdBuff, + *ctx.context.defaultResource, ctx.lg, + resourceIndex, set, user, node); } - void begin(const ComputePass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const ComputePass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; for (const auto& [name, views] : pass.computeViews) { for (const auto& view : views) { if (view.clearFlags != gfx::ClearFlags::NONE) { @@ -596,35 +935,42 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } } } - void begin(const CopyPass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const CopyPass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; for (const auto& copy : pass.copyPairs) { } } - void begin(const MovePass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const MovePass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; // if fully optimized, move pass should have been removed from graph // here we just do copy for (const auto& copy : pass.movePairs) { } } - void begin(const PresentPass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const PresentPass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; for (const auto& [name, present] : pass.presents) { // do presents } } - void begin(const RaytracePass& pass) const { // NOLINT(readability-convert-member-functions-to-static) + void begin(const RaytracePass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; + std::ignore = vertID; // not implemented yet CC_EXPECTS(false); } - void begin(const RenderQueue& pass) const { + void begin(const RenderQueue& pass, RenderGraph::vertex_descriptor vertID) const { // update uniform buffers and descriptor sets } - void begin(const SceneData& sceneData) const { - return; + void begin(const SceneData& sceneData, RenderGraph::vertex_descriptor sceneID) const { auto* camera = sceneData.camera; + CC_EXPECTS(camera); + if (camera) { // update camera data + updateCameraUniformBufferAndDescriptorSet(ctx, sceneID); + } const auto* scene = camera->getScene(); const auto& queues = ctx.sceneQueues.at(scene); const auto& queue = queues.at(camera); @@ -635,39 +981,134 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { bDrawInstancing = true; } if (any(sceneData.flags & (SceneFlags::OPAQUE_OBJECT | SceneFlags::CUTOUT_OBJECT))) { - if (bDraw) { - queue.opaqueQueue.recordCommandBuffer( - ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); - } + queue.opaqueQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); if (bDrawInstancing) { queue.opaqueInstancingQueue.recordCommandBuffer( ctx.currentPass, ctx.cmdBuff); } } if (any(sceneData.flags & SceneFlags::TRANSPARENT_OBJECT)) { - if (bDraw) { - queue.transparentQueue.recordCommandBuffer( - ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); - } + queue.transparentQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); if (bDrawInstancing) { queue.transparentInstancingQueue.recordCommandBuffer( ctx.currentPass, ctx.cmdBuff); } } } - void begin(const Blit& pass) const { + void begin(const Blit& blit, RenderGraph::vertex_descriptor vertID) const { + const auto& programLib = *dynamic_cast(ctx.programLib); + CC_EXPECTS(blit.material); + CC_EXPECTS(blit.material->getPasses()); + if (blit.camera) { + updateCameraUniformBufferAndDescriptorSet(ctx, vertID); + } + // get pass + auto& pass = *blit.material->getPasses()->at(static_cast(blit.passID)); + // get shader + auto& shader = *pass.getShaderVariant(); + // get pso + auto* pso = pipeline::PipelineStateManager::getOrCreatePipelineState( + &pass, &shader, ctx.context.fullscreenQuad.quadIA.get(), ctx.currentPass); + if (!pso) { + return; + } + // update material ubo and descriptor set + pass.update(); + + // get or create program per-instance descriptor set + auto& node = ctx.context.layoutGraphResources.at(vertID); + auto iter = node.programResources.find(std::string_view{shader.getName()}); + if (iter == node.programResources.end()) { + // make program resource + auto res = node.programResources.emplace( + std::piecewise_construct, + std::forward_as_tuple(shader.getName()), + std::forward_as_tuple()); + CC_ENSURES(res.second); + iter = res.first; + auto& instance = res.first->second; + + // make per-instance layout + IntrusivePtr instanceSetLayout = + &const_cast( + ctx.programLib->getLocalDescriptorSetLayout( + ctx.device, pass.getPhaseID(), shader.getName())); + + // init per-instance descriptor set pool + instance.descriptorSetPool.init(ctx.device, std::move(instanceSetLayout)); + + for (const auto& block : shader.getBlocks()) { + if (static_cast(block.set) != pipeline::SetIndex::LOCAL) { + continue; + } + const auto& name = block.name; + auto iter = ctx.lg.attributeIndex.find(std::string_view{name}); + CC_EXPECTS(iter != ctx.lg.attributeIndex.end()); + const auto attrID = iter->second; + auto sz = getUniformBlockSize(block.members); + const auto bDynamic = isDynamicUniformBlock(block.name); + instance.uniformBuffers[attrID].init(ctx.device, sz, bDynamic); + } + } + + // update per-instance buffer and descriptor set + const auto& data = programLib.localLayoutData; + auto& instance = iter->second; + auto* set = instance.descriptorSetPool.allocateDescriptorSet(); + CC_ENSURES(set); + for (const auto& block : shader.getBlocks()) { + if (static_cast(block.set) != pipeline::SetIndex::LOCAL) { + continue; + } + // find descriptor name ID + const auto& name = block.name; + auto iter = ctx.lg.attributeIndex.find(std::string_view{name}); + CC_EXPECTS(iter != ctx.lg.attributeIndex.end()); + const auto attrID = iter->second; + + // get uniformBuffer + auto& uniformBuffer = instance.uniformBuffers[attrID]; + CC_EXPECTS(uniformBuffer.cpuBuffer.size() == uniformBuffer.bufferPool.bufferSize); + + // fill cpu buffer + auto& cpuData = uniformBuffer.cpuBuffer; + if (false) { // NOLINT(readability-simplify-boolean-expr) + for (const auto& v : block.members) { + CC_LOG_INFO(v.name.c_str()); + } + } + + // create and upload buffer + auto* buffer = uniformBuffer.createFromCpuBuffer(); + + // set buffer descriptor + const auto binding = data.bindingMap.at(attrID); + set->bindBuffer(binding, buffer); + } + + // execution + ctx.cmdBuff->bindPipelineState(pso); + ctx.cmdBuff->bindDescriptorSet( + static_cast(pipeline::SetIndex::MATERIAL), pass.getDescriptorSet()); + ctx.cmdBuff->bindDescriptorSet( + static_cast(pipeline::SetIndex::LOCAL), set); + ctx.cmdBuff->bindInputAssembler(ctx.context.fullscreenQuad.quadIA.get()); + ctx.cmdBuff->draw(ctx.context.fullscreenQuad.quadIA.get()); } - void begin(const Dispatch& pass) const { + void begin(const Dispatch& pass, RenderGraph::vertex_descriptor vertID) const { } - void begin(const ccstd::pmr::vector& pass) const { + void begin(const ccstd::pmr::vector& pass, RenderGraph::vertex_descriptor vertID) const { } - void begin(const gfx::Viewport& pass) const { + void begin(const gfx::Viewport& pass, RenderGraph::vertex_descriptor vertID) const { } void end(const RasterPass& pass) const { std::ignore = pass; auto* cmdBuff = ctx.cmdBuff; cmdBuff->endRenderPass(); ctx.currentPass = nullptr; + ctx.currentPassLayoutID = LayoutGraphData::null_vertex(); } void end(const ComputePass& pass) const { } @@ -761,29 +1202,29 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { [&](const ComputePass& pass) { mountResources(pass); frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const CopyPass& pass) { mountResources(pass); frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const MovePass& pass) { mountResources(pass); frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const PresentPass& pass) { frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const RaytracePass& pass) { mountResources(pass); frontBarriers(vertID); - begin(pass); + begin(pass, vertID); }, [&](const auto& queue) { - begin(queue); + begin(queue, vertID); }); } @@ -1094,11 +1535,12 @@ void extendResourceLifetime(const NativeRenderQueue& queue, ResourceGroup& group } void buildRenderQueues( + const pipeline::PipelineSceneData& sceneData, NativeRenderContext& context, ccstd::pmr::unordered_map< const scene::RenderScene*, ccstd::pmr::unordered_map>& sceneQueues) { - const scene::Skybox* skyBox = nullptr; + const scene::Skybox* skybox = sceneData.getSkybox(); auto& group = context.resourceGroups[context.nextFenceValue]; @@ -1109,8 +1551,25 @@ void buildRenderQueues( if (!camera->isCullingEnabled()) { continue; } + + // skybox + if (skybox && skybox->isEnabled() && + (static_cast(camera->getClearFlag()) & scene::Camera::SKYBOX_FLAG)) { + CC_EXPECTS(skybox->getModel()); + const auto& model = *skybox->getModel(); + const auto* node = model.getNode(); + float depth = 0; + if (node) { + Vec3 tempVec3{}; + tempVec3 = node->getWorldPosition() - camera->getPosition(); + depth = tempVec3.dot(camera->getForward()); + } + queue.opaqueQueue.add(model, depth, 0, 0); + } + + // culling if (octree && octree->isEnabled()) { - octreeCulling(octree, scene, skyBox, *camera, queue); + octreeCulling(octree, scene, skybox, *camera, queue); } else { frustumCulling(scene, *camera, queue); } @@ -1128,14 +1587,13 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { auto& ppl = *this; auto* scratch = &ppl.unsyncPool; - auto& lg = dynamic_cast(getProgramLibrary())->layoutGraph; - RenderGraphContextCleaner contextCleaner(ppl.nativeContext); ResourceCleaner cleaner(ppl.resourceGraph); + auto& lg = ppl.programLibrary->layoutGraph; FrameGraphDispatcher fgd( ppl.resourceGraph, rg, - ppl.layoutGraph, &ppl.unsyncPool, scratch); + lg, &ppl.unsyncPool, scratch); fgd.enableMemoryAliasing(false); fgd.enablePassReorder(false); fgd.setParalellWeight(0); @@ -1147,10 +1605,11 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { { // Mark all culled vertices RenderGraphCullVisitor visitor{{}, validPasses}; for (const auto& vertID : fgd.resourceAccessGraph.culledPasses) { - const auto passID = get(ResourceAccessGraph::PassID, fgd.resourceAccessGraph, vertID); - if (passID == RenderGraph::null_vertex()) { + const auto nodeID = get(ResourceAccessGraph::PassID, fgd.resourceAccessGraph, vertID); + if (nodeID == RenderGraph::null_vertex()) { continue; } + const auto passID = fgd.resourceAccessGraph.passIndex.at(nodeID); boost::depth_first_visit(graphView, passID, visitor, get(colors, rg)); } colors.clear(); @@ -1164,7 +1623,7 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { sceneQueues(scratch); { mergeSceneFlags(rg, sceneQueues); - buildRenderQueues(ppl.nativeContext, sceneQueues); + buildRenderQueues(*ppl.getPipelineSceneData(), ppl.nativeContext, sceneQueues); } // Execute all valid passes @@ -1193,6 +1652,7 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { ppl.device, submit.primaryCommandBuffer, sceneQueues, &ppl, + programLibrary, scratch}; RenderGraphVisitor visitor{{}, ctx}; diff --git a/native/cocos/renderer/pipeline/custom/NativeLayoutGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeLayoutGraph.cpp index cb650442d9..f79203c16f 100644 --- a/native/cocos/renderer/pipeline/custom/NativeLayoutGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeLayoutGraph.cpp @@ -266,66 +266,7 @@ ccstd::string getName(gfx::ShaderStageFlagBit stage) { } // namespace ccstd::string NativeLayoutGraphBuilder::print() const { - std::ostringstream oss; - boost::container::pmr::unsynchronized_pool_resource pool( - boost::container::pmr::get_default_resource()); - ccstd::pmr::string space(&pool); - - oss << "\n"; - - const auto &g = *data; - for (const auto v : makeRange(vertices(g))) { - if (parent(v, g) != LayoutGraphData::null_vertex()) { - continue; - } - const auto &name = get(LayoutGraphData::Name, g, v); - OSS << "\"" << name << "\": "; - - visit( - [&](auto tag) { - oss << getName(tag); - }, - tag(v, g)); - - oss << " {\n"; - INDENT_BEG(); - const auto &info = get(LayoutGraphData::Layout, g, v); - for (const auto &set : info.descriptorSets) { - OSS << "Set<" << getName(set.first) << "> {\n"; - { - INDENT(); - for (const auto &block : set.second.descriptorSetLayoutData.descriptorBlocks) { - OSS << "Block<" << getName(block.type) << ", " << getName(block.visibility) << "> {\n"; - { - INDENT(); - OSS << "capacity: " << block.capacity << ",\n"; - OSS << "count: " << block.descriptors.size() << ",\n"; - if (!block.descriptors.empty()) { - OSS << "Descriptors{ "; - int count = 0; - for (const auto &d : block.descriptors) { - if (count++) { - oss << ", "; - } - const auto &name = g.valueNames.at(d.descriptorID.value); - oss << "\"" << name; - if (d.count != 1) { - oss << "[" << d.count << "]"; - } - oss << "\""; - } - oss << " }\n"; - } - } - OSS << "}\n"; - } - } - OSS << "}\n"; - } - INDENT_END(); - OSS << "}\n"; - } - return oss.str(); + return {}; } } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index 00a7fc84fd..c3803a7b69 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -23,37 +23,39 @@ ****************************************************************************/ #include -#include #include -#include -#include -#include -#include #include "LayoutGraphFwd.h" #include "LayoutGraphGraphs.h" #include "LayoutGraphNames.h" #include "LayoutGraphTypes.h" +#include "LayoutGraphUtils.h" #include "NativePipelineFwd.h" #include "NativePipelineTypes.h" +#include "NativeUtils.h" #include "RenderCommonTypes.h" #include "RenderGraphGraphs.h" #include "RenderGraphTypes.h" #include "RenderInterfaceFwd.h" #include "RenderInterfaceTypes.h" +#include "RenderingModule.h" +#include "cocos/application/ApplicationManager.h" #include "cocos/base/Macros.h" #include "cocos/base/Ptr.h" #include "cocos/base/StringUtil.h" #include "cocos/base/std/container/string.h" +#include "cocos/core/Root.h" #include "cocos/math/Mat4.h" #include "cocos/renderer/gfx-base/GFXBuffer.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" #include "cocos/renderer/gfx-base/GFXDevice.h" +#include "cocos/renderer/gfx-base/GFXInputAssembler.h" #include "cocos/renderer/gfx-base/GFXSwapchain.h" #include "cocos/renderer/gfx-base/states/GFXSampler.h" #include "cocos/renderer/pipeline/Enum.h" #include "cocos/renderer/pipeline/GlobalDescriptorSetManager.h" #include "cocos/renderer/pipeline/PipelineSceneData.h" +#include "cocos/renderer/pipeline/PipelineStateManager.h" #include "cocos/renderer/pipeline/RenderPipeline.h" #include "cocos/scene/RenderScene.h" #include "cocos/scene/RenderWindow.h" @@ -76,11 +78,15 @@ SceneTask *NativeSceneTransversal::transverse(SceneVisitor *visitor) const { NativePipeline::NativePipeline(const allocator_type &alloc) noexcept : device(gfx::Device::getInstance()), globalDSManager(std::make_unique()), - layoutGraph(alloc), + programLibrary(dynamic_cast(getProgramLibrary())), pipelineSceneData(ccnew pipeline::PipelineSceneData()), // NOLINT - nativeContext(alloc), + nativeContext(std::make_unique(device), alloc), + dummyLayoutGraph(alloc), resourceGraph(alloc), - renderGraph(alloc) {} + renderGraph(alloc), + name(alloc) { + programLibrary->setPipeline(this); +} gfx::Device *NativePipeline::getDevice() const { return device; @@ -128,6 +134,9 @@ uint32_t NativePipeline::addRenderTexture(const ccstd::string &name, gfx::Format CC_ASSERT(renderWindow->getFramebuffer()->getColorTextures().size() == 1); CC_ASSERT(renderWindow->getFramebuffer()->getColorTextures().at(0)); + + desc.format = renderWindow->getFramebuffer()->getColorTextures()[0]->getFormat(); + return addVertex( SwapchainTag{}, std::forward_as_tuple(name.c_str()), @@ -219,11 +228,27 @@ void NativePipeline::updateRenderWindow(const ccstd::string &name, scene::Render void NativePipeline::updateRenderTarget( const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) { // NOLINT(bugprone-easily-swappable-parameters) + auto resID = findVertex(ccstd::pmr::string(name, get_allocator()), resourceGraph); + if (resID == ResourceGraph::null_vertex()) { + return; + } + auto &desc = get(ResourceGraph::Desc, resourceGraph, resID); + visitObject( + resID, resourceGraph, + [&](ManagedTexture & /*tex*/) { + desc.width = width; + desc.height = height; + if (format != gfx::Format::UNKNOWN) { + desc.format = format; + } + }, + [](const auto & /*res*/) {}); } void NativePipeline::updateDepthStencil( const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) { // NOLINT(bugprone-easily-swappable-parameters) + updateRenderTarget(name, width, height, format); } void NativePipeline::beginFrame() { @@ -232,6 +257,66 @@ void NativePipeline::beginFrame() { void NativePipeline::endFrame() { } +namespace { + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters) +void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter) { + const auto &root = *Root::getInstance(); + const auto shadingWidth = static_cast(width); + const auto shadingHeight = static_cast(height); + setter.setVec4( + "cc_time", + Vec4( + root.getCumulativeTime(), + root.getFrameTime(), + static_cast(CC_CURRENT_ENGINE()->getTotalFrames()), + 0.0F)); + + setter.setVec4( + "cc_screenSize", + Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); + setter.setVec4( + "cc_nativeSize", + Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); + const auto *debugView = root.getDebugView(); + if (debugView) { + setter.setVec4( + "cc_debug_view_mode", + Vec4(static_cast(debugView->getSingleMode()), + debugView->isLightingWithAlbedo() ? 1.0F : 0.0F, + debugView->isCsmLayerColoration() ? 1.0F : 0.0F, + 0.0F)); + Vec4 debugPackVec{}; + for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); + i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + const auto idx = i % 4; + (&debugPackVec.x)[idx] = debugView->isCompositeModeEnabled(i) ? 1.0F : 0.0F; + const auto packIdx = static_cast(floor(static_cast(i) / 4.0F)); + if (idx == 3) { + std::string name("cc_debug_view_composite_pack_"); + name.append(std::to_string(packIdx + 1)); + setter.setVec4(name, debugPackVec); + } + } + } else { + setter.setVec4("cc_debug_view_mode", Vec4(0.0F, 1.0F, 0.0F, 0.0F)); + Vec4 debugPackVec{}; + for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); + i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + const auto idx = i % 4; + (&debugPackVec.x)[idx] = 1.0F; + const auto packIdx = static_cast(floor(i / 4.0)); + if (idx == 3) { + std::string name("cc_debug_view_composite_pack_"); + name.append(std::to_string(packIdx + 1)); + setter.setVec4(name, debugPackVec); + } + } + } +} + +} // namespace + RasterPassBuilder *NativePipeline::addRasterPass( uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) const ccstd::string &layoutName) { @@ -251,10 +336,13 @@ RasterPassBuilder *NativePipeline::addRasterPass( std::forward_as_tuple(std::move(pass)), renderGraph); - auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, layoutGraph); + auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, programLibrary->layoutGraph); CC_EXPECTS(passLayoutID != LayoutGraphData::null_vertex()); - return ccnew NativeRasterPassBuilder(&renderGraph, passID, &layoutGraph, passLayoutID); + auto *builder = ccnew NativeRasterPassBuilder(this, &renderGraph, passID, &programLibrary->layoutGraph, passLayoutID); + updateRasterPassConstants(width, height, *builder); + + return builder; } // NOLINTNEXTLINE @@ -269,9 +357,9 @@ ComputePassBuilder *NativePipeline::addComputePass(const ccstd::string &layoutNa std::forward_as_tuple(), renderGraph); - auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, layoutGraph); + auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, programLibrary->layoutGraph); - return ccnew NativeComputePassBuilder(&renderGraph, passID, &layoutGraph, passLayoutID); + return ccnew NativeComputePassBuilder(&renderGraph, passID, &programLibrary->layoutGraph, passLayoutID); } // NOLINTNEXTLINE @@ -336,13 +424,14 @@ SceneTransversal *NativePipeline::createSceneTransversal(const scene::Camera *ca } LayoutGraphBuilder *NativePipeline::getLayoutGraphBuilder() { - return ccnew NativeLayoutGraphBuilder(device, &layoutGraph); + return ccnew NativeLayoutGraphBuilder(device, &dummyLayoutGraph); } gfx::DescriptorSetLayout *NativePipeline::getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) { - auto iter = layoutGraph.shaderLayoutIndex.find(std::string_view{shaderName}); - if (iter != layoutGraph.shaderLayoutIndex.end()) { - const auto &layouts = get(LayoutGraphData::Layout, layoutGraph, iter->second).descriptorSets; + const auto &lg = programLibrary->layoutGraph; + auto iter = lg.shaderLayoutIndex.find(std::string_view{shaderName}); + if (iter != lg.shaderLayoutIndex.end()) { + const auto &layouts = get(LayoutGraphData::Layout, lg, iter->second).descriptorSets; auto iter2 = layouts.find(freq); if (iter2 != layouts.end()) { return iter2->second.descriptorSetLayout.get(); @@ -363,33 +452,33 @@ const ccstd::vector &NativePipeline::getCommandBuffers() c namespace { -void generateConstantMacros( +void buildLayoutGraphNodeBuffer( gfx::Device *device, - ccstd::string &constantMacros, bool clusterEnabled) { - constantMacros = StringUtil::format( - R"( -#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE %d -#define CC_ENABLE_CLUSTERED_LIGHT_CULLING %d -#define CC_DEVICE_MAX_VERTEX_UNIFORM_VECTORS %d -#define CC_DEVICE_MAX_FRAGMENT_UNIFORM_VECTORS %d -#define CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT %d -#define CC_PLATFORM_ANDROID_AND_WEBGL 0 -#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES 0 - )", - hasAnyFlags(device->getFormatFeatures(gfx::Format::RGBA32F), - gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE), - clusterEnabled ? 1 : 0, - device->getCapabilities().maxVertexUniformVectors, - device->getCapabilities().maxFragmentUniformVectors, - device->hasFeature(gfx::Feature::INPUT_ATTACHMENT_BENEFIT)); + const DescriptorSetLayoutData &data, + LayoutGraphNodeResource &node) { + for (const auto &[nameID, uniformBlock] : data.uniformBlocks) { + auto res = node.uniformBuffers.emplace( + std::piecewise_construct, + std::forward_as_tuple(nameID), + std::forward_as_tuple()); + CC_ENSURES(res.second); + auto &buffer = res.first->second; + CC_EXPECTS(uniformBlock.count); + const auto bufferSize = + getUniformBlockSize(uniformBlock.members) * uniformBlock.count; + + CC_ENSURES(bufferSize); + buffer.init(device, bufferSize, false); + } } } // namespace // NOLINTNEXTLINE bool NativePipeline::activate(gfx::Swapchain *swapchainIn) { + // setMacroInt("CC_PIPELINE_TYPE", 1); + swapchain = swapchainIn; - macros["CC_PIPELINE_TYPE"] = 0; globalDSManager->activate(device); pipelineSceneData->activate(device); #if CC_USE_DEBUG_RENDERER @@ -401,6 +490,101 @@ bool NativePipeline::activate(gfx::Swapchain *swapchainIn) { generateConstantMacros(device, constantMacros, false); _commandBuffers.resize(1, device->getCommandBuffer()); + + // reserve layout graph resource + const auto &lg = programLibrary->layoutGraph; + const auto numNodes = num_vertices(lg); + nativeContext.layoutGraphResources.reserve(numNodes); + + for (uint32_t i = 0; i != numNodes; ++i) { + auto &node = nativeContext.layoutGraphResources.emplace_back(); + const auto &layout = get(LayoutGraphData::Layout, lg, i); + if (holds(i, lg)) { + auto iter = layout.descriptorSets.find(UpdateFrequency::PER_PASS); + if (iter == layout.descriptorSets.end()) { + continue; + } + const auto &set = iter->second; + // reserve buffer + buildLayoutGraphNodeBuffer(device, set.descriptorSetLayoutData, node); + // reserve descriptor sets + node.descriptorSetPool.init(device, set.descriptorSetLayout); + } else { + auto iter = layout.descriptorSets.find(UpdateFrequency::PER_PHASE); + if (iter == layout.descriptorSets.end()) { + continue; + } + const auto &set = iter->second; + // reserve buffer + buildLayoutGraphNodeBuffer(device, set.descriptorSetLayoutData, node); + // reserve descriptor sets + node.descriptorSetPool.init(device, set.descriptorSetLayout); + } + } + + // create ia + { + CC_EXPECTS(device); + // create vertex buffer + const auto vbStride = sizeof(float) * 4; // 4 float per vertex + const auto vbSize = vbStride * 4; // 4 vertices + IntrusivePtr quadVB = device->createBuffer(gfx::BufferInfo{ + gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::DEVICE | gfx::MemoryUsageBit::HOST, + vbSize, + vbStride}); + + CC_ENSURES(quadVB); + + // update vertex buffer + float vbData[16] = {}; + render::setupQuadVertexBuffer(*device, Vec4{0, 0, 1, 1}, vbData); + static_assert(sizeof(vbData) == 16 * 4); + CC_ENSURES(sizeof(vbData) == vbSize); + quadVB->update(vbData, sizeof(vbData)); + + // create index buffer + const auto ibStride = sizeof(uint16_t); + const auto ibSize = ibStride * 6; + + IntrusivePtr quadIB = device->createBuffer(gfx::BufferInfo{ + gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::DEVICE, + ibSize, + ibStride}); + + CC_ENSURES(quadIB); + + ccstd::vector indices(6); + indices[0] = 0; + indices[1] = 1; + indices[2] = 2; + indices[3] = 1; + indices[4] = 3; + indices[5] = 2; + + quadIB->update(indices.data(), + static_cast(indices.size() * sizeof(decltype(indices)::value_type))); + + // create input assembler + ccstd::vector attributes; + attributes.reserve(2); + attributes.emplace_back(gfx::Attribute{"a_position", gfx::Format::RG32F}); + attributes.emplace_back(gfx::Attribute{"a_texCoord", gfx::Format::RG32F}); + + ccstd::vector buffers; + buffers.emplace_back(quadVB.get()); + + IntrusivePtr quadIA = device->createInputAssembler( + gfx::InputAssemblerInfo{attributes, buffers, quadIB}); + CC_ENSURES(quadIA); + + // init fullscreenQuad + nativeContext.fullscreenQuad.quadIB = quadIB; + nativeContext.fullscreenQuad.quadVB = quadVB; + nativeContext.fullscreenQuad.quadIA = quadIA; + } + return true; } @@ -413,7 +597,7 @@ bool NativePipeline::destroy() noexcept { pipelineSceneData->destroy(); pipelineSceneData = {}; } - + pipeline::PipelineStateManager::destroyAll(); return true; } diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h index b3fa31c8aa..49625d1170 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h @@ -54,11 +54,18 @@ struct NativeRenderQueue; class DefaultSceneVisitor; class DefaultForwardLightingTransversal; struct ResourceGroup; +struct BufferPool; +struct DescriptorSetPool; +struct UniformBlockResource; +struct ProgramResource; +struct LayoutGraphNodeResource; +struct QuadResource; struct NativeRenderContext; +class NativeProgramLibrary; class NativePipeline; class NativeProgramProxy; -class NativeProgramLibrary; class NativeRenderingModule; +class NativeSetter; } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp index 20afedbea8..9b5c8486bf 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp @@ -43,7 +43,8 @@ PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(Persisten clearColors(std::move(rhs.clearColors), alloc), clearDepth(rhs.clearDepth), clearStencil(rhs.clearStencil), - refCount(rhs.refCount) {} + refCount(rhs.refCount), + hash(rhs.hash) {} PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(PersistentRenderPassAndFramebuffer const& rhs, const allocator_type& alloc) : renderPass(rhs.renderPass), @@ -51,7 +52,8 @@ PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(Persisten clearColors(rhs.clearColors, alloc), clearDepth(rhs.clearDepth), clearStencil(rhs.clearStencil), - refCount(rhs.refCount) {} + refCount(rhs.refCount), + hash(rhs.hash) {} RenderInstancingQueue::RenderInstancingQueue(const allocator_type& alloc) noexcept : batches(alloc), @@ -103,13 +105,82 @@ DefaultForwardLightingTransversal::DefaultForwardLightingTransversal(const alloc ResourceGroup::ResourceGroup(const allocator_type& alloc) noexcept : instancingBuffers(alloc) {} -NativeRenderContext::NativeRenderContext(const allocator_type& alloc) noexcept -: renderPasses(alloc), - resourceGroups(alloc) {} +BufferPool::BufferPool(const allocator_type& alloc) noexcept +: currentBuffers(alloc), + currentBufferViews(alloc), + freeBuffers(alloc), + freeBufferViews(alloc) {} + +BufferPool::BufferPool(gfx::Device* deviceIn, uint32_t bufferSizeIn, bool dynamicIn, const allocator_type& alloc) noexcept // NOLINT +: device(deviceIn), + bufferSize(bufferSizeIn), + dynamic(dynamicIn), + currentBuffers(alloc), + currentBufferViews(alloc), + freeBuffers(alloc), + freeBufferViews(alloc) {} + +BufferPool::BufferPool(BufferPool&& rhs, const allocator_type& alloc) +: device(rhs.device), + bufferSize(rhs.bufferSize), + dynamic(rhs.dynamic), + currentBuffers(std::move(rhs.currentBuffers), alloc), + currentBufferViews(std::move(rhs.currentBufferViews), alloc), + freeBuffers(std::move(rhs.freeBuffers), alloc), + freeBufferViews(std::move(rhs.freeBufferViews), alloc) {} + +DescriptorSetPool::DescriptorSetPool(const allocator_type& alloc) noexcept +: currentDescriptorSets(alloc), + freeDescriptorSets(alloc) {} + +DescriptorSetPool::DescriptorSetPool(gfx::Device* deviceIn, IntrusivePtr setLayoutIn, const allocator_type& alloc) noexcept // NOLINT +: device(deviceIn), + setLayout(std::move(setLayoutIn)), + currentDescriptorSets(alloc), + freeDescriptorSets(alloc) {} + +DescriptorSetPool::DescriptorSetPool(DescriptorSetPool&& rhs, const allocator_type& alloc) +: device(rhs.device), + setLayout(std::move(rhs.setLayout)), + currentDescriptorSets(std::move(rhs.currentDescriptorSets), alloc), + freeDescriptorSets(std::move(rhs.freeDescriptorSets), alloc) {} + +UniformBlockResource::UniformBlockResource(const allocator_type& alloc) noexcept +: cpuBuffer(alloc), + bufferPool(alloc) {} + +UniformBlockResource::UniformBlockResource(UniformBlockResource&& rhs, const allocator_type& alloc) +: cpuBuffer(std::move(rhs.cpuBuffer), alloc), + bufferPool(std::move(rhs.bufferPool), alloc) {} + +ProgramResource::ProgramResource(const allocator_type& alloc) noexcept +: uniformBuffers(alloc), + descriptorSetPool(alloc) {} + +ProgramResource::ProgramResource(ProgramResource&& rhs, const allocator_type& alloc) +: uniformBuffers(std::move(rhs.uniformBuffers), alloc), + descriptorSetPool(std::move(rhs.descriptorSetPool), alloc) {} + +LayoutGraphNodeResource::LayoutGraphNodeResource(const allocator_type& alloc) noexcept +: uniformBuffers(alloc), + descriptorSetPool(alloc), + programResources(alloc) {} + +LayoutGraphNodeResource::LayoutGraphNodeResource(LayoutGraphNodeResource&& rhs, const allocator_type& alloc) +: uniformBuffers(std::move(rhs.uniformBuffers), alloc), + descriptorSetPool(std::move(rhs.descriptorSetPool), alloc), + programResources(std::move(rhs.programResources), alloc) {} + +NativeRenderContext::NativeRenderContext(std::unique_ptr defaultResourceIn, const allocator_type& alloc) noexcept +: defaultResource(std::move(defaultResourceIn)), + renderPasses(alloc), + resourceGroups(alloc), + layoutGraphResources(alloc) {} NativeProgramLibrary::NativeProgramLibrary(const allocator_type& alloc) noexcept : layoutGraph(alloc), - phases(alloc) {} + phases(alloc), + localLayoutData(alloc) {} } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index 05449f73b8..4cf3501855 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -70,8 +70,9 @@ public: class NativeRasterQueueBuilder final : public RasterQueueBuilder { public: NativeRasterQueueBuilder() = default; - NativeRasterQueueBuilder(RenderGraph* renderGraphIn, uint32_t queueIDIn, const LayoutGraphData* layoutGraphIn) noexcept - : renderGraph(renderGraphIn), + NativeRasterQueueBuilder(const PipelineRuntime* pipelineRuntimeIn, RenderGraph* renderGraphIn, uint32_t queueIDIn, const LayoutGraphData* layoutGraphIn) noexcept + : pipelineRuntime(pipelineRuntimeIn), + renderGraph(renderGraphIn), layoutGraph(layoutGraphIn), queueID(queueIDIn) {} @@ -97,6 +98,7 @@ public: void clearRenderTarget(const ccstd::string &name, const gfx::Color &color) override; void setViewport(const gfx::Viewport &viewport) override; + const PipelineRuntime* pipelineRuntime{nullptr}; RenderGraph* renderGraph{nullptr}; const LayoutGraphData* layoutGraph{nullptr}; uint32_t queueID{RenderGraph::null_vertex()}; @@ -105,8 +107,9 @@ public: class NativeRasterPassBuilder final : public RasterPassBuilder { public: NativeRasterPassBuilder() = default; - NativeRasterPassBuilder(RenderGraph* renderGraphIn, uint32_t passIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn) noexcept // NOLINT - : renderGraph(renderGraphIn), + NativeRasterPassBuilder(const PipelineRuntime* pipelineRuntimeIn, RenderGraph* renderGraphIn, uint32_t passIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn) noexcept // NOLINT + : pipelineRuntime(pipelineRuntimeIn), + renderGraph(renderGraphIn), layoutGraph(layoutGraphIn), passID(passIDIn), layoutID(layoutIDIn) {} @@ -132,6 +135,7 @@ public: void setViewport(const gfx::Viewport &viewport) override; void setVersion(const ccstd::string &name, uint64_t version) override; + const PipelineRuntime* pipelineRuntime{nullptr}; RenderGraph* renderGraph{nullptr}; const LayoutGraphData* layoutGraph{nullptr}; uint32_t passID{RenderGraph::null_vertex()}; @@ -267,6 +271,7 @@ struct PersistentRenderPassAndFramebuffer { float clearDepth{0}; uint8_t clearStencil{0}; int32_t refCount{1}; + uint32_t hash{0}; }; struct RenderInstancingQueue { @@ -405,13 +410,137 @@ struct ResourceGroup { PmrUnorderedSet> instancingBuffers; }; +struct BufferPool { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {currentBuffers.get_allocator().resource()}; + } + + BufferPool(const allocator_type& alloc) noexcept; // NOLINT + BufferPool(gfx::Device* deviceIn, uint32_t bufferSizeIn, bool dynamicIn, const allocator_type& alloc) noexcept; + BufferPool(BufferPool&& rhs, const allocator_type& alloc); + + BufferPool(BufferPool&& rhs) noexcept = default; + BufferPool(BufferPool const& rhs) = delete; + BufferPool& operator=(BufferPool&& rhs) = default; + BufferPool& operator=(BufferPool const& rhs) = delete; + void init(gfx::Device* deviceIn, uint32_t sz, bool bDynamic); + void syncResources(); + gfx::Buffer* allocateBuffer(); + + gfx::Device* device{nullptr}; + uint32_t bufferSize{0}; + bool dynamic{false}; + ccstd::pmr::vector> currentBuffers; + ccstd::pmr::vector> currentBufferViews; + ccstd::pmr::vector> freeBuffers; + ccstd::pmr::vector> freeBufferViews; +}; + +struct DescriptorSetPool { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {currentDescriptorSets.get_allocator().resource()}; + } + + DescriptorSetPool(const allocator_type& alloc) noexcept; // NOLINT + DescriptorSetPool(gfx::Device* deviceIn, IntrusivePtr setLayoutIn, const allocator_type& alloc) noexcept; + DescriptorSetPool(DescriptorSetPool&& rhs, const allocator_type& alloc); + + DescriptorSetPool(DescriptorSetPool&& rhs) noexcept = default; + DescriptorSetPool(DescriptorSetPool const& rhs) = delete; + DescriptorSetPool& operator=(DescriptorSetPool&& rhs) = default; + DescriptorSetPool& operator=(DescriptorSetPool const& rhs) = delete; + void init(gfx::Device* deviceIn, IntrusivePtr layout); + void syncDescriptorSets(); + const gfx::DescriptorSet& getCurrentDescriptorSet() const; + gfx::DescriptorSet& getCurrentDescriptorSet(); + gfx::DescriptorSet* allocateDescriptorSet(); + + gfx::Device* device{nullptr}; + IntrusivePtr setLayout; + ccstd::pmr::vector> currentDescriptorSets; + ccstd::pmr::vector> freeDescriptorSets; +}; + +struct UniformBlockResource { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {cpuBuffer.get_allocator().resource()}; + } + + UniformBlockResource(const allocator_type& alloc) noexcept; // NOLINT + UniformBlockResource(UniformBlockResource&& rhs, const allocator_type& alloc); + + UniformBlockResource(UniformBlockResource&& rhs) noexcept = default; + UniformBlockResource(UniformBlockResource const& rhs) = delete; + UniformBlockResource& operator=(UniformBlockResource&& rhs) = default; + UniformBlockResource& operator=(UniformBlockResource const& rhs) = delete; + void init(gfx::Device* deviceIn, uint32_t sz, bool bDynamic); + gfx::Buffer* createFromCpuBuffer(); + + ccstd::pmr::vector cpuBuffer; + BufferPool bufferPool; +}; + +struct ProgramResource { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {uniformBuffers.get_allocator().resource()}; + } + + ProgramResource(const allocator_type& alloc) noexcept; // NOLINT + ProgramResource(ProgramResource&& rhs, const allocator_type& alloc); + + ProgramResource(ProgramResource&& rhs) noexcept = default; + ProgramResource(ProgramResource const& rhs) = delete; + ProgramResource& operator=(ProgramResource&& rhs) = default; + ProgramResource& operator=(ProgramResource const& rhs) = delete; + void syncResources() noexcept; + + ccstd::pmr::unordered_map uniformBuffers; + DescriptorSetPool descriptorSetPool; +}; + +struct LayoutGraphNodeResource { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {uniformBuffers.get_allocator().resource()}; + } + + LayoutGraphNodeResource(const allocator_type& alloc) noexcept; // NOLINT + LayoutGraphNodeResource(LayoutGraphNodeResource&& rhs, const allocator_type& alloc); + + LayoutGraphNodeResource(LayoutGraphNodeResource&& rhs) noexcept = default; + LayoutGraphNodeResource(LayoutGraphNodeResource const& rhs) = delete; + LayoutGraphNodeResource& operator=(LayoutGraphNodeResource&& rhs) = default; + LayoutGraphNodeResource& operator=(LayoutGraphNodeResource const& rhs) = delete; + void syncResources() noexcept; + + PmrFlatMap uniformBuffers; + DescriptorSetPool descriptorSetPool; + PmrTransparentMap programResources; +}; + +struct QuadResource { + QuadResource() = default; + QuadResource(IntrusivePtr quadVBIn, IntrusivePtr quadIBIn, IntrusivePtr quadIAIn) noexcept // NOLINT + : quadVB(std::move(quadVBIn)), + quadIB(std::move(quadIBIn)), + quadIA(std::move(quadIAIn)) {} + + IntrusivePtr quadVB; + IntrusivePtr quadIB; + IntrusivePtr quadIA; +}; + struct NativeRenderContext { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT return {renderPasses.get_allocator().resource()}; } - NativeRenderContext(const allocator_type& alloc) noexcept; // NOLINT + NativeRenderContext(std::unique_ptr defaultResourceIn, const allocator_type& alloc) noexcept; NativeRenderContext(NativeRenderContext&& rhs) = delete; NativeRenderContext(NativeRenderContext const& rhs) = delete; NativeRenderContext& operator=(NativeRenderContext&& rhs) = delete; @@ -419,16 +548,60 @@ struct NativeRenderContext { void clearPreviousResources(uint64_t finishedFenceValue) noexcept; + std::unique_ptr defaultResource; ccstd::pmr::unordered_map renderPasses; ccstd::pmr::map resourceGroups; + ccstd::pmr::vector layoutGraphResources; + QuadResource fullscreenQuad; uint64_t nextFenceValue{0}; }; +class NativeProgramLibrary final : public ProgramLibrary { +public: + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {layoutGraph.get_allocator().resource()}; + } + + NativeProgramLibrary(const allocator_type& alloc) noexcept; // NOLINT + + void addEffect(const EffectAsset *effectAsset) override; + void precompileEffect(gfx::Device *device, EffectAsset *effectAsset) override; + ccstd::string getKey(uint32_t phaseID, const ccstd::string &programName, const MacroRecord &defines) const override; + IntrusivePtr getPipelineLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) override; + const gfx::DescriptorSetLayout &getMaterialDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) override; + const gfx::DescriptorSetLayout &getLocalDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) override; + const IProgramInfo &getProgramInfo(uint32_t phaseID, const ccstd::string &programName) const override; + const gfx::ShaderInfo &getShaderInfo(uint32_t phaseID, const ccstd::string &programName) const override; + ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, MacroRecord &defines, const ccstd::pmr::string *key) override; + const ccstd::vector &getBlockSizes(uint32_t phaseID, const ccstd::string &programName) const override; + const Record &getHandleMap(uint32_t phaseID, const ccstd::string &programName) const override; + uint32_t getProgramID(uint32_t phaseID, const ccstd::pmr::string &programName) override; + uint32_t getDescriptorNameID(const ccstd::pmr::string &name) override; + const ccstd::pmr::string &getDescriptorName(uint32_t nameID) override; + + void init(gfx::Device* deviceIn); + void setPipeline(PipelineRuntime* pipelineIn); + void destroy(); + + LayoutGraphData layoutGraph; + PmrFlatMap phases; + boost::container::pmr::unsynchronized_pool_resource unsycPool; + bool mergeHighFrequency{false}; + bool fixedLocal{true}; + DescriptorSetLayoutData localLayoutData; + IntrusivePtr localDescriptorSetLayout; + IntrusivePtr emptyDescriptorSetLayout; + IntrusivePtr emptyPipelineLayout; + PipelineRuntime* pipeline{nullptr}; + gfx::Device* device{nullptr}; +}; + class NativePipeline final : public Pipeline { public: using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT - return {nativeContext.get_allocator().resource()}; + return {name.get_allocator().resource()}; } NativePipeline(const allocator_type& alloc) noexcept; // NOLINT @@ -493,11 +666,13 @@ public: MacroRecord macros; ccstd::string constantMacros; std::unique_ptr globalDSManager; + ccstd::pmr::string name; + NativeProgramLibrary* programLibrary; scene::Model* profiler{nullptr}; LightingMode lightingMode{LightingMode::DEFAULT}; IntrusivePtr pipelineSceneData; NativeRenderContext nativeContext; - LayoutGraphData layoutGraph; + LayoutGraphData dummyLayoutGraph; ResourceGraph resourceGraph; RenderGraph renderGraph; }; @@ -514,43 +689,6 @@ public: IntrusivePtr shader; }; -class NativeProgramLibrary final : public ProgramLibrary { -public: - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {layoutGraph.get_allocator().resource()}; - } - - NativeProgramLibrary(const allocator_type& alloc) noexcept; // NOLINT - - void addEffect(const EffectAsset *effectAsset) override; - void precompileEffect(gfx::Device *device, EffectAsset *effectAsset) override; - ccstd::string getKey(uint32_t phaseID, const ccstd::string &programName, const MacroRecord &defines) const override; - IntrusivePtr getPipelineLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) override; - const gfx::DescriptorSetLayout &getMaterialDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) override; - const gfx::DescriptorSetLayout &getLocalDescriptorSetLayout(gfx::Device *device, uint32_t phaseID, const ccstd::string &programName) override; - const IProgramInfo &getProgramInfo(uint32_t phaseID, const ccstd::string &programName) const override; - const gfx::ShaderInfo &getShaderInfo(uint32_t phaseID, const ccstd::string &programName) const override; - ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, MacroRecord &defines, const ccstd::pmr::string *key) override; - const ccstd::vector &getBlockSizes(uint32_t phaseID, const ccstd::string &programName) const override; - const Record &getHandleMap(uint32_t phaseID, const ccstd::string &programName) const override; - uint32_t getProgramID(uint32_t phaseID, const ccstd::pmr::string &programName) override; - uint32_t getDescriptorNameID(const ccstd::pmr::string &name) override; - const ccstd::pmr::string &getDescriptorName(uint32_t nameID) override; - - void init(gfx::Device* device); - void destroy(); - - LayoutGraphData layoutGraph; - PmrFlatMap phases; - boost::container::pmr::unsynchronized_pool_resource unsycPool; - bool mergeHighFrequency{false}; - bool fixedLocal{true}; - IntrusivePtr emptyDescriptorSetLayout; - IntrusivePtr emptyPipelineLayout; - PipelineRuntime* pipeline{nullptr}; -}; - class NativeRenderingModule final : public RenderingModule { public: NativeRenderingModule() = default; @@ -563,6 +701,37 @@ public: std::shared_ptr programLibrary; }; +class NativeSetter final : public Setter { +public: + NativeSetter(const LayoutGraphData& layoutGraphIn, RenderData& renderDataIn) noexcept + : layoutGraph(layoutGraphIn), + renderData(renderDataIn) {} + + ccstd::string getName() const override; + void setName(const ccstd::string &name) override; + + void setMat4(const ccstd::string &name, const Mat4 &mat) override; + void setQuaternion(const ccstd::string &name, const Quaternion &quat) override; + void setColor(const ccstd::string &name, const gfx::Color &color) override; + void setVec4(const ccstd::string &name, const Vec4 &vec) override; + void setVec2(const ccstd::string &name, const Vec2 &vec) override; + void setFloat(const ccstd::string &name, float v) override; + void setBuffer(const ccstd::string &name, gfx::Buffer *buffer) override; + void setTexture(const ccstd::string &name, gfx::Texture *texture) override; + void setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) override; + void setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) override; + void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override; + + void setVec4ArraySize(const ccstd::string& name, uint32_t sz); + void setVec4ArrayElem(const ccstd::string& name, const cc::Vec4& vec, uint32_t id); + + void setMat4ArraySize(const ccstd::string& name, uint32_t sz); + void setMat4ArrayElem(const ccstd::string& name, const cc::Mat4& mat, uint32_t id); + + const LayoutGraphData& layoutGraph; + RenderData& renderData; +}; + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativePools.cpp b/native/cocos/renderer/pipeline/custom/NativePools.cpp new file mode 100644 index 0000000000..f8de04f386 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativePools.cpp @@ -0,0 +1,149 @@ +#include "NativePipelineTypes.h" +#include "details/GslUtils.h" + +namespace cc { + +namespace render { + +void BufferPool::init(gfx::Device* deviceIn, uint32_t sz, bool bDynamic) { + CC_EXPECTS(deviceIn); + CC_EXPECTS(sz); + CC_EXPECTS(!device); + CC_EXPECTS(bufferSize == 0); + + device = deviceIn; + bufferSize = sz; + dynamic = bDynamic; +} + +void BufferPool::syncResources() { + for (auto& buffer : currentBuffers) { + freeBuffers.emplace_back(std::move(buffer)); + } + currentBuffers.clear(); + + for (auto& bufferView : currentBufferViews) { + freeBufferViews.emplace_back(std::move(bufferView)); + } + currentBufferViews.clear(); +} + +gfx::Buffer* BufferPool::allocateBuffer() { + CC_EXPECTS(device); + CC_EXPECTS(bufferSize); + + gfx::Buffer* ptr = nullptr; + + if (freeBuffers.empty()) { + { + gfx::BufferInfo info{ + gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST, + gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, + bufferSize, + bufferSize}; + freeBuffers.emplace_back(device->createBuffer(info)); + } + + if (dynamic) { + gfx::BufferViewInfo info{ + freeBuffers.back().get(), + 0, bufferSize}; + freeBufferViews.emplace_back(device->createBuffer(info)); + } + } + { + CC_ENSURES(!freeBuffers.empty()); + auto& buffer = freeBuffers.back(); + ptr = buffer.get(); + CC_EXPECTS(buffer->getSize() == bufferSize); + currentBuffers.emplace_back(std::move(buffer)); + freeBuffers.pop_back(); + } + if (dynamic) { + CC_ENSURES(!freeBufferViews.empty()); + auto& bufferView = freeBufferViews.back(); + ptr = bufferView.get(); + CC_EXPECTS(bufferView->getSize() == bufferSize); + currentBufferViews.emplace_back(std::move(bufferView)); + freeBufferViews.pop_back(); + } + CC_ENSURES(ptr); + if (dynamic) { + CC_ENSURES(ptr->isBufferView()); + } else { + CC_ENSURES(!ptr->isBufferView()); + } + return ptr; +} + +void UniformBlockResource::init(gfx::Device* deviceIn, uint32_t sz, bool bDynamic) { + CC_EXPECTS(cpuBuffer.empty()); + cpuBuffer.resize(sz); + bufferPool.init(deviceIn, sz, bDynamic); +} + +gfx::Buffer* UniformBlockResource::createFromCpuBuffer() { + CC_EXPECTS(cpuBuffer.size() == bufferPool.bufferSize); + auto* bufferOrView = bufferPool.allocateBuffer(); + if (bufferPool.dynamic) { + auto* buffer = bufferPool.currentBuffers.back().get(); + buffer->update(cpuBuffer.data(), static_cast(cpuBuffer.size())); + } else { + bufferOrView->update(cpuBuffer.data(), static_cast(cpuBuffer.size())); + } + return bufferOrView; +} + +void DescriptorSetPool::init(gfx::Device* deviceIn, + IntrusivePtr layout) { + CC_EXPECTS(deviceIn); + CC_EXPECTS(layout); + CC_EXPECTS(!device); + CC_EXPECTS(!setLayout); + device = deviceIn; + setLayout = std::move(layout); +} + +void DescriptorSetPool::syncDescriptorSets() { + for (auto& set : currentDescriptorSets) { + freeDescriptorSets.emplace_back(std::move(set)); + } + currentDescriptorSets.clear(); +} + +gfx::DescriptorSet& DescriptorSetPool::getCurrentDescriptorSet() { + CC_EXPECTS(!currentDescriptorSets.empty()); + return *currentDescriptorSets.back(); +} + +const gfx::DescriptorSet& DescriptorSetPool::getCurrentDescriptorSet() const { + CC_EXPECTS(!currentDescriptorSets.empty()); + return *currentDescriptorSets.back(); +} + +gfx::DescriptorSet* DescriptorSetPool::allocateDescriptorSet() { + CC_EXPECTS(device); + CC_EXPECTS(setLayout); + + gfx::DescriptorSet* ptr = nullptr; + + if (freeDescriptorSets.empty()) { + freeDescriptorSets.emplace_back( + device->createDescriptorSet(gfx::DescriptorSetInfo{setLayout.get()})); + } + + { + CC_ENSURES(!freeDescriptorSets.empty()); + auto& set = freeDescriptorSets.back(); + ptr = set.get(); + CC_EXPECTS(set->getLayout() == setLayout); + currentDescriptorSets.emplace_back(std::move(set)); + freeDescriptorSets.pop_back(); + } + CC_ENSURES(ptr); + return ptr; +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp b/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp index 0af2cd0a67..dc77017df1 100644 --- a/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp @@ -23,7 +23,10 @@ THE SOFTWARE. ****************************************************************************/ +#include +#include #include +#include #include #include #include @@ -128,51 +131,59 @@ IProgramInfo makeProgramInfo(const ccstd::string &effectName, const IShaderInfo return programInfo; } -std::tuple getDescriptorNameAndType( - const pipeline::DescriptorSetLayoutInfos &source, - uint32_t binding) { +ccstd::pmr::vector> getDescriptorNameAndType( + const pipeline::DescriptorSetLayoutInfos &source, uint32_t binding, + boost::container::pmr::memory_resource *scratch) { + ccstd::pmr::vector> results(scratch); + for (const auto &[name, block] : source.blocks) { if (block.binding == binding) { - return {name, gfx::Type::UNKNOWN}; + results.emplace_back(std::tuple{name, gfx::Type::UNKNOWN}); } } for (const auto &[name, texture] : source.samplers) { if (texture.binding == binding) { - return {name, texture.type}; + results.emplace_back(std::tuple{name, texture.type}); } } for (const auto &[name, image] : source.storeImages) { if (image.binding == binding) { - return {name, image.type}; + results.emplace_back(std::tuple{name, image.type}); } } - return {"", gfx::Type::UNKNOWN}; + return results; } void makeLocalDescriptorSetLayoutData( LayoutGraphData &lg, const pipeline::DescriptorSetLayoutInfos &source, - DescriptorSetLayoutData &data) { + DescriptorSetLayoutData &data, + boost::container::pmr::memory_resource *scratch) { for (const auto &b : source.bindings) { - const auto [name, type] = getDescriptorNameAndType(source, b.binding); - const auto nameID = getOrCreateDescriptorID(lg, name); - const auto order = getDescriptorTypeOrder(b.descriptorType); + const auto &descriptors = getDescriptorNameAndType(source, b.binding, scratch); + CC_ENSURES(!descriptors.empty()); { + const auto &[name, type] = descriptors.front(); + const auto nameID = getOrCreateDescriptorID(lg, name); + const auto order = getDescriptorTypeOrder(b.descriptorType); auto &block = data.descriptorBlocks.emplace_back(order, b.stageFlags, b.count); block.offset = b.binding; block.descriptors.emplace_back(nameID, type, b.count); } - { - auto iter = data.bindingMap.find(nameID); - if (iter != data.bindingMap.end()) { - CC_LOG_ERROR("Duplicate descriptor name: %s", name.data()); + for (const auto &[name, type] : descriptors) { + const auto nameID = getOrCreateDescriptorID(lg, name); + { + auto iter = data.bindingMap.find(nameID); + if (iter != data.bindingMap.end()) { + CC_LOG_ERROR("Duplicate descriptor name: %s", name.data()); + } + data.bindingMap.emplace(nameID, b.binding); } - data.bindingMap.emplace(nameID, b.binding); - } - { - auto iter = source.blocks.find(ccstd::string(name)); - if (iter != source.blocks.end()) { - data.uniformBlocks.emplace(nameID, iter->second); + { + auto iter = source.blocks.find(ccstd::string(name)); + if (iter != source.blocks.end()) { + data.uniformBlocks.emplace(nameID, iter->second); + } } } } @@ -218,7 +229,7 @@ ShaderProgramData &buildProgramData( CC_ENSURES(res.second); auto &setData = res.first->second; auto &perInstance = setData.descriptorSetLayoutData; - makeLocalDescriptorSetLayoutData(lg, pipeline::localDescriptorSetLayout, perInstance); + makeLocalDescriptorSetLayoutData(lg, pipeline::localDescriptorSetLayout, perInstance, scratch); initializeDescriptorSetLayoutInfo( setData.descriptorSetLayoutData, setData.descriptorSetLayoutInfo); @@ -272,7 +283,7 @@ void populateMergedShaderInfo( continue; } const auto &uniformBlock = iter->second; - blockSizes.emplace_back(getSize(uniformBlock.members)); + blockSizes.emplace_back(getUniformBlockSize(uniformBlock.members)); shaderInfo.blocks.emplace_back( gfx::UniformBlock{ set, @@ -388,7 +399,7 @@ void populateGroupedShaderInfo( if (block.stageFlags != visibility) { continue; } - blockSizes.emplace_back(getSize(block.members)); + blockSizes.emplace_back(getUniformBlockSize(block.members)); shaderInfo.blocks.emplace_back( gfx::UniformBlock{ set, @@ -507,7 +518,7 @@ void populateLocalShaderInfo( const IDescriptorInfo &target, const pipeline::DescriptorSetLayoutInfos &source, gfx::ShaderInfo &shaderInfo, ccstd::vector &blockSizes) { - const auto set = setIndex(UpdateFrequency::PER_INSTANCE); + constexpr auto set = setIndex(UpdateFrequency::PER_INSTANCE); for (const auto &block : target.blocks) { auto blockIter = source.blocks.find(block.name); if (blockIter == source.blocks.end()) { @@ -527,7 +538,7 @@ void populateLocalShaderInfo( } const auto &binding = *pBinding; - blockSizes.emplace_back(getSize(block.members)); + blockSizes.emplace_back(getUniformBlockSize(block.members)); shaderInfo.blocks.emplace_back( gfx::UniformBlock{ set, @@ -787,9 +798,176 @@ void makeShaderInfo( shaderInfo.stages.emplace_back(gfx::ShaderStage{gfx::ShaderStageFlagBit::FRAGMENT, ""}); } +std::pair findBinding( + const gfx::ShaderInfo &shaderInfo, std::string_view name) { + for (const auto &v : shaderInfo.blocks) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.buffers) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.samplerTextures) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.samplers) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.textures) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + for (const auto &v : shaderInfo.images) { + if (v.name == name) { + return std::pair{v.set, v.binding}; + } + } + CC_EXPECTS(false); + return {}; +} + +void overwriteShaderSourceBinding( + const gfx::ShaderInfo &shaderInfo, + ccstd::string &source, + boost::container::pmr::memory_resource *scratch) { + // find first uniform + auto pos = source.find(" uniform "); + while (pos != ccstd::string::npos) { + // uniform statement is separated by ";{}"; + auto beg = source.find_last_of(";}", pos); + auto end = source.find_first_of(";{", pos); + if (beg == ccstd::string::npos) { + // if separator is not found, start from 0 + beg = 0; + } else { + // bypass last separator + beg += 1; + } + // uniform declaration is found + CC_EXPECTS(beg != ccstd::string::npos); + CC_EXPECTS(end != ccstd::string::npos); + CC_ENSURES(end > beg); + + // find uniform name + std::string_view name{}; + { + std::string_view decl(source.c_str() + beg, end - beg); + auto nameEnd = decl.size(); + for (; nameEnd-- > 0;) { + if (!std::isspace(decl[nameEnd])) { + break; + } + } + auto nameBeg = decl.find_last_of(' ', nameEnd); + nameBeg += 1; + nameEnd += 1; + // uniform name found + name = decl.substr(nameBeg, nameEnd - nameBeg); + } + CC_ENSURES(!name.empty()); + + // layout + std::ptrdiff_t offset = 0; + { + std::string_view prevLayout; + // find layout expression + auto layoutBeg = source.rfind("layout", pos); + auto layoutEnd = ccstd::string::npos; + if (layoutBeg == ccstd::string::npos || layoutBeg < beg) { + // layout not found + layoutBeg = ccstd::string::npos; + CC_ENSURES(layoutBeg == ccstd::string::npos); + CC_ENSURES(layoutEnd == ccstd::string::npos); + } else { + CC_EXPECTS(layoutBeg >= beg && layoutBeg <= end); + layoutEnd = source.find(')', layoutBeg) + 1; + CC_EXPECTS(layoutEnd != ccstd::string::npos); + CC_ENSURES(layoutBeg < layoutEnd && layoutEnd <= end); + prevLayout = std::string_view(source.c_str() + layoutBeg, layoutEnd - layoutBeg); + + // check layout expression is within uniform declaration + // prev layout expression is from layoutBeg to layoutEnd + CC_ENSURES(layoutBeg >= beg && layoutBeg <= end); + CC_ENSURES(layoutEnd >= layoutBeg && layoutEnd <= end); + } + + // find uniform set and binding + auto [set, binding] = findBinding(shaderInfo, name); + + // compose new layout expression + ccstd::pmr::string newLayout(scratch); + newLayout.reserve(32); + newLayout.append("layout(set = "); + newLayout.append(std::to_string(set)); + newLayout.append(", binding = "); + newLayout.append(std::to_string(binding)); + newLayout.append(")"); + + // replace layout expression + if (layoutBeg == ccstd::string::npos) { // layout not found + source.insert(pos, newLayout); + offset = static_cast(newLayout.size()); + } else { + // layout is found + source.erase(layoutBeg, prevLayout.size()); + source.insert(layoutBeg, newLayout); + // calculate string difference + offset = static_cast(newLayout.size()) - + static_cast(prevLayout.size()); + } + } + // offset end of uniform declaration, offset is caused by modification of layout + end += offset; + // find next uniform + pos = source.find(" uniform ", end); + auto exceptionPos = source.find(" uniform subpassInput ", end); + if (exceptionPos != ccstd::string::npos) { + while (pos == exceptionPos) { + end += strlen(" uniform subpassInput "); + pos = source.find(" uniform ", end); + exceptionPos = source.find(" uniform subpassInput ", end); + } + } + } +} + +void overwriteShaderProgramBinding( + gfx::Device *device, + const gfx::ShaderInfo &shaderInfo, IProgramInfo &programInfo, + boost::container::pmr::memory_resource *scratch) { + // get shader source to use + IShaderSource *src = &programInfo.glsl3; + const auto *deviceShaderVersion = getDeviceShaderVersion(device); + if (deviceShaderVersion) { + if (deviceShaderVersion != std::string_view{"glsl4"}) { + return; + } + src = programInfo.getSource(deviceShaderVersion); + } else { + CC_LOG_ERROR("Invalid GFX API!"); + } + CC_ENSURES(src); + + overwriteShaderSourceBinding(shaderInfo, src->vert, scratch); + overwriteShaderSourceBinding(shaderInfo, src->frag, scratch); +} + // overwrite IProgramInfo using gfx.ShaderInfo -void overwriteProgramBlockInfo(const gfx::ShaderInfo &shaderInfo, IProgramInfo &programInfo) { - const auto set = setIndex(UpdateFrequency::PER_BATCH); +void overwriteProgramBlockInfo( + gfx::Device *device, + const gfx::ShaderInfo &shaderInfo, IProgramInfo &programInfo, + boost::container::pmr::memory_resource *scratch) { + overwriteShaderProgramBinding(device, shaderInfo, programInfo, scratch); + + constexpr auto set = setIndex(UpdateFrequency::PER_BATCH); for (auto &block : programInfo.blocks) { auto found = false; for (const auto &src : shaderInfo.blocks) { @@ -944,9 +1122,23 @@ void populatePipelineLayoutInfo( } // namespace -void NativeProgramLibrary::init(gfx::Device *device) { +void NativeProgramLibrary::init(gfx::Device *deviceIn) { + boost::container::pmr::memory_resource *scratch = &unsycPool; + device = deviceIn; emptyDescriptorSetLayout = device->createDescriptorSetLayout({}); emptyPipelineLayout = device->createPipelineLayout({}); + + if (false) { // NOLINT(readability-simplify-boolean-expr) + std::ostringstream oss; + printLayoutGraphData(layoutGraph, oss, scratch); + auto content = oss.str(); + std::istringstream iss(content); + std::string line; + while (std::getline(iss, line)) { + CC_LOG_INFO(line.c_str()); + } + } + auto &lg = layoutGraph; for (const auto v : makeRange(vertices(lg))) { auto &layout = get(LayoutGraphData::Layout, lg, v); @@ -980,6 +1172,35 @@ void NativeProgramLibrary::init(gfx::Device *device) { auto &phase = get(RenderPhaseTag{}, phaseID, lg); phase.pipelineLayout = device->createPipelineLayout(info); } + + // init local descriptor set + { + const auto &localSetLayout = pipeline::localDescriptorSetLayout; + makeLocalDescriptorSetLayoutData(lg, localSetLayout, localLayoutData, scratch); + gfx::DescriptorSetLayoutInfo info{}; + initializeDescriptorSetLayoutInfo(localLayoutData, info); + localDescriptorSetLayout = device->createDescriptorSetLayout(info); + CC_ENSURES(localDescriptorSetLayout); + + uint32_t numUniformBuffers = 0; + for (const auto &block : localLayoutData.descriptorBlocks) { + if (block.type != DescriptorTypeOrder::UNIFORM_BUFFER && + block.type != DescriptorTypeOrder::DYNAMIC_UNIFORM_BUFFER) { + continue; + } + for (const auto &d : block.descriptors) { + numUniformBuffers += d.count; + } + } + CC_ENSURES(numUniformBuffers == 7); // 7 is currently max uniform binding + } + + // generate constant macros string + generateConstantMacros(device, lg.constantMacros, false); +} + +void NativeProgramLibrary::setPipeline(PipelineRuntime *pipelineIn) { + pipeline = pipelineIn; } void NativeProgramLibrary::destroy() { @@ -1037,7 +1258,7 @@ void NativeProgramLibrary::addEffect(const EffectAsset *effectAssetIn) { fixedLocal, shaderInfo, blockSizes); // overwrite programInfo - overwriteProgramBlockInfo(shaderInfo, programInfo); + overwriteProgramBlockInfo(device, shaderInfo, programInfo, scratch); // handle map auto handleMap = genHandles(shaderInfo); @@ -1160,6 +1381,9 @@ const gfx::DescriptorSetLayout &NativeProgramLibrary::getLocalDescriptorSetLayou return getOrCreateDescriptorSetLayout( *this, layoutGraph, passID, phaseID, UpdateFrequency::PER_INSTANCE); } + if (fixedLocal) { + return *localDescriptorSetLayout; + } return getOrCreateProgramDescriptorSetLayout( *this, device, layoutGraph, phaseID, programName, UpdateFrequency::PER_INSTANCE); } @@ -1232,9 +1456,7 @@ ProgramProxy *NativeProgramLibrary::getProgramVariant( } std::string prefix; - if (pipeline) { - prefix += pipeline->getConstantMacros(); - } + prefix += layoutGraph.constantMacros; prefix += programInfo.constantMacros + ss.str(); const IShaderSource *src = &programInfo.glsl3; diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp index 2ab06e9d6d..88a85181d2 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp @@ -28,18 +28,229 @@ #include "NativePipelineGraphs.h" #include "NativePipelineTypes.h" #include "RenderCommonNames.h" +#include "RenderCommonTypes.h" +#include "RenderGraphFwd.h" #include "RenderGraphGraphs.h" +#include "RenderGraphTypes.h" +#include "cocos/math/Utils.h" +#include "cocos/renderer/pipeline/Define.h" +#include "cocos/renderer/pipeline/PipelineUBO.h" +#include "cocos/scene/DirectionalLight.h" +#include "cocos/scene/Fog.h" +#include "cocos/scene/Skybox.h" +#include "cocos/scene/SpotLight.h" #include "details/DebugUtils.h" #include "details/GraphView.h" +#include "details/GslUtils.h" #include "gfx-base/GFXDef-common.h" -#include "pipeline/custom/RenderCommonTypes.h" -#include "pipeline/custom/RenderGraphFwd.h" -#include "pipeline/custom/RenderGraphTypes.h" +#include "gfx-base/GFXDevice.h" +#include "pipeline/PipelineSceneData.h" namespace cc { namespace render { +namespace { + +render::NameLocalID getNameID( + const PmrFlatMap &index, + std::string_view name) { + auto iter = index.find(name); + CC_EXPECTS(iter != index.end()); + return iter->second; +} + +void addMat4( + const LayoutGraphData &lg, std::string_view name, + const cc::Mat4 &v, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Mat4) == 16 * 4, "sizeof(Mat4) is not 64 bytes"); + data.constants[nameID.value].resize(sizeof(Mat4)); + memcpy(data.constants[nameID.value].data(), v.m, sizeof(v)); +} + +void setMat4ArrayElemImpl( + const LayoutGraphData &lg, std::string_view name, + const cc::Mat4 &v, uint32_t i, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Mat4) == 16 * 4, "sizeof(Mat4) is not 64 bytes"); + auto &dst = data.constants[nameID.value]; + CC_EXPECTS(sizeof(Mat4) * (i + 1) <= dst.size()); + memcpy(dst.data() + sizeof(Mat4) * i, v.m, sizeof(v)); +} + +void setMat4ArraySizeImpl( + const LayoutGraphData &lg, std::string_view name, + uint32_t sz, RenderData &data) { + CC_EXPECTS(sz); + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Mat4) == 16 * 4, "sizeof(Mat4) is not 64 bytes"); + data.constants[nameID.value].resize(sizeof(Mat4) * sz); +} + +void addQuaternion(const LayoutGraphData &lg, const ccstd::string &name, const Quaternion &quat, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Quaternion) == 4 * 4, "sizeof(Quaternion) is not 16 bytes"); + static_assert(std::is_trivially_copyable::value, "Quaternion is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(Quaternion)); + memcpy(data.constants[nameID.value].data(), &quat, sizeof(quat)); +} + +void addColor(const LayoutGraphData &lg, const ccstd::string &name, const gfx::Color &color, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(gfx::Color) == 4 * 4, "sizeof(Color) is not 16 bytes"); + static_assert(std::is_trivially_copyable::value, "Color is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(gfx::Color)); + memcpy(data.constants[nameID.value].data(), &color, sizeof(color)); +} + +void addVec4(const LayoutGraphData &lg, const ccstd::string &name, const Vec4 &vec, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Vec4) == 4 * 4, "sizeof(Vec4) is not 16 bytes"); + // static_assert(std::is_trivially_copyable::value, "Vec4 is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(Vec4)); + memcpy(data.constants[nameID.value].data(), &vec.x, sizeof(vec)); +} + +void setVec4ArrayElemImpl(const LayoutGraphData &lg, const ccstd::string &name, + const Vec4 &vec, uint32_t i, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Vec4) == 4 * 4, "sizeof(Vec4) is not 16 bytes"); + // static_assert(std::is_trivially_copyable::value, "Vec4 is not trivially copyable"); + auto &dst = data.constants[nameID.value]; + CC_EXPECTS(sizeof(Vec4) * (i + 1) <= dst.size()); + memcpy(dst.data() + sizeof(Vec4) * i, &vec.x, sizeof(vec)); +} + +void setVec4ArraySizeImpl(const LayoutGraphData &lg, const ccstd::string &name, + uint32_t sz, RenderData &data) { + CC_EXPECTS(sz); + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Vec4) == 4 * 4, "sizeof(Vec4) is not 16 bytes"); + // static_assert(std::is_trivially_copyable::value, "Vec4 is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(Vec4) * sz); +} + +void addVec2(const LayoutGraphData &lg, const ccstd::string &name, const Vec2 &vec, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(Vec2) == 2 * 4, "sizeof(Vec2) is not 8 bytes"); + // static_assert(std::is_trivially_copyable::value, "Vec2 is not trivially copyable"); + data.constants[nameID.value].resize(sizeof(Vec2)); + memcpy(data.constants[nameID.value].data(), &vec.x, sizeof(vec)); +} + +void addFloat(const LayoutGraphData &lg, const ccstd::string &name, float v, RenderData &data) { + auto nameID = getNameID(lg.constantIndex, name); + static_assert(sizeof(float) == 4, "sizeof(float) is not 4 bytes"); + data.constants[nameID.value].resize(sizeof(float)); + memcpy(data.constants[nameID.value].data(), &v, sizeof(v)); +} + +void addBuffer(const LayoutGraphData &lg, const ccstd::string &name, gfx::Buffer *buffer, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.buffers[nameID.value] = IntrusivePtr(buffer); +} + +void addTexture(const LayoutGraphData &lg, const ccstd::string &name, gfx::Texture *texture, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.textures[nameID.value] = IntrusivePtr(texture); +} + +void addReadWriteBuffer(const LayoutGraphData &lg, const ccstd::string &name, gfx::Buffer *buffer, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.buffers[nameID.value] = IntrusivePtr(buffer); +} + +void addReadWriteTexture(const LayoutGraphData &lg, const ccstd::string &name, gfx::Texture *texture, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.textures[nameID.value] = IntrusivePtr(texture); +} + +void addSampler(const LayoutGraphData &lg, const ccstd::string &name, gfx::Sampler *sampler, RenderData &data) { + auto nameID = getNameID(lg.attributeIndex, name); + data.samplers[nameID.value].ptr = sampler; +} + +} // namespace + +ccstd::string NativeSetter::getName() const { + return {}; +} +void NativeSetter::setName(const ccstd::string &name) { + // noop +} + +void NativeSetter::setMat4(const ccstd::string &name, const Mat4 &mat) { + auto &data = renderData; + addMat4(layoutGraph, name, mat, data); +} + +void NativeSetter::setQuaternion(const ccstd::string &name, const Quaternion &quat) { + auto &data = renderData; + addQuaternion(layoutGraph, name, quat, data); +} + +void NativeSetter::setColor(const ccstd::string &name, const gfx::Color &color) { + auto &data = renderData; + addColor(layoutGraph, name, color, data); +} + +void NativeSetter::setVec4(const ccstd::string &name, const Vec4 &vec) { + auto &data = renderData; + addVec4(layoutGraph, name, vec, data); +} + +void NativeSetter::setVec2(const ccstd::string &name, const Vec2 &vec) { + auto &data = renderData; + addVec2(layoutGraph, name, vec, data); +} + +void NativeSetter::setFloat(const ccstd::string &name, float v) { + auto &data = renderData; + addFloat(layoutGraph, name, v, data); +} + +void NativeSetter::setBuffer(const ccstd::string &name, gfx::Buffer *buffer) { + auto &data = renderData; + addBuffer(layoutGraph, name, buffer, data); +} + +void NativeSetter::setTexture(const ccstd::string &name, gfx::Texture *texture) { + auto &data = renderData; + addTexture(layoutGraph, name, texture, data); +} + +void NativeSetter::setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) { + auto &data = renderData; + addReadWriteBuffer(layoutGraph, name, buffer, data); +} + +void NativeSetter::setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) { + auto &data = renderData; + addReadWriteTexture(layoutGraph, name, texture, data); +} + +void NativeSetter::setSampler(const ccstd::string &name, gfx::Sampler *sampler) { + auto &data = renderData; + addSampler(layoutGraph, name, sampler, data); +} + +void NativeSetter::setVec4ArraySize(const ccstd::string &name, uint32_t sz) { + setVec4ArraySizeImpl(layoutGraph, name, sz, renderData); +} + +void NativeSetter::setVec4ArrayElem(const ccstd::string &name, const cc::Vec4 &vec, uint32_t id) { + setVec4ArrayElemImpl(layoutGraph, name, vec, id, renderData); +} + +void NativeSetter::setMat4ArraySize(const ccstd::string &name, uint32_t sz) { + setMat4ArraySizeImpl(layoutGraph, name, sz, renderData); +} + +void NativeSetter::setMat4ArrayElem(const ccstd::string &name, const cc::Mat4 &mat, uint32_t id) { + setMat4ArrayElemImpl(layoutGraph, name, mat, id, renderData); +} + ccstd::string NativeRasterPassBuilder::getName() const { return std::string(get(RenderGraph::Name, *renderGraph, passID)); } @@ -50,13 +261,18 @@ void NativeRasterPassBuilder::setName(const ccstd::string &name) { void NativeRasterPassBuilder::addRasterView(const ccstd::string &name, const RasterView &view) { auto &pass = get(RasterTag{}, passID, *renderGraph); - pass.rasterViews.emplace( + auto slotID = static_cast(pass.rasterViews.size()); + auto res = pass.rasterViews.emplace( std::piecewise_construct, std::forward_as_tuple(name.c_str()), std::forward_as_tuple(view)); + CC_ENSURES(res.second); + res.first->second.slotID = slotID; } void NativeRasterPassBuilder::addComputeView(const ccstd::string &name, const ComputeView &view) { + CC_EXPECTS(!name.empty()); + CC_EXPECTS(!view.name.empty()); auto &pass = get(RasterTag{}, passID, *renderGraph); auto iter = pass.computeViews.find(name.c_str()); if (iter == pass.computeViews.end()) { @@ -78,13 +294,386 @@ void NativeRasterQueueBuilder::setName(const ccstd::string &name) { get(RenderGraph::Name, *renderGraph, queueID) = std::string_view{name}; } -void NativeRasterQueueBuilder::addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) { +namespace { + +void setCameraUBOValues( + const scene::Camera &camera, + const pipeline::PipelineSceneData &cfg, + const scene::DirectionalLight *mainLight, + Setter &setter) { + CC_EXPECTS(camera.getNode()); + CC_EXPECTS(cfg.getSkybox()); + const auto &skybox = *cfg.getSkybox(); + const auto &shadingScale = cfg.getShadingScale(); + // Camera + setter.setMat4("cc_matView", camera.getMatView()); + setter.setMat4("cc_matViewInv", camera.getNode()->getWorldMatrix()); + setter.setMat4("cc_matProj", camera.getMatProj()); + setter.setMat4("cc_matProjInv", camera.getMatProjInv()); + setter.setMat4("cc_matViewProj", camera.getMatViewProj()); + setter.setMat4("cc_matViewProjInv", camera.getMatViewProjInv()); + setter.setVec4("cc_cameraPos", Vec4(camera.getPosition().x, + camera.getPosition().y, + camera.getPosition().z, + pipeline::PipelineUBO::getCombineSignY())); + setter.setVec4("cc_surfaceTransform", Vec4(static_cast(camera.getSurfaceTransform()), + 0.0F, + cosf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))), + sinf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))))); + setter.setVec4("cc_screenScale", Vec4(cfg.getShadingScale(), + cfg.getShadingScale(), + 1.0F / cfg.getShadingScale(), + 1.0F / cfg.getShadingScale())); + setter.setVec4("cc_exposure", Vec4(camera.getExposure(), + 1.0F / camera.getExposure(), + cfg.isHDR() ? 1.0F : 0.0F, + 1.0F / scene::Camera::getStandardExposureValue())); + + if (mainLight) { + const auto &shadowInfo = *cfg.getShadows(); + const bool shadowEnable = (mainLight->isShadowEnabled() && + shadowInfo.getType() == scene::ShadowType::SHADOW_MAP); + setter.setVec4("cc_mainLitDir", Vec4(mainLight->getDirection().x, + mainLight->getDirection().y, + mainLight->getDirection().z, + shadowEnable)); + auto r = mainLight->getColor().x; + auto g = mainLight->getColor().y; + auto b = mainLight->getColor().z; + if (mainLight->isUseColorTemperature()) { + r *= mainLight->getColorTemperatureRGB().x; + g *= mainLight->getColorTemperatureRGB().y; + b *= mainLight->getColorTemperatureRGB().z; + } + auto w = mainLight->getIlluminance(); + if (cfg.isHDR()) { + w *= camera.getExposure(); + } + setter.setVec4("cc_mainLitColor", Vec4(r, g, b, w)); + } else { + setter.setVec4("cc_mainLitDir", Vec4(0, 0, 1, 0)); + setter.setVec4("cc_mainLitColor", Vec4(0, 0, 0, 0)); + } + + CC_EXPECTS(cfg.getAmbient()); + auto &ambient = *cfg.getAmbient(); + auto &skyColor = ambient.getSkyColor(); + if (cfg.isHDR()) { + skyColor.w = ambient.getSkyIllum() * camera.getExposure(); + } else { + skyColor.w = ambient.getSkyIllum(); + } + setter.setVec4("cc_ambientSky", Vec4(skyColor.x, skyColor.y, skyColor.z, skyColor.w)); + setter.setVec4("cc_ambientGround", Vec4(ambient.getGroundAlbedo().x, + ambient.getGroundAlbedo().y, + ambient.getGroundAlbedo().z, + skybox.getEnvmap() + ? static_cast(skybox.getEnvmap()->mipmapLevel()) + : 1.0F)); + + CC_EXPECTS(cfg.getFog()); + const auto &fog = *cfg.getFog(); + + const auto &colorTempRGB = fog.getColorArray(); + setter.setVec4("cc_fogColor", Vec4(colorTempRGB.x, colorTempRGB.y, colorTempRGB.z, colorTempRGB.z)); + setter.setVec4("cc_fogBase", Vec4(fog.getFogStart(), fog.getFogEnd(), fog.getFogDensity(), 0.0F)); + setter.setVec4("cc_fogAdd", Vec4(fog.getFogTop(), fog.getFogRange(), fog.getFogAtten(), 0.0F)); + setter.setVec4("cc_nearFar", Vec4(camera.getNearClip(), camera.getFarClip(), 0.0F, 0.0F)); + setter.setVec4("cc_viewPort", Vec4(camera.getViewport().x, + camera.getViewport().y, + shadingScale * static_cast(camera.getWindow()->getWidth()) * camera.getViewport().z, + shadingScale * static_cast(camera.getWindow()->getHeight()) * camera.getViewport().w)); +} + +void setShadowUBOLightView( + gfx::Device *device, + const pipeline::PipelineSceneData &sceneData, + const scene::Light &light, + uint32_t level, Setter &setter) { + const auto &shadowInfo = *sceneData.getShadows(); + const auto &csmLayers = *sceneData.getCSMLayers(); + const auto &packing = pipeline::supportsR32FloatTexture(device) ? 0.0F : 1.0F; + const auto &cap = device->getCapabilities(); + Vec4 vec4ShadowInfo{}; + + // ShadowMap + switch (light.getType()) { + case scene::LightType::DIRECTIONAL: { + const auto &mainLight = dynamic_cast(light); + if (shadowInfo.isEnabled() && mainLight.isShadowEnabled()) { + if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { + float near = 0.1; + float far = 0; + Mat4 matShadowView; + Mat4 matShadowProj; + Mat4 matShadowViewProj; + scene::CSMLevel levelCount{}; + if (mainLight.isShadowFixedArea() || mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1) { + matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); + matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); + matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); + if (mainLight.isShadowFixedArea()) { + near = mainLight.getShadowNear(); + far = mainLight.getShadowFar(); + levelCount = static_cast(0); + } else { + near = 0.1; + far = csmLayers.getSpecialLayer()->getShadowCameraFar(); + levelCount = scene::CSMLevel::LEVEL_1; + } + vec4ShadowInfo.set(0.0F, packing, mainLight.getShadowNormalBias(), 0); + setter.setVec4("cc_shadowLPNNInfo", vec4ShadowInfo); + } else { + const auto &layer = *csmLayers.getLayers()[level]; + matShadowView = layer.getMatShadowView(); + matShadowProj = layer.getMatShadowProj(); + matShadowViewProj = layer.getMatShadowViewProj(); + + near = layer.getSplitCameraNear(); + far = layer.getSplitCameraFar(); + levelCount = mainLight.getCSMLevel(); + } + setter.setMat4("cc_matLightView", matShadowView); + setter.setVec4("cc_shadowProjDepthInfo", Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15])); + setter.setVec4("cc_shadowProjInfo", Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05])); + setter.setMat4("cc_matLightViewProj", matShadowViewProj); + vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); + setter.setVec4("cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set(0.0F, packing, mainLight.getShadowNormalBias(), static_cast(levelCount)); + setter.setVec4("cc_shadowLPNNInfo", vec4ShadowInfo); + vec4ShadowInfo.set(shadowInfo.getSize().x, shadowInfo.getSize().y, static_cast(mainLight.getShadowPcf()), mainLight.getShadowBias()); + setter.setVec4("cc_shadowWHPBInfo", vec4ShadowInfo); + } + } + break; + } + case scene::LightType::SPOT: { + const auto &spotLight = dynamic_cast(light); + if (shadowInfo.isEnabled() && spotLight.isShadowEnabled()) { + const auto &matShadowCamera = spotLight.getNode()->getWorldMatrix(); + const auto matShadowView = matShadowCamera.getInversed(); + setter.setMat4("cc_matLightView", matShadowView); + + Mat4 matShadowViewProj{}; + Mat4::createPerspective(spotLight.getAngle(), 1.0F, 0.001F, + spotLight.getRange(), true, + cap.clipSpaceMinZ, cap.clipSpaceSignY, 0, &matShadowViewProj); + matShadowViewProj.multiply(matShadowView); + setter.setMat4("cc_matLightViewProj", matShadowViewProj); + + const Vec4 shadowNFLSInfos(0.01F, spotLight.getRange(), 0.0F, 0.0F); + setter.setVec4("cc_shadowNFLSInfo", shadowNFLSInfos); + + const Vec4 shadowWHPBInfos( + shadowInfo.getSize().x, + shadowInfo.getSize().y, + spotLight.getShadowPcf(), + spotLight.getShadowBias()); + setter.setVec4("cc_shadowWHPBInfo", shadowWHPBInfos); + + const Vec4 shadowLPNNInfos(1.0F, packing, spotLight.getShadowNormalBias(), 0.0F); + setter.setVec4("cc_shadowLPNNInfo", shadowLPNNInfos); + } + break; + } + default: + break; + } + + const auto &data = shadowInfo.getShadowColor4f(); + setter.setColor("cc_shadowColor", gfx::Color{data[0], data[1], data[2], data[3]}); +} + +float getPCFRadius( + const scene::Shadows &shadowInfo, + const scene::DirectionalLight &mainLight) { + const auto &shadowMapSize = shadowInfo.getSize().x; + switch (mainLight.getShadowPcf()) { + case scene::PCFType::HARD: + return 0.0F; + case scene::PCFType::SOFT: + return 1.0F / (shadowMapSize * 0.5F); + case scene::PCFType::SOFT_2X: + return 2.0F / (shadowMapSize * 0.5F); + // case PCFType.SOFT_4X: + // return 3.0F / (shadowMapSize * 0.5F); + default: + break; + } + return 0.0F; +} + +void setShadowUBOView( + gfx::Device &device, + const pipeline::PipelineSceneData &sceneData, + const scene::DirectionalLight &mainLight, + NativeSetter &setter) { + const auto &shadowInfo = *sceneData.getShadows(); + const auto &csmLayers = *sceneData.getCSMLayers(); + const auto &csmSupported = sceneData.getCSMSupported(); + const auto &packing = pipeline::supportsR32FloatTexture(&device) ? 0.0F : 1.0F; + Vec4 vec4ShadowInfo{}; + if (shadowInfo.isEnabled()) { + if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { + if (mainLight.isShadowEnabled()) { + if (mainLight.isShadowFixedArea() || + mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1 || !csmSupported) { + // Shadow + const auto &matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); + const auto &matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); + const auto &matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); + const auto &near = mainLight.getShadowNear(); + const auto &far = mainLight.getShadowFar(); + + setter.setMat4("cc_matLightView", matShadowView); + setter.setVec4("cc_shadowProjDepthInfo", + Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15])); + + setter.setVec4("cc_shadowProjInfo", + Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05])); + setter.setMat4("cc_matLightViewProj", matShadowViewProj); + vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); + setter.setVec4("cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set(0.0F, packing, mainLight.getShadowNormalBias(), 0); + setter.setVec4("cc_shadowLPNNInfo", vec4ShadowInfo); + } else { + { // CSM + const auto layerThreshold = getPCFRadius(shadowInfo, mainLight); + const auto numCascades = static_cast(mainLight.getCSMLevel()); + setter.setVec4ArraySize("cc_csmViewDir0", numCascades); + setter.setVec4ArraySize("cc_csmViewDir1", numCascades); + setter.setVec4ArraySize("cc_csmViewDir2", numCascades); + setter.setVec4ArraySize("cc_csmAtlas", numCascades); + setter.setMat4ArraySize("cc_matCSMViewProj", numCascades); + setter.setVec4ArraySize("cc_csmProjDepthInfo", numCascades); + setter.setVec4ArraySize("cc_csmProjInfo", numCascades); + + Vec4 csmSplitsInfo{}; + for (uint32_t i = 0; i < numCascades; ++i) { + const auto &layer = *csmLayers.getLayers()[i]; + + const auto &matShadowView = layer.getMatShadowView(); + vec4ShadowInfo.set(matShadowView.m[0], matShadowView.m[4], matShadowView.m[8], layerThreshold); + setter.setVec4ArrayElem("cc_csmViewDir0", vec4ShadowInfo, i); + vec4ShadowInfo.set(matShadowView.m[1], matShadowView.m[5], matShadowView.m[9], 0.0F); + setter.setVec4ArrayElem("cc_csmViewDir1", vec4ShadowInfo, i); + vec4ShadowInfo.set(matShadowView.m[2], matShadowView.m[6], matShadowView.m[0], 0.0F); + setter.setVec4ArrayElem("cc_csmViewDir2", vec4ShadowInfo, i); + + const auto &csmAtlas = layer.getCSMAtlas(); + setter.setVec4ArrayElem("cc_csmAtlas", csmAtlas, i); + + const auto &matShadowViewProj = layer.getMatShadowViewProj(); + setter.setMat4ArrayElem("cc_matCSMViewProj", matShadowViewProj, i); + + const auto &matShadowProj = layer.getMatShadowProj(); + setter.setVec4ArrayElem( + "cc_csmProjDepthInfo", + Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15]), + i); + + setter.setVec4ArrayElem( + "cc_csmProjInfo", + Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05]), + i); + + (&csmSplitsInfo.x)[i] = layer.getSplitCameraFar() / mainLight.getShadowDistance(); + } + setter.setVec4("cc_csmSplitsInfo", csmSplitsInfo); + } + { // Shadow + vec4ShadowInfo.set(0, 0, 0, 1.0F - mainLight.getShadowSaturation()); + setter.setVec4("cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set( + 0.0F, packing, + mainLight.getShadowNormalBias(), + static_cast(mainLight.getCSMLevel())); + setter.setVec4("cc_shadowLPNNInfo", vec4ShadowInfo); + } + } + { // Shadow + vec4ShadowInfo.set( + shadowInfo.getSize().x, shadowInfo.getSize().y, + static_cast(mainLight.getShadowPcf()), mainLight.getShadowBias()); + setter.setVec4("cc_shadowWHPBInfo", vec4ShadowInfo); + } + } + } else { + Vec3 tempVec3 = shadowInfo.getNormal().getNormalized(); + setter.setVec4( + "cc_planarNDInfo", + Vec4(tempVec3.x, tempVec3.y, tempVec3.z, -shadowInfo.getDistance())); + } + { + const auto &data = shadowInfo.getShadowColor4f(); + setter.setColor("cc_shadowColor", gfx::Color{data[0], data[1], data[2], data[3]}); + } + } +} + +void setTextureUBOView( + gfx::Device &device, + const pipeline::PipelineSceneData &sceneData, + Setter &setter) { + const auto &skybox = *sceneData.getSkybox(); + if (skybox.getReflectionMap()) { + auto &texture = *skybox.getReflectionMap()->getGFXTexture(); + auto *sampler = device.getSampler(skybox.getReflectionMap()->getSamplerInfo()); + setter.setTexture("cc_environment", &texture); + setter.setSampler("cc_environment", sampler); + } else { + const auto *envmap = + skybox.getEnvmap() + ? skybox.getEnvmap() + : BuiltinResMgr::getInstance()->get("default-cube-texture"); + if (envmap) { + auto *texture = envmap->getGFXTexture(); + auto *sampler = device.getSampler(envmap->getSamplerInfo()); + setter.setTexture("cc_environment", texture); + setter.setSampler("cc_environment", sampler); + } + } + const auto *diffuseMap = + skybox.getDiffuseMap() + ? skybox.getDiffuseMap() + : BuiltinResMgr::getInstance()->get("default-cube-texture"); + if (diffuseMap) { + auto *texture = diffuseMap->getGFXTexture(); + auto *sampler = device.getSampler(diffuseMap->getSamplerInfo()); + setter.setTexture("cc_diffuseMap", texture); + setter.setSampler("cc_diffuseMap", sampler); + } + gfx::SamplerInfo samplerPointInfo{ + gfx::Filter::POINT, + gfx::Filter::POINT, + gfx::Filter::NONE, + gfx::Address::CLAMP, + gfx::Address::CLAMP, + gfx::Address::CLAMP}; + auto *pointSampler = device.getSampler(samplerPointInfo); + setter.setSampler("cc_shadowMap", pointSampler); + setter.setTexture("cc_shadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); + setter.setSampler("cc_spotShadowMap", pointSampler); + setter.setTexture("cc_spotShadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); +} + +} // namespace + +void NativeRasterQueueBuilder::addSceneOfCamera( + scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) { std::string_view name = "Camera"; + auto *pLight = light.light.get(); SceneData scene(renderGraph->get_allocator()); scene.name = name; scene.flags = sceneFlags; scene.camera = camera; - scene.light = std::move(light); + scene.light = light; auto sceneID = addVertex( SceneTag{}, std::forward_as_tuple(name), @@ -94,6 +683,34 @@ void NativeRasterQueueBuilder::addSceneOfCamera(scene::Camera *camera, LightInfo std::forward_as_tuple(std::move(scene)), *renderGraph, queueID); CC_ENSURES(sceneID != RenderGraph::null_vertex()); + + auto &data = get(RenderGraph::Data, *renderGraph, sceneID); + NativeSetter setter{*layoutGraph, data}; + + setCameraUBOValues( + *camera, + *pipelineRuntime->getPipelineSceneData(), + camera->getScene()->getMainLight(), setter); + + if (any(sceneFlags & SceneFlags::SHADOW_CASTER)) { + if (pLight) { + setShadowUBOLightView( + pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + *pLight, light.level, setter); + } + } else { + const auto *pDirLight = camera->getScene()->getMainLight(); + if (pDirLight) { + setShadowUBOView(*pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + *pDirLight, setter); + } + } + setTextureUBOView( + *pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + setter); } void NativeRasterQueueBuilder::addScene(const ccstd::string &name, SceneFlags sceneFlags) { @@ -139,6 +756,28 @@ void NativeRasterQueueBuilder::addCameraQuad( std::forward_as_tuple(material, passID, sceneFlags, camera), *renderGraph, queueID); CC_ENSURES(drawID != RenderGraph::null_vertex()); + + auto &data = get(RenderGraph::Data, *renderGraph, drawID); + NativeSetter setter{*layoutGraph, data}; + + setCameraUBOValues( + *camera, + *pipelineRuntime->getPipelineSceneData(), + camera->getScene()->getMainLight(), setter); + + if (any(sceneFlags & SceneFlags::SHADOW_CASTER)) { + } else { + const auto *pDirLight = camera->getScene()->getMainLight(); + if (pDirLight) { + setShadowUBOView(*pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + *pDirLight, setter); + } + } + setTextureUBOView( + *pipelineRuntime->getDevice(), + *pipelineRuntime->getPipelineSceneData(), + setter); } void NativeRasterQueueBuilder::clearRenderTarget(const ccstd::string &name, const gfx::Color &color) { @@ -168,91 +807,6 @@ void NativeRasterQueueBuilder::setViewport(const gfx::Viewport &viewport) { CC_ENSURES(viewportID != RenderGraph::null_vertex()); } -namespace { - -render::NameLocalID getNameID( - const PmrFlatMap &index, - std::string_view name) { - auto iter = index.find(name); - CC_EXPECTS(iter != index.end()); - return iter->second; -} - -void addMat4( - const LayoutGraphData &lg, std::string_view name, - const cc::Mat4 &v, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(Mat4) == 16 * 4, "sizeof(Mat4) is not 64 bytes"); - data.constants[nameID.value].resize(sizeof(Mat4)); - memcpy(data.constants[nameID.value].data(), v.m, sizeof(v)); -} - -void addQuaternion(const LayoutGraphData &lg, const ccstd::string &name, const Quaternion &quat, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(Quaternion) == 4 * 4, "sizeof(Quaternion) is not 16 bytes"); - static_assert(std::is_trivially_copyable::value, "Quaternion is not trivially copyable"); - data.constants[nameID.value].resize(sizeof(Quaternion)); - memcpy(data.constants[nameID.value].data(), &quat, sizeof(quat)); -} - -void addColor(const LayoutGraphData &lg, const ccstd::string &name, const gfx::Color &color, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(gfx::Color) == 4 * 4, "sizeof(Color) is not 16 bytes"); - static_assert(std::is_trivially_copyable::value, "Color is not trivially copyable"); - data.constants[nameID.value].resize(sizeof(gfx::Color)); - memcpy(data.constants[nameID.value].data(), &color, sizeof(color)); -} - -void addVec4(const LayoutGraphData &lg, const ccstd::string &name, const Vec4 &vec, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(Vec4) == 4 * 4, "sizeof(Vec4) is not 16 bytes"); - // static_assert(std::is_trivially_copyable::value, "Vec4 is not trivially copyable"); - data.constants[nameID.value].resize(sizeof(Vec4)); - memcpy(data.constants[nameID.value].data(), &vec.x, sizeof(vec)); -} - -void addVec2(const LayoutGraphData &lg, const ccstd::string &name, const Vec2 &vec, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(Vec2) == 2 * 4, "sizeof(Vec2) is not 8 bytes"); - // static_assert(std::is_trivially_copyable::value, "Vec2 is not trivially copyable"); - data.constants[nameID.value].resize(sizeof(Vec2)); - memcpy(data.constants[nameID.value].data(), &vec.x, sizeof(vec)); -} - -void addFloat(const LayoutGraphData &lg, const ccstd::string &name, float v, RenderData &data) { - auto nameID = getNameID(lg.constantIndex, name); - static_assert(sizeof(float) == 4, "sizeof(float) is not 4 bytes"); - data.constants[nameID.value].resize(sizeof(float)); - memcpy(data.constants[nameID.value].data(), &v, sizeof(v)); -} - -void addBuffer(const LayoutGraphData &lg, const ccstd::string &name, gfx::Buffer *buffer, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.buffers[nameID.value] = IntrusivePtr(buffer); -} - -void addTexture(const LayoutGraphData &lg, const ccstd::string &name, gfx::Texture *texture, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.textures[nameID.value] = IntrusivePtr(texture); -} - -void addReadWriteBuffer(const LayoutGraphData &lg, const ccstd::string &name, gfx::Buffer *buffer, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.buffers[nameID.value] = IntrusivePtr(buffer); -} - -void addReadWriteTexture(const LayoutGraphData &lg, const ccstd::string &name, gfx::Texture *texture, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.textures[nameID.value] = IntrusivePtr(texture); -} - -void addSampler(const LayoutGraphData &lg, const ccstd::string &name, gfx::Sampler *sampler, RenderData &data) { - auto nameID = getNameID(lg.attributeIndex, name); - data.samplers[nameID.value].ptr = sampler; -} - -} // namespace - void NativeRasterQueueBuilder::setMat4(const ccstd::string &name, const Mat4 &mat) { auto &data = get(RenderGraph::Data, *renderGraph, queueID); addMat4(*layoutGraph, name, mat, data); @@ -319,7 +873,7 @@ RasterQueueBuilder *NativeRasterPassBuilder::addQueue(QueueHint hint) { std::forward_as_tuple(hint), *renderGraph, passID); - return new NativeRasterQueueBuilder(renderGraph, queueID, layoutGraph); + return new NativeRasterQueueBuilder(pipelineRuntime, renderGraph, queueID, layoutGraph); } void NativeRasterPassBuilder::setViewport(const gfx::Viewport &viewport) { @@ -475,6 +1029,8 @@ void NativeComputePassBuilder::setName(const ccstd::string &name) { } void NativeComputePassBuilder::addComputeView(const ccstd::string &name, const ComputeView &view) { + CC_EXPECTS(!name.empty()); + CC_EXPECTS(!view.name.empty()); auto &pass = get(ComputeTag{}, passID, *renderGraph); auto iter = pass.computeViews.find(name.c_str()); if (iter == pass.computeViews.end()) { diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index 08c3333be0..bf230a21f0 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -40,6 +40,23 @@ ResourceGroup::~ResourceGroup() noexcept { } } +void ProgramResource::syncResources() noexcept { + for (auto&& [nameID, buffer] : uniformBuffers) { + buffer.bufferPool.syncResources(); + } + descriptorSetPool.syncDescriptorSets(); +} + +void LayoutGraphNodeResource::syncResources() noexcept { + for (auto&& [nameID, buffer] : uniformBuffers) { + buffer.bufferPool.syncResources(); + } + descriptorSetPool.syncDescriptorSets(); + for (auto&& [programName, programResource] : programResources) { + programResource.syncResources(); + } +} + void NativeRenderContext::clearPreviousResources(uint64_t finishedFenceValue) noexcept { for (auto iter = resourceGroups.begin(); iter != resourceGroups.end();) { if (iter->first <= finishedFenceValue) { @@ -48,6 +65,9 @@ void NativeRenderContext::clearPreviousResources(uint64_t finishedFenceValue) no break; } } + for (auto& node : layoutGraphResources) { + node.syncResources(); + } } namespace { @@ -138,6 +158,14 @@ gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { } // namespace +bool ManagedTexture::checkResource(const ResourceDesc& desc) const { + if (!texture) { + return false; + } + const auto& info = texture->getInfo(); + return desc.width == info.width && desc.height == info.height && desc.format == info.format; +} + void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { std::ignore = device; auto& resg = *this; @@ -156,20 +184,28 @@ void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { buffer.fenceValue = nextFenceValue; }, [&](ManagedTexture& texture) { - if (!texture.texture) { + if (!texture.checkResource(desc)) { auto info = getTextureInfo(desc); texture.texture = device->createTexture(info); } CC_ENSURES(texture.texture); texture.fenceValue = nextFenceValue; }, - [&](const IntrusivePtr& pass) { + [&](const IntrusivePtr& buffer) { + CC_EXPECTS(buffer); + std::ignore = buffer; }, - [&](const IntrusivePtr& pass) { + [&](const IntrusivePtr& texture) { + CC_EXPECTS(texture); + std::ignore = texture; }, - [&](const IntrusivePtr& pass) { + [&](const IntrusivePtr& fb) { + CC_EXPECTS(fb); + std::ignore = fb; }, [&](const RenderSwapchain& queue) { + CC_EXPECTS(queue.swapchain); + std::ignore = queue; }); } @@ -191,17 +227,51 @@ void ResourceGraph::unmount(uint64_t completedFenceValue) { texture.texture.reset(); } }, - [&](const IntrusivePtr& pass) { + [&](const IntrusivePtr& buffer) { + CC_EXPECTS(buffer); + std::ignore = buffer; }, - [&](const IntrusivePtr& pass) { + [&](const IntrusivePtr& texture) { + CC_EXPECTS(texture); + std::ignore = texture; }, - [&](const IntrusivePtr& pass) { + [&](const IntrusivePtr& fb) { + CC_EXPECTS(fb); + std::ignore = fb; }, [&](const RenderSwapchain& queue) { + CC_EXPECTS(queue.swapchain); + std::ignore = queue; }); } } +gfx::Texture* ResourceGraph::getTexture(vertex_descriptor resID) { + gfx::Texture* texture = nullptr; + visitObject( + resID, *this, + [&](const ManagedTexture& res) { + texture = res.texture.get(); + }, + [&](const IntrusivePtr& tex) { + texture = tex.get(); + }, + [&](const IntrusivePtr& fb) { + std::ignore = fb; + CC_EXPECTS(false); + }, + [&](const RenderSwapchain& sc) { + texture = sc.swapchain->getColorTexture(); + }, + [&](const auto& buffer) { + std::ignore = buffer; + CC_EXPECTS(false); + }); + CC_ENSURES(texture); + + return texture; +} + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeUtils.cpp b/native/cocos/renderer/pipeline/custom/NativeUtils.cpp new file mode 100644 index 0000000000..a581071153 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeUtils.cpp @@ -0,0 +1,35 @@ +#include "NativeUtils.h" +#include "cocos/renderer/gfx-base/GFXDevice.h" + +namespace cc { +namespace render { + +void setupQuadVertexBuffer(gfx::Device& device, const Vec4& viewport, float vbData[16]) { + auto minX = static_cast(viewport.x); + auto maxX = static_cast(viewport.x + viewport.z); + auto minY = static_cast(viewport.y); + auto maxY = static_cast(viewport.y + viewport.w); + if (device.getCapabilities().screenSpaceSignY > 0) { + std::swap(minY, maxY); + } + int n = 0; + vbData[n++] = -1.0F; + vbData[n++] = -1.0F; + vbData[n++] = minX; // uv + vbData[n++] = maxY; + vbData[n++] = 1.0F; + vbData[n++] = -1.0F; + vbData[n++] = maxX; + vbData[n++] = maxY; + vbData[n++] = -1.0F; + vbData[n++] = 1.0F; + vbData[n++] = minX; + vbData[n++] = minY; + vbData[n++] = 1.0F; + vbData[n++] = 1.0F; + vbData[n++] = maxX; + vbData[n++] = minY; +} + +} // namespace render +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeUtils.h b/native/cocos/renderer/pipeline/custom/NativeUtils.h new file mode 100644 index 0000000000..17c728fde1 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeUtils.h @@ -0,0 +1,13 @@ +#pragma once +#include "cocos/math/Vec4.h" + +namespace cc { +namespace gfx { +class Device; +} +namespace render { + +void setupQuadVertexBuffer(gfx::Device& device, const Vec4& viewport, float vbData[16]); + +} // namespace render +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp index 674463fa9d..2d060aa901 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp @@ -59,6 +59,9 @@ bool nativevalue_to_se(const cc::render::RasterView &from, se::Value &to, se::Ob nativevalue_to_se(from.clearColor, tmp, ctx); obj->setProperty("clearColor", tmp); + nativevalue_to_se(from.slotID, tmp, ctx); + obj->setProperty("slotID", tmp); + to.setObject(obj); return true; } @@ -262,6 +265,10 @@ bool sevalue_to_native(const se::Value &from, cc::render if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->clearColor), ctx); } + obj->getProperty("slotID", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->slotID), ctx); + } return ok; } diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h index a1432dc7e5..6ad04371ff 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h @@ -45,6 +45,7 @@ inline void save(OutputArchive& ar, const RasterView& v) { save(ar, v.storeOp); save(ar, v.clearFlags); save(ar, v.clearColor); + save(ar, v.slotID); } inline void load(InputArchive& ar, RasterView& v) { @@ -55,6 +56,7 @@ inline void load(InputArchive& ar, RasterView& v) { load(ar, v.storeOp); load(ar, v.clearFlags); load(ar, v.clearColor); + load(ar, v.slotID); } inline void save(OutputArchive& ar, const ComputeView& v) { diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp index 9408292582..6841ebe77b 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp @@ -53,7 +53,8 @@ RasterView::RasterView(RasterView&& rhs, const allocator_type& alloc) loadOp(rhs.loadOp), storeOp(rhs.storeOp), clearFlags(rhs.clearFlags), - clearColor(rhs.clearColor) {} + clearColor(rhs.clearColor), + slotID(rhs.slotID) {} RasterView::RasterView(RasterView const& rhs, const allocator_type& alloc) : slotName(rhs.slotName, alloc), @@ -62,7 +63,8 @@ RasterView::RasterView(RasterView const& rhs, const allocator_type& alloc) loadOp(rhs.loadOp), storeOp(rhs.storeOp), clearFlags(rhs.clearFlags), - clearColor(rhs.clearColor) {} + clearColor(rhs.clearColor), + slotID(rhs.slotID) {} ComputeView::ComputeView(const allocator_type& alloc) noexcept : name(alloc) {} diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h index 3120ea2147..4408e1b8de 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h @@ -212,6 +212,7 @@ struct RasterView { gfx::StoreOp storeOp{gfx::StoreOp::STORE}; gfx::ClearFlagBit clearFlags{gfx::ClearFlagBit::ALL}; gfx::Color clearColor; + uint32_t slotID{0}; }; inline bool operator==(const RasterView& lhs, const RasterView& rhs) noexcept { diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h index a4868dcc5d..fc29eb43fc 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h @@ -109,6 +109,8 @@ struct ManagedTexture { ManagedTexture(IntrusivePtr textureIn) noexcept // NOLINT : texture(std::move(textureIn)) {} + bool checkResource(const ResourceDesc &desc) const; + IntrusivePtr texture; uint64_t fenceValue{0}; }; @@ -228,6 +230,7 @@ struct ResourceGraph { void mount(gfx::Device* device, vertex_descriptor vertID); void unmount(uint64_t completedFenceValue); + gfx::Texture* getTexture(vertex_descriptor resID); // ContinuousContainer void reserve(vertices_size_type sz); diff --git a/native/cocos/scene/Ambient.cpp b/native/cocos/scene/Ambient.cpp index 0322bd1ec7..080b833d0a 100644 --- a/native/cocos/scene/Ambient.cpp +++ b/native/cocos/scene/Ambient.cpp @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to @@ -157,6 +157,11 @@ Vec4 &Ambient::getSkyColor() { return isHDR ? _skyColorHDR : _skyColorLDR; } +const Vec4 &Ambient::getSkyColor() const { + const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); + return isHDR ? _skyColorHDR : _skyColorLDR; +} + void Ambient::setSkyColor(const Vec4 &color) { const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); if (isHDR) { diff --git a/native/cocos/scene/Ambient.h b/native/cocos/scene/Ambient.h index 6c9f91d228..05c1b0a27f 100644 --- a/native/cocos/scene/Ambient.h +++ b/native/cocos/scene/Ambient.h @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to @@ -59,6 +59,7 @@ public: */ Vec4 &getSkyColor(); + const Vec4 &getSkyColor() const; void setSkyColor(const Vec4 &color); /** @@ -168,9 +169,9 @@ public: void activate(Ambient *resource); - //cjh JSB need to bind the property, so need to make it public - // @serializable - // @formerlySerializedAs('_skyColor')); + // cjh JSB need to bind the property, so need to make it public + // @serializable + // @formerlySerializedAs('_skyColor')); Vec4 _skyColorHDR{0.2F, 0.5F, 0.8F, 1.F}; // @serializable // @formerlySerializedAs('_skyIllum') diff --git a/native/cocos/scene/Pass.cpp b/native/cocos/scene/Pass.cpp index 07c903d32b..d49467334a 100644 --- a/native/cocos/scene/Pass.cpp +++ b/native/cocos/scene/Pass.cpp @@ -414,27 +414,53 @@ void Pass::resetTexture(const ccstd::string &name, uint32_t index) { } void Pass::resetUBOs() { - for (const auto &u : _shaderInfo->blocks) { + auto updateBuffer = [&](const IBlockInfo &u) { uint32_t ofs = 0; for (const auto &cur : u.members) { const auto &block = _blocks[u.binding]; const auto &info = _properties[cur.name]; const auto &givenDefault = info.value; - const auto &value = (givenDefault.has_value() ? ccstd::get>(givenDefault.value()) : getDefaultFloatArrayFromType(cur.type)); + const auto &value = + (givenDefault.has_value() + ? ccstd::get>(givenDefault.value()) + : getDefaultFloatArrayFromType(cur.type)); const uint32_t size = (gfx::getTypeSize(cur.type) >> 2) * cur.count; for (size_t k = 0; (k + value.size()) <= size; k += value.size()) { std::copy(value.begin(), value.end(), block.data + ofs + k); } ofs += size; } + }; + auto *programLib = render::getProgramLibrary(); + if (programLib) { + const auto &set = _shaderInfo->descriptors.at( + static_cast(pipeline::SetIndex::MATERIAL)); + for (const auto &block : set.blocks) { + updateBuffer(block); + } + } else { + for (const auto &u : _shaderInfo->blocks) { + updateBuffer(u); + } + _rootBufferDirty = true; } - _rootBufferDirty = true; } void Pass::resetTextures() { - for (const auto &u : _shaderInfo->samplerTextures) { - for (int32_t j = 0; j < u.count; j++) { - resetTexture(u.name, j); + auto *programLib = render::getProgramLibrary(); + if (programLib) { + const auto &set = _shaderInfo->descriptors.at( + static_cast(pipeline::SetIndex::MATERIAL)); + for (const auto &combined : set.samplerTextures) { + for (int32_t j = 0; j < combined.count; j++) { + resetTexture(combined.name, j); + } + } + } else { + for (const auto &u : _shaderInfo->samplerTextures) { + for (int32_t j = 0; j < u.count; j++) { + resetTexture(u.name, j); + } } } } @@ -630,10 +656,10 @@ void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */) // calculate total size required const auto &blocks = _shaderInfo->blocks; - const auto *tmplInfo - = programLib2 - ? nullptr - : programLib->getTemplateInfo(info.program); + const auto *tmplInfo = + programLib2 + ? nullptr + : programLib->getTemplateInfo(info.program); const auto &blockSizes = [&]() -> const auto & { if (programLib2) { return programLib2->getBlockSizes(_phaseID, _programName); diff --git a/native/cocos/scene/Pass.h b/native/cocos/scene/Pass.h index d2830a73f2..d80a83ef23 100644 --- a/native/cocos/scene/Pass.h +++ b/native/cocos/scene/Pass.h @@ -286,6 +286,8 @@ public: inline gfx::PrimitiveMode getPrimitive() const { return _primitive; } inline pipeline::RenderPassStage getStage() const { return _stage; } inline uint32_t getPhase() const { return _phase; } + inline uint32_t getPassID() const { return _passID; } + inline uint32_t getPhaseID() const { return _phaseID; } inline const gfx::RasterizerState *getRasterizerState() const { return &_rs; } inline const gfx::DepthStencilState *getDepthStencilState() const { return &_depthStencilState; } inline const gfx::BlendState *getBlendState() const { return &_blendState; }