From 43b4cb30f2624c2b2700f1b2a5d70a14171dfb83 Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Thu, 1 Jun 2023 10:39:20 +0800 Subject: [PATCH] develop pipeline add subpass (#15166) pr-test is not ready, skip it. --- cc.config.json | 4 +- cocos/asset/assets/effect-asset.jsb.ts | 1 + cocos/asset/assets/effect-asset.ts | 1 + cocos/gfx/base/define.ts | 4 - cocos/gfx/base/descriptor-set.ts | 4 +- cocos/rendering/custom/builtin-pipelines.ts | 60 +- cocos/rendering/custom/compiler.ts | 59 +- cocos/rendering/custom/custom-pipeline.ts | 131 ++- cocos/rendering/custom/define.ts | 327 +++++- cocos/rendering/custom/executor.ts | 8 +- cocos/rendering/custom/index.ts | 1 + cocos/rendering/custom/pipeline-define.ts | 613 +++++++++++ cocos/rendering/custom/pipeline.ts | 22 +- cocos/rendering/custom/render-graph.ts | 144 ++- cocos/rendering/custom/utils.ts | 2 +- cocos/rendering/custom/web-pipeline.ts | 2 +- .../effects/pipeline/cluster-build.effect | 63 ++ .../pipeline/cluster-build.effect.meta | 11 + .../effects/pipeline/cluster-culling.effect | 135 +++ .../pipeline/cluster-culling.effect.meta | 11 + native/cocos/core/assets/EffectAsset.cpp | 6 +- native/cocos/core/assets/EffectAsset.h | 4 + .../cocos/renderer/frame-graph/DevicePass.cpp | 6 +- .../frame-graph/RenderTargetAttachment.h | 1 - .../renderer/gfx-agent/DescriptorSetAgent.cpp | 9 +- .../renderer/gfx-agent/DescriptorSetAgent.h | 2 +- .../cocos/renderer/gfx-base/GFXDef-common.h | 18 +- .../renderer/gfx-base/GFXDescriptorSet.cpp | 9 +- .../renderer/gfx-base/GFXDescriptorSet.h | 7 +- native/cocos/renderer/gfx-base/SPIRVUtils.cpp | 4 +- .../cocos/renderer/gfx-gles2/GLES2Device.cpp | 4 +- .../renderer/gfx-gles3/GLES3Commands.cpp | 6 +- .../cocos/renderer/gfx-gles3/GLES3Device.cpp | 4 +- .../renderer/gfx-metal/MTLCommandBuffer.mm | 5 - native/cocos/renderer/gfx-metal/MTLDevice.mm | 3 + .../renderer/gfx-metal/MTLPipelineState.mm | 31 +- .../cocos/renderer/gfx-metal/MTLRenderPass.h | 8 +- .../cocos/renderer/gfx-metal/MTLRenderPass.mm | 49 + native/cocos/renderer/gfx-metal/MTLShader.h | 6 +- native/cocos/renderer/gfx-metal/MTLShader.mm | 36 +- native/cocos/renderer/gfx-metal/MTLUtils.h | 3 +- native/cocos/renderer/gfx-metal/MTLUtils.mm | 66 +- .../gfx-validator/DescriptorSetValidator.cpp | 6 +- .../gfx-validator/DescriptorSetValidator.h | 2 +- .../renderer/gfx-vulkan/VKCommandBuffer.cpp | 20 + .../renderer/gfx-vulkan/VKCommandBuffer.h | 3 + .../cocos/renderer/gfx-vulkan/VKCommands.cpp | 131 ++- .../renderer/gfx-vulkan/VKDescriptorSet.cpp | 2 +- native/cocos/renderer/gfx-vulkan/VKDevice.cpp | 2 +- .../cocos/renderer/gfx-vulkan/VKGPUObjects.h | 23 +- native/cocos/renderer/gfx-vulkan/VKUtils.cpp | 4 +- .../renderer/pipeline/custom/CustomTypes.h | 1 + .../pipeline/custom/FGDispatcherTypes.cpp | 3 +- .../pipeline/custom/FGDispatcherTypes.h | 3 + .../pipeline/custom/FrameGraphDispatcher.cpp | 62 +- .../pipeline/custom/NativeExecutor.cpp | 117 +- .../pipeline/custom/NativePipeline.cpp | 28 +- .../pipeline/custom/NativePipelineFwd.h | 4 + .../pipeline/custom/NativePipelineTypes.cpp | 13 +- .../pipeline/custom/NativePipelineTypes.h | 55 +- .../pipeline/custom/NativeProgramLibrary.cpp | 195 ++-- .../pipeline/custom/NativeRenderGraph.cpp | 94 +- .../pipeline/custom/NativeResourceGraph.cpp | 52 + .../renderer/pipeline/custom/RenderGraphFwd.h | 4 + .../pipeline/custom/RenderGraphGraphs.h | 997 ++++++++++++------ .../pipeline/custom/RenderGraphTypes.cpp | 2 + .../pipeline/custom/RenderGraphTypes.h | 62 +- .../pipeline/custom/RenderInterfaceTypes.h | 35 +- platforms/native/engine/jsb-gfx.js | 4 +- 69 files changed, 2937 insertions(+), 877 deletions(-) create mode 100644 cocos/rendering/custom/pipeline-define.ts create mode 100644 editor/assets/effects/pipeline/cluster-build.effect create mode 100644 editor/assets/effects/pipeline/cluster-build.effect.meta create mode 100644 editor/assets/effects/pipeline/cluster-culling.effect create mode 100644 editor/assets/effects/pipeline/cluster-culling.effect.meta diff --git a/cc.config.json b/cc.config.json index 217bb8cffa..8097c0454c 100644 --- a/cc.config.json +++ b/cc.config.json @@ -33,7 +33,9 @@ "620b6bf3-0369-4560-837f-2a2c00b73c26", "2df0a40b-26c2-47ce-be0d-4d3cd4164737", "39f74202-ead5-4a45-b966-273d526adbf1", - "8f6ac413-2f1e-4b88-b26f-54556b5dd510" + "8f6ac413-2f1e-4b88-b26f-54556b5dd510", + "45e7c0c8-2699-4912-b45f-d42bb8384189", + "84ac6f69-3086-455a-86a4-561da8ee710b" ] }, "animation": { diff --git a/cocos/asset/assets/effect-asset.jsb.ts b/cocos/asset/assets/effect-asset.jsb.ts index d13d92a227..3cc9133abe 100644 --- a/cocos/asset/assets/effect-asset.jsb.ts +++ b/cocos/asset/assets/effect-asset.jsb.ts @@ -64,6 +64,7 @@ export declare namespace EffectAsset { dynamicStates?: DynamicStateFlags; phase?: string | number; pass?: string; + subpass?: string; } export interface IPassInfo extends IPassStates { program: string; // auto-generated from 'vert' and 'frag' diff --git a/cocos/asset/assets/effect-asset.ts b/cocos/asset/assets/effect-asset.ts index 53626428b8..4902cf590d 100644 --- a/cocos/asset/assets/effect-asset.ts +++ b/cocos/asset/assets/effect-asset.ts @@ -54,6 +54,7 @@ export declare namespace EffectAsset { dynamicStates?: DynamicStateFlags; phase?: string | number; pass?: string; + subpass?: string; } export interface IPassInfo extends IPassStates { program: string; // auto-generated from 'vert' and 'frag' diff --git a/cocos/gfx/base/define.ts b/cocos/gfx/base/define.ts index 573ba7c767..87ec5bd34c 100644 --- a/cocos/gfx/base/define.ts +++ b/cocos/gfx/base/define.ts @@ -1509,7 +1509,6 @@ export class ColorAttachment { public loadOp: LoadOp = LoadOp.CLEAR, public storeOp: StoreOp = StoreOp.STORE, public barrier: GeneralBarrier = null!, - public isGeneralLayout: boolean = false, ) {} public copy (info: Readonly) { @@ -1518,7 +1517,6 @@ export class ColorAttachment { this.loadOp = info.loadOp; this.storeOp = info.storeOp; this.barrier = info.barrier; - this.isGeneralLayout = info.isGeneralLayout; return this; } } @@ -1534,7 +1532,6 @@ export class DepthStencilAttachment { public stencilLoadOp: LoadOp = LoadOp.CLEAR, public stencilStoreOp: StoreOp = StoreOp.STORE, public barrier: GeneralBarrier = null!, - public isGeneralLayout: boolean = false, ) {} public copy (info: Readonly) { @@ -1545,7 +1542,6 @@ export class DepthStencilAttachment { this.stencilLoadOp = info.stencilLoadOp; this.stencilStoreOp = info.stencilStoreOp; this.barrier = info.barrier; - this.isGeneralLayout = info.isGeneralLayout; return this; } } diff --git a/cocos/gfx/base/descriptor-set.ts b/cocos/gfx/base/descriptor-set.ts index 23796d21a9..4afea6d4ca 100644 --- a/cocos/gfx/base/descriptor-set.ts +++ b/cocos/gfx/base/descriptor-set.ts @@ -26,7 +26,7 @@ import { Buffer } from './buffer'; import { DescriptorSetLayout } from './descriptor-set-layout'; import { Sampler } from './states/sampler'; import { Texture } from './texture'; -import { GFXObject, ObjectType, DescriptorSetInfo, DESCRIPTOR_BUFFER_TYPE, DESCRIPTOR_SAMPLER_TYPE } from './define'; +import { GFXObject, ObjectType, DescriptorSetInfo, DESCRIPTOR_BUFFER_TYPE, DESCRIPTOR_SAMPLER_TYPE, AccessFlags } from './define'; /** * @en GFX descriptor sets. @@ -96,7 +96,7 @@ export abstract class DescriptorSet extends GFXObject { * @param binding The target binding. * @param texture The texture to be bound. */ - public bindTexture (binding: number, texture: Texture, index = 0) { + public bindTexture (binding: number, texture: Texture, index = 0, flags?: AccessFlags) { const bindingIndex = this._layout!.bindingIndices[binding]; const info = this._layout!.bindings[bindingIndex]; if (!info) { return; } if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) { diff --git a/cocos/rendering/custom/builtin-pipelines.ts b/cocos/rendering/custom/builtin-pipelines.ts index e6548b9128..ad3f6c823b 100644 --- a/cocos/rendering/custom/builtin-pipelines.ts +++ b/cocos/rendering/custom/builtin-pipelines.ts @@ -25,9 +25,12 @@ import { EDITOR } from 'internal:constants'; import { Camera, CameraUsage } from '../../render-scene/scene'; import { BasicPipeline, PipelineBuilder } from './pipeline'; -import { buildForwardPass, buildGBufferPass, buildLightingPass, buildPostprocessPass, - buildReflectionProbePasss, buildUIPass } from './define'; +import { buildForwardPass, buildGBufferPass, buildLightingPass, buildPostprocessPass, buildUIPass } from './define'; import { isUICamera } from './utils'; +import { prepareResource, setupForwardPass, setupForwardRes, setupReflectionProbePass, setupReflectionProbeRes, + updateForwardRes, updateReflectionProbeRes, CameraInfo, setupGBufferPass, + updateGBufferRes, setupGBufferRes, setupLightingPass, setupLightingRes, updateLightingRes, + setupPostprocessPass, setupPostprocessRes, updatePostprocessRes, setupUIPass, setupUIRes, updateUIRes } from './pipeline-define'; export class ForwardPipelineBuilder implements PipelineBuilder { public setup (cameras: Camera[], ppl: BasicPipeline): void { @@ -36,13 +39,21 @@ export class ForwardPipelineBuilder implements PipelineBuilder { if (camera.scene === null) { continue; } - // forward pass - buildForwardPass(camera, ppl, false); + const info = prepareResource(ppl, camera, this.initResource, this.updateResource); + setupForwardPass(ppl, info); if (EDITOR) { - buildReflectionProbePasss(camera, ppl); + setupReflectionProbePass(ppl, info); } } } + private initResource (ppl: BasicPipeline, cameraInfo: CameraInfo) { + setupForwardRes(ppl, cameraInfo); + if (EDITOR) setupReflectionProbeRes(ppl, cameraInfo); + } + private updateResource (ppl: BasicPipeline, cameraInfo: CameraInfo) { + updateForwardRes(ppl, cameraInfo); + if (EDITOR) updateReflectionProbeRes(ppl, cameraInfo); + } } export class DeferredPipelineBuilder implements PipelineBuilder { @@ -54,21 +65,48 @@ export class DeferredPipelineBuilder implements PipelineBuilder { } const isGameView = camera.cameraUsage === CameraUsage.GAME || camera.cameraUsage === CameraUsage.GAME_VIEW; + const info = prepareResource(ppl, camera, this.initResource, this.updateResource); if (!isGameView) { - buildForwardPass(camera, ppl, false); + setupForwardPass(ppl, info); continue; } if (!isUICamera(camera)) { - // GBuffer Pass - const gBufferInfo = buildGBufferPass(camera, ppl); + // GBuffer Pass + setupGBufferPass(ppl, info); // Lighting Pass - const lightInfo = buildLightingPass(camera, ppl, gBufferInfo); + const lightInfo = setupLightingPass(ppl, info); // Postprocess - buildPostprocessPass(camera, ppl, lightInfo.rtName); + setupPostprocessPass(ppl, info, lightInfo.rtName); continue; } // render ui - buildUIPass(camera, ppl); + setupUIPass(ppl, info); + } + } + private initResource (ppl: BasicPipeline, cameraInfo: CameraInfo) { + if (EDITOR) { + setupForwardRes(ppl, cameraInfo); + return; + } + if (!isUICamera(cameraInfo.camera)) { + setupGBufferRes(ppl, cameraInfo); + setupLightingRes(ppl, cameraInfo); + setupPostprocessRes(ppl, cameraInfo); + } else { + setupUIRes(ppl, cameraInfo); + } + } + private updateResource (ppl: BasicPipeline, cameraInfo: CameraInfo) { + if (EDITOR) { + updateForwardRes(ppl, cameraInfo); + return; + } + if (!isUICamera(cameraInfo.camera)) { + updateGBufferRes(ppl, cameraInfo); + updateLightingRes(ppl, cameraInfo); + updatePostprocessRes(ppl, cameraInfo); + } else { + updateUIRes(ppl, cameraInfo); } } } diff --git a/cocos/rendering/custom/compiler.ts b/cocos/rendering/custom/compiler.ts index 317d655800..d2ba1512fd 100644 --- a/cocos/rendering/custom/compiler.ts +++ b/cocos/rendering/custom/compiler.ts @@ -28,9 +28,9 @@ import { VectorGraphColorMap } from './effect'; import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph'; import { LayoutGraphData } from './layout-graph'; import { BasicPipeline } from './pipeline'; -import { Blit, ClearView, ComputePass, ComputeSubpass, CopyPass, Dispatch, ManagedBuffer, ManagedResource, ManagedTexture, MovePass, +import { Blit, ClearView, ComputePass, ComputeSubpass, CopyPass, Dispatch, FormatView, ManagedBuffer, ManagedResource, ManagedTexture, MovePass, RasterPass, RasterSubpass, RaytracePass, RenderGraph, RenderGraphVisitor, - RenderQueue, RenderSwapchain, ResolvePass, ResourceGraph, ResourceGraphVisitor, SceneData } from './render-graph'; + RenderQueue, RenderSwapchain, ResolvePass, ResourceGraph, ResourceGraphVisitor, SceneData, SubresourceView } from './render-graph'; import { AccessType, RasterView, ComputeView, ResourceResidency, SceneFlags } from './types'; let hashCode = 0; @@ -105,8 +105,10 @@ class PassVisitor implements RenderGraphVisitor { public resID = 0xFFFFFFFF; public context: CompilerContext; private _currPass: RasterPass | CopyPass | null = null; + private _resVisitor: ResourceVisitor; constructor (context: CompilerContext) { this.context = context; + this._resVisitor = new ResourceVisitor(this.context); } protected _isRasterPass (u: number): boolean { return !!this.context.renderGraph.tryGetRasterPass(u); @@ -219,16 +221,14 @@ class PassVisitor implements RenderGraphVisitor { for (const [readName, raster] of pass.rasterViews) { context.pipeline.resourceUses.push(readName); } - let resVisitor; let resourceGraph; let vertID; for (const [rasterName, raster] of readViews) { - resVisitor = new ResourceVisitor(this.context); resourceGraph = this.context.resourceGraph; vertID = resourceGraph.find(rasterName); if (vertID !== 0xFFFFFFFF) { - resVisitor.resID = vertID; - resourceGraph.visitVertex(resVisitor, vertID); + this._resVisitor.resID = vertID; + resourceGraph.visitVertex(this._resVisitor, vertID); } } for (const [computeName, cViews] of pass.computeViews) { @@ -246,12 +246,11 @@ class PassVisitor implements RenderGraphVisitor { computes.set(this.passID, [cViews]); } } - resVisitor = new ResourceVisitor(this.context); resourceGraph = this.context.resourceGraph; vertID = resourceGraph.find(computeName); if (vertID !== 0xFFFFFFFF) { - resVisitor.resID = vertID; - resourceGraph.visitVertex(resVisitor, vertID); + this._resVisitor.resID = vertID; + resourceGraph.visitVertex(this._resVisitor, vertID); } } genHashValue(pass); @@ -288,15 +287,14 @@ class PassVisitor implements RenderGraphVisitor { this._currPass = value; const outputId = this.resID; const outputName = resourceGraph.vertexName(outputId); - let resVisitor; let vertID; + let vertID; for (const pair of value.copyPairs) { if (pair.target === outputName) { rg.setValid(this.passID, true); - if (!resVisitor) resVisitor = new ResourceVisitor(this.context); vertID = resourceGraph.find(pair.source); if (vertID !== 0xFFFFFFFF) { - resVisitor.resID = vertID; - resourceGraph.visitVertex(resVisitor, vertID); + this._resVisitor.resID = vertID; + resourceGraph.visitVertex(this._resVisitor, vertID); } } } @@ -319,10 +317,18 @@ class PassManagerVisitor extends DefaultVisitor { private _colorMap: VectorGraphColorMap; private _graphView: ReferenceGraphView; private _passVisitor: PassVisitor; - public resId = 0xFFFFFFFF; + private _resId = 0xFFFFFFFF; + + set resId (value: number) { + this._resId = value; + this._colorMap.colors.length = context.renderGraph.numVertices(); + } + get resId () { + return this._resId; + } constructor (context: CompilerContext, resId: number) { super(); - this.resId = resId; + this._resId = resId; this._passVisitor = new PassVisitor(context); this._graphView = new ReferenceGraphView(context.renderGraph); this._colorMap = new VectorGraphColorMap(context.renderGraph.numVertices()); @@ -339,6 +345,7 @@ class PassManagerVisitor extends DefaultVisitor { class ResourceVisitor implements ResourceGraphVisitor { private readonly _context: CompilerContext; public resID = 0xFFFFFFFF; + private _passManagerVis; constructor (context: CompilerContext) { this._context = context; } @@ -355,8 +362,12 @@ class ResourceVisitor implements ResourceGraphVisitor { } dependency () { - const visitor = new PassManagerVisitor(this._context, this.resID); - depthFirstSearch(visitor.graphView, visitor, visitor.colorMap); + if (!this._passManagerVis) { + this._passManagerVis = new PassManagerVisitor(this._context, this.resID); + } else { + this._passManagerVis.resId = this.resID; + } + depthFirstSearch(this._passManagerVis.graphView, this._passManagerVis, this._passManagerVis.colorMap); } persistentTexture (value: Texture) { @@ -368,6 +379,10 @@ class ResourceVisitor implements ResourceGraphVisitor { swapchain (value: RenderSwapchain) { this.dependency(); } + formatView (value: FormatView) { + } + subresourceView (value: SubresourceView) { + } } class ResourceUseContext { @@ -401,17 +416,23 @@ export class Compiler { private _resourceGraph: ResourceGraph; private _pipeline: BasicPipeline; private _layoutGraph: LayoutGraphData; + private _visitor: ResourceManagerVisitor; constructor (pipeline: BasicPipeline, + renderGraph: RenderGraph, resGraph: ResourceGraph, layoutGraph: LayoutGraphData) { this._pipeline = pipeline; this._resourceGraph = resGraph; this._layoutGraph = layoutGraph; + context.set(this._pipeline, this._resourceGraph, renderGraph, this._layoutGraph); + this._visitor = new ResourceManagerVisitor(context); } compile (rg: RenderGraph) { context.set(this._pipeline, this._resourceGraph, rg, this._layoutGraph); - const visitor = new ResourceManagerVisitor(context); - depthFirstSearch(this._resourceGraph, visitor, visitor.colorMap); + context.pipeline.resourceUses.length = 0; + this._visitor.colorMap.colors.length = context.resourceGraph.numVertices(); + depthFirstSearch(this._resourceGraph, this._visitor, this._visitor.colorMap); + if (DEBUG) { const useContext = context.resourceContext; for (const [name, use] of useContext) { diff --git a/cocos/rendering/custom/custom-pipeline.ts b/cocos/rendering/custom/custom-pipeline.ts index 79e25b4ead..17bc04fbd9 100644 --- a/cocos/rendering/custom/custom-pipeline.ts +++ b/cocos/rendering/custom/custom-pipeline.ts @@ -23,13 +23,17 @@ */ import { Format, LoadOp } from '../../gfx/base/define'; -import { Camera, CameraUsage } from '../../render-scene/scene'; +import { Camera, CameraUsage, Light, SpotLight } from '../../render-scene/scene'; import { BasicPipeline, PipelineBuilder } from './pipeline'; import { CopyPair, LightInfo, QueueHint, ResourceResidency, SceneFlags } from './types'; import { AntiAliasing, buildBloomPass, buildForwardPass, buildFxaaPass, buildPostprocessPass, buildSSSSPass, - buildToneMappingPass, buildTransparencyPass, buildUIPass, hasSkinObject, buildHBAOPasses, buildCopyPass, getRenderArea, buildReflectionProbePasss } from './define'; + buildToneMappingPass, buildTransparencyPass, buildUIPass, hasSkinObject, + buildHBAOPasses, buildCopyPass, getRenderArea, buildReflectionProbePasss } from './define'; import { isUICamera } from './utils'; import { RenderWindow } from '../../render-scene/core/render-window'; +import { geometry } from '../../core'; +import { RenderScene } from '../../render-scene'; +import { AABB } from '../../core/geometry/aabb'; const copyPair = new CopyPair(); const pairs = [copyPair]; @@ -67,7 +71,7 @@ export class CustomPipelineBuilder implements PipelineBuilder { buildCopyPass(ppl, pairs); // skin pass - const skinInfo = buildSSSSPass(camera, ppl, forwardInfo.rtName, forwardInfo.dsName); + const skinInfo = buildSSSSPass(camera, ppl, 'copyTexTest', forwardInfo.dsName); // deferred transparency objects const deferredTransparencyInfo = buildTransparencyPass(camera, ppl, skinInfo.rtName, skinInfo.dsName, hasDeferredTransparencyObjects); // hbao pass @@ -80,7 +84,7 @@ export class CustomPipelineBuilder implements PipelineBuilder { // todo: bloom need to be rendered before tone-mapping const bloomInfo = buildBloomPass(camera, ppl, fxaaInfo.rtName); // Present Pass - buildPostprocessPass(camera, ppl, bloomInfo.rtName, AntiAliasing.NONE); + buildPostprocessPass(camera, ppl, bloomInfo.rtName); continue; } // render ui @@ -89,24 +93,79 @@ export class CustomPipelineBuilder implements PipelineBuilder { } } -class CameraInfo { - constructor (id: number, windowID: number, width: number, height: number) { +class WindowInfo { + constructor (id: number, width: number, height: number) { this.id = id; - this.windowID = windowID; this.width = width; this.height = height; } id = 0xFFFFFFFF; - windowID = 0xFFFFFFFF; width = 0; height = 0; } +class SceneInfo { + public reset () { + this.punctualLights.length = 0; + this.spotLights.length = 0; + } + punctualLights: Light[] = []; + spotLights: SpotLight[] = []; +} + export class TestPipelineBuilder implements PipelineBuilder { + private prepareSceneInfo (scene: Readonly, + frustum: geometry.Frustum, + sceneInfo: SceneInfo) { + // clear scene info + sceneInfo.reset(); + // spot lights + for (let i = 0; i < scene.spotLights.length; i++) { + const light = scene.spotLights[i]; + if (light.baked) { + continue; + } + geometry.Sphere.set(this._sphere, light.position.x, light.position.y, light.position.z, light.range); + if (geometry.intersect.sphereFrustum(this._sphere, frustum)) { + sceneInfo.punctualLights.push(light); + sceneInfo.spotLights.push(light); + } + } + // sphere lights + for (let i = 0; i < scene.sphereLights.length; i++) { + const light = scene.sphereLights[i]; + if (light.baked) { + continue; + } + geometry.Sphere.set(this._sphere, light.position.x, light.position.y, light.position.z, light.range); + if (geometry.intersect.sphereFrustum(this._sphere, frustum)) { + sceneInfo.punctualLights.push(light); + } + } + // point lights + for (let i = 0; i < scene.pointLights.length; i++) { + const light = scene.pointLights[i]; + if (light.baked) { + continue; + } + geometry.Sphere.set(this._sphere, light.position.x, light.position.y, light.position.z, light.range); + if (geometry.intersect.sphereFrustum(this._sphere, frustum)) { + sceneInfo.punctualLights.push(light); + } + } + // ranged dir lights + for (let i = 0; i < scene.rangedDirLights.length; i++) { + const light = scene.rangedDirLights[i]; + AABB.transform(this._tmpBoundingBox, this._rangedDirLightBoundingBox, light.node!.getWorldMatrix()); + if (geometry.intersect.aabbFrustum(this._tmpBoundingBox, frustum)) { + sceneInfo.punctualLights.push(light); + } + } + } public setup (cameras: Camera[], ppl: BasicPipeline): void { for (let i = 0; i < cameras.length; i++) { const camera = cameras[i]; - if (camera.scene === null) { + if (camera.scene === null || camera.window === null) { continue; } if (camera.cameraUsage !== CameraUsage.GAME) { @@ -114,19 +173,13 @@ export class TestPipelineBuilder implements PipelineBuilder { continue; } const info = this.prepareGameCamera(ppl, camera); - this.buildForward(ppl, camera, info.id, info.width, info.height); + this.prepareSceneInfo(camera.scene, camera.frustum, this._sceneInfo); + this.buildForwardWithoutShadow(ppl, camera, + info.id, info.width, info.height, this._sceneInfo); } } - private prepareRenderWindow (camera: Camera): number { - let windowID = this._windows.get(camera.window); - if (windowID === undefined) { - windowID = this._windows.size; - this._windows.set(camera.window, windowID); - } - return windowID; - } - private prepareGameCamera (ppl: BasicPipeline, camera: Camera): CameraInfo { - let info = this._cameras.get(camera); + private prepareGameCamera (ppl: BasicPipeline, camera: Camera): WindowInfo { + let info = this._windows.get(camera.window); if (info !== undefined) { let width = camera.window.width; let height = camera.window.height; @@ -136,33 +189,35 @@ export class TestPipelineBuilder implements PipelineBuilder { if (height === 0) { height = 1; } - const windowID = this.prepareRenderWindow(camera); - if (info.width === width && info.height === height && info.windowID === windowID) { + if (info.width === width && info.height === height) { return info; } - this.updateGameCamera(ppl, camera, info.id, info.windowID, info.width, info.height); + info.width = width; + info.height = height; + this.updateGameCamera(ppl, camera, info.id, info.width, info.height); return info; } - const windowID = this.prepareRenderWindow(camera); - info = new CameraInfo( - this._cameras.size, - windowID, + const id = this._windows.size; + info = new WindowInfo( + id, camera.window.width ? camera.window.width : 1, camera.window.height ? camera.window.height : 1, ); - this.initGameCamera(ppl, camera, info.id, info.windowID, info.width, info.height); - this._cameras.set(camera, info); + this.initGameCamera(ppl, camera, info.id, info.width, info.height); + this._windows.set(camera.window, info); return info; } - private initGameCamera (ppl: BasicPipeline, camera: Camera, id: number, windowID: number, width: number, height: number) { - ppl.addRenderWindow(`Color${windowID}`, Format.BGRA8, width, height, camera.window); + private initGameCamera (ppl: BasicPipeline, camera: Camera, id: number, width: number, height: number) { + ppl.addRenderWindow(`Color${id}`, Format.BGRA8, width, height, camera.window); ppl.addDepthStencil(`DepthStencil${id}`, Format.DEPTH_STENCIL, width, height); } - private updateGameCamera (ppl: BasicPipeline, camera: Camera, id: number, windowID: number, width: number, height: number) { - ppl.updateRenderWindow(`Color${windowID}`, camera.window); + private updateGameCamera (ppl: BasicPipeline, camera: Camera, id: number, width: number, height: number) { + ppl.updateRenderWindow(`Color${id}`, camera.window); ppl.updateDepthStencil(`DepthStencil${id}`, width, height); } - private buildForward (ppl: BasicPipeline, camera: Camera, id: number, width: number, height: number) { + private buildForwardWithoutShadow (ppl: BasicPipeline, + camera: Camera, id: number, width: number, height: number, + sceneInfo: SceneInfo) { const scene = camera.scene; const pass = ppl.addRenderPass(width, height, 'default'); @@ -180,6 +235,10 @@ export class TestPipelineBuilder implements PipelineBuilder { .addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.DEFAULT_LIGHTING); } } - readonly _cameras = new Map(); - readonly _windows = new Map(); + readonly _windows = new Map(); + readonly _sceneInfo = new SceneInfo(); + // context + readonly _sphere = geometry.Sphere.create(0, 0, 0, 1); + readonly _rangedDirLightBoundingBox = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5); + readonly _tmpBoundingBox = new AABB(); } diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index 9df57dfe3b..773116efe0 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -25,12 +25,17 @@ import { EDITOR } from 'internal:constants'; import { BufferInfo, Buffer, BufferUsageBit, ClearFlagBit, Color, DescriptorSet, LoadOp, Format, Rect, Sampler, StoreOp, Texture, Viewport, MemoryUsageBit, Filter, Address } from '../../gfx'; -import { Camera, CSMLevel, DirectionalLight, Light, LightType, ProbeType, ReflectionProbe, ShadowType, SKYBOX_FLAG, SpotLight } from '../../render-scene/scene'; +import { + Camera, CSMLevel, DirectionalLight, Light, LightType, ProbeType, ReflectionProbe, + ShadowType, SKYBOX_FLAG, SpotLight, PointLight, RangedDirectionalLight, SphereLight, +} from '../../render-scene/scene'; import { supportsR32FloatTexture, supportsRGBA16FloatTexture } from '../define'; -import { BasicPipeline } from './pipeline'; -import { AccessType, AttachmentType, ComputeView, CopyPair, LightInfo, - QueueHint, RasterView, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; -import { Vec2, Vec3, Vec4, macro, geometry, toRadian, cclegacy, assert } from '../../core'; +import { BasicPipeline, Pipeline } from './pipeline'; +import { + AccessType, AttachmentType, ComputeView, CopyPair, LightInfo, + QueueHint, RasterView, ResourceResidency, SceneFlags, UpdateFrequency, UploadPair, +} from './types'; +import { Vec2, Vec3, Vec4, macro, geometry, toRadian, cclegacy, assert, nextPow2 } from '../../core'; import { ImageAsset, Material, Texture2D } from '../../asset/assets'; import { getProfilerCamera, SRGBToLinear } from '../pipeline-funcs'; import { RenderWindow } from '../../render-scene/core/render-window'; @@ -40,7 +45,6 @@ import { DescriptorSetData } from './layout-graph'; import { AABB } from '../../core/geometry'; import { MeshRenderer } from '../../3d'; import { DebugViewCompositeType, DebugViewSingleType } from '../debug-view'; -import { Pipeline } from '../../asset/asset-manager/pipeline'; const _rangedDirLightBoundingBox = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5); const _tmpBoundingBox = new AABB(); @@ -52,7 +56,7 @@ export enum AntiAliasing { FXAAHQ, } -function getRTFormatBeforeToneMapping (ppl: BasicPipeline) { +export function getRTFormatBeforeToneMapping (ppl: BasicPipeline) { const useFloatOutput = ppl.getMacroBool('CC_USE_FLOAT_OUTPUT'); return ppl.pipelineSceneData.isHDR && useFloatOutput && supportsRGBA16FloatTexture(ppl.device) ? Format.RGBA16F : Format.RGBA8; } @@ -446,7 +450,7 @@ export function buildBloomPass (camera: Camera, return { rtName: bloomPassCombineRTName, dsName: bloomPassCombineDSName }; } -class PostInfo { +export class PostInfo { declare postMaterial: Material; antiAliasing: AntiAliasing = AntiAliasing.NONE; private _init () { @@ -472,14 +476,13 @@ class PostInfo { } } -let postInfo: PostInfo | null = null; +let postInfo: PostInfo; export function buildPostprocessPass (camera: Camera, ppl: BasicPipeline, - inputTex: string, - antiAliasing: AntiAliasing = AntiAliasing.NONE) { - if (!postInfo || (postInfo && postInfo.antiAliasing !== antiAliasing)) { - postInfo = new PostInfo(antiAliasing); + inputTex: string) { + if (!postInfo) { + postInfo = new PostInfo(); } const cameraID = getCameraUniqueID(camera); const area = getRenderArea(camera, camera.window.width, camera.window.height); @@ -489,7 +492,7 @@ export function buildPostprocessPass (camera: Camera, const postprocessPassDS = `postprocessPassDS${cameraID}`; if (!ppl.containsResource(postprocessPassRTName)) { ppl.addRenderWindow(postprocessPassRTName, Format.BGRA8, width, height, camera.window); - ppl.addDepthStencil(postprocessPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.EXTERNAL); + ppl.addDepthStencil(postprocessPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); } ppl.updateRenderWindow(postprocessPassRTName, camera.window); ppl.updateDepthStencil(postprocessPassDS, width, height); @@ -528,7 +531,7 @@ export function buildForwardPass (camera: Camera, } const cameraID = getCameraUniqueID(camera); const cameraName = `Camera${cameraID}`; - const cameraInfo = buildShadowPasses(cameraName, camera, ppl); + const shadowInfo = buildShadowPasses(cameraName, camera, ppl); const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; const height = area.height; @@ -553,12 +556,12 @@ export function buildForwardPass (camera: Camera, const forwardPass = ppl.addRenderPass(width, height, 'default'); forwardPass.name = `CameraForwardPass${cameraID}`; forwardPass.setViewport(new Viewport(area.x, area.y, width, height)); - for (const dirShadowName of cameraInfo.mainLightShadowNames) { + for (const dirShadowName of shadowInfo.mainLightShadowNames) { if (ppl.containsResource(dirShadowName)) { forwardPass.addTexture(dirShadowName, 'cc_shadowMap'); } } - for (const spotShadowName of cameraInfo.spotLightShadowNames) { + for (const spotShadowName of shadowInfo.spotLightShadowNames) { if (ppl.containsResource(spotShadowName)) { forwardPass.addTexture(spotShadowName, 'cc_spotShadowMap'); } @@ -676,30 +679,36 @@ export function buildReflectionProbePass (camera: Camera, updateCameraUBO(passBuilder as unknown as any, probeCamera, ppl); } -class CameraInfo { +export class ShadowInfo { shadowEnabled = false; mainLightShadowNames = new Array(); spotLightShadowNames = new Array(); + validLights: Light[] = []; + reset () { + this.shadowEnabled = false; + this.mainLightShadowNames.length = 0; + this.spotLightShadowNames.length = 0; + this.validLights.length = 0; + } } -export function buildShadowPasses (cameraName: string, camera: Camera, ppl: BasicPipeline): CameraInfo { +export function buildShadowPasses (cameraName: string, camera: Camera, ppl: BasicPipeline): ShadowInfo { validPunctualLightsCulling(ppl, camera); const pipeline = ppl; - const shadowInfo = pipeline.pipelineSceneData.shadows; + const shadow = pipeline.pipelineSceneData.shadows; const validPunctualLights = ppl.pipelineSceneData.validPunctualLights; - const cameraInfo = new CameraInfo(); + shadowInfo.reset(); const shadows = ppl.pipelineSceneData.shadows; - if (!shadowInfo.enabled || shadowInfo.type !== ShadowType.ShadowMap) { return cameraInfo; } - cameraInfo.shadowEnabled = true; - const _validLights: Light[] = []; + if (!shadow.enabled || shadow.type !== ShadowType.ShadowMap) { return shadowInfo; } + shadowInfo.shadowEnabled = true; let n = 0; let m = 0; - for (;n < shadowInfo.maxReceived && m < validPunctualLights.length;) { + for (;n < shadow.maxReceived && m < validPunctualLights.length;) { const light = validPunctualLights[m]; if (light.type === LightType.SPOT) { const spotLight = light as SpotLight; if (spotLight.shadowEnabled) { - _validLights.push(light); + shadowInfo.validLights.push(light); n++; } } @@ -711,29 +720,30 @@ export function buildShadowPasses (cameraName: string, camera: Camera, ppl: Basi const mapWidth = shadows.size.x; const mapHeight = shadows.size.y; if (mainLight && mainLight.shadowEnabled) { - cameraInfo.mainLightShadowNames[0] = `MainLightShadow${cameraName}`; + shadowInfo.mainLightShadowNames[0] = `MainLightShadow${cameraName}`; if (mainLight.shadowFixedArea) { - buildShadowPass(cameraInfo.mainLightShadowNames[0], ppl, + buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, camera, mainLight, 0, mapWidth, mapHeight); } else { const csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1; - cameraInfo.mainLightShadowNames[0] = `MainLightShadow${cameraName}`; + shadowInfo.mainLightShadowNames[0] = `MainLightShadow${cameraName}`; for (let i = 0; i < csmLevel; i++) { - buildShadowPass(cameraInfo.mainLightShadowNames[0], ppl, + buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, camera, mainLight, i, mapWidth, mapHeight); } } } - for (let l = 0; l < _validLights.length; l++) { - const light = _validLights[l]; + for (let l = 0; l < shadowInfo.validLights.length; l++) { + const light = shadowInfo.validLights[l]; const passName = `SpotLightShadow${l.toString()}${cameraName}`; - cameraInfo.spotLightShadowNames[l] = passName; + shadowInfo.spotLightShadowNames[l] = passName; buildShadowPass(passName, ppl, camera, light, 0, mapWidth, mapHeight); } - return cameraInfo; + return shadowInfo; } +const shadowInfo = new ShadowInfo(); export class GBufferInfo { color!: string; @@ -792,7 +802,7 @@ export function buildGBufferPass (camera: Camera, return gBufferInfo; } -class LightingInfo { +export class LightingInfo { declare deferredLightingMaterial: Material; private _init () { this.deferredLightingMaterial = new Material(); @@ -810,7 +820,7 @@ class LightingInfo { } } -let lightingInfo: LightingInfo | null = null; +let lightingInfo: LightingInfo; // deferred lighting pass export function buildLightingPass (camera: Camera, ppl: BasicPipeline, gBuffer: GBufferInfo) { @@ -903,7 +913,7 @@ export function buildUIPass (camera: Camera, const dsUIAndProfilerPassDSName = `dsUIAndProfilerPassDS${cameraName}`; if (!ppl.containsResource(dsUIAndProfilerPassRTName)) { ppl.addRenderWindow(dsUIAndProfilerPassRTName, Format.BGRA8, width, height, camera.window); - ppl.addDepthStencil(dsUIAndProfilerPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.EXTERNAL); + ppl.addDepthStencil(dsUIAndProfilerPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); } ppl.updateRenderWindow(dsUIAndProfilerPassRTName, camera.window); ppl.updateDepthStencil(dsUIAndProfilerPassDSName, width, height); @@ -2169,3 +2179,246 @@ export function buildHBAOPasses (camera: Camera, const haboCombined = _buildHBAOCombinedPass(camera, ppl, hbaoCombinedInputRTName, inputDS, inputRT); return { rtName: haboCombined.rtName, dsName: inputDS }; } + +export const MAX_LIGHTS_PER_CLUSTER = 100; +export const CLUSTERS_X = 16; +export const CLUSTERS_Y = 8; +export const CLUSTERS_Z = 24; +export const CLUSTER_COUNT = CLUSTERS_X * CLUSTERS_Y * CLUSTERS_Z; + +class ClusterLightData { + declare clusterBuildCS: Material; + declare clusterLightCullingCS: Material + clusters_x_threads = 16; + clusters_y_threads = 8; + clusters_z_threads = 1; + dispatchX = 1; + dispatchY = 1; + dispatchZ = 1; + + private _initMaterial (id: string, effect: string) { + const mat = new Material(); + mat.name = id; + mat.initialize({ effectName: effect }); + for (let i = 0; i < mat.passes.length; ++i) { + mat.passes[i].tryCompile(); + } + return mat; + } + + private _init () { + this.clusterBuildCS = this._initMaterial('builtin-cluster-build-cs-material', 'pipeline/cluster-build'); + this.clusterLightCullingCS = this._initMaterial('builtin-cluster-culling-cs-material', 'pipeline/cluster-culling'); + + this.dispatchX = CLUSTERS_X / this.clusters_x_threads; + this.dispatchY = CLUSTERS_Y / this.clusters_y_threads; + this.dispatchZ = CLUSTERS_Z / this.clusters_z_threads; + } + + constructor () { + this._init(); + } +} + +let _clusterLightData: ClusterLightData | null = null; +export function buildLightClusterBuildPass (camera: Camera, clusterData: ClusterLightData, + ppl: Pipeline) { + const cameraID = getCameraUniqueID(camera); + const clusterBufferName = `clusterBuffer${cameraID}`; + + const clusterBufferSize = CLUSTER_COUNT * 2 * 4; + if (!ppl.containsResource(clusterBufferName)) { + ppl.addStorageBuffer(clusterBufferName, Format.UNKNOWN, clusterBufferSize, ResourceResidency.PERSISTENT); + } + ppl.updateStorageBuffer(clusterBufferName, clusterBufferSize); + + const clusterPass = ppl.addComputePass('cluster-build-cs'); + clusterPass.addStorageBuffer(clusterBufferName, AccessType.WRITE, 'b_clustersBuffer'); + clusterPass.addQueue() + .addDispatch(clusterData.dispatchX, clusterData.dispatchY, clusterData.dispatchZ, clusterData.clusterBuildCS, 0); + + const width = camera.width * ppl.pipelineSceneData.shadingScale; + const height = camera.height * ppl.pipelineSceneData.shadingScale; + clusterPass.setVec4('cc_nearFar', new Vec4(camera.nearClip, camera.farClip, 0, 0)); + clusterPass.setVec4('cc_viewPort', new Vec4(width, height, width, height)); + clusterPass.setVec4('cc_workGroup', new Vec4(CLUSTERS_X, CLUSTERS_Y, CLUSTERS_Z, 0)); + clusterPass.setMat4('cc_matView', camera.matView); + clusterPass.setMat4('cc_matProjInv', camera.matProjInv); +} + +export function buildLightClusterCullingPass (camera: Camera, clusterData: ClusterLightData, + ppl: Pipeline) { + const cameraID = getCameraUniqueID(camera); + const clusterBufferName = `clusterBuffer${cameraID}`; + const clusterLightBufferName = `clusterLightBuffer${cameraID}`; + const clusterGlobalIndexBufferName = `b_globalIndexBuffer${cameraID}`; + const clusterLightIndicesBufferName = `clusterLIghtIndicesBuffer${cameraID}`; + const clusterLightGridBufferName = `clusterLightGridBuffer${cameraID}`; + + // index buffer + const lightIndexBufferSize = MAX_LIGHTS_PER_CLUSTER * CLUSTER_COUNT * 4; + const lightGridBufferSize = CLUSTER_COUNT * 4 * 4; + if (!ppl.containsResource(clusterLightIndicesBufferName)) { + ppl.addStorageBuffer(clusterLightIndicesBufferName, Format.UNKNOWN, lightIndexBufferSize, ResourceResidency.PERSISTENT); + } + if (!ppl.containsResource(clusterLightGridBufferName)) { + ppl.addStorageBuffer(clusterLightGridBufferName, Format.UNKNOWN, lightGridBufferSize, ResourceResidency.PERSISTENT); + } + + const clusterPass = ppl.addComputePass('cluster-culling-cs'); + clusterPass.addStorageBuffer(clusterLightBufferName, AccessType.READ, 'b_ccLightsBuffer'); + clusterPass.addStorageBuffer(clusterBufferName, AccessType.READ, 'b_clustersBuffer'); + clusterPass.addStorageBuffer(clusterLightIndicesBufferName, AccessType.WRITE, 'b_clusterLightIndicesBuffer'); + clusterPass.addStorageBuffer(clusterLightGridBufferName, AccessType.WRITE, 'b_clusterLightGridBuffer'); + clusterPass.addStorageBuffer(clusterGlobalIndexBufferName, AccessType.WRITE, 'b_globalIndexBuffer'); + clusterPass.addQueue() + .addDispatch(clusterData.dispatchX, clusterData.dispatchY, clusterData.dispatchZ, clusterData.clusterLightCullingCS, 0); + + const width = camera.width * ppl.pipelineSceneData.shadingScale; + const height = camera.height * ppl.pipelineSceneData.shadingScale; + clusterPass.setVec4('cc_nearFar', new Vec4(camera.nearClip, camera.farClip, 0, 0)); + clusterPass.setVec4('cc_viewPort', new Vec4(width, height, width, height)); + clusterPass.setVec4('cc_workGroup', new Vec4(CLUSTERS_X, CLUSTERS_Y, CLUSTERS_Z, 0)); + clusterPass.setMat4('cc_matView', camera.matView); + clusterPass.setMat4('cc_matProjInv', camera.matProjInv); +} + +export function buildLightData (camera: Camera, pipeline: BasicPipeline) { + validPunctualLightsCulling(pipeline, camera); + + // build cluster light data + const data = pipeline.pipelineSceneData; + const validLightCountForBuffer = nextPow2(Math.max(data.validPunctualLights.length, 1)); + + const lightBufferStride = 16; // 4 * vec4 + const clusterLightBufferSize = validLightCountForBuffer * 4 * lightBufferStride; + + const lightMeterScale = 10000.0; + const exposure = camera.exposure; + + const cameraID = getCameraUniqueID(camera); + const clusterLightBufferName = `clusterLightBuffer${cameraID}`; + const clusterGlobalIndexBufferName = `b_globalIndexBuffer${cameraID}`; + + const ppl = (pipeline as Pipeline); + if (!ppl.containsResource(clusterGlobalIndexBufferName)) { + ppl.addStorageBuffer(clusterGlobalIndexBufferName, Format.UNKNOWN, 4, ResourceResidency.PERSISTENT); + } + + if (!ppl.containsResource(clusterLightBufferName)) { + ppl.addStorageBuffer(clusterLightBufferName, Format.UNKNOWN, clusterLightBufferSize, ResourceResidency.PERSISTENT); + } + ppl.updateStorageBuffer(clusterLightBufferName, clusterLightBufferSize); + + const buffer = new ArrayBuffer(clusterLightBufferSize); + const view = new Float32Array(buffer); + + // gather light data + let index = 0; + for (const light of data.validPunctualLights) { + const offset = index * lightBufferStride; + const positionOffset = offset + 0; + const colorOffset = offset + 4; + const sizeRangeAngleOffset = offset + 8; + const directionOffset = offset + 12; + + let luminanceHDR = 0; + let luminanceLDR = 0; + let position: Vec3 | null; + if (light.type === LightType.POINT) { + const point = light as PointLight; + position = point.position; + luminanceLDR = point.luminanceLDR; + luminanceHDR = point.luminanceHDR; + + view[sizeRangeAngleOffset] = 0; + view[sizeRangeAngleOffset + 1] = point.range; + view[sizeRangeAngleOffset + 2] = 0; + view[sizeRangeAngleOffset + 3] = 0; + } else if (light.type === LightType.SPHERE) { + const sphere = light as SphereLight; + position = sphere.position; + luminanceLDR = sphere.luminanceLDR; + luminanceHDR = sphere.luminanceHDR; + + view[sizeRangeAngleOffset] = sphere.size; + view[sizeRangeAngleOffset + 1] = sphere.range; + view[sizeRangeAngleOffset + 2] = 0; + view[sizeRangeAngleOffset + 3] = 0; + } else if (light.type === LightType.SPOT) { + const spot = light as SpotLight; + position = spot.position; + luminanceLDR = spot.luminanceLDR; + luminanceHDR = spot.luminanceHDR; + + view[sizeRangeAngleOffset] = spot.size; + view[sizeRangeAngleOffset + 1] = spot.range; + view[sizeRangeAngleOffset + 2] = spot.spotAngle; + view[sizeRangeAngleOffset + 3] = 0; + + const dir = spot.direction; + view[directionOffset] = dir.x; + view[directionOffset + 1] = dir.y; + view[directionOffset + 2] = dir.z; + view[directionOffset + 3] = 0; + } else if (light.type === LightType.RANGED_DIRECTIONAL) { + const directional = light as RangedDirectionalLight; + position = directional.position; + luminanceLDR = directional.illuminanceLDR; + luminanceHDR = directional.illuminanceHDR; + + const right = directional.right; + view[sizeRangeAngleOffset] = right.x; + view[sizeRangeAngleOffset + 1] = right.y; + view[sizeRangeAngleOffset + 2] = right.z; + view[sizeRangeAngleOffset + 3] = 0; + + const dir = directional.direction; + view[directionOffset] = dir.x; + view[directionOffset + 1] = dir.y; + view[directionOffset + 2] = dir.z; + view[directionOffset + 3] = 0; + } + // position + view[positionOffset] = position!.x; + view[positionOffset + 1] = position!.y; + view[positionOffset + 2] = position!.z; + view[positionOffset + 3] = light.type; + + // color + const color = light.color; + if (light.useColorTemperature) { + const tempRGB = light.colorTemperatureRGB; + view[colorOffset] = color.x * tempRGB.x; + view[colorOffset + 1] = color.y * tempRGB.y; + view[colorOffset + 2] = color.z * tempRGB.z; + } else { + view[colorOffset] = color.x; + view[colorOffset + 1] = color.y; + view[colorOffset + 2] = color.z; + } + view[colorOffset + 3] = data.isHDR ? luminanceHDR * exposure * lightMeterScale : luminanceLDR; + index++; + } + // last float of first light data + view[3 * 4 + 3] = data.validPunctualLights.length; + + // global index buffer + const globalIndexBuffer = new ArrayBuffer(4); + const globalIndexBufferView = new Uint32Array(globalIndexBuffer); + globalIndexBufferView[0] = 0; + + const uploadPair1 = new UploadPair(new Uint8Array(buffer), clusterLightBufferName); + const uploadPair2 = new UploadPair(new Uint8Array(globalIndexBuffer), clusterGlobalIndexBufferName); + ppl.addUploadPass([uploadPair1, uploadPair2]); +} + +export function buildClusterPasses (camera: Camera, pipeline: BasicPipeline) { + buildLightData(camera, pipeline); + + const ppl = (pipeline as Pipeline); + if (!_clusterLightData) _clusterLightData = new ClusterLightData(); + + buildLightClusterBuildPass(camera, _clusterLightData, ppl); + buildLightClusterCullingPass(camera, _clusterLightData, ppl); +} diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 89048add3d..d5a53fa004 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -47,9 +47,9 @@ import { PipelineSceneData } from '../pipeline-scene-data'; import { PipelineInputAssemblerData } from '../render-pipeline'; import { DescriptorSetData, LayoutGraphData, PipelineLayoutData, RenderPhaseData, RenderStageData } from './layout-graph'; import { BasicPipeline, SceneVisitor } from './pipeline'; -import { Blit, ClearView, ComputePass, ComputeSubpass, CopyPass, Dispatch, ManagedBuffer, ManagedResource, ManagedTexture, MovePass, +import { Blit, ClearView, ComputePass, ComputeSubpass, CopyPass, Dispatch, FormatView, ManagedBuffer, ManagedResource, ManagedTexture, MovePass, RasterPass, RasterSubpass, RaytracePass, RenderData, RenderGraph, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResolvePass, ResourceDesc, - ResourceGraph, ResourceGraphVisitor, ResourceTraits, SceneData } from './render-graph'; + ResourceGraph, ResourceGraphVisitor, ResourceTraits, SceneData, SubresourceView } from './render-graph'; import { AttachmentType, ComputeView, QueueHint, RasterView, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; import { PipelineUBO } from '../pipeline-ubo'; import { RenderInfo, RenderObject, WebSceneTask, WebSceneTransversal } from './web-scene'; @@ -1760,6 +1760,10 @@ class ResourceVisitor implements ResourceGraphVisitor { swapchain (value: RenderSwapchain) { this.createDeviceTex(value); } + formatView (value: FormatView) { + } + subresourceView (value: SubresourceView) { + } } export class Executor { diff --git a/cocos/rendering/custom/index.ts b/cocos/rendering/custom/index.ts index 1230f9d72a..1df20bcded 100644 --- a/cocos/rendering/custom/index.ts +++ b/cocos/rendering/custom/index.ts @@ -75,6 +75,7 @@ function addCustomBuiltinPipelines (map: Map) { map.set('Forward', new ForwardPipelineBuilder()); map.set('Deferred', new DeferredPipelineBuilder()); map.set('Deprecated', new CustomPipelineBuilder()); + map.set('Test', new TestPipelineBuilder()); } addCustomBuiltinPipelines(customPipelineBuilderMap); diff --git a/cocos/rendering/custom/pipeline-define.ts b/cocos/rendering/custom/pipeline-define.ts new file mode 100644 index 0000000000..2ccc422a37 --- /dev/null +++ b/cocos/rendering/custom/pipeline-define.ts @@ -0,0 +1,613 @@ +import { EDITOR } from 'internal:constants'; +import { cclegacy } from '../../core'; +import { ClearFlagBit, Color, Format, LoadOp, StoreOp, Viewport } from '../../gfx'; +import { RenderWindow } from '../../render-scene/core/render-window'; +import { Camera, Light, LightType, ProbeType, ReflectionProbe, ShadowType } from '../../render-scene/scene'; +import { supportsR32FloatTexture } from '../define'; +import { AntiAliasing, GBufferInfo, getRTFormatBeforeToneMapping, LightingInfo, PostInfo, ShadowInfo, getLoadOpOfClearFlag, + getRenderArea, updateCameraUBO, validPunctualLightsCulling } from './define'; +import { BasicPipeline } from './pipeline'; +import { AttachmentType, LightInfo, QueueHint, ResourceResidency, SceneFlags } from './types'; +import { SRGBToLinear, getProfilerCamera } from '../pipeline-funcs'; + +export class CameraInfo { + constructor (camera: Camera, id: number, windowID: number, width: number, height: number) { + this.camera = camera; + this.id = id; + this.windowID = windowID; + this.width = width; + this.height = height; + } + public camera; + public id = 0xFFFFFFFF; + public windowID = 0xFFFFFFFF; + public width = 0; + public height = 0; +} +export const cameraInfos = new Map(); +export const windowInfos = new Map(); + +function prepareRenderWindow (camera: Camera): number { + let windowID = windowInfos.get(camera.window); + if (windowID === undefined) { + windowID = windowInfos.size; + windowInfos.set(camera.window, windowID); + } + return windowID; +} + +export function prepareResource (ppl: BasicPipeline, camera: Camera, + initResourceFunc: (ppl: BasicPipeline, info: CameraInfo) => void, + updateResourceFunc: (ppl: BasicPipeline, info: CameraInfo) => void): CameraInfo { + let info = cameraInfos.get(camera); + if (info !== undefined) { + let width = camera.window.width; + let height = camera.window.height; + if (width === 0) { + width = 1; + } + if (height === 0) { + height = 1; + } + const windowID = prepareRenderWindow(camera); + if (info.width !== width || info.height !== height || info.windowID !== windowID) { + return info; + } + updateResourceFunc(ppl, info); + return info; + } + const windowID = prepareRenderWindow(camera); + info = new CameraInfo( + camera, + cameraInfos.size, + windowID, + camera.window.width ? camera.window.width : 1, + camera.window.height ? camera.window.height : 1, + ); + + initResourceFunc(ppl, info); + cameraInfos.set(camera, info); + return info; +} + +function buildShadowRes (ppl: BasicPipeline, name: string, width, height) { + const fboW = width; + const fboH = height; + const shadowMapName = name; + const device = ppl.device; + if (!ppl.containsResource(shadowMapName)) { + const format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8; + ppl.addRenderTarget(shadowMapName, format, fboW, fboH, ResourceResidency.MANAGED); + ppl.addDepthStencil(`${shadowMapName}Depth`, Format.DEPTH_STENCIL, fboW, fboH, ResourceResidency.MANAGED); + } + ppl.updateRenderTarget(shadowMapName, fboW, fboH); + ppl.updateDepthStencil(`${shadowMapName}Depth`, fboW, fboH); +} +const shadowInfo = new ShadowInfo(); +export function setupShadowRes (ppl: BasicPipeline, cameraInfo: CameraInfo): ShadowInfo { + const camera = cameraInfo.camera; + validPunctualLightsCulling(ppl, camera); + const pipeline = ppl; + const shadow = pipeline.pipelineSceneData.shadows; + const validPunctualLights = ppl.pipelineSceneData.validPunctualLights; + const shadows = ppl.pipelineSceneData.shadows; + shadowInfo.reset(); + if (!shadow.enabled || shadow.type !== ShadowType.ShadowMap) { return shadowInfo; } + shadowInfo.shadowEnabled = true; + const _validLights: Light[] = shadowInfo.validLights; + let n = 0; + let m = 0; + for (;n < shadow.maxReceived && m < validPunctualLights.length;) { + const light = validPunctualLights[m]; + if (light.type === LightType.SPOT) { + const spotLight = light as any; + if (spotLight.shadowEnabled) { + _validLights.push(light); + n++; + } + } + m++; + } + + const { mainLight } = camera.scene!; + // build shadow map + const mapWidth = shadows.size.x; + const mapHeight = shadows.size.y; + if (mainLight && mainLight.shadowEnabled) { + shadowInfo.mainLightShadowNames[0] = `MainLightShadow${cameraInfo.id}`; + if (mainLight.shadowFixedArea) { + buildShadowRes(ppl, shadowInfo.mainLightShadowNames[0], mapWidth, mapHeight); + } else { + const csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1; + shadowInfo.mainLightShadowNames[0] = `MainLightShadow${cameraInfo.id}`; + for (let i = 0; i < csmLevel; i++) { + buildShadowRes(ppl, shadowInfo.mainLightShadowNames[0], mapWidth, mapHeight); + } + } + } + + for (let l = 0; l < _validLights.length; l++) { + const light = _validLights[l]; + const passName = `SpotLightShadow${l.toString()}${cameraInfo.id}`; + shadowInfo.spotLightShadowNames[l] = passName; + buildShadowRes(ppl, shadowInfo.spotLightShadowNames[l], mapWidth, mapHeight); + } + return shadowInfo; +} + +export const updateShadowRes = setupShadowRes; +let shadowPass; +function buildShadowPass (passName: Readonly, + ppl: BasicPipeline, + camera: Camera, light: Light, level: number, + width: Readonly, height: Readonly) { + const fboW = width; + const fboH = height; + const area = getRenderArea(camera, width, height, light, level); + width = area.width; + height = area.height; + const shadowMapName = passName; + if (!level) { + shadowPass = ppl.addRenderPass(width, height, 'default'); + shadowPass.name = passName; + shadowPass.setViewport(new Viewport(0, 0, fboW, fboH)); + shadowPass.addRenderTarget(shadowMapName, LoadOp.CLEAR, StoreOp.STORE, new Color(1, 1, 1, camera.clearColor.w)); + shadowPass.addDepthStencil(`${shadowMapName}Depth`, LoadOp.CLEAR, StoreOp.DISCARD, + camera.clearDepth, camera.clearStencil, ClearFlagBit.DEPTH_STENCIL); + } + const queue = shadowPass.addQueue(QueueHint.RENDER_OPAQUE); + queue.addSceneOfCamera(camera, new LightInfo(light, level), + SceneFlags.SHADOW_CASTER); + queue.setViewport(new Viewport(area.x, area.y, area.width, area.height)); +} +export function setupShadowPass (ppl: BasicPipeline, cameraInfo: CameraInfo) { + if (!shadowInfo.shadowEnabled) return; + const camera = cameraInfo.camera; + const shadows = ppl.pipelineSceneData.shadows; + // build shadow map + const mapWidth = shadows.size.x; + const mapHeight = shadows.size.y; + const { mainLight } = camera.scene!; + if (mainLight && mainLight.shadowEnabled) { + shadowInfo.mainLightShadowNames[0] = `MainLightShadow${cameraInfo.id}`; + if (mainLight.shadowFixedArea) { + buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, + camera, mainLight, 0, mapWidth, mapHeight); + } else { + const csmLevel = ppl.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1; + shadowInfo.mainLightShadowNames[0] = `MainLightShadow${cameraInfo.id}`; + for (let i = 0; i < csmLevel; i++) { + buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, + camera, mainLight, i, mapWidth, mapHeight); + } + } + } + + for (let l = 0; l < shadowInfo.validLights.length; l++) { + const light = shadowInfo.validLights[l]; + const passName = `SpotLightShadow${l.toString()}${cameraInfo.id}`; + shadowInfo.spotLightShadowNames[l] = passName; + buildShadowPass(passName, ppl, + camera, light, 0, mapWidth, mapHeight); + } +} + +export function setupForwardRes (ppl: BasicPipeline, cameraInfo: CameraInfo, isOffScreen = false) { + const camera = cameraInfo.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + setupShadowRes(ppl, cameraInfo); + if (!isOffScreen) { + ppl.addRenderWindow(`ForwardColor${cameraInfo.id}`, Format.BGRA8, width, height, cameraInfo.camera.window); + } else { + ppl.addRenderTarget(`ForwardColor${cameraInfo.id}`, getRTFormatBeforeToneMapping(ppl), + width, height, ResourceResidency.PERSISTENT); + } + ppl.addDepthStencil(`ForwardDepthStencil${cameraInfo.id}`, Format.DEPTH_STENCIL, width, height); +} + +export function updateForwardRes (ppl: BasicPipeline, cameraInfo: CameraInfo, isOffScreen = false) { + const camera = cameraInfo.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + updateShadowRes(ppl, cameraInfo); + if (!isOffScreen) { + ppl.updateRenderWindow(`ForwardColor${cameraInfo.id}`, cameraInfo.camera.window); + } else { + ppl.updateRenderTarget(`ForwardColor${cameraInfo.id}`, width, height); + } + ppl.updateDepthStencil(`ForwardDepthStencil${cameraInfo.id}`, width, height); +} + +export function setupForwardPass (ppl: BasicPipeline, cameraInfo: CameraInfo, isOffScreen = false, enabledAlpha = true) { + if (EDITOR) { + ppl.setMacroInt('CC_PIPELINE_TYPE', 0); + } + setupShadowPass(ppl, cameraInfo); + const cameraID = cameraInfo.id; + const area = getRenderArea(cameraInfo.camera, cameraInfo.camera.window.width, cameraInfo.camera.window.height); + const width = area.width; + const height = area.height; + const forwardPass = ppl.addRenderPass(width, height, 'default'); + forwardPass.name = `ForwardPass${cameraID}`; + forwardPass.setViewport(new Viewport(area.x, area.y, width, height)); + for (const dirShadowName of shadowInfo.mainLightShadowNames) { + if (ppl.containsResource(dirShadowName)) { + forwardPass.addTexture(dirShadowName, 'cc_shadowMap'); + } + } + for (const spotShadowName of shadowInfo.spotLightShadowNames) { + if (ppl.containsResource(spotShadowName)) { + forwardPass.addTexture(spotShadowName, 'cc_spotShadowMap'); + } + } + const camera = cameraInfo.camera; + forwardPass.addRenderTarget(`ForwardColor${cameraInfo.id}`, + isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), + StoreOp.STORE, + new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); + forwardPass.addDepthStencil(`ForwardDepthStencil${cameraInfo.id}`, + isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), + // If the depth texture is used by subsequent passes, it must be set to store. + isOffScreen ? StoreOp.DISCARD : StoreOp.STORE, + camera.clearDepth, + camera.clearStencil, + camera.clearFlag); + forwardPass + .addQueue(QueueHint.RENDER_OPAQUE) + .addSceneOfCamera(camera, new LightInfo(), + SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT + | SceneFlags.DEFAULT_LIGHTING | SceneFlags.DRAW_INSTANCING); + let sceneFlags = SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY; + if (!isOffScreen) { + sceneFlags |= SceneFlags.UI; + forwardPass.showStatistics = true; + } + if (enabledAlpha) { + forwardPass + .addQueue(QueueHint.RENDER_TRANSPARENT) + .addSceneOfCamera(camera, new LightInfo(), sceneFlags); + } + return { rtName: `ForwardColor${cameraInfo.id}`, dsName: `ForwardDepthStencil${cameraInfo.id}` }; +} + +export function buildReflectionProbeRes (ppl: BasicPipeline, probe: ReflectionProbe, renderWindow: RenderWindow, faceIdx: number) { + const area = probe.renderArea(); + const width = area.x; + const height = area.y; + + const probePassRTName = `reflectionProbePassColor${faceIdx}`; + const probePassDSName = `reflectionProbePassDS${faceIdx}`; + + if (!ppl.containsResource(probePassRTName)) { + ppl.addRenderWindow(probePassRTName, Format.RGBA8, width, height, renderWindow); + ppl.addDepthStencil(probePassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.EXTERNAL); + } + ppl.updateRenderWindow(probePassRTName, renderWindow); + ppl.updateDepthStencil(probePassDSName, width, height); +} + +export function setupReflectionProbeRes (ppl: BasicPipeline, info: CameraInfo) { + if (!cclegacy.internal.reflectionProbeManager) return; + const probes = cclegacy.internal.reflectionProbeManager.getProbes(); + if (probes.length === 0) return; + for (let i = 0; i < probes.length; i++) { + const probe = probes[i]; + if (probe.needRender) { + if (probes[i].probeType === ProbeType.PLANAR) { + buildReflectionProbeRes(ppl, probe, probe.realtimePlanarTexture.window!, 0); + } else if (EDITOR) { + for (let faceIdx = 0; faceIdx < probe.bakedCubeTextures.length; faceIdx++) { + probe.updateCameraDir(faceIdx); + buildReflectionProbeRes(ppl, probe, probe.bakedCubeTextures[faceIdx].window!, faceIdx); + } + probe.needRender = false; + } + } + } +} + +export const updateReflectionProbeRes = setupReflectionProbeRes; + +function buildReflectProbePass (ppl: BasicPipeline, info: CameraInfo, probe: ReflectionProbe, renderWindow: RenderWindow, faceIdx: number) { + const area = probe.renderArea(); + const width = area.x; + const height = area.y; + const probeCamera = probe.camera; + + const probePassRTName = `reflectionProbePassColor${faceIdx}`; + const probePassDSName = `reflectionProbePassDS${faceIdx}`; + + const probePass = ppl.addRenderPass(width, height, 'default'); + probePass.name = `ReflectionProbePass${faceIdx}`; + probePass.setViewport(new Viewport(0, 0, width, height)); + probePass.addRenderTarget(probePassRTName, getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.RENDER_TARGET), + StoreOp.STORE, new Color(probeCamera.clearColor.x, probeCamera.clearColor.y, probeCamera.clearColor.z, probeCamera.clearColor.w)); + probePass.addDepthStencil(probePassDSName, getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.DEPTH_STENCIL), + StoreOp.STORE, probeCamera.clearDepth, probeCamera.clearStencil, probeCamera.clearFlag); + const passBuilder = probePass.addQueue(QueueHint.RENDER_OPAQUE); + passBuilder.addSceneOfCamera(info.camera, new LightInfo(), SceneFlags.REFLECTION_PROBE); + updateCameraUBO(passBuilder as unknown as any, probeCamera, ppl); +} + +export function setupReflectionProbePass (ppl: BasicPipeline, info: CameraInfo) { + if (!cclegacy.internal.reflectionProbeManager) return; + const probes = cclegacy.internal.reflectionProbeManager.getProbes(); + if (probes.length === 0) return; + for (let i = 0; i < probes.length; i++) { + const probe = probes[i]; + if (probe.needRender) { + if (probes[i].probeType === ProbeType.PLANAR) { + buildReflectProbePass(ppl, info, probe, probe.realtimePlanarTexture.window!, 0); + } else if (EDITOR) { + for (let faceIdx = 0; faceIdx < probe.bakedCubeTextures.length; faceIdx++) { + probe.updateCameraDir(faceIdx); + buildReflectProbePass(ppl, info, probe, probe.bakedCubeTextures[faceIdx].window!, faceIdx); + } + probe.needRender = false; + } + } + } +} +const gBufferInfo = new GBufferInfo(); +export function setupGBufferRes (ppl: BasicPipeline, info: CameraInfo) { + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + const gBufferPassRTName = `gBufferPassColorCamera`; + const gBufferPassNormal = `gBufferPassNormal`; + const gBufferPassEmissive = `gBufferPassEmissive`; + const gBufferPassDSName = `gBufferPassDSCamera`; + const colFormat = Format.RGBA16F; + ppl.addRenderTarget(gBufferPassRTName, colFormat, width, height, ResourceResidency.MANAGED); + ppl.addRenderTarget(gBufferPassNormal, colFormat, width, height, ResourceResidency.MANAGED); + ppl.addRenderTarget(gBufferPassEmissive, colFormat, width, height, ResourceResidency.MANAGED); + ppl.addDepthStencil(gBufferPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + gBufferInfo.color = gBufferPassRTName; + gBufferInfo.normal = gBufferPassNormal; + gBufferInfo.emissive = gBufferPassEmissive; + gBufferInfo.ds = gBufferPassDSName; +} + +export function updateGBufferRes (ppl: BasicPipeline, info: CameraInfo) { + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + const gBufferPassRTName = `gBufferPassColorCamera`; + const gBufferPassNormal = `gBufferPassNormal`; + const gBufferPassEmissive = `gBufferPassEmissive`; + const gBufferPassDSName = `gBufferPassDSCamera`; + ppl.updateRenderTarget(gBufferPassRTName, width, height); + ppl.updateRenderTarget(gBufferPassNormal, width, height); + ppl.updateRenderTarget(gBufferPassEmissive, width, height); + ppl.updateDepthStencil(gBufferPassDSName, width, height); +} + +export function setupGBufferPass (ppl: BasicPipeline, info: CameraInfo) { + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + const gBufferPassRTName = gBufferInfo.color; + const gBufferPassNormal = gBufferInfo.normal; + const gBufferPassEmissive = gBufferInfo.emissive; + const gBufferPassDSName = gBufferInfo.ds; + // gbuffer pass + const gBufferPass = ppl.addRenderPass(width, height, 'default'); + gBufferPass.name = `CameraGBufferPass${info.id}`; + gBufferPass.setViewport(new Viewport(area.x, area.y, width, height)); + const rtColor = new Color(0, 0, 0, 0); + if (camera.clearFlag & ClearFlagBit.COLOR) { + if (ppl.pipelineSceneData.isHDR) { + SRGBToLinear(rtColor, camera.clearColor); + } else { + rtColor.x = camera.clearColor.x; + rtColor.y = camera.clearColor.y; + rtColor.z = camera.clearColor.z; + } + } + gBufferPass.addRenderTarget(gBufferPassRTName, LoadOp.CLEAR, StoreOp.STORE, rtColor); + gBufferPass.addRenderTarget(gBufferPassNormal, LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0)); + gBufferPass.addRenderTarget(gBufferPassEmissive, LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0)); + gBufferPass.addDepthStencil(gBufferPassDSName, LoadOp.CLEAR, StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag); + gBufferPass + .addQueue(QueueHint.RENDER_OPAQUE) + .addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT); + return gBufferPass; +} + +export function setupLightingRes (ppl: BasicPipeline, info: CameraInfo) { + setupShadowRes(ppl, info); + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + + const deferredLightingPassRTName = `deferredLightingPassRTName`; + const deferredLightingPassDS = `deferredLightingPassDS`; + ppl.addRenderTarget(deferredLightingPassRTName, Format.RGBA8, width, height, ResourceResidency.MANAGED); + ppl.addDepthStencil(deferredLightingPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); +} + +export function updateLightingRes (ppl: BasicPipeline, info: CameraInfo) { + updateShadowRes(ppl, info); + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + + const deferredLightingPassRTName = `deferredLightingPassRTName`; + const deferredLightingPassDS = `deferredLightingPassDS`; + ppl.updateRenderTarget(deferredLightingPassRTName, width, height); + ppl.updateDepthStencil(deferredLightingPassDS, width, height); +} +let lightingInfo: LightingInfo; +export function setupLightingPass (ppl: BasicPipeline, info: CameraInfo) { + setupShadowPass(ppl, info); + if (!lightingInfo) { + lightingInfo = new LightingInfo(); + } + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + + const deferredLightingPassRTName = `deferredLightingPassRTName`; + const deferredLightingPassDS = `deferredLightingPassDS`; + // lighting pass + const lightingPass = ppl.addRenderPass(width, height, 'deferred-lighting'); + lightingPass.name = `CameraLightingPass${info.id}`; + lightingPass.setViewport(new Viewport(area.x, area.y, width, height)); + for (const dirShadowName of shadowInfo.mainLightShadowNames) { + if (ppl.containsResource(dirShadowName)) { + lightingPass.addTexture(dirShadowName, 'cc_shadowMap'); + } + } + for (const spotShadowName of shadowInfo.spotLightShadowNames) { + if (ppl.containsResource(spotShadowName)) { + lightingPass.addTexture(spotShadowName, 'cc_spotShadowMap'); + } + } + if (ppl.containsResource(gBufferInfo.color)) { + lightingPass.addTexture(gBufferInfo.color, 'gbuffer_albedoMap'); + lightingPass.addTexture(gBufferInfo.normal, 'gbuffer_normalMap'); + lightingPass.addTexture(gBufferInfo.emissive, 'gbuffer_emissiveMap'); + lightingPass.addTexture(gBufferInfo.ds, 'depth_stencil'); + } + const lightingClearColor = new Color(0, 0, 0, 0); + if (camera.clearFlag & ClearFlagBit.COLOR) { + lightingClearColor.x = camera.clearColor.x; + lightingClearColor.y = camera.clearColor.y; + lightingClearColor.z = camera.clearColor.z; + } + lightingClearColor.w = 0; + lightingPass.addRenderTarget(deferredLightingPassRTName, LoadOp.CLEAR, StoreOp.STORE, lightingClearColor); + lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( + camera, lightingInfo.deferredLightingMaterial, 0, + SceneFlags.VOLUMETRIC_LIGHTING, + ); + // lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), + // SceneFlags.TRANSPARENT_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.GEOMETRY); + return { rtName: deferredLightingPassRTName, dsName: deferredLightingPassDS }; +} + +export function setupPostprocessRes (ppl: BasicPipeline, info: CameraInfo) { + const cameraID = info.id; + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + const postprocessPassRTName = `postprocessPassRTName${cameraID}`; + const postprocessPassDS = `postprocessPassDS${cameraID}`; + ppl.addRenderWindow(postprocessPassRTName, Format.BGRA8, width, height, camera.window); + ppl.addDepthStencil(postprocessPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.EXTERNAL); +} + +export function updatePostprocessRes (ppl: BasicPipeline, info: CameraInfo) { + const cameraID = info.id; + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + const postprocessPassRTName = `postprocessPassRTName${cameraID}`; + const postprocessPassDS = `postprocessPassDS${cameraID}`; + ppl.updateRenderWindow(postprocessPassRTName, camera.window); + ppl.updateDepthStencil(postprocessPassDS, width, height); +} +let postInfo: PostInfo; +export function setupPostprocessPass (ppl: BasicPipeline, + info: CameraInfo, + inputTex: string) { + if (!postInfo) { + postInfo = new PostInfo(); + } + const cameraID = info.id; + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + const postprocessPassRTName = `postprocessPassRTName${cameraID}`; + const postprocessPassDS = `postprocessPassDS${cameraID}`; + const postprocessPass = ppl.addRenderPass(width, height, 'post-process'); + postprocessPass.name = `CameraPostprocessPass${cameraID}`; + postprocessPass.setViewport(new Viewport(area.x, area.y, area.width, area.height)); + if (ppl.containsResource(inputTex)) { + postprocessPass.addTexture(inputTex, 'outputResultMap'); + } + const postClearColor = new Color(0, 0, 0, camera.clearColor.w); + if (camera.clearFlag & ClearFlagBit.COLOR) { + postClearColor.x = camera.clearColor.x; + postClearColor.y = camera.clearColor.y; + postClearColor.z = camera.clearColor.z; + } + postprocessPass.addRenderTarget(postprocessPassRTName, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, postClearColor); + postprocessPass.addDepthStencil(postprocessPassDS, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), + StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag); + postprocessPass.addQueue(QueueHint.NONE).addFullscreenQuad( + postInfo.postMaterial, 0, SceneFlags.NONE, + ); + if (getProfilerCamera() === camera) { + postprocessPass.showStatistics = true; + } + return { rtName: postprocessPassRTName, dsName: postprocessPassDS }; +} + +export function setupUIRes (ppl: BasicPipeline, + info: CameraInfo) { + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + + const dsUIAndProfilerPassRTName = `dsUIAndProfilerPassColor${info.id}`; + const dsUIAndProfilerPassDSName = `dsUIAndProfilerPassDS${info.id}`; + ppl.addRenderWindow(dsUIAndProfilerPassRTName, Format.BGRA8, width, height, camera.window); + ppl.addDepthStencil(dsUIAndProfilerPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.EXTERNAL); +} + +export function updateUIRes (ppl: BasicPipeline, + info: CameraInfo) { + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + + const dsUIAndProfilerPassRTName = `dsUIAndProfilerPassColor${info.id}`; + const dsUIAndProfilerPassDSName = `dsUIAndProfilerPassDS${info.id}`; + ppl.updateRenderWindow(dsUIAndProfilerPassRTName, camera.window); + ppl.updateDepthStencil(dsUIAndProfilerPassDSName, width, height); +} + +export function setupUIPass (ppl: BasicPipeline, + info: CameraInfo) { + const camera = info.camera; + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + const dsUIAndProfilerPassRTName = `dsUIAndProfilerPassColor${info.id}`; + const dsUIAndProfilerPassDSName = `dsUIAndProfilerPassDS${info.id}`; + const uiAndProfilerPass = ppl.addRenderPass(width, height, 'default'); + uiAndProfilerPass.name = `CameraUIAndProfilerPass${info.id}`; + uiAndProfilerPass.setViewport(new Viewport(area.x, area.y, width, height)); + uiAndProfilerPass.addRenderTarget(dsUIAndProfilerPassRTName, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), + StoreOp.STORE, + new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); + uiAndProfilerPass.addDepthStencil(dsUIAndProfilerPassDSName, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), + StoreOp.STORE, + camera.clearDepth, camera.clearStencil, camera.clearFlag); + const sceneFlags = SceneFlags.UI; + uiAndProfilerPass + .addQueue(QueueHint.RENDER_TRANSPARENT) + .addSceneOfCamera(camera, new LightInfo(), sceneFlags); + if (getProfilerCamera() === camera) { + uiAndProfilerPass.showStatistics = true; + } +} diff --git a/cocos/rendering/custom/pipeline.ts b/cocos/rendering/custom/pipeline.ts index 2a1e40e41c..f61804b2fe 100644 --- a/cocos/rendering/custom/pipeline.ts +++ b/cocos/rendering/custom/pipeline.ts @@ -168,7 +168,7 @@ export interface BasicRenderPassBuilder extends Setter { * @deprecated method will be removed in 3.8.0 */ addComputeView (name: string, view: ComputeView): void; - addQueue (hint?: QueueHint, layoutName?: string): RenderQueueBuilder; + addQueue (hint?: QueueHint, phaseName?: string): RenderQueueBuilder; setViewport (viewport: Viewport): void; setVersion (name: string, version: number): void; showStatistics: boolean; @@ -223,13 +223,13 @@ export interface BasicPipeline extends PipelineRuntime { addRenderPass ( width: number, height: number, - layoutName?: string): BasicRenderPassBuilder; + passName?: string): BasicRenderPassBuilder; addMultisampleRenderPass ( width: number, height: number, count: number, quality: number, - layoutName?: string): BasicRenderPassBuilder; + passName?: string): BasicRenderPassBuilder; addResolvePass (resolvePairs: ResolvePair[]): void; addCopyPass (copyPairs: CopyPair[]): void; getDescriptorSetLayout (shaderName: string, freq: UpdateFrequency): DescriptorSetLayout | null; @@ -271,7 +271,7 @@ export interface RenderSubpassBuilder extends Setter { */ addComputeView (name: string, view: ComputeView): void; setViewport (viewport: Viewport): void; - addQueue (hint?: QueueHint, layoutName?: string): RenderQueueBuilder; + addQueue (hint?: QueueHint, phaseName?: string): RenderQueueBuilder; showStatistics: boolean; /** * @beta function signature might change @@ -316,7 +316,7 @@ export interface ComputeSubpassBuilder extends Setter { * @deprecated method will be removed in 3.8.0 */ addComputeView (name: string, view: ComputeView): void; - addQueue (layoutName?: string): ComputeQueueBuilder; + addQueue (phaseName?: string): ComputeQueueBuilder; /** * @beta function signature might change */ @@ -332,12 +332,12 @@ export interface RenderPassBuilder extends BasicRenderPassBuilder { name: string, accessType: AccessType, slotName: string): void; - addRenderSubpass (layoutName?: string): RenderSubpassBuilder; + addRenderSubpass (subpassName: string): RenderSubpassBuilder; addMultisampleRenderSubpass ( count: number, quality: number, - layoutName?: string): MultisampleRenderSubpassBuilder; - addComputeSubpass (layoutName?: string): ComputeSubpassBuilder; + subpassName: string): MultisampleRenderSubpassBuilder; + addComputeSubpass (subpassName?: string): ComputeSubpassBuilder; /** * @beta function signature might change */ @@ -362,7 +362,7 @@ export interface ComputePassBuilder extends Setter { * @deprecated method will be removed in 3.8.0 */ addComputeView (name: string, view: ComputeView): void; - addQueue (layoutName?: string): ComputeQueueBuilder; + addQueue (phaseName?: string): ComputeQueueBuilder; /** * @beta function signature might change */ @@ -425,8 +425,8 @@ export interface Pipeline extends BasicPipeline { addRenderPass ( width: number, height: number, - layoutName?: string): RenderPassBuilder; - addComputePass (layoutName: string): ComputePassBuilder; + passName: string): RenderPassBuilder; + addComputePass (passName: string): ComputePassBuilder; addUploadPass (uploadPairs: UploadPair[]): void; addMovePass (movePairs: MovePair[]): void; /** diff --git a/cocos/rendering/custom/render-graph.ts b/cocos/rendering/custom/render-graph.ts index 7559d52490..6cf3f4bada 100644 --- a/cocos/rendering/custom/render-graph.ts +++ b/cocos/rendering/custom/render-graph.ts @@ -452,6 +452,21 @@ export class PersistentRenderPassAndFramebuffer { clearStencil = 0; } +export class FormatView { + format: Format = Format.UNKNOWN; +} + +export class SubresourceView { + /*refcount*/ textureView: Texture | null = null; + format: Format = Format.UNKNOWN; + indexOrFirstMipLevel = 0; + numMipLevels = 0; + firstArraySlice = 0; + numArraySlices = 0; + firstPlane = 0; + numPlanes = 0; +} + //================================================================= // ResourceGraph //================================================================= @@ -464,6 +479,8 @@ export const enum ResourceGraphValue { PersistentTexture, Framebuffer, Swapchain, + FormatView, + SubresourceView, } export function getResourceGraphValueName (e: ResourceGraphValue): string { @@ -475,6 +492,8 @@ export function getResourceGraphValueName (e: ResourceGraphValue): string { case ResourceGraphValue.PersistentTexture: return 'PersistentTexture'; case ResourceGraphValue.Framebuffer: return 'Framebuffer'; case ResourceGraphValue.Swapchain: return 'Swapchain'; + case ResourceGraphValue.FormatView: return 'FormatView'; + case ResourceGraphValue.SubresourceView: return 'SubresourceView'; default: return ''; } } @@ -487,6 +506,8 @@ export interface ResourceGraphValueType { [ResourceGraphValue.PersistentTexture]: Texture [ResourceGraphValue.Framebuffer]: Framebuffer [ResourceGraphValue.Swapchain]: RenderSwapchain + [ResourceGraphValue.FormatView]: FormatView + [ResourceGraphValue.SubresourceView]: SubresourceView } export interface ResourceGraphVisitor { @@ -497,6 +518,8 @@ export interface ResourceGraphVisitor { persistentTexture(value: Texture): unknown; framebuffer(value: Framebuffer): unknown; swapchain(value: RenderSwapchain): unknown; + formatView(value: FormatView): unknown; + subresourceView(value: SubresourceView): unknown; } export type ResourceGraphObject = ManagedResource @@ -505,7 +528,9 @@ export type ResourceGraphObject = ManagedResource | Buffer | Texture | Framebuffer -| RenderSwapchain; +| RenderSwapchain +| FormatView +| SubresourceView; //----------------------------------------------------------------- // Graph Concept @@ -614,6 +639,8 @@ export class ResourceGraph implements BidirectionalGraph , NamedGraph , ComponentGraph , PolymorphicGraph +, ReferenceGraph +, MutableReferenceGraph , UuidGraph { //----------------------------------------------------------------- // Graph @@ -711,6 +738,7 @@ export class ResourceGraph implements BidirectionalGraph traits: ResourceTraits, states: ResourceStates, sampler: SamplerInfo, + u = 0xFFFFFFFF, ): number { const vert = new ResourceGraphVertex(id, object); const v = this._vertices.length; @@ -722,9 +750,16 @@ export class ResourceGraph implements BidirectionalGraph this._samplerInfo.push(sampler); // UuidGraph this._valueIndex.set(name, v); + + // ReferenceGraph + if (u !== 0xFFFFFFFF) { + this.addEdge(u, v); + } + return v; } clearVertex (v: number): void { + // ReferenceGraph(Alias) const vert = this._vertices[v]; // clear out edges for (const oe of vert._outEdges) { @@ -947,6 +982,10 @@ export class ResourceGraph implements BidirectionalGraph return visitor.framebuffer(vert._object as Framebuffer); case ResourceGraphValue.Swapchain: return visitor.swapchain(vert._object as RenderSwapchain); + case ResourceGraphValue.FormatView: + return visitor.formatView(vert._object as FormatView); + case ResourceGraphValue.SubresourceView: + return visitor.subresourceView(vert._object as SubresourceView); default: throw Error('polymorphic type not found'); } @@ -1000,6 +1039,20 @@ export class ResourceGraph implements BidirectionalGraph throw Error('value id not match'); } } + getFormatView (v: number): FormatView { + if (this._vertices[v]._id === ResourceGraphValue.FormatView) { + return this._vertices[v]._object as FormatView; + } else { + throw Error('value id not match'); + } + } + getSubresourceView (v: number): SubresourceView { + if (this._vertices[v]._id === ResourceGraphValue.SubresourceView) { + return this._vertices[v]._object as SubresourceView; + } else { + throw Error('value id not match'); + } + } tryGetManaged (v: number): ManagedResource | null { if (this._vertices[v]._id === ResourceGraphValue.Managed) { return this._vertices[v]._object as ManagedResource; @@ -1049,6 +1102,95 @@ export class ResourceGraph implements BidirectionalGraph return null; } } + tryGetFormatView (v: number): FormatView | null { + if (this._vertices[v]._id === ResourceGraphValue.FormatView) { + return this._vertices[v]._object as FormatView; + } else { + return null; + } + } + tryGetSubresourceView (v: number): SubresourceView | null { + if (this._vertices[v]._id === ResourceGraphValue.SubresourceView) { + return this._vertices[v]._object as SubresourceView; + } else { + return null; + } + } + //----------------------------------------------------------------- + // ReferenceGraph + // type reference_descriptor = ED; + // type child_iterator = OutEI; + // type parent_iterator = InEI; + reference (u: number, v: number): boolean { + for (const oe of this._vertices[u]._outEdges) { + if (v === oe.target as number) { + return true; + } + } + return false; + } + parent (e: ED): number { + return e.source as number; + } + child (e: ED): number { + return e.target as number; + } + parents (v: number): InEI { + return new InEI(this._vertices[v]._inEdges.values(), v); + } + children (v: number): OutEI { + return new OutEI(this._vertices[v]._outEdges.values(), v); + } + numParents (v: number): number { + return this._vertices[v]._inEdges.length; + } + numChildren (v: number): number { + return this._vertices[v]._outEdges.length; + } + getParent (v: number): number { + if (v === 0xFFFFFFFF) { + return 0xFFFFFFFF; + } + const list = this._vertices[v]._inEdges; + if (list.length === 0) { + return 0xFFFFFFFF; + } else { + return list[0].target as number; + } + } + isAncestor (ancestor: number, descendent: number): boolean { + const pseudo = 0xFFFFFFFF; + if (ancestor === descendent) { + // when ancestor === descendent, is_ancestor is defined as false + return false; + } + if (ancestor === pseudo) { + // special case: pseudo root is always ancestor + return true; + } + if (descendent === pseudo) { + // special case: pseudo root is never descendent + return false; + } + for (let parent = this.getParent(descendent); parent !== pseudo;) { + if (ancestor === parent) { + return true; + } + parent = this.getParent(parent); + } + return false; + } + //----------------------------------------------------------------- + // MutableReferenceGraph + addReference (u: number, v: number): ED | null { + return this.addEdge(u, v); + } + removeReference (e: ED): void { + return this.removeEdge(e); + } + removeReferences (u: number, v: number): void { + return this.removeEdges(u, v); + } //----------------------------------------------------------------- // UuidGraph contains (key: string): boolean { diff --git a/cocos/rendering/custom/utils.ts b/cocos/rendering/custom/utils.ts index 5489f4a602..3d4cab5c3a 100644 --- a/cocos/rendering/custom/utils.ts +++ b/cocos/rendering/custom/utils.ts @@ -30,7 +30,7 @@ import { Camera } from '../../render-scene/scene/camera'; export function isUICamera (camera: Camera): boolean { const scene = camera.scene!; const batches = scene.batches; - for (let i = 0; i < batches.length; i++) { + for (let i = 0; batches && i < batches.length; i++) { const batch = batches[i]; if (camera.visibility & batch.visFlags) { return true; diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index b95d70cb7c..58cb8624ef 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -1712,7 +1712,7 @@ export class WebPipeline implements BasicPipeline { throw new Error('RenderGraph cannot be built without being created'); } if (!this._compiler) { - this._compiler = new Compiler(this, this._resourceGraph, this._layoutGraph); + this._compiler = new Compiler(this, this._renderGraph, this._resourceGraph, this._layoutGraph); } this._compiler.compile(this._renderGraph); } diff --git a/editor/assets/effects/pipeline/cluster-build.effect b/editor/assets/effects/pipeline/cluster-build.effect new file mode 100644 index 0000000000..505e1ccac7 --- /dev/null +++ b/editor/assets/effects/pipeline/cluster-build.effect @@ -0,0 +1,63 @@ +// Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - compute: cluster-main + pass: cluster-build-cs +}% + + +CCProgram cluster-main %{ + precision highp float; + #define LOCAL_SIZE_Z 1 + + layout (local_size_x = 16, local_size_y = 8, local_size_z = LOCAL_SIZE_Z) in; + + #pragma rate CCConst pass + layout(std140) uniform CCConst { + vec4 cc_nearFar; + vec4 cc_viewPort; + vec4 cc_workGroup; + mat4 cc_matView; + mat4 cc_matProjInv; + }; + #pragma rate b_clustersBuffer pass + layout(std430) buffer b_clustersBuffer { vec4 b_clusters[]; }; + + vec4 screen2Eye(vec4 coord) { + vec3 ndc = vec3( + 2.0 * (coord.x - cc_viewPort.x) / cc_viewPort.x - 1.0, + 2.0 * (coord.y - cc_viewPort.y) / cc_viewPort.y - 1.0, + 2.0 * coord.z - 1.0); + vec4 eye = ((cc_matProjInv) * (vec4(ndc, 1.0))); + eye = eye / eye.w; + return eye; + } + + void main () { + + uint clusterIndex = gl_GlobalInvocationID.z * gl_WorkGroupSize.x * gl_WorkGroupSize.y + + gl_GlobalInvocationID.y * gl_WorkGroupSize.x + + gl_GlobalInvocationID.x; + + float clusterSizeX = ceil(cc_viewPort.x / cc_workGroup.x); + float clusterSizeY = ceil(cc_viewPort.y / cc_workGroup.y); + vec4 minScreen = vec4(vec2(gl_GlobalInvocationID.xy) * vec2(clusterSizeX, clusterSizeY), 1.0, 1.0); + vec4 maxScreen = vec4(vec2(gl_GlobalInvocationID.xy + uvec2(1, 1)) * vec2(clusterSizeX, clusterSizeY), 1.0, 1.0); + vec3 minEye = screen2Eye(minScreen).xyz; + vec3 maxEye = screen2Eye(maxScreen).xyz; + float clusterNear = -cc_nearFar.x * pow(cc_nearFar.y / cc_nearFar.x, float(gl_GlobalInvocationID.z) / cc_workGroup.z); + float clusterFar = -cc_nearFar.x * pow(cc_nearFar.y / cc_nearFar.x, float(gl_GlobalInvocationID.z + 1u) / cc_workGroup.z); + vec3 minNear = minEye * clusterNear / minEye.z; + vec3 minFar = minEye * clusterFar / minEye.z; + vec3 maxNear = maxEye * clusterNear / maxEye.z; + vec3 maxFar = maxEye * clusterFar / maxEye.z; + vec3 minBounds = min(min(minNear, minFar), min(maxNear, maxFar)); + vec3 maxBounds = max(max(minNear, minFar), max(maxNear, maxFar)); + + b_clusters[2u * clusterIndex + 0u] = vec4(minBounds, 1.0); + b_clusters[2u * clusterIndex + 1u] = vec4(maxBounds, 1.0); + } +}% diff --git a/editor/assets/effects/pipeline/cluster-build.effect.meta b/editor/assets/effects/pipeline/cluster-build.effect.meta new file mode 100644 index 0000000000..9a260f9227 --- /dev/null +++ b/editor/assets/effects/pipeline/cluster-build.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.7.0", + "importer": "effect", + "imported": true, + "uuid": "45e7c0c8-2699-4912-b45f-d42bb8384189", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/pipeline/cluster-culling.effect b/editor/assets/effects/pipeline/cluster-culling.effect new file mode 100644 index 0000000000..e9f4fff53e --- /dev/null +++ b/editor/assets/effects/pipeline/cluster-culling.effect @@ -0,0 +1,135 @@ +// Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - compute: cluster-main + pass: cluster-culling-cs +}% + + +CCProgram cluster-main %{ + precision highp float; + #define LOCAL_SIZE_Z 1 + + #pragma rate CCConst pass + layout(std140) uniform CCConst { + vec4 cc_nearFar; + vec4 cc_viewPort; + vec4 cc_workGroup; + mat4 cc_matView; + mat4 cc_matProjInv; + }; + + #pragma rate b_ccLightsBuffer pass + layout(std430) readonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; }; + + #pragma rate b_clustersBuffer pass + layout(std430) readonly buffer b_clustersBuffer { vec4 b_clusters[]; }; + + #pragma rate b_clusterLightIndicesBuffer pass + layout(std430) buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; }; + + #pragma rate b_clusterLightGridBuffer pass + layout(std430) buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; }; + + #pragma rate b_globalIndexBuffer pass + layout(std430) buffer b_globalIndexBuffer { uint b_globalIndex[]; }; + + struct CCLight { + vec4 cc_lightPos; + vec4 cc_lightColor; + vec4 cc_lightSizeRangeAngle; + vec4 cc_lightDir; + }; + uint ccLightCount() + { + return uint(b_ccLights[3].w); + } + CCLight getCCLight(uint i) + { + CCLight light; + light.cc_lightPos = b_ccLights[4u * i + 0u]; + light.cc_lightColor = b_ccLights[4u * i + 1u]; + light.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u]; + light.cc_lightDir = b_ccLights[4u * i + 3u]; + return light; + } + struct Cluster { + vec3 minBounds; + vec3 maxBounds; + }; + struct LightGrid { + uint offset; + uint ccLights; + }; + Cluster getCluster(uint index) + { + Cluster cluster; + cluster.minBounds = b_clusters[2u * index + 0u].xyz; + cluster.maxBounds = b_clusters[2u * index + 1u].xyz; + return cluster; + } + bool ccLightIntersectsCluster(CCLight light, Cluster cluster) + { + if (light.cc_lightPos.w > 0.0) { + vec3 halfExtents = (cluster.maxBounds - cluster.minBounds) * 0.5; + vec3 center = (cluster.minBounds + cluster.maxBounds) * 0.5; + float sphereRadius = sqrt(dot(halfExtents, halfExtents)); + light.cc_lightDir = ((cc_matView) * (vec4(light.cc_lightDir.xyz, 1.0))); + light.cc_lightDir.xyz = normalize((light.cc_lightDir - ((cc_matView) * (vec4(0,0,0, 1.0)))).xyz).xyz; + vec3 v = center - light.cc_lightPos.xyz; + float lenSq = dot(v, v); + float v1Len = dot(v, light.cc_lightDir.xyz); + float cosAngle = light.cc_lightSizeRangeAngle.z; + float sinAngle = sqrt(1.0 - cosAngle * cosAngle); + float distanceClosestPoint = cosAngle * sqrt(lenSq - v1Len * v1Len) - v1Len * sinAngle; + bool angleCull = distanceClosestPoint > sphereRadius; + bool frontCull = v1Len > sphereRadius + light.cc_lightSizeRangeAngle.y; + bool backCull = v1Len < -sphereRadius; + return !(angleCull || frontCull || backCull); + } + vec3 closest = max(cluster.minBounds, min(light.cc_lightPos.xyz, cluster.maxBounds)); + vec3 dist = closest - light.cc_lightPos.xyz; + return dot(dist, dist) <= (light.cc_lightSizeRangeAngle.y * light.cc_lightSizeRangeAngle.y); + } + shared CCLight lights[(16 * 8 * LOCAL_SIZE_Z)]; + layout(local_size_x = 16, local_size_y = 8, local_size_z = LOCAL_SIZE_Z) in; + void main() + { + uint visibleLights[100]; + uint visibleCount = 0u; + uint clusterIndex = gl_GlobalInvocationID.z * gl_WorkGroupSize.x * gl_WorkGroupSize.y + + gl_GlobalInvocationID.y * gl_WorkGroupSize.x + + gl_GlobalInvocationID.x; + + Cluster cluster = getCluster(clusterIndex); + uint lightCount = ccLightCount(); + uint lightOffset = 0u; + while (lightOffset < lightCount) { + uint batchSize = min((16u * 8u * uint(LOCAL_SIZE_Z)), lightCount - lightOffset); + if (uint(gl_LocalInvocationIndex) < batchSize) { + uint lightIndex = lightOffset + gl_LocalInvocationIndex; + CCLight light = getCCLight(lightIndex); + light.cc_lightPos.xyz = ((cc_matView) * (vec4(light.cc_lightPos.xyz, 1.0))).xyz; + lights[gl_LocalInvocationIndex] = light; + } + barrier(); + for (uint i = 0u; i < batchSize; i++) { + if (visibleCount < 100u && ccLightIntersectsCluster(lights[i], cluster)) { + visibleLights[visibleCount] = lightOffset + i; + visibleCount++; + } + } + lightOffset += batchSize; + } + barrier(); + uint offset = 0u; + offset = atomicAdd(b_globalIndex[0], visibleCount); + for (uint i = 0u; i < visibleCount; i++) { + b_clusterLightIndices[offset + i] = visibleLights[i]; + } + b_clusterLightGrid[clusterIndex] = uvec4(offset, visibleCount, 0, 0); + } +}% diff --git a/editor/assets/effects/pipeline/cluster-culling.effect.meta b/editor/assets/effects/pipeline/cluster-culling.effect.meta new file mode 100644 index 0000000000..443cf29b85 --- /dev/null +++ b/editor/assets/effects/pipeline/cluster-culling.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.7.0", + "importer": "effect", + "imported": true, + "uuid": "84ac6f69-3086-455a-86a4-561da8ee710b", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/native/cocos/core/assets/EffectAsset.cpp b/native/cocos/core/assets/EffectAsset.cpp index 78d4e069d7..da675688ea 100644 --- a/native/cocos/core/assets/EffectAsset.cpp +++ b/native/cocos/core/assets/EffectAsset.cpp @@ -25,9 +25,9 @@ #include "core/assets/EffectAsset.h" #include "ProgramUtils.h" #include "cocos.h" +#include "cocos/renderer/pipeline/custom/RenderingModule.h" #include "core/Root.h" #include "core/platform/Debug.h" -#include "cocos/renderer/pipeline/custom/RenderingModule.h" #include "engine/BaseEngine.h" #include "renderer/core/ProgramLib.h" @@ -46,6 +46,7 @@ IPassStates &IPassStates::operator=(const IPassInfoFull &o) { blendState = o.blendState; dynamicStates = o.dynamicStates; phase = o.phase; + subpass = o.subpass; return *this; } @@ -74,6 +75,9 @@ void IPassStates::overrides(const IPassInfoFull &o) { if (o.phase.has_value()) { this->phase = o.phase.value(); } + if (o.subpass.has_value()) { + this->subpass = o.subpass.value(); + } } EffectAsset::RegisteredEffectAssetMap EffectAsset::effects; diff --git a/native/cocos/core/assets/EffectAsset.h b/native/cocos/core/assets/EffectAsset.h index aec19b88c5..cc8b4204f2 100644 --- a/native/cocos/core/assets/EffectAsset.h +++ b/native/cocos/core/assets/EffectAsset.h @@ -378,6 +378,7 @@ struct IPassStates { ccstd::optional dynamicStates; ccstd::optional phase; ccstd::optional pass; + ccstd::optional subpass; IPassStates() = default; explicit IPassStates(const IPassInfoFull &o); @@ -399,6 +400,7 @@ struct IPassInfoFull final { // cjh } : public IPassInfo { ccstd::optional dynamicStates; ccstd::optional phase; ccstd::optional pass; + ccstd::optional subpass; // IPassInfo ccstd::string program; // auto-generated from 'vert' and 'frag' ccstd::optional embeddedMacros; @@ -410,6 +412,7 @@ struct IPassInfoFull final { // cjh } : public IPassInfo { // generated part index_t passIndex{0}; uint32_t passID = 0xFFFFFFFF; + uint32_t subpassID = 0xFFFFFFFF; uint32_t phaseID = 0xFFFFFFFF; MacroRecord defines; ccstd::optional stateOverrides; @@ -427,6 +430,7 @@ struct IPassInfoFull final { // cjh } : public IPassInfo { blendState = o.blendState; dynamicStates = o.dynamicStates; phase = o.phase; + subpass = o.subpass; return *this; } }; diff --git a/native/cocos/renderer/frame-graph/DevicePass.cpp b/native/cocos/renderer/frame-graph/DevicePass.cpp index f8ef50106f..4c538a108e 100644 --- a/native/cocos/renderer/frame-graph/DevicePass.cpp +++ b/native/cocos/renderer/frame-graph/DevicePass.cpp @@ -261,6 +261,7 @@ void DevicePass::append(const FrameGraph &graph, const PassNode *passNode, ccstd void DevicePass::append(const FrameGraph &graph, const RenderTargetAttachment &attachment, ccstd::vector *attachments, gfx::SubpassInfo *subpass, const ccstd::vector &reads) { + std::ignore = reads; RenderTargetAttachment::Usage usage{attachment.desc.usage}; uint32_t slot{attachment.desc.slot}; if (attachment.desc.usage == RenderTargetAttachment::Usage::COLOR) { @@ -298,9 +299,6 @@ void DevicePass::append(const FrameGraph &graph, const RenderTargetAttachment &a output->storeOp = attachment.storeOp; output->desc.endAccesses = attachment.desc.endAccesses; } - if (std::find(reads.begin(), reads.end(), output->textureHandle) != reads.end()) { - output->isGeneralLayout = true; // it's an 'inout' attachment - } } else { CC_ASSERT(attachment.desc.usage == RenderTargetAttachment::Usage::COLOR); attachments->emplace_back(attachment); @@ -371,7 +369,6 @@ void DevicePass::begin(gfx::CommandBuffer *cmdBuff) { attachmentInfo.loadOp = attachElem.attachment.desc.loadOp; attachmentInfo.storeOp = attachElem.attachment.storeOp; attachmentInfo.barrier = gfx::Device::getInstance()->getGeneralBarrier({attachElem.attachment.desc.beginAccesses, attachElem.attachment.desc.endAccesses}); - attachmentInfo.isGeneralLayout = attachElem.attachment.isGeneralLayout; fboInfo.colorTextures.push_back(attachElem.renderTarget); clearColors.emplace_back(attachElem.attachment.desc.clearColor); } else { @@ -382,7 +379,6 @@ void DevicePass::begin(gfx::CommandBuffer *cmdBuff) { attachmentInfo.depthStoreOp = attachElem.attachment.storeOp; attachmentInfo.stencilStoreOp = attachElem.attachment.storeOp; attachmentInfo.barrier = gfx::Device::getInstance()->getGeneralBarrier({attachElem.attachment.desc.beginAccesses, attachElem.attachment.desc.endAccesses}); - attachmentInfo.isGeneralLayout = attachElem.attachment.isGeneralLayout; fboInfo.depthStencilTexture = attachElem.renderTarget; clearDepth = attachElem.attachment.desc.clearDepth; clearStencil = attachElem.attachment.desc.clearStencil; diff --git a/native/cocos/renderer/frame-graph/RenderTargetAttachment.h b/native/cocos/renderer/frame-graph/RenderTargetAttachment.h index cba52c9436..40dbbace46 100644 --- a/native/cocos/renderer/frame-graph/RenderTargetAttachment.h +++ b/native/cocos/renderer/frame-graph/RenderTargetAttachment.h @@ -66,7 +66,6 @@ struct RenderTargetAttachment final { uint8_t layer{0}; uint8_t index{0}; StoreOp storeOp{StoreOp::DISCARD}; - bool isGeneralLayout{false}; }; inline bool RenderTargetAttachment::Sorter::operator()(const RenderTargetAttachment &a1, const RenderTargetAttachment &a2) const noexcept { diff --git a/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp b/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp index 48ba863ddb..b4df711e62 100644 --- a/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp @@ -113,18 +113,19 @@ void DescriptorSetAgent::bindBuffer(uint32_t binding, Buffer *buffer, uint32_t i }); } -void DescriptorSetAgent::bindTexture(uint32_t binding, Texture *texture, uint32_t index) { - DescriptorSet::bindTexture(binding, texture, index); +void DescriptorSetAgent::bindTexture(uint32_t binding, Texture *texture, uint32_t index, AccessFlags flags) { + DescriptorSet::bindTexture(binding, texture, index, flags); - ENQUEUE_MESSAGE_4( + ENQUEUE_MESSAGE_5( DeviceAgent::getInstance()->getMessageQueue(), DescriptorSetBindTexture, actor, getActor(), binding, binding, texture, static_cast(texture)->getActor(), index, index, + flags, flags, { - actor->bindTexture(binding, texture, index); + actor->bindTexture(binding, texture, index, flags); }); } diff --git a/native/cocos/renderer/gfx-agent/DescriptorSetAgent.h b/native/cocos/renderer/gfx-agent/DescriptorSetAgent.h index 1b74dda69a..a89eaaa09e 100644 --- a/native/cocos/renderer/gfx-agent/DescriptorSetAgent.h +++ b/native/cocos/renderer/gfx-agent/DescriptorSetAgent.h @@ -39,7 +39,7 @@ public: void forceUpdate() override; void bindBuffer(uint32_t binding, Buffer *buffer, uint32_t index) override; - void bindTexture(uint32_t binding, Texture *texture, uint32_t index) override; + void bindTexture(uint32_t binding, Texture *texture, uint32_t index, AccessFlags flags) override; void bindSampler(uint32_t binding, Sampler *sampler, uint32_t index) override; protected: diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 621ba6d41c..943cc1242c 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -177,7 +177,7 @@ enum class Feature : uint32_t { INPUT_ATTACHMENT_BENEFIT, SUBPASS_COLOR_INPUT, SUBPASS_DEPTH_STENCIL_INPUT, - RASTERIZATION_ORDER_COHERENT, + RASTERIZATION_ORDER_NOCOHERENT, COUNT, }; CC_ENUM_CONVERSION_OPERATOR(Feature); @@ -1276,10 +1276,6 @@ struct ALIGNAS(8) ColorAttachment { LoadOp loadOp{LoadOp::CLEAR}; StoreOp storeOp{StoreOp::STORE}; GeneralBarrier *barrier{nullptr}; - uint32_t isGeneralLayout{0}; // @ts-boolean -#if CC_CPU_ARCH == CC_CPU_ARCH_64 - uint32_t _padding{0}; -#endif EXPOSE_COPY_FN(ColorAttachment) }; @@ -1294,10 +1290,6 @@ struct ALIGNAS(8) DepthStencilAttachment { LoadOp stencilLoadOp{LoadOp::CLEAR}; StoreOp stencilStoreOp{StoreOp::STORE}; GeneralBarrier *barrier{nullptr}; - uint32_t isGeneralLayout{0}; // @ts-boolean -#if CC_CPU_ARCH == CC_CPU_ARCH_64 - uint32_t _padding{0}; -#endif EXPOSE_COPY_FN(DepthStencilAttachment) }; @@ -1319,17 +1311,13 @@ struct SubpassInfo { using SubpassInfoList = ccstd::vector; -using AccessFlagList = ccstd::vector; struct ALIGNAS(8) SubpassDependency { uint32_t srcSubpass{0}; uint32_t dstSubpass{0}; GeneralBarrier *generalBarrier{nullptr}; - AccessFlagList prevAccesses{}; - AccessFlagList nextAccesses{}; -#if CC_CPU_ARCH == CC_CPU_ARCH_32 - uint32_t _padding{0}; -#endif + AccessFlags prevAccesses{}; + AccessFlags nextAccesses{}; EXPOSE_COPY_FN(SubpassDependency) }; diff --git a/native/cocos/renderer/gfx-base/GFXDescriptorSet.cpp b/native/cocos/renderer/gfx-base/GFXDescriptorSet.cpp index 2c9f263081..242886cb17 100644 --- a/native/cocos/renderer/gfx-base/GFXDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-base/GFXDescriptorSet.cpp @@ -71,11 +71,16 @@ void DescriptorSet::bindBuffer(uint32_t binding, Buffer *buffer, uint32_t index) } void DescriptorSet::bindTexture(uint32_t binding, Texture *texture, uint32_t index) { + bindTexture(binding, texture, index, AccessFlagBit::NONE); +} + +void DescriptorSet::bindTexture(uint32_t binding, Texture *texture, uint32_t index, AccessFlags flags) { const uint32_t descriptorIndex = _layout->getDescriptorIndices()[binding] + index; const uint32_t newId = getObjectID(texture); if (_textures[descriptorIndex].id != newId) { _textures[descriptorIndex].ptr = texture; _textures[descriptorIndex].id = newId; + _textures[descriptorIndex].flags = flags; _isDirty = true; } } @@ -95,8 +100,8 @@ bool DescriptorSet::bindBufferJSB(uint32_t binding, Buffer *buffer, uint32_t ind return _isDirty; } -bool DescriptorSet::bindTextureJSB(uint32_t binding, Texture *texture, uint32_t index) { - bindTexture(binding, texture, index); +bool DescriptorSet::bindTextureJSB(uint32_t binding, Texture *texture, uint32_t index, AccessFlags flags) { + bindTexture(binding, texture, index, flags); return _isDirty; } diff --git a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h index f0f213ad6e..cb0b6897d0 100644 --- a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h +++ b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h @@ -42,12 +42,14 @@ public: virtual void forceUpdate() = 0; virtual void bindBuffer(uint32_t binding, Buffer *buffer, uint32_t index); - virtual void bindTexture(uint32_t binding, Texture *texture, uint32_t index); virtual void bindSampler(uint32_t binding, Sampler *sampler, uint32_t index); + virtual void bindTexture(uint32_t binding, Texture *texture, uint32_t index, AccessFlags flags); + + void bindTexture(uint32_t binding, Texture *texture, uint32_t index); // Functions invoked by JSB adapter bool bindBufferJSB(uint32_t binding, Buffer *buffer, uint32_t index); - bool bindTextureJSB(uint32_t binding, Texture *texture, uint32_t index); + bool bindTextureJSB(uint32_t binding, Texture *texture, uint32_t index, AccessFlags flags); bool bindSamplerJSB(uint32_t binding, Sampler *sampler, uint32_t index); Buffer *getBuffer(uint32_t binding, uint32_t index) const; @@ -71,6 +73,7 @@ protected: struct ObjectWithId { T *ptr = nullptr; uint32_t id = INVALID_OBJECT_ID; + AccessFlags flags = AccessFlagBit::NONE; }; const DescriptorSetLayout *_layout = nullptr; diff --git a/native/cocos/renderer/gfx-base/SPIRVUtils.cpp b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp index b47fb238d1..dfbb2e839c 100644 --- a/native/cocos/renderer/gfx-base/SPIRVUtils.cpp +++ b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp @@ -143,11 +143,11 @@ void SPIRVUtils::compileGLSL(ShaderStageFlagBit type, const ccstd::string &sourc _output.clear(); spv::SpvBuildLogger logger; glslang::SpvOptions spvOptions; - spvOptions.disableOptimizer = false; - spvOptions.optimizeSize = true; #if CC_DEBUG > 0 // spvOptions.validate = true; #else + spvOptions.disableOptimizer = false; + spvOptions.optimizeSize = true; spvOptions.stripDebugInfo = true; #endif glslang::GlslangToSpv(*_program->getIntermediate(stage), _output, &logger, &spvOptions); diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index 18f21f5a10..1b25d640e4 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -124,6 +124,7 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { _gpuConstantRegistry->useDiscardFramebuffer = checkExtension("discard_framebuffer"); _features[toNumber(Feature::INSTANCED_ARRAYS)] = _gpuConstantRegistry->useInstancedArrays; + _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = false; ccstd::string fbfLevelStr = "NONE"; // PVRVFrame has issues on their support @@ -139,15 +140,16 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { if (*it == CC_TOSTR(GL_EXT_shader_framebuffer_fetch_non_coherent)) { _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_EXT; fbfLevelStr = "NON_COHERENT_EXT"; + _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; } else if (*it == CC_TOSTR(GL_QCOM_shader_framebuffer_fetch_noncoherent)) { _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_QCOM; fbfLevelStr = "NON_COHERENT_QCOM"; GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); + _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; } } else if (checkExtension(CC_TOSTR(GL_EXT_shader_framebuffer_fetch))) { // we only care about EXT_shader_framebuffer_fetch, the ARM version does not support MRT _gpuConstantRegistry->mFBF = FBFSupportLevel::COHERENT; - _features[toNumber(Feature::RASTERIZATION_ORDER_COHERENT)] = true; fbfLevelStr = "COHERENT"; } _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = _gpuConstantRegistry->mFBF != FBFSupportLevel::NONE; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 1b1be5ba6a..c063cad07d 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -1433,7 +1433,7 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * std::vector visited(gpuRenderPass->colorAttachments.size()); for (auto &input : sub.inputs) { visited[input] = true; - drawBuffer.emplace_back(input); + drawBuffer.emplace_back(gpuRenderPass->indices[input]); } for (auto &color : sub.colors) { @@ -1443,7 +1443,7 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * gpuRenderPass->colors.emplace_back(color); } if (!visited[color]) { - drawBuffer.emplace_back(color); + drawBuffer.emplace_back(index); } } @@ -2737,7 +2737,7 @@ void cmdFuncGLES3UpdateBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer, co GLES3ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; if (hasFlag(gpuBuffer->usage, BufferUsageBit::INDIRECT)) { memcpy(reinterpret_cast(gpuBuffer->indirects.data()) + offset, buffer, size); - } else if (hasFlag(gpuBuffer->usage, BufferUsageBit::TRANSFER_SRC)) { + } else if (hasFlag(gpuBuffer->usage, BufferUsageBit::TRANSFER_SRC) && gpuBuffer->buffer != nullptr) { memcpy(gpuBuffer->buffer + offset, buffer, size); } else { switch (gpuBuffer->glTarget) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index ce0c29e14b..c8de3ad8f3 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -113,6 +113,7 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; _features[toNumber(Feature::BLEND_MINMAX)] = true; _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; + _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = false; if (_gpuConstantRegistry->glMinorVersion) { _features[toNumber(Feature::COMPUTE_SHADER)] = true; @@ -131,16 +132,17 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { if (it != _extensions.end()) { if (*it == CC_TOSTR(GL_EXT_shader_framebuffer_fetch_non_coherent)) { _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_EXT; + _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; fbfLevelStr = "NON_COHERENT_EXT"; } else if (*it == CC_TOSTR(GL_QCOM_shader_framebuffer_fetch_noncoherent)) { _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_QCOM; fbfLevelStr = "NON_COHERENT_QCOM"; + _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); } } else if (checkExtension(CC_TOSTR(GL_EXT_shader_framebuffer_fetch))) { // we only care about EXT_shader_framebuffer_fetch, the ARM version does not support MRT _gpuConstantRegistry->mFBF = FBFSupportLevel::COHERENT; - _features[toNumber(Feature::RASTERIZATION_ORDER_COHERENT)] = true; fbfLevelStr = "COHERENT"; } _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = _gpuConstantRegistry->mFBF != FBFSupportLevel::NONE; diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index 08d679cc70..79eba7a43a 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -266,11 +266,6 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; } } - - for (size_t j = 0; j < subpasses[i].preserves.size(); ++j) { - uint32_t preserves = subpasses[i].preserves[j]; - mtlRenderPassDescriptor.colorAttachments[preserves].storeAction = MTLStoreActionStoreAndMultisampleResolve; - } } updateDepthStencilState(ccMtlRenderPass->getCurrentSubpassIndex(), mtlRenderPassDescriptor); } diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index 3610b9535d..db0ceef627 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -135,6 +135,9 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; _features[toNumber(Feature::COMPUTE_SHADER)] = true; _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = true; + _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = false; + _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = false; + _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm index 835a857142..7bd26adbae 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm @@ -92,8 +92,9 @@ bool CCMTLPipelineState::initRenderPipeline() { _GPUPipelineState->stencilRefBack = _depthStencilState.stencilRefBack; _GPUPipelineState->primitiveType = mu::toMTLPrimitiveType(_primitive); if (_pipelineLayout) - _GPUPipelineState->gpuPipelineLayout = static_cast(_pipelineLayout)->gpuPipelineLayout(); - _GPUPipelineState->gpuShader = static_cast(_shader)->gpuShader(); + _GPUPipelineState->gpuPipelineLayout = static_cast(_pipelineLayout)->gpuPipelineLayout(); + _GPUPipelineState->gpuShader = static_cast(_shader)->gpuShader( + static_cast(_renderPass), _subpass); _renderPipelineReady = true; return true; @@ -123,7 +124,7 @@ bool CCMTLPipelineState::createGPUPipelineState() { return false; } _GPUPipelineState->mtlComputePipelineState = _mtlComputePipeline; - _GPUPipelineState->gpuShader = static_cast(_shader)->gpuShader(); + _GPUPipelineState->gpuShader = static_cast(_shader)->gpuShader(nullptr, 0); if (_pipelineLayout) _GPUPipelineState->gpuPipelineLayout = static_cast(_pipelineLayout)->gpuPipelineLayout(); } @@ -150,12 +151,12 @@ bool CCMTLPipelineState::createMTLDepthStencilState() { return attachemnt.format == Format::DEPTH ||attachemnt.format == Format::DEPTH_STENCIL; }); hasDS |= _renderPass->getDepthStencilAttachment().format != Format::UNKNOWN; - + if(!hasDS) { // default nil return true; } - + MTLDepthStencilDescriptor *descriptor = [[MTLDepthStencilDescriptor alloc] init]; if (descriptor == nil) { CC_LOG_ERROR("CCMTLPipelineState: MTLDepthStencilDescriptor could not be allocated."); @@ -265,7 +266,7 @@ bool CCMTLPipelineState::setVertexDescriptor(MTLRenderPipelineDescriptor *descri descriptor.vertexDescriptor.attributes[dummy.location].bufferIndex = static_cast(_shader)->getAvailableBufferBindingIndex(ShaderStageFlagBit::VERTEX, dummy.stream); CC_LOG_WARNING("Attribute %s is missing, add a dummy data for it.", dummy.name.c_str()); } - + if(layouts.empty()) { res = false; } @@ -287,17 +288,13 @@ bool CCMTLPipelineState::setVertexDescriptor(MTLRenderPipelineDescriptor *descri } bool CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor *descriptor) { + auto *mtlPass = static_cast(_renderPass); const SubpassInfoList &subpasses = _renderPass->getSubpasses(); const ColorAttachmentList &colorAttachments = _renderPass->getColorAttachments(); const auto &ccShader = static_cast(_shader); - ccstd::vector bindingIndices; - ccstd::vector bindingOffsets; + const CCMTLGPUShader *gpuShader = ccShader->gpuShader(mtlPass, _subpass); - const CCMTLGPUShader *gpuShader = ccShader->gpuShader(); - uint32_t outputNum = static_cast(gpuShader->outputs.size()); - bindingIndices.reserve(outputNum); - bindingOffsets.reserve(outputNum); MTLPixelFormat mtlPixelFormat; ccstd::set inputs; uint32_t depthStencilTexIndex = INVALID_BINDING; @@ -328,18 +325,10 @@ bool CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor * descriptor.colorAttachments[output].pixelFormat = mtlPixelFormat; } } - const uint32_t curIndex = static_cast(_renderPass)->getCurrentSubpassIndex(); - const SubpassInfo &curSubpass = subpasses[curIndex]; - for (size_t i = 0; i < curSubpass.colors.size(); ++i) { - bindingIndices.emplace_back(i); - bindingOffsets.emplace_back(curSubpass.colors[i]); - } } else { for (size_t i = 0; i < colorAttachments.size(); ++i) { mtlPixelFormat = mu::toMTLPixelFormat(colorAttachments[i].format); descriptor.colorAttachments[i].pixelFormat = mtlPixelFormat; - bindingIndices.emplace_back(i); - bindingOffsets.emplace_back(i); depthStencilTexIndex = INVALID_BINDING; } } @@ -357,7 +346,7 @@ bool CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor * auto *ccMTLShader = static_cast(_shader); descriptor.vertexFunction = ccMTLShader->getVertMTLFunction(); - descriptor.fragmentFunction = ccMTLShader->getSpecializedFragFunction(bindingIndices.data(), bindingOffsets.data(), static_cast(bindingIndices.size())); + descriptor.fragmentFunction = ccMTLShader->getFragmentMTLFunction(); mtlPixelFormat = mu::toMTLPixelFormat(depthStencilFormat); if (mtlPixelFormat != MTLPixelFormatInvalid) { diff --git a/native/cocos/renderer/gfx-metal/MTLRenderPass.h b/native/cocos/renderer/gfx-metal/MTLRenderPass.h index cf9432bd32..99e1f273c1 100644 --- a/native/cocos/renderer/gfx-metal/MTLRenderPass.h +++ b/native/cocos/renderer/gfx-metal/MTLRenderPass.h @@ -41,6 +41,8 @@ public: explicit CCMTLRenderPass(); ~CCMTLRenderPass(); + using BufferList = ccstd::vector; // offset to draw buffer, also means [[color(N)]] of input + void setColorAttachment(size_t slot, CCMTLTexture *texture, int level); void setDepthStencilAttachment(CCMTLTexture *texture, int level); @@ -50,16 +52,20 @@ public: inline void nextSubpass() { _currentSubpassIndex++; } inline uint32_t getCurrentSubpassIndex() { return _currentSubpassIndex; } inline void reset() { _currentSubpassIndex = 0; } + inline const BufferList &getDrawBuffer(uint32_t subPassIndex) { return _drawBuffers[subPassIndex]; } + inline const BufferList &getReadBuffer(uint32_t subPassIndex) { return _readBuffers[subPassIndex]; } protected: void doInit(const RenderPassInfo &info) override; void doDestroy() override; - uint32_t _outputAttachmentOffset = 0; uint32_t _currentSubpassIndex = 0; MTLRenderPassDescriptor *_mtlRenderPassDescriptor = nil; uint32_t _colorRenderTargetNums = 0; ccstd::vector _renderTargetSizes; + ccstd::vector _drawBuffers; + ccstd::vector _readBuffers; + ccstd::vector _colorIndices; // attachment index to draw buffer index }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm index 873955287c..06c177998e 100644 --- a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm +++ b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm @@ -58,6 +58,55 @@ void CCMTLRenderPass::doInit(const RenderPassInfo& info) { _mtlRenderPassDescriptor.depthAttachment.storeAction = mu::toMTLStoreAction(_depthStencilAttachment.depthStoreOp); _mtlRenderPassDescriptor.stencilAttachment.loadAction = mu::toMTLLoadAction(_depthStencilAttachment.stencilLoadOp); _mtlRenderPassDescriptor.stencilAttachment.storeAction = mu::toMTLStoreAction(_depthStencilAttachment.stencilStoreOp); + + uint32_t colorCount = utils::toUint(_colorAttachments.size()); + if (_subpasses.empty()) { + _subpasses.emplace_back(); + auto &subpass = _subpasses.back(); + subpass.colors.resize(_colorAttachments.size()); + for (uint32_t i = 0U; i < _colorAttachments.size(); ++i) { + subpass.colors[i] = i; + } + if (_depthStencilAttachment.format != Format::UNKNOWN) { + subpass.depthStencil = colorCount; + } + } else { + // unify depth stencil index + for (auto &subpass : _subpasses) { + if (subpass.depthStencil != INVALID_BINDING && subpass.depthStencil > colorCount) { + subpass.depthStencil = colorCount; + } + if (subpass.depthStencilResolve != INVALID_BINDING && subpass.depthStencilResolve > colorCount) { + subpass.depthStencilResolve = colorCount; + } + } + } + + _colorIndices.resize(_colorAttachments.size(), INVALID_BINDING); + _drawBuffers.resize(_subpasses.size()); + _readBuffers.resize(_subpasses.size()); + std::vector colors; + + for (uint32_t i = 0; i < _subpasses.size(); ++i) { + auto &subPass = _subpasses[i]; + auto &readBuffer = _readBuffers[i]; + auto &drawBuffer = _drawBuffers[i]; + + for (auto &input : subPass.inputs) { + auto &index = _colorIndices[input]; + CC_ASSERT(index != INVALID_BINDING); // input should not appear before color or depthstencil. + readBuffer.emplace_back(index); + } + + for (auto &color : subPass.colors) { + auto &index = _colorIndices[color]; + if (index == INVALID_BINDING) { + index = static_cast(colors.size()); + colors.emplace_back(color); + } + drawBuffer.emplace_back(index); + } + } } void CCMTLRenderPass::doDestroy() { diff --git a/native/cocos/renderer/gfx-metal/MTLShader.h b/native/cocos/renderer/gfx-metal/MTLShader.h index 2b1de6edc8..42c86271b3 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.h +++ b/native/cocos/renderer/gfx-metal/MTLShader.h @@ -30,6 +30,7 @@ namespace cc { namespace gfx { +class CCMTLRenderPass; class CCMTLGPUShader; class SPIRVUtils; class CCMTLShader final : public Shader { @@ -45,7 +46,7 @@ public: inline id getFragmentMTLFunction() const { return _fragFunction; } inline id getComputeMTLFunction() const { return _cmptFunction; } inline const ccstd::unordered_map &getFragmentSamplerBindings() const { return _mtlFragmentSamplerBindings; } - inline const CCMTLGPUShader *gpuShader() const { return _gpuShader; } + const CCMTLGPUShader *gpuShader(CCMTLRenderPass *renderPass, uint32_t subPass); uint32_t getAvailableBufferBindingIndex(ShaderStageFlagBit stage, uint32_t stream); @@ -64,7 +65,8 @@ protected: void doInit(const ShaderInfo &info) override; void doDestroy() override; - bool createMTLFunction(const ShaderStage &); + bool checkInputAttachment(const ShaderInfo& info) const; + bool createMTLFunction(const ShaderStage &, CCMTLRenderPass *renderPass, uint32_t subPass); void setAvailableBufferBindingIndex(); id _vertFunction = nil; diff --git a/native/cocos/renderer/gfx-metal/MTLShader.mm b/native/cocos/renderer/gfx-metal/MTLShader.mm index 33ae651d70..b6e8c7546f 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.mm +++ b/native/cocos/renderer/gfx-metal/MTLShader.mm @@ -26,6 +26,7 @@ #import "MTLDevice.h" #import "MTLGPUObjects.h" #import "MTLShader.h" +#import "MTLRenderPass.h" #import #import "gfx-base/SPIRVUtils.h" #include "base/Log.h" @@ -43,14 +44,16 @@ CCMTLShader::~CCMTLShader() { destroy(); } -void CCMTLShader::doInit(const ShaderInfo& info) { +const CCMTLGPUShader *CCMTLShader::gpuShader(CCMTLRenderPass *renderPass, uint32_t subPass) +{ + if (_gpuShader != nullptr) { + return _gpuShader; + } _gpuShader = ccnew CCMTLGPUShader; - _specializedFragFuncs = [[NSMutableDictionary alloc] init]; - for (const auto& stage : _stages) { - if (!createMTLFunction(stage)) { + if (!createMTLFunction(stage, renderPass, subPass)) { destroy(); - return; + return nullptr; } } @@ -63,6 +66,16 @@ void CCMTLShader::doInit(const ShaderInfo& info) { stage.source.clear(); stage.source.shrink_to_fit(); } + return _gpuShader; +} + +void CCMTLShader::doInit(const ShaderInfo& info) { + _specializedFragFuncs = [[NSMutableDictionary alloc] init]; + // spirv-cross for input attachment needs RenderPass to build [[color(index)]], + // build gpu shader only when there is no subPass input. + if (!checkInputAttachment(info)) { + gpuShader(nullptr, 0); + } } void CCMTLShader::doDestroy() { @@ -123,7 +136,11 @@ void CCMTLShader::doDestroy() { CCMTLGPUGarbageCollectionPool::getInstance()->collect(destroyFunc); } -bool CCMTLShader::createMTLFunction(const ShaderStage& stage) { +bool CCMTLShader::checkInputAttachment(const ShaderInfo& info) const { + return !info.subpassInputs.empty(); +} + +bool CCMTLShader::createMTLFunction(const ShaderStage& stage, CCMTLRenderPass *renderPass, uint32_t subPass) { bool isVertexShader = false; bool isFragmentShader = false; bool isComputeShader = false; @@ -147,7 +164,12 @@ bool CCMTLShader::createMTLFunction(const ShaderStage& stage) { auto* spvData = spirv->getOutputData(); size_t unitSize = sizeof(std::remove_pointer::type); - ccstd::string mtlShaderSrc = mu::spirv2MSL(spirv->getOutputData(), spirv->getOutputSize() / unitSize, stage.stage, _gpuShader); + + static const ccstd::vector emptyBuffer; + const auto &drawBuffer = renderPass != nullptr ? renderPass->getDrawBuffer(subPass) : emptyBuffer; + const auto &readBuffer = renderPass != nullptr ? renderPass->getReadBuffer(subPass) : emptyBuffer; + ccstd::string mtlShaderSrc = mu::spirv2MSL(spirv->getOutputData(), spirv->getOutputSize() / unitSize, stage.stage, + _gpuShader, drawBuffer, readBuffer); NSString* shader = [NSString stringWithUTF8String:mtlShaderSrc.c_str()]; NSError* error = nil; diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.h b/native/cocos/renderer/gfx-metal/MTLUtils.h index 79fe042b3a..f055f6de26 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.h +++ b/native/cocos/renderer/gfx-metal/MTLUtils.h @@ -71,7 +71,8 @@ MTLSamplerAddressMode toMTLSamplerAddressMode(Address); int toMTLSamplerBorderColor(const Color &); MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(Filter); MTLSamplerMipFilter toMTLSamplerMipFilter(Filter); -ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader); +ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader, + const ccstd::vector &drawBuffer, const ccstd::vector &readBuffer); const uint8_t *convertRGB8ToRGBA8(const uint8_t *source, uint32_t length); const uint8_t *convertRGB32FToRGBA32F(const uint8_t *source, uint32_t length); NSUInteger highestSupportedFeatureSet(id device); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index 5dfd67089a..7684baf24f 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -922,16 +922,14 @@ bool mu::isImageBlockSupported() { } bool mu::isFramebufferFetchSupported() { -#if (CC_PLATFORM == CC_PLATFORM_IOS) //|| TARGET_CPU_ARM64 return true; -#else - return false; -#endif } ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, - CCMTLGPUShader *gpuShader) { + CCMTLGPUShader *gpuShader, + const ccstd::vector &drawBuffer, + const ccstd::vector &readBuffer) { CCMTLDevice *device = CCMTLDevice::getInstance(); spirv_cross::CompilerMSL msl(ir, word_count); @@ -1051,7 +1049,7 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, newBinding.binding = binding + i; newBinding.msl_texture = mappedBinding; newBinding.msl_sampler = gpuShader->samplerIndex; - + if(gpuShader->resourceBinding.find(fakeHash) == gpuShader->resourceBinding.end()) { gpuShader->resourceBinding[fakeHash] = {0, mappedBinding, mappedBinding}; gpuShader->samplers[mappedBinding] = {sampler.name, set, binding, newBinding.msl_texture, newBinding.msl_sampler, shaderType}; @@ -1069,57 +1067,33 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, } if (executionModel == spv::ExecutionModelFragment) { - gpuShader->outputs.resize(resources.stage_outputs.size()); - for (size_t i = 0; i < resources.stage_outputs.size(); i++) { - const auto &stageOutput = resources.stage_outputs[i]; - auto set = msl.get_decoration(stageOutput.id, spv::DecorationDescriptorSet); - auto attachmentIndex = static_cast(i); - msl.set_decoration(stageOutput.id, spv::DecorationLocation, attachmentIndex); - gpuShader->outputs[i].name = stageOutput.name; - gpuShader->outputs[i].set = set; - gpuShader->outputs[i].binding = attachmentIndex; - } - if (!resources.subpass_inputs.empty()) { gpuShader->inputs.resize(resources.subpass_inputs.size()); for (size_t i = 0; i < resources.subpass_inputs.size(); i++) { const auto &attachment = resources.subpass_inputs[i]; gpuShader->inputs[i].name = attachment.name; - auto set = msl.get_decoration(attachment.id, spv::DecorationDescriptorSet); - auto index = msl.get_decoration(attachment.id, spv::DecorationInputAttachmentIndex); - auto binding = msl.get_decoration(attachment.id, spv::DecorationBinding); - - spirv_cross::MSLResourceBinding textureBinding; - textureBinding.stage = executionModel; - uint32_t fakeHash = set * 128 + binding; - if(gpuShader->resourceBinding.find(fakeHash) == gpuShader->resourceBinding.end()) { - gpuShader->resourceBinding[fakeHash] = {0, index, index}; - } else { - gpuShader->resourceBinding[fakeHash].samplerBinding = index; - gpuShader->resourceBinding[fakeHash].textureBinding = index; - textureBinding.msl_buffer = gpuShader->resourceBinding[fakeHash].bufferBinding; - } - msl.set_decoration(attachment.id, spv::DecorationBinding, index); - // avoid (set, index) collision - msl.set_decoration(attachment.id, spv::DecorationDescriptorSet, 4); - gpuShader->inputs[i].binding = index; - gpuShader->inputs[i].set = set; + auto id = msl.get_decoration(attachment.id, spv::DecorationInputAttachmentIndex); + auto loc = id >= readBuffer.size() ? id : readBuffer[id]; + msl.set_decoration(attachment.id, spv::DecorationInputAttachmentIndex, loc); } } + + gpuShader->outputs.resize(resources.stage_outputs.size()); + for (size_t i = 0; i < resources.stage_outputs.size(); i++) { + const auto &stageOutput = resources.stage_outputs[i]; + auto set = msl.get_decoration(stageOutput.id, spv::DecorationDescriptorSet); + auto id = msl.get_decoration(stageOutput.id, spv::DecorationLocation); + auto loc = id >= drawBuffer.size() ? id : drawBuffer[id]; + msl.set_decoration(stageOutput.id, spv::DecorationLocation, loc); + + gpuShader->outputs[i].name = stageOutput.name; + gpuShader->outputs[i].set = set; + gpuShader->outputs[i].binding = loc; + } } // Compile to MSL, ready to give to metal driver. ccstd::string output = msl.compile(); - if (executionModel == spv::ExecutionModelFragment) { - // add custom function constant to achieve delay binding for color attachment. - auto customCodingPos = output.find("using namespace metal;"); - int32_t maxIndex = static_cast(resources.stage_outputs.size() - 1); - for (int i = maxIndex; i >= 0; --i) { - ccstd::string indexStr = std::to_string(i); - output.insert(customCodingPos, "\nconstant int indexOffset" + indexStr + " [[function_constant(" + indexStr + ")]];\n"); - output.replace(output.find("color(" + indexStr + ")"), 8, "color(indexOffset" + indexStr + ")"); - } - } if (!output.size()) { CC_LOG_ERROR("Compile to MSL failed."); CC_LOG_ERROR("%s", output.c_str()); diff --git a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp index b85bac174c..b487e9262b 100644 --- a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp @@ -144,7 +144,7 @@ void DescriptorSetValidator::bindBuffer(uint32_t binding, Buffer *buffer, uint32 _actor->bindBuffer(binding, vBuffer->getActor(), index); } -void DescriptorSetValidator::bindTexture(uint32_t binding, Texture *texture, uint32_t index) { +void DescriptorSetValidator::bindTexture(uint32_t binding, Texture *texture, uint32_t index, AccessFlags flags) { CC_ASSERT(isInited()); CC_ASSERT(texture && static_cast(texture)->isInited()); @@ -165,9 +165,9 @@ void DescriptorSetValidator::bindTexture(uint32_t binding, Texture *texture, uin /////////// execute /////////// - DescriptorSet::bindTexture(binding, texture, index); + DescriptorSet::bindTexture(binding, texture, index, flags); - _actor->bindTexture(binding, static_cast(texture)->getActor(), index); + _actor->bindTexture(binding, static_cast(texture)->getActor(), index, flags); } void DescriptorSetValidator::bindSampler(uint32_t binding, Sampler *sampler, uint32_t index) { diff --git a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.h b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.h index e948bdb1e6..95e14838c6 100644 --- a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.h +++ b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.h @@ -39,7 +39,7 @@ public: void forceUpdate() override; void bindBuffer(uint32_t binding, Buffer *buffer, uint32_t index) override; - void bindTexture(uint32_t binding, Texture *texture, uint32_t index) override; + void bindTexture(uint32_t binding, Texture *texture, uint32_t index, AccessFlags flags) override; void bindSampler(uint32_t binding, Sampler *sampler, uint32_t index) override; void updateReferenceStamp(); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index b0154f354b..fb62c102e0 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -206,6 +206,8 @@ void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo vkCmdSetScissor(_gpuCommandBuffer->vkCommandBuffer, 0, 1, &passBeginInfo.renderArea); _curDynamicStates.scissor = safeArea; } + _currentSubPass = 0; + _hasSubPassSelfDependency = false; } void CCVKCommandBuffer::endRenderPass() { @@ -399,6 +401,9 @@ void CCVKCommandBuffer::setStencilCompareMask(StencilFace face, uint32_t referen void CCVKCommandBuffer::nextSubpass() { vkCmdNextSubpass(_gpuCommandBuffer->vkCommandBuffer, _secondaryRP ? VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS : VK_SUBPASS_CONTENTS_INLINE); + ++_currentSubPass; + CC_ASSERT(_currentSubPass < _curGPURenderPass->subpasses.size()); + _hasSubPassSelfDependency = _curGPURenderPass->hasSelfDependency[_currentSubPass]; } void CCVKCommandBuffer::draw(const DrawInfo &info) { @@ -474,6 +479,9 @@ void CCVKCommandBuffer::draw(const DrawInfo &info) { } } } + if (_hasSubPassSelfDependency) { + selfDependency(); + } } void CCVKCommandBuffer::execute(CommandBuffer *const *cmdBuffs, uint32_t count) { @@ -638,6 +646,18 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co } } +void CCVKCommandBuffer::selfDependency() { + VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + + vkCmdPipelineBarrier(_gpuCommandBuffer->vkCommandBuffer, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_DEPENDENCY_BY_REGION_BIT, + 1, &barrier, 0, nullptr, 0, nullptr); +} + void CCVKCommandBuffer::bindDescriptorSets(VkPipelineBindPoint bindPoint) { CCVKDevice *device = CCVKDevice::getInstance(); CCVKGPUDevice *gpuDevice = device->gpuDevice(); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h index 32b497cd09..3438684cbe 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h @@ -76,6 +76,7 @@ protected: void doDestroy() override; void bindDescriptorSets(VkPipelineBindPoint bindPoint); + void selfDependency(); IntrusivePtr _gpuCommandBuffer; @@ -91,6 +92,8 @@ protected: IntrusivePtr _curGPURenderPass; bool _secondaryRP = false; + bool _hasSubPassSelfDependency = false; + uint32_t _currentSubPass = 0; DynamicStates _curDynamicStates; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index acd0fa4a2e..b8dca00fcd 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -350,6 +350,27 @@ private: ccstd::unordered_set _hashes; }; +std::pair getInitialFinalLayout(CCVKDevice *device, CCVKGeneralBarrier *barrier, bool depthSetncil) { + const auto *gpuBarrier = barrier ? barrier->gpuBarrier() : + (depthSetncil ? &device->gpuDevice()->defaultDepthStencilBarrier : &device->gpuDevice()->defaultColorBarrier); + + ThsvsImageBarrier imageBarrier = {}; + imageBarrier.prevAccessCount = utils::toUint(gpuBarrier->prevAccesses.size()); + imageBarrier.pPrevAccesses = gpuBarrier->prevAccesses.data(); + imageBarrier.nextAccessCount = utils::toUint(gpuBarrier->nextAccesses.size()); + imageBarrier.pNextAccesses = gpuBarrier->nextAccesses.data(); + imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + imageBarrier.prevLayout = barrier ? getAccessLayout(barrier->getInfo().prevAccesses) : THSVS_IMAGE_LAYOUT_OPTIMAL; + imageBarrier.nextLayout = barrier ? getAccessLayout(barrier->getInfo().nextAccesses) : THSVS_IMAGE_LAYOUT_OPTIMAL; + + VkPipelineStageFlags srcStages = {}; + VkPipelineStageFlags dstStages = {}; + VkImageMemoryBarrier vkImageBarrier = {}; + thsvsGetVulkanImageMemoryBarrier(imageBarrier, &srcStages, &dstStages, &vkImageBarrier); + return {vkImageBarrier.oldLayout, vkImageBarrier.newLayout}; +} + void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRenderPass) { static ccstd::vector depthStencilResolves; static ccstd::vector attachmentDescriptions; @@ -371,14 +392,8 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende for (size_t i = 0U; i < colorAttachmentCount; ++i) { const auto &attachment{gpuRenderPass->colorAttachments[i]}; - auto &beginAccessInfo = beginAccessInfos[i]; - auto &endAccessInfo = endAccessInfos[i]; - - const auto *gpuBarrier{gpuRenderPass->getBarrier(i, device->gpuDevice())}; - thsvsGetAccessInfo(utils::toUint(gpuBarrier->prevAccesses.size()), gpuBarrier->prevAccesses.data(), &beginAccessInfo.stageMask, - &beginAccessInfo.accessMask, &beginAccessInfo.imageLayout, &beginAccessInfo.hasWriteAccess); - thsvsGetAccessInfo(utils::toUint(gpuBarrier->nextAccesses.size()), gpuBarrier->nextAccesses.data(), &endAccessInfo.stageMask, - &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); + auto [initialLayout, finalLayout] = + getInitialFinalLayout(device, static_cast(attachment.barrier), false); VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); bool hasStencil = GFX_FORMAT_INFOS[toNumber(attachment.format)].hasStencil; @@ -390,19 +405,12 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende attachmentDescriptions[i].storeOp = mapVkStoreOp(attachment.storeOp); attachmentDescriptions[i].stencilLoadOp = hasStencil ? attachmentDescriptions[i].loadOp : VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescriptions[i].stencilStoreOp = hasStencil ? attachmentDescriptions[i].storeOp : VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachmentDescriptions[i].initialLayout = attachment.loadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : beginAccessInfo.imageLayout; - attachmentDescriptions[i].finalLayout = endAccessInfo.imageLayout; + attachmentDescriptions[i].initialLayout = attachment.loadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : initialLayout; + attachmentDescriptions[i].finalLayout = finalLayout; } if (hasDepth) { const DepthStencilAttachment &depthStencilAttachment = gpuRenderPass->depthStencilAttachment; - CCVKAccessInfo &beginAccessInfo = beginAccessInfos[colorAttachmentCount]; - CCVKAccessInfo &endAccessInfo = endAccessInfos[colorAttachmentCount]; - - const auto *gpuBarrier{gpuRenderPass->getBarrier(colorAttachmentCount, device->gpuDevice())}; - thsvsGetAccessInfo(utils::toUint(gpuBarrier->prevAccesses.size()), gpuBarrier->prevAccesses.data(), &beginAccessInfo.stageMask, - &beginAccessInfo.accessMask, &beginAccessInfo.imageLayout, &beginAccessInfo.hasWriteAccess); - thsvsGetAccessInfo(utils::toUint(gpuBarrier->nextAccesses.size()), gpuBarrier->nextAccesses.data(), &endAccessInfo.stageMask, - &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); + auto [initialLayout, finalLayout] = getInitialFinalLayout(device, static_cast(depthStencilAttachment.barrier), true); VkFormat vkFormat = mapVkFormat(depthStencilAttachment.format, device->gpuDevice()); bool hasStencil = GFX_FORMAT_INFOS[toNumber(depthStencilAttachment.format)].hasStencil; @@ -414,8 +422,8 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende attachmentDescriptions[colorAttachmentCount].storeOp = mapVkStoreOp(depthStencilAttachment.depthStoreOp); attachmentDescriptions[colorAttachmentCount].stencilLoadOp = hasStencil ? mapVkLoadOp(depthStencilAttachment.stencilLoadOp) : VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescriptions[colorAttachmentCount].stencilStoreOp = hasStencil ? mapVkStoreOp(depthStencilAttachment.stencilStoreOp) : VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachmentDescriptions[colorAttachmentCount].initialLayout = depthStencilAttachment.depthLoadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : beginAccessInfo.imageLayout; - attachmentDescriptions[colorAttachmentCount].finalLayout = endAccessInfo.imageLayout; + attachmentDescriptions[colorAttachmentCount].initialLayout = depthStencilAttachment.depthLoadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : initialLayout; + attachmentDescriptions[colorAttachmentCount].finalLayout = finalLayout; } size_t subpassCount = gpuRenderPass->subpasses.size(); @@ -427,66 +435,62 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende for (uint32_t input : subpassInfo.inputs) { if (input == gpuRenderPass->colorAttachments.size()) { - VkImageLayout layout = gpuRenderPass->depthStencilAttachment.isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; + VkImageLayout layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, VK_IMAGE_ASPECT_DEPTH_BIT}); } else { - VkImageLayout layout = gpuRenderPass->colorAttachments[input].isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, VK_IMAGE_ASPECT_COLOR_BIT}); } } for (uint32_t color : subpassInfo.colors) { const ColorAttachment &desc = gpuRenderPass->colorAttachments[color]; const VkAttachmentDescription2 &attachment = attachmentDescriptions[color]; - VkImageLayout layout = desc.isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + bool appearsInInput = std::find(subpassInfo.inputs.begin(), subpassInfo.inputs.end(), color) != subpassInfo.inputs.end(); + VkImageLayout layout = appearsInInput ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, color, layout, VK_IMAGE_ASPECT_COLOR_BIT}); sampleCount = std::max(sampleCount, attachment.samples); } for (uint32_t resolve : subpassInfo.resolves) { - VkImageLayout layout = gpuRenderPass->colorAttachments[resolve].isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, resolve, layout, VK_IMAGE_ASPECT_COLOR_BIT}); } if (subpassInfo.depthStencil != INVALID_BINDING) { Format dsFormat{Format::UNKNOWN}; - bool isGeneralLayout{false}; if (subpassInfo.depthStencil >= colorAttachmentCount) { const DepthStencilAttachment &desc = gpuRenderPass->depthStencilAttachment; const VkAttachmentDescription2 &attachment = attachmentDescriptions.back(); - isGeneralLayout = desc.isGeneralLayout; dsFormat = desc.format; sampleCount = std::max(sampleCount, attachment.samples); } else { const ColorAttachment &desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencil]; const VkAttachmentDescription2 &attachment = attachmentDescriptions[subpassInfo.depthStencil]; - isGeneralLayout = desc.isGeneralLayout; dsFormat = desc.format; sampleCount = std::max(sampleCount, attachment.samples); } + bool appearsInInput = std::find(subpassInfo.inputs.begin(), subpassInfo.inputs.end(), subpassInfo.depthStencil) != subpassInfo.inputs.end(); VkImageAspectFlags aspect = GFX_FORMAT_INFOS[toNumber(dsFormat)].hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; - VkImageLayout layout = isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + VkImageLayout layout = appearsInInput ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, subpassInfo.depthStencil, layout, aspect}); } if (subpassInfo.depthStencilResolve != INVALID_BINDING) { Format dsFormat{Format::UNKNOWN}; - bool isGeneralLayout{false}; if (subpassInfo.depthStencilResolve >= colorAttachmentCount) { const DepthStencilAttachment &desc = gpuRenderPass->depthStencilAttachment; - isGeneralLayout = desc.isGeneralLayout; dsFormat = desc.format; } else { const ColorAttachment &desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencilResolve]; - isGeneralLayout = desc.isGeneralLayout; dsFormat = desc.format; } VkImageAspectFlags aspect = GFX_FORMAT_INFOS[toNumber(dsFormat)].hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; - VkImageLayout layout = isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + VkImageLayout layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, subpassInfo.depthStencilResolve, layout, aspect}); } @@ -582,6 +586,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende // offset = 0U; ccstd::unordered_set subpassExternalFilter; + gpuRenderPass->hasSelfDependency.resize(subpassCount, false); for (uint32_t i = 0U; i < dependencyCount; ++i) { const auto &dependency{gpuRenderPass->dependencies[i]}; VkSubpassDependency2 vkDependency{VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2}; @@ -589,53 +594,35 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende vkDependency.dstSubpass = dependency.dstSubpass; vkDependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; + if (dependency.srcSubpass == dependency.dstSubpass && dependency.srcSubpass < subpassCount) { + gpuRenderPass->hasSelfDependency[dependency.srcSubpass] = true; + } + auto addStageAccessMask = [&vkDependency](const SubpassDependency& deps) { - VkPipelineStageFlags srcStageMask; - VkAccessFlags srcAccessMask; - VkPipelineStageFlags dstStageMask; - VkAccessFlags dstAccessMask; - VkImageLayout imageLayout{VK_IMAGE_LAYOUT_UNDEFINED}; - bool hasWriteAccess{false}; - ccstd::vector prev; - ccstd::vector next; + ccstd::vector prevAccesses; + ccstd::vector nextAccesses; + getAccessTypes(deps.prevAccesses, prevAccesses); + getAccessTypes(deps.nextAccesses, nextAccesses); - ccstd::unordered_set flags; - for (const auto &access : deps.prevAccesses) { - if (flags.emplace(access).second) { - getAccessTypes(access, prev); - } - } - flags.clear(); - for (const auto &access : deps.nextAccesses) { - if (flags.emplace(access).second) { - getAccessTypes(access, next); - } - } - thsvsGetAccessInfo( - utils::toUint(prev.size()), - prev.data(), - &srcStageMask, - &srcAccessMask, - &imageLayout, &hasWriteAccess); + ThsvsImageBarrier imageBarrier = {}; + imageBarrier.prevAccessCount = utils::toUint(prevAccesses.size()); + imageBarrier.pPrevAccesses = prevAccesses.data(); + imageBarrier.nextAccessCount = utils::toUint(nextAccesses.size()); + imageBarrier.pNextAccesses = nextAccesses.data(); + imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + imageBarrier.prevLayout = getAccessLayout(deps.prevAccesses); + imageBarrier.nextLayout = getAccessLayout(deps.nextAccesses); - // offset += gpuBarrier->prevAccesses.size(); + VkImageMemoryBarrier vkImageBarrier = {}; + thsvsGetVulkanImageMemoryBarrier(imageBarrier, &vkDependency.srcStageMask, &vkDependency.dstStageMask, &vkImageBarrier); - thsvsGetAccessInfo( - utils::toUint(next.size()), - next.data(), - &dstStageMask, - &dstAccessMask, - &imageLayout, &hasWriteAccess); - - // offset += gpuBarrier->nextAccesses.size(); - vkDependency.srcStageMask |= srcStageMask; - vkDependency.srcAccessMask |= srcAccessMask; - vkDependency.dstStageMask |= dstStageMask; - vkDependency.dstAccessMask |= dstAccessMask; + vkDependency.srcAccessMask = vkImageBarrier.srcAccessMask; + vkDependency.dstAccessMask = vkImageBarrier.dstAccessMask; dependencyManager.append(vkDependency); }; if (vkDependency.srcStageMask == 0) { - vkDependency.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; + vkDependency.srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } addStageAccessMask(dependency); } diff --git a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp index 727597846b..785440f8dd 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp @@ -192,7 +192,7 @@ void CCVKDescriptorSet::update() { } if (textureView) { descriptorHub->connect(_gpuDescriptorSet, textureView, &descriptorInfo.image); - descriptorHub->update(textureView, &descriptorInfo.image); + descriptorHub->update(textureView, &descriptorInfo.image, _textures[i].flags); layoutMgr->checkIn(textureView->gpuTexture, binding.accessTypes.data(), utils::toUint(binding.accessTypes.size())); } } diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index 413a6a2496..acc577be13 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -767,7 +767,7 @@ void CCVKDevice::initDeviceFeature() { _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = true; _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = true; _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = true; - _features[toNumber(Feature::RASTERIZATION_ORDER_COHERENT)] = _gpuContext->checkExtension("VK_EXT_rasterization_order_attachment_access"); + _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; } void CCVKDevice::initFormatFeature() { diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index 619c7d11a5..c47e4a76fa 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -127,6 +127,7 @@ public: // helper storage ccstd::vector clearValues; ccstd::vector sampleCounts; // per subpass + ccstd::vector hasSelfDependency; // per subpass const CCVKGPUGeneralBarrier *getBarrier(size_t index, CCVKGPUDevice *gpuDevice) const; bool hasShadingAttachment(uint32_t subPassId) const; @@ -945,6 +946,19 @@ public: } } } + + void update(const CCVKGPUTextureView *texture, VkDescriptorImageInfo *descriptor, AccessFlags flags) { + auto it = _gpuTextureViewSet.find(texture); + if (it == _gpuTextureViewSet.end()) return; + auto &descriptors = it->second.descriptors; + for (uint32_t i = 0U; i < descriptors.size(); i++) { + if (descriptors[i] == descriptor) { + doUpdate(texture, descriptor, flags); + break; + } + } + } + void update(const CCVKGPUSampler *sampler, VkDescriptorImageInfo *descriptor) { auto it = _samplers.find(sampler); if (it == _samplers.end()) return; @@ -1028,10 +1042,17 @@ private: static void doUpdate(const CCVKGPUTextureView *texture, VkDescriptorImageInfo *descriptor) { descriptor->imageView = texture->vkImageView; + } + + static void doUpdate(const CCVKGPUTextureView *texture, VkDescriptorImageInfo *descriptor, AccessFlags flags) { + descriptor->imageView = texture->vkImageView; if (hasFlag(texture->gpuTexture->flags, TextureFlagBit::GENERAL_LAYOUT)) { descriptor->imageLayout = VK_IMAGE_LAYOUT_GENERAL; } else { - if (hasFlag(texture->gpuTexture->usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT)) { + if (hasAllFlags(flags, AccessFlagBit::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT | AccessFlagBit::COLOR_ATTACHMENT_WRITE) || + hasAllFlags(flags, AccessFlagBit::FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT | AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE)) { + descriptor->imageLayout = VK_IMAGE_LAYOUT_GENERAL; + } else if (hasFlag(texture->gpuTexture->usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT)) { descriptor->imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; } else { descriptor->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp index 0bd50ef3ab..2b328b47e1 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp @@ -568,8 +568,8 @@ const ThsvsAccessType *getAccessType(AccessFlagBit flag) { } ThsvsImageLayout getAccessLayout(AccessFlags flag) { - if (hasAnyFlags(flag, AccessFlagBit::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT | AccessFlagBit::COLOR_ATTACHMENT_WRITE) || - hasAnyFlags(flag, AccessFlagBit::FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT | AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE)) { + if (hasAllFlags(flag, AccessFlagBit::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT | AccessFlagBit::COLOR_ATTACHMENT_WRITE) || + hasAllFlags(flag, AccessFlagBit::FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT | AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE)) { return THSVS_IMAGE_LAYOUT_GENERAL; } return THSVS_IMAGE_LAYOUT_OPTIMAL; diff --git a/native/cocos/renderer/pipeline/custom/CustomTypes.h b/native/cocos/renderer/pipeline/custom/CustomTypes.h index f4ca648675..b7d9af9169 100644 --- a/native/cocos/renderer/pipeline/custom/CustomTypes.h +++ b/native/cocos/renderer/pipeline/custom/CustomTypes.h @@ -61,6 +61,7 @@ public: struct CustomRenderGraphContext { std::shared_ptr pipelineContext; const RenderGraph* renderGraph{nullptr}; + const ResourceGraph* resourceGraph{nullptr}; gfx::CommandBuffer* primaryCommandBuffer{nullptr}; }; diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp index eeee3025ec..01ba6c84a2 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp @@ -46,7 +46,8 @@ ResourceAccessGraph::ResourceAccessGraph(const allocator_type& alloc) noexcept accessRecord(alloc), resourceLifeRecord(alloc), topologicalOrder(alloc), - rpInfos(alloc) {} + rpInfos(alloc), + subpassIndex(alloc) {} // ContinuousContainer void ResourceAccessGraph::reserve(vertices_size_type sz) { diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index 865267f948..f89f2c4aa2 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -258,6 +258,7 @@ struct ResourceAccessGraph { PmrFlatMap resourceLifeRecord; ccstd::pmr::vector topologicalOrder; PmrFlatMap rpInfos; + PmrFlatMap subpassIndex; }; struct RelationGraph { @@ -420,6 +421,8 @@ struct FrameGraphDispatcher { void run(); + const ResourceAccessNode& getAttachmentStatus(RenderGraph::vertex_descriptor renderGraphVertID) const; + inline const BarrierMap& getBarriers() const { return barrierMap; } BarrierMap barrierMap; diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index 9b59533ac2..458f48f804 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -90,6 +90,23 @@ void FrameGraphDispatcher::setParalellWeight(float paralellExecWeight) { _paralellExecWeight = clampf(paralellExecWeight, 0.0F, 1.0F); } +const ResourceAccessNode &FrameGraphDispatcher::getAttachmentStatus(RenderGraph::vertex_descriptor renderGraphVertID) const { + auto iter = resourceAccessGraph.subpassIndex.find(renderGraphVertID); + auto ragVertID = resourceAccessGraph.passIndex.at(renderGraphVertID); + const ResourceAccessNode* accessNode = &resourceAccessGraph.access.at(ragVertID); + if( iter != resourceAccessGraph.subpassIndex.end()) { + auto subpassIndex = iter->second; + accessNode = accessNode->nextSubpass; + CC_ASSERT(accessNode); + while(subpassIndex) { + accessNode = accessNode->nextSubpass; + --subpassIndex; + CC_ASSERT(accessNode); + } + } + return *accessNode; +} + /////////////////////////////////////////////////////////////////////////////////////INTERNALâš¡IMPLEMENTATION///////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------predefine------------------------------------------------------------------ @@ -491,8 +508,8 @@ struct BarrierVisitor : public boost::bfs_visitor<> { auto &dsDep = subpassDependencies.emplace_back(); dsDep.srcSubpass = dependency.srcSubpass; dsDep.dstSubpass = dependency.dstSubpass; - dsDep.prevAccesses.emplace_back(barrier.beginStatus.accessFlag); - dsDep.nextAccesses.emplace_back(barrier.endStatus.accessFlag); + dsDep.prevAccesses |= barrier.beginStatus.accessFlag; + dsDep.nextAccesses |= barrier.endStatus.accessFlag; } } else { bool isWriteAccess = !isReadOnlyAccess(barrier.endStatus.accessFlag); @@ -500,22 +517,22 @@ struct BarrierVisitor : public boost::bfs_visitor<> { auto &dep = subpassDependencies.emplace_back(); dep.srcSubpass = dependency.srcSubpass; dep.dstSubpass = dependency.dstSubpass; - dep.prevAccesses.emplace_back(barrier.beginStatus.accessFlag); - dep.nextAccesses.emplace_back(barrier.endStatus.accessFlag); - if (hasReadAccess(barrier.endStatus.accessFlag) && !cc::gfx::Device::getInstance()->hasFeature(gfx::Feature::RASTERIZATION_ORDER_COHERENT)) { + dep.prevAccesses |= barrier.beginStatus.accessFlag; + dep.nextAccesses |= barrier.endStatus.accessFlag; + if (hasReadAccess(barrier.endStatus.accessFlag)) { auto &selfDep = subpassDependencies.emplace_back(); selfDep.srcSubpass = dependency.dstSubpass; selfDep.dstSubpass = dependency.dstSubpass; - selfDep.prevAccesses.emplace_back(barrier.endStatus.accessFlag); - selfDep.nextAccesses.emplace_back(barrier.endStatus.accessFlag); + selfDep.prevAccesses |= barrier.endStatus.accessFlag; + selfDep.nextAccesses |= barrier.endStatus.accessFlag; } } else { - dependency.prevAccesses.emplace_back(barrier.beginStatus.accessFlag); - dependency.nextAccesses.emplace_back(barrier.endStatus.accessFlag); + dependency.prevAccesses |= barrier.beginStatus.accessFlag; + dependency.nextAccesses |= barrier.endStatus.accessFlag; } } } - if (!dependency.prevAccesses.empty()) { + if (dependency.prevAccesses != gfx::AccessFlagBit::NONE) { subpassDependencies.emplace_back(dependency); } } @@ -537,8 +554,8 @@ struct BarrierVisitor : public boost::bfs_visitor<> { auto &dsDep = subpassDependencies.emplace_back(); dsDep.srcSubpass = dependency.srcSubpass; dsDep.dstSubpass = dependency.dstSubpass; - dsDep.prevAccesses.emplace_back(barrier.beginStatus.accessFlag); - dsDep.nextAccesses.emplace_back(barrier.endStatus.accessFlag); + dsDep.prevAccesses |= barrier.beginStatus.accessFlag; + dsDep.nextAccesses |= barrier.endStatus.accessFlag; } } else { bool isWriteAccess = !isReadOnlyAccess(barrier.endStatus.accessFlag); @@ -546,22 +563,22 @@ struct BarrierVisitor : public boost::bfs_visitor<> { auto &dep = subpassDependencies.emplace_back(); dep.srcSubpass = dependency.srcSubpass; dep.dstSubpass = dependency.dstSubpass; - dep.prevAccesses.emplace_back(barrier.beginStatus.accessFlag); - dep.nextAccesses.emplace_back(barrier.endStatus.accessFlag); - if (hasReadAccess(barrier.endStatus.accessFlag) && !cc::gfx::Device::getInstance()->hasFeature(gfx::Feature::RASTERIZATION_ORDER_COHERENT)) { + dep.prevAccesses |= barrier.beginStatus.accessFlag; + dep.nextAccesses |= barrier.endStatus.accessFlag; + if (hasReadAccess(barrier.endStatus.accessFlag)) { auto &selfDep = subpassDependencies.emplace_back(); selfDep.srcSubpass = dependency.dstSubpass; selfDep.dstSubpass = dependency.dstSubpass; - selfDep.prevAccesses.emplace_back(barrier.endStatus.accessFlag); - selfDep.nextAccesses.emplace_back(barrier.endStatus.accessFlag); + selfDep.prevAccesses |= barrier.endStatus.accessFlag; + selfDep.nextAccesses |= barrier.endStatus.accessFlag; } } else { - dependency.prevAccesses.emplace_back(barrier.beginStatus.accessFlag); - dependency.nextAccesses.emplace_back(barrier.endStatus.accessFlag); + dependency.prevAccesses |= barrier.beginStatus.accessFlag; + dependency.nextAccesses |= barrier.endStatus.accessFlag; } } } - if (!dependency.prevAccesses.empty()) { + if (dependency.prevAccesses != gfx::AccessFlagBit::NONE) { subpassDependencies.emplace_back(dependency); } @@ -2069,7 +2086,6 @@ void fillRenderPassInfo(const RasterView &view, gfx::RenderPassInfo &rpInfo, uin colorAttachment.loadOp = view.loadOp; colorAttachment.storeOp = view.storeOp; colorAttachment.sampleCount = viewDesc.sampleCount; - colorAttachment.isGeneralLayout = gfx::hasFlag(viewDesc.textureFlags, gfx::TextureFlags::GENERAL_LAYOUT); // colorAttachment.barrier = getGeneralBarrier(gfx::Device::getInstance(), view, prevAccess, nextAccess); } else { auto &depthStencilAttachment = rpInfo.depthStencilAttachment; @@ -2079,7 +2095,6 @@ void fillRenderPassInfo(const RasterView &view, gfx::RenderPassInfo &rpInfo, uin depthStencilAttachment.stencilLoadOp = view.loadOp; depthStencilAttachment.stencilStoreOp = view.storeOp; depthStencilAttachment.sampleCount = viewDesc.sampleCount; - depthStencilAttachment.isGeneralLayout = gfx::hasFlag(viewDesc.textureFlags, gfx::TextureFlags::GENERAL_LAYOUT); // depthStencilAttachment.barrier = getGeneralBarrier(gfx::Device::getInstance(), view, prevAccess, nextAccess); } } @@ -2270,10 +2285,13 @@ void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSub auto &rpInfo = fgRenderpassInfo.rpInfo; auto &subpassInfo = rpInfo.subpasses.emplace_back(); auto *lastNode = &node; + uint32_t subpassIndex = 0; while (lastNode->nextSubpass) { lastNode = lastNode->nextSubpass; + ++subpassIndex; } lastNode->nextSubpass = new ResourceAccessNode; + resourceAccessGraph.subpassIndex.emplace(passID, subpassIndex); auto *head = lastNode->nextSubpass; bool dependent{false}; dependent |= checkRasterViews(graphs, parentRagVert, passID, PassType::RASTER, *head, pass.rasterViews); diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index 5c46cd7455..f5c413887c 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -231,6 +231,16 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( }, [&](const RenderSwapchain& sc) { fbInfo.colorTextures.emplace_back(sc.swapchain->getColorTexture()); + }, + [&](const FormatView& view) { + // TODO(zhouzhenglong): add ImageView support + std::ignore = view; + CC_EXPECTS(false); + }, + [&](const SubresourceView& view) { + // TODO(zhouzhenglong): add ImageView support + std::ignore = view; + CC_EXPECTS(false); }); } else if (view.attachmentType == AttachmentType::DEPTH_STENCIL) { // DepthStencil data.clearDepth = view.clearColor.x; @@ -249,6 +259,14 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( CC_EXPECTS(!fbInfo.depthStencilTexture); fbInfo.depthStencilTexture = tex.get(); }, + [&](const FormatView& view) { + std::ignore = view; + CC_EXPECTS(false); + }, + [&](const SubresourceView& view) { + std::ignore = view; + CC_EXPECTS(false); + }, [](const auto& /*unused*/) { CC_EXPECTS(false); }); @@ -470,7 +488,9 @@ gfx::DescriptorSet* initDescriptorSet( const PmrFlatMap& resourceIndex, const DescriptorSetData& set, const RenderData& user, - LayoutGraphNodeResource& node) { + LayoutGraphNodeResource& node, + const ResourceAccessNode* accessNode = nullptr, + const SceneResource* sceneResource = nullptr) { // update per pass resources const auto& data = set.descriptorSetLayoutData; @@ -518,10 +538,21 @@ gfx::DescriptorSet* initDescriptorSet( newSet->bindTexture(bindID, texture); } else { // user provided textures - auto iter = user.textures.find(d.descriptorID.value); - if (iter != user.textures.end()) { + bool found = false; + if (auto iter = user.textures.find(d.descriptorID.value); + iter != user.textures.end()) { newSet->bindTexture(bindID, iter->second.get()); - } else { + found = true; + } else if (sceneResource) { + auto iter = sceneResource->resourceIndex.find(d.descriptorID); + if (iter != sceneResource->resourceIndex.end()) { + CC_EXPECTS(iter->second == ResourceType::STORAGE_IMAGE); + auto* pTex = sceneResource->storageImages.at(d.descriptorID).get(); + newSet->bindTexture(bindID, pTex); + found = true; + } + } + if (!found) { // default textures gfx::TextureType type{}; switch (d.type) { @@ -574,15 +605,25 @@ gfx::DescriptorSet* initDescriptorSet( case DescriptorTypeOrder::STORAGE_BUFFER: CC_EXPECTS(newSet); for (const auto& d : block.descriptors) { + bool found = false; CC_EXPECTS(d.count == 1); - - auto iter = resourceIndex.find(d.descriptorID); - if (iter != resourceIndex.end()) { + if (auto iter = resourceIndex.find(d.descriptorID); + iter != resourceIndex.end()) { // render graph textures auto* buffer = resg.getBuffer(iter->second); CC_ENSURES(buffer); newSet->bindBuffer(bindID, buffer); + found = true; + } else if (sceneResource) { + auto iter = sceneResource->resourceIndex.find(d.descriptorID); + if (iter != sceneResource->resourceIndex.end()) { + CC_EXPECTS(iter->second == ResourceType::STORAGE_BUFFER); + auto* pBuffer = sceneResource->storageBuffers.at(d.descriptorID).get(); + newSet->bindBuffer(bindID, pBuffer); + found = true; + } } + CC_ENSURES(found); bindID += d.count; } break; @@ -614,8 +655,18 @@ gfx::DescriptorSet* initDescriptorSet( if (iter != resourceIndex.end()) { // render graph textures auto* texture = resg.getTexture(iter->second); + gfx::AccessFlags access = gfx::AccessFlagBit::NONE; + if (accessNode != nullptr) { + auto accIter = std::find_if( + accessNode->attachmentStatus.begin(), accessNode->attachmentStatus.end(), + [iter](const AccessStatus& status) { + return status.vertID == iter->second; + }); + access = accIter != accessNode->attachmentStatus.end() ? accIter->accessFlag : gfx::AccessFlagBit::NONE; + } + CC_ENSURES(texture); - newSet->bindTexture(bindID, texture); + newSet->bindTexture(bindID, texture, 0, access); } bindID += d.count; } @@ -947,6 +998,24 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { ctx.perInstanceDescriptorSets[vertID] = set; } + const SceneResource* getFirstSceneResource(RenderGraph::vertex_descriptor vertID) const { + const auto& g = ctx.g; + CC_EXPECTS(holds(vertID, g)); + for (const auto e : makeRange(children(vertID, g))) { + const auto sceneID = target(e, g); + if (holds(sceneID, g)) { + const auto& sceneData = get(SceneTag{}, sceneID, g); + for (const auto& scene : sceneData.scenes) { + auto iter = ctx.context.renderSceneResources.find(scene); + if (iter != ctx.context.renderSceneResources.end()) { + return &iter->second; + } + } + } + } + return nullptr; + } + void discover_vertex( RenderGraph::vertex_descriptor vertID, const boost::filtered_graph< @@ -1011,6 +1080,9 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { const auto& resourceIndex = buildResourceIndex( ctx.resourceGraph, ctx.lg, computeViews, ctx.scratch); + // find scene resource + const auto* const sceneResource = getFirstSceneResource(vertID); + // populate set auto& set = iter->second; const auto& user = get(RenderGraph::DataTag{}, ctx.g, vertID); @@ -1020,7 +1092,7 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { ctx.resourceGraph, ctx.device, ctx.cmdBuff, *ctx.context.defaultResource, ctx.lg, - resourceIndex, set, user, node); + resourceIndex, set, user, node, nullptr, sceneResource); CC_ENSURES(perPhaseSet); ctx.renderGraphDescriptorSet[vertID] = perPhaseSet; @@ -1062,9 +1134,16 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { /* const auto& resourceIndex = buildResourceIndex( ctx.resourceGraph, ctx.lg, subpass.computeViews, ctx.scratch);*/ PmrFlatMap resourceIndex(ctx.scratch); + resourceIndex.reserve(subpass.rasterViews.size() * 2); for (const auto& [resName, rasterView] : subpass.rasterViews) { const auto resID = vertex(resName, ctx.resourceGraph); + auto ragId = ctx.fgd.resourceAccessGraph.passIndex.at(vertID); + const auto& attachments = ctx.fgd.resourceAccessGraph.access[ragId].attachmentStatus; + auto resIter = std::find_if(attachments.begin(), attachments.end(), [resID](const AccessStatus& status) { + return status.vertID == resID; + }); + auto slotName = rasterView.slotName; if (rasterView.accessType == AccessType::READ || rasterView.accessType == AccessType::READ_WRITE) { slotName.insert(0, "__in"); @@ -1079,11 +1158,13 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { auto& set = iter->second; const auto& user = get(RenderGraph::DataTag{}, ctx.g, vertID); auto& node = ctx.context.layoutGraphResources.at(layoutID); + const auto& accessNode = ctx.fgd.getAttachmentStatus(vertID); + auto* perPassSet = initDescriptorSet( ctx.resourceGraph, ctx.device, ctx.cmdBuff, *ctx.context.defaultResource, ctx.lg, - resourceIndex, set, user, node); + resourceIndex, set, user, node, &accessNode); CC_ENSURES(perPassSet); ctx.renderGraphDescriptorSet[vertID] = perPassSet; } @@ -1503,8 +1584,8 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { // auto* perInstanceSet = ctx.perInstanceDescriptorSets.at(vertID); // execution ctx.cmdBuff->bindPipelineState(pso); - // ctx.cmdBuff->bindDescriptorSet( - // static_cast(pipeline::SetIndex::MATERIAL), pass.getDescriptorSet()); + ctx.cmdBuff->bindDescriptorSet( + static_cast(pipeline::SetIndex::MATERIAL), pass.getDescriptorSet()); // ctx.cmdBuff->bindDescriptorSet( // static_cast(pipeline::SetIndex::LOCAL), perInstanceSet); ctx.cmdBuff->dispatch(gfx::DispatchInfo{ @@ -1913,6 +1994,7 @@ struct RenderGraphContextCleaner { prevFenceValue(context.nextFenceValue) { ++context.nextFenceValue; context.clearPreviousResources(prevFenceValue); + context.renderSceneResources.clear(); } RenderGraphContextCleaner(const RenderGraphContextCleaner&) = delete; RenderGraphContextCleaner& operator=(const RenderGraphContextCleaner&) = delete; @@ -2309,6 +2391,16 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { sceneQueues); } + // gpu driven + if constexpr (ENABLE_GPU_DRIVEN) { + // TODO(jilin): consider populating renderSceneResources here + const scene::RenderScene* const ptr = nullptr; + auto& sceneResource = ppl.nativeContext.renderSceneResources[ptr]; + const auto& nameID = lg.attributeIndex.find("cc_xxxDescriptor")->second; + sceneResource.resourceIndex.emplace(nameID, ResourceType::STORAGE_BUFFER); + sceneResource.storageBuffers.emplace(nameID, nullptr); + } + // Execute all valid passes { boost::filtered_graph< @@ -2357,6 +2449,7 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { CustomRenderGraphContext{ custom.currentContext, &rg, + &ppl.resourceGraph, submit.primaryCommandBuffer, }, scratch}; diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index 16c3da65bf..8bed7b5dfb 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -521,7 +521,7 @@ RenderPassBuilder *addRenderPassImpl( RenderGraph &renderGraph, const NativeProgramLibrary &lib, uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) uint32_t count, uint32_t quality, // NOLINT(bugprone-easily-swappable-parameters) - const ccstd::string &layoutName) { + const ccstd::string &passName) { RasterPass pass(renderGraph.get_allocator()); pass.width = width; pass.height = height; @@ -532,14 +532,14 @@ RenderPassBuilder *addRenderPassImpl( auto passID = addVertex( RasterPassTag{}, - std::forward_as_tuple(std::string_view{layoutName}), - std::forward_as_tuple(std::string_view{layoutName}), + std::forward_as_tuple(passName), + std::forward_as_tuple(passName), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(std::move(pass)), renderGraph); - auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, lib.layoutGraph); + auto passLayoutID = locate(LayoutGraphData::null_vertex(), passName, lib.layoutGraph); CC_EXPECTS(passLayoutID != LayoutGraphData::null_vertex()); auto *builder = ccnew NativeRenderPassBuilder( @@ -553,18 +553,18 @@ RenderPassBuilder *addRenderPassImpl( RenderPassBuilder *NativePipeline::addRenderPass( uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) - const ccstd::string &layoutName) { + const ccstd::string &passName) { return addRenderPassImpl( - this, renderGraph, *programLibrary, width, height, 1, 0, layoutName); + this, renderGraph, *programLibrary, width, height, 1, 0, passName); } BasicRenderPassBuilder *NativePipeline::addMultisampleRenderPass( uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) uint32_t count, uint32_t quality, - const ccstd::string &layoutName) { + const ccstd::string &passName) { CC_EXPECTS(count > 1); return addRenderPassImpl( - this, renderGraph, *programLibrary, width, height, count, quality, layoutName); + this, renderGraph, *programLibrary, width, height, count, quality, passName); } void NativePipeline::addResolvePass(const ccstd::vector &resolvePairs) { @@ -585,17 +585,17 @@ void NativePipeline::addResolvePass(const ccstd::vector &resolvePai } // NOLINTNEXTLINE -ComputePassBuilder *NativePipeline::addComputePass(const ccstd::string &layoutName) { +ComputePassBuilder *NativePipeline::addComputePass(const ccstd::string &passName) { auto passID = addVertex( ComputeTag{}, - std::forward_as_tuple(std::string_view{layoutName}), - std::forward_as_tuple(std::string_view{layoutName}), + std::forward_as_tuple(passName), + std::forward_as_tuple(passName), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(), renderGraph); - auto passLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, programLibrary->layoutGraph); + auto passLayoutID = locate(LayoutGraphData::null_vertex(), passName, programLibrary->layoutGraph); return ccnew NativeComputePassBuilder(this, &renderGraph, passID, &programLibrary->layoutGraph, passLayoutID); } @@ -634,14 +634,14 @@ void NativePipeline::addCopyPass(const ccstd::vector ©Pairs) { renderGraph); } -void NativePipeline::addUploadPass(ccstd::vector& uploadPairs) { +void NativePipeline::addUploadPass(ccstd::vector &uploadPairs) { CopyPass pass(renderGraph.get_allocator()); pass.uploadPairs.reserve(uploadPairs.size()); for (auto &&pair : uploadPairs) { pass.uploadPairs.emplace_back(std::move(pair)); } uploadPairs.clear(); - std::string_view name("Copy"); + std::string_view name("Upload"); addVertex( CopyTag{}, std::forward_as_tuple(name), diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h index 3a34d45ce4..1d55792fb5 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h @@ -61,6 +61,10 @@ struct UniformBlockResource; struct ProgramResource; struct LayoutGraphNodeResource; struct QuadResource; + +enum class ResourceType; + +struct SceneResource; struct NativeRenderContext; class NativeProgramLibrary; struct PipelineCustomization; diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp index bef46029ec..365952ccfe 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp @@ -152,10 +152,21 @@ LayoutGraphNodeResource::LayoutGraphNodeResource(LayoutGraphNodeResource&& rhs, descriptorSetPool(std::move(rhs.descriptorSetPool), alloc), programResources(std::move(rhs.programResources), alloc) {} +SceneResource::SceneResource(const allocator_type& alloc) noexcept +: resourceIndex(alloc), + storageBuffers(alloc), + storageImages(alloc) {} + +SceneResource::SceneResource(SceneResource&& rhs, const allocator_type& alloc) +: resourceIndex(std::move(rhs.resourceIndex), alloc), + storageBuffers(std::move(rhs.storageBuffers), alloc), + storageImages(std::move(rhs.storageImages), alloc) {} + NativeRenderContext::NativeRenderContext(std::unique_ptr defaultResourceIn, const allocator_type& alloc) noexcept : defaultResource(std::move(defaultResourceIn)), resourceGroups(alloc), - layoutGraphResources(alloc) {} + layoutGraphResources(alloc), + renderSceneResources(alloc) {} NativeProgramLibrary::NativeProgramLibrary(const allocator_type& alloc) noexcept : layoutGraph(alloc), diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index d6b31fd020..688793928f 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -109,7 +109,7 @@ public: void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) /*implements*/; void addComputeView(const ccstd::string &name, const ComputeView &view) /*implements*/; void setViewport(const gfx::Viewport &viewport) /*implements*/; - RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &layoutName) /*implements*/; + RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &phaseName) /*implements*/; bool getShowStatistics() const /*implements*/; void setShowStatistics(bool enable) /*implements*/; void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) /*implements*/; @@ -255,8 +255,8 @@ public: void setViewport(const gfx::Viewport &viewport) override { NativeRenderSubpassBuilderImpl::setViewport(viewport); } - RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &layoutName) override { - return NativeRenderSubpassBuilderImpl::addQueue(hint, layoutName); + RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &phaseName) override { + return NativeRenderSubpassBuilderImpl::addQueue(hint, phaseName); } bool getShowStatistics() const override { return NativeRenderSubpassBuilderImpl::getShowStatistics(); @@ -345,8 +345,8 @@ public: void setViewport(const gfx::Viewport &viewport) override { NativeRenderSubpassBuilderImpl::setViewport(viewport); } - RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &layoutName) override { - return NativeRenderSubpassBuilderImpl::addQueue(hint, layoutName); + RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &phaseName) override { + return NativeRenderSubpassBuilderImpl::addQueue(hint, phaseName); } bool getShowStatistics() const override { return NativeRenderSubpassBuilderImpl::getShowStatistics(); @@ -422,7 +422,7 @@ public: void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; void addComputeView(const ccstd::string &name, const ComputeView &view) override; - ComputeQueueBuilder *addQueue(const ccstd::string &layoutName) override; + ComputeQueueBuilder *addQueue(const ccstd::string &phaseName) override; void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) override; }; @@ -486,7 +486,7 @@ public: void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; void addRasterView(const ccstd::string &name, const RasterView &view) override; void addComputeView(const ccstd::string &name, const ComputeView &view) override; - RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &layoutName) override; + RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &phaseName) override; void setViewport(const gfx::Viewport &viewport) override; void setVersion(const ccstd::string &name, uint64_t version) override; bool getShowStatistics() const override; @@ -494,9 +494,9 @@ public: void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; - RenderSubpassBuilder *addRenderSubpass(const ccstd::string &layoutName) override; - MultisampleRenderSubpassBuilder *addMultisampleRenderSubpass(uint32_t count, uint32_t quality, const ccstd::string &layoutName) override; - ComputeSubpassBuilder *addComputeSubpass(const ccstd::string &layoutName) override; + RenderSubpassBuilder *addRenderSubpass(const ccstd::string &subpassName) override; + MultisampleRenderSubpassBuilder *addMultisampleRenderSubpass(uint32_t count, uint32_t quality, const ccstd::string &subpassName) override; + ComputeSubpassBuilder *addComputeSubpass(const ccstd::string &subpassName) override; void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) override; }; @@ -617,7 +617,7 @@ public: void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; void addComputeView(const ccstd::string &name, const ComputeView &view) override; - ComputeQueueBuilder *addQueue(const ccstd::string &layoutName) override; + ComputeQueueBuilder *addQueue(const ccstd::string &phaseName) override; void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) override; }; @@ -895,6 +895,30 @@ struct QuadResource { IntrusivePtr quadIA; }; +enum class ResourceType { + STORAGE_BUFFER, + STORAGE_IMAGE, +}; + +struct SceneResource { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {resourceIndex.get_allocator().resource()}; + } + + SceneResource(const allocator_type& alloc) noexcept; // NOLINT + SceneResource(SceneResource&& rhs, const allocator_type& alloc); + + SceneResource(SceneResource&& rhs) noexcept = default; + SceneResource(SceneResource const& rhs) = delete; + SceneResource& operator=(SceneResource&& rhs) = default; + SceneResource& operator=(SceneResource const& rhs) = delete; + + ccstd::pmr::unordered_map resourceIndex; + ccstd::pmr::unordered_map> storageBuffers; + ccstd::pmr::unordered_map> storageImages; +}; + struct NativeRenderContext { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -910,10 +934,11 @@ struct NativeRenderContext { void clearPreviousResources(uint64_t finishedFenceValue) noexcept; std::unique_ptr defaultResource; + uint64_t nextFenceValue{0}; ccstd::pmr::map resourceGroups; ccstd::pmr::vector layoutGraphResources; + ccstd::pmr::unordered_map renderSceneResources; QuadResource fullscreenQuad; - uint64_t nextFenceValue{0}; }; class NativeProgramLibrary final : public ProgramLibrary { @@ -1035,7 +1060,7 @@ public: void updateDepthStencil(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; void beginFrame() override; void endFrame() override; - BasicRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &layoutName) override; + BasicRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) override; void addResolvePass(const ccstd::vector &resolvePairs) override; void addCopyPass(const ccstd::vector ©Pairs) override; gfx::DescriptorSetLayout *getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) override; @@ -1046,8 +1071,8 @@ public: void updateStorageBuffer(const ccstd::string &name, uint32_t size, gfx::Format format) override; void updateStorageTexture(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; void updateShadingRateTexture(const ccstd::string &name, uint32_t width, uint32_t height) override; - RenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &layoutName) override; - ComputePassBuilder *addComputePass(const ccstd::string &layoutName) override; + RenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &passName) override; + ComputePassBuilder *addComputePass(const ccstd::string &passName) override; void addUploadPass(ccstd::vector &uploadPairs) override; void addMovePass(const ccstd::vector &movePairs) override; uint32_t addCustomBuffer(const ccstd::string &name, const gfx::BufferInfo &info, const std::string &type) override; diff --git a/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp b/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp index 06e34e0763..096677dbe7 100644 --- a/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp @@ -844,104 +844,111 @@ 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; + const char* keyWords[] = { + " uniform ", " buffer " + }; + + for (auto &keyword : keyWords) { + // find first uniform + auto pos = source.find(keyword); + 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)); + + auto inputIndex = prevLayout.find("input_attachment_index"); + if (inputIndex != ccstd::string::npos) { + newLayout.append(", "); + auto endIndex = prevLayout.find_first_of(",)", inputIndex + 1); + newLayout.append(prevLayout.data(), inputIndex, endIndex - inputIndex); + } + + 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()); } } - auto nameBeg = decl.find_last_of(' ', nameEnd); - nameBeg += 1; - nameEnd += 1; - // uniform name found - name = decl.substr(nameBeg, nameEnd - nameBeg); + // offset end of uniform declaration, offset is caused by modification of layout + end += offset; + // find next uniform + pos = source.find(keyword, end); } - 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)); - - auto inputIndex = prevLayout.find("input_attachment_index"); - if (inputIndex != ccstd::string::npos) { - newLayout.append(", "); - auto endIndex = prevLayout.find_first_of(",)", inputIndex + 1); - newLayout.append(prevLayout.data(), inputIndex, endIndex - inputIndex); - } - - 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); } } diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp index 8d9dfc2f30..41d23abfd8 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp @@ -757,20 +757,20 @@ void NativeRenderSubpassBuilderImpl::setViewport(const gfx::Viewport &viewport) subpass.viewport = viewport; } -RenderQueueBuilder *NativeRenderSubpassBuilderImpl::addQueue(QueueHint hint, const ccstd::string &layoutName) { +RenderQueueBuilder *NativeRenderSubpassBuilderImpl::addQueue( + QueueHint hint, const ccstd::string &phaseName) { CC_EXPECTS(layoutID != LayoutGraphData::null_vertex()); auto phaseLayoutID = LayoutGraphData::null_vertex(); - if (!layoutName.empty()) { - phaseLayoutID = locate(layoutID, layoutName, *layoutGraph); + if (!phaseName.empty()) { + phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); } - std::string_view name = "Queue"; auto queueID = addVertex( QueueTag{}, - std::forward_as_tuple(name), - std::forward_as_tuple(), + std::forward_as_tuple(phaseName), + std::forward_as_tuple(phaseName), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(hint, phaseLayoutID), @@ -889,20 +889,19 @@ void NativeComputeSubpassBuilder::addComputeView(const ccstd::string &name, cons addComputeViewImpl(name, view, nodeID, *renderGraph); } -ComputeQueueBuilder *NativeComputeSubpassBuilder::addQueue(const ccstd::string &layoutName) { +ComputeQueueBuilder *NativeComputeSubpassBuilder::addQueue(const ccstd::string &phaseName) { CC_EXPECTS(layoutID != LayoutGraphData::null_vertex()); auto phaseLayoutID = LayoutGraphData::null_vertex(); - if (!layoutName.empty()) { - phaseLayoutID = locate(layoutID, layoutName, *layoutGraph); + if (!phaseName.empty()) { + phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); } - std::string_view name = "Queue"; auto queueID = addVertex( QueueTag{}, - std::forward_as_tuple(name), - std::forward_as_tuple(), + std::forward_as_tuple(phaseName), + std::forward_as_tuple(phaseName), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(phaseLayoutID), @@ -1381,20 +1380,19 @@ void NativeRenderQueueBuilder::addCustomCommand(std::string_view customBehavior) } RenderQueueBuilder *NativeRenderPassBuilder::addQueue( - QueueHint hint, const ccstd::string &layoutName) { + QueueHint hint, const ccstd::string &phaseName) { CC_EXPECTS(layoutID != LayoutGraphData::null_vertex()); auto phaseLayoutID = LayoutGraphData::null_vertex(); - if (!layoutName.empty()) { - phaseLayoutID = locate(layoutID, layoutName, *layoutGraph); + if (!phaseName.empty()) { + phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); } - std::string_view name = "Queue"; auto queueID = addVertex( QueueTag{}, - std::forward_as_tuple(name), - std::forward_as_tuple(), + std::forward_as_tuple(phaseName), + std::forward_as_tuple(phaseName), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(hint, phaseLayoutID), @@ -1408,16 +1406,17 @@ namespace { template SubpassBuilder *addRenderSubpassImpl( const PipelineRuntime *pipelineRuntime, - RenderGraph &renderGraph, const LayoutGraphData &layoutGraph, - uint32_t nodeID, const ccstd::string &layoutName, + RenderGraph &renderGraph, RenderGraph::vertex_descriptor passID, + const LayoutGraphData &layoutGraph, LayoutGraphData::vertex_descriptor passLayoutID, + const ccstd::string &subpassName, uint32_t count, uint32_t quality) { // NOLINT(bugprone-easily-swappable-parameters) - auto &pass = get(RasterPassTag{}, nodeID, renderGraph); + auto &pass = get(RasterPassTag{}, passID, renderGraph); auto &subpassGraph = pass.subpassGraph; const auto subpassIndex = num_vertices(pass.subpassGraph); { auto id = addVertex( std::piecewise_construct, - std::forward_as_tuple(std::string_view{layoutName}), + std::forward_as_tuple(subpassName), std::forward_as_tuple(), subpassGraph); CC_ENSURES(id == subpassIndex); @@ -1429,14 +1428,20 @@ SubpassBuilder *addRenderSubpassImpl( auto subpassID = addVertex( RasterSubpassTag{}, - std::forward_as_tuple(std::string_view{layoutName}), - std::forward_as_tuple(std::string_view{layoutName}), + std::forward_as_tuple(subpassName), + std::forward_as_tuple(subpassName), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(std::move(subpass)), - renderGraph, nodeID); + renderGraph, passID); + + auto subpassLayoutID = LayoutGraphData::null_vertex(); + if constexpr (ENABLE_SUBPASS) { + subpassLayoutID = locate(passLayoutID, subpassName, layoutGraph); + } else { + subpassLayoutID = locate(LayoutGraphData::null_vertex(), subpassName, layoutGraph); + } - auto subpassLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, layoutGraph); CC_EXPECTS(subpassLayoutID != LayoutGraphData::null_vertex()); auto *builder = ccnew SubpassBuilder( @@ -1449,26 +1454,25 @@ SubpassBuilder *addRenderSubpassImpl( } // namespace -RenderSubpassBuilder *NativeRenderPassBuilder::addRenderSubpass(const ccstd::string &layoutName) { +RenderSubpassBuilder *NativeRenderPassBuilder::addRenderSubpass(const ccstd::string &subpassName) { return addRenderSubpassImpl( - pipelineRuntime, *renderGraph, *layoutGraph, nodeID, layoutName, 1, 0); + pipelineRuntime, *renderGraph, nodeID, *layoutGraph, layoutID, subpassName, 1, 0); } MultisampleRenderSubpassBuilder *NativeRenderPassBuilder::addMultisampleRenderSubpass( - uint32_t count, uint32_t quality, const ccstd::string &layoutName) { // NOLINT(bugprone-easily-swappable-parameters) + uint32_t count, uint32_t quality, const ccstd::string &subpassName) { // NOLINT(bugprone-easily-swappable-parameters) return addRenderSubpassImpl( - pipelineRuntime, *renderGraph, *layoutGraph, nodeID, layoutName, count, quality); + pipelineRuntime, *renderGraph, nodeID, *layoutGraph, layoutID, subpassName, count, quality); } -ComputeSubpassBuilder *NativeRenderPassBuilder::addComputeSubpass(const ccstd::string &layoutName) { - std::string_view name("ComputeSubpass"); +ComputeSubpassBuilder *NativeRenderPassBuilder::addComputeSubpass(const ccstd::string &subpassName) { auto &pass = get(RasterPassTag{}, nodeID, *renderGraph); auto &subpassGraph = pass.subpassGraph; const auto subpassIndex = num_vertices(pass.subpassGraph); { auto id = addVertex( std::piecewise_construct, - std::forward_as_tuple(name), + std::forward_as_tuple(subpassName), std::forward_as_tuple(), subpassGraph); CC_ENSURES(id == subpassIndex); @@ -1478,14 +1482,19 @@ ComputeSubpassBuilder *NativeRenderPassBuilder::addComputeSubpass(const ccstd::s auto subpassID = addVertex( ComputeSubpassTag{}, - std::forward_as_tuple(name), - std::forward_as_tuple(layoutName.c_str()), + std::forward_as_tuple(subpassName), + std::forward_as_tuple(subpassName), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(std::move(subpass)), *renderGraph, nodeID); - auto subpassLayoutID = locate(LayoutGraphData::null_vertex(), layoutName, *layoutGraph); + auto subpassLayoutID = LayoutGraphData::null_vertex(); + if constexpr (ENABLE_SUBPASS) { + subpassLayoutID = locate(layoutID, subpassName, *layoutGraph); + } else { + subpassLayoutID = locate(LayoutGraphData::null_vertex(), subpassName, *layoutGraph); + } CC_EXPECTS(subpassLayoutID != LayoutGraphData::null_vertex()); auto *builder = ccnew NativeComputeSubpassBuilder( @@ -1521,7 +1530,7 @@ void NativeComputeQueueBuilder::addDispatch( threadGroupCountX, threadGroupCountY, threadGroupCountZ), - *renderGraph, passID); + *renderGraph, nodeID); } // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) @@ -1599,20 +1608,19 @@ void NativeComputePassBuilder::addComputeView(const ccstd::string &name, const C iter->second.emplace_back(view); } -ComputeQueueBuilder *NativeComputePassBuilder::addQueue(const ccstd::string &layoutName) { +ComputeQueueBuilder *NativeComputePassBuilder::addQueue(const ccstd::string &phaseName) { CC_EXPECTS(layoutID != LayoutGraphData::null_vertex()); auto phaseLayoutID = LayoutGraphData::null_vertex(); - if (!layoutName.empty()) { - phaseLayoutID = locate(layoutID, layoutName, *layoutGraph); + if (!phaseName.empty()) { + phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); } - std::string_view name("Queue"); auto queueID = addVertex( QueueTag{}, - std::forward_as_tuple(name), - std::forward_as_tuple(), + std::forward_as_tuple(phaseName), + std::forward_as_tuple(phaseName), std::forward_as_tuple(), std::forward_as_tuple(), std::forward_as_tuple(QueueHint::NONE, phaseLayoutID), diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index 16686ad8e6..20709a6f97 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -182,6 +182,7 @@ void ResourceGraph::validateSwapchains() { } } +// NOLINTNEXTLINE(misc-no-recursion) void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { std::ignore = device; auto& resg = *this; @@ -222,6 +223,30 @@ void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { [&](const RenderSwapchain& queue) { CC_EXPECTS(queue.swapchain); std::ignore = queue; + }, + [&](const FormatView& view) { // NOLINT(misc-no-recursion) + std::ignore = view; + auto parentID = parent(vertID, resg); + CC_EXPECTS(parentID != resg.null_vertex()); + while (resg.isTextureView(parentID)) { + parentID = parent(parentID, resg); + } + CC_EXPECTS(parentID != resg.null_vertex()); + CC_EXPECTS(resg.isTexture(parentID)); + CC_ENSURES(!resg.isTextureView(parentID)); + mount(device, parentID); + }, + [&](const SubresourceView& view) { // NOLINT(misc-no-recursion) + std::ignore = view; + auto parentID = parent(vertID, resg); + CC_EXPECTS(parentID != resg.null_vertex()); + while (resg.isTextureView(parentID)) { + parentID = parent(parentID, resg); + } + CC_EXPECTS(parentID != resg.null_vertex()); + CC_EXPECTS(resg.isTexture(parentID)); + CC_ENSURES(!resg.isTextureView(parentID)); + mount(device, parentID); }); } @@ -267,6 +292,23 @@ bool ResourceGraph::isTexture(vertex_descriptor resID) const noexcept { }); } +bool ResourceGraph::isTextureView(vertex_descriptor resID) const noexcept { + return visitObject( + resID, *this, + [&](const FormatView& view) { + std::ignore = view; + return true; + }, + [&](const SubresourceView& view) { + std::ignore = view; + return true; + }, + [&](const auto& res) { + std::ignore = res; + return false; + }); +} + gfx::Buffer* ResourceGraph::getBuffer(vertex_descriptor resID) { gfx::Buffer* buffer = nullptr; visitObject( @@ -304,6 +346,16 @@ gfx::Texture* ResourceGraph::getTexture(vertex_descriptor resID) { [&](const RenderSwapchain& sc) { texture = sc.swapchain->getColorTexture(); }, + [&](const FormatView& view) { + // TODO(zhouzhenglong): add ImageView support + std::ignore = view; + CC_EXPECTS(false); + }, + [&](const SubresourceView& view) { + // TODO(zhouzhenglong): add ImageView support + std::ignore = view; + CC_EXPECTS(false); + }, [&](const auto& buffer) { std::ignore = buffer; CC_EXPECTS(false); diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h b/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h index d2f2c39c46..95483b4ad7 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphFwd.h @@ -59,6 +59,10 @@ struct PersistentTextureTag; struct FramebufferTag; struct SwapchainTag; struct SamplerTag; +struct FormatViewTag; +struct SubresourceViewTag; +struct FormatView; +struct SubresourceView; struct ResourceGraph; struct ComputePass; struct ResolvePass; diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h b/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h index 9f6cc99c02..e14bfd7c41 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphGraphs.h @@ -375,340 +375,90 @@ inline void remove_edge(ResourceGraph::edge_descriptor e, ResourceGraph& g) noex remove_edge(ResourceGraph::out_edge_iterator(outIter, u), g); } -// MutableGraph(Vertex) -inline void clear_out_edges(ResourceGraph::vertex_descriptor u, ResourceGraph& g) noexcept { // NOLINT - // Bidirectional (OutEdges) - auto& outEdgeList = g.getOutEdgeList(u); - auto outEnd = outEdgeList.end(); - for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { - auto& inEdgeList = g.getInEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); +// AddressableGraph +inline ResourceGraph::vertex_descriptor +parent(const ResourceGraph::ownership_descriptor& e, const ResourceGraph& /*g*/) noexcept { + return e.source; +} + +inline ResourceGraph::vertex_descriptor +child(const ResourceGraph::ownership_descriptor& e, const ResourceGraph& /*g*/) noexcept { + return e.target; +} + +inline std::pair +children(ResourceGraph::vertex_descriptor u, const ResourceGraph& g) noexcept { + return std::make_pair( + ResourceGraph::children_iterator(const_cast(g).getChildrenList(u).begin(), u), + ResourceGraph::children_iterator(const_cast(g).getChildrenList(u).end(), u)); +} + +inline ResourceGraph::children_size_type +numChildren(ResourceGraph::vertex_descriptor u, const ResourceGraph& g) noexcept { + return gsl::narrow_cast(g.getChildrenList(u).size()); +} + +inline std::pair +reference(ResourceGraph::vertex_descriptor u, ResourceGraph::vertex_descriptor v, ResourceGraph& g) noexcept { + auto& outEdgeList = g.getChildrenList(u); + auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), ResourceGraph::OutEdge(v)); + bool hasEdge = (iter != outEdgeList.end()); + return {ResourceGraph::ownership_descriptor(u, v), hasEdge}; +} + +inline std::pair +parents(ResourceGraph::vertex_descriptor u, const ResourceGraph& g) noexcept { + return std::make_pair( + ResourceGraph::parent_iterator(const_cast(g).getParentsList(u).begin(), u), + ResourceGraph::parent_iterator(const_cast(g).getParentsList(u).end(), u)); +} + +inline ResourceGraph::children_size_type +numParents(ResourceGraph::vertex_descriptor u, const ResourceGraph& g) noexcept { + return gsl::narrow_cast(g.getParentsList(u).size()); +} + +inline ResourceGraph::vertex_descriptor +parent(ResourceGraph::vertex_descriptor u, const ResourceGraph& g) noexcept { + auto r = parents(u, g); + if (r.first == r.second) { + return ResourceGraph::null_vertex(); } - outEdgeList.clear(); + return parent(*r.first, g); } -inline void clear_in_edges(ResourceGraph::vertex_descriptor u, ResourceGraph& g) noexcept { // NOLINT - // Bidirectional (InEdges) - auto& inEdgeList = g.getInEdgeList(u); - auto inEnd = inEdgeList.end(); - for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { - auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - inEdgeList.clear(); -} - -inline void clear_vertex(ResourceGraph::vertex_descriptor u, ResourceGraph& g) noexcept { // NOLINT - clear_out_edges(u, g); - clear_in_edges(u, g); -} - -inline void remove_vertex_value_impl(const ResourceGraph::VertexHandle& h, ResourceGraph& g) noexcept { // NOLINT - using vertex_descriptor = ResourceGraph::vertex_descriptor; - ccstd::visit( - overload( - [&](const impl::ValueHandle& h) { - g.resources.erase(g.resources.begin() + static_cast(h.value)); - if (h.value == g.resources.size()) { - return; - } - impl::reindexVectorHandle(g._vertices, h.value); - }, - [&](const impl::ValueHandle& h) { - g.managedBuffers.erase(g.managedBuffers.begin() + static_cast(h.value)); - if (h.value == g.managedBuffers.size()) { - return; - } - impl::reindexVectorHandle(g._vertices, h.value); - }, - [&](const impl::ValueHandle& h) { - g.managedTextures.erase(g.managedTextures.begin() + static_cast(h.value)); - if (h.value == g.managedTextures.size()) { - return; - } - impl::reindexVectorHandle(g._vertices, h.value); - }, - [&](const impl::ValueHandle& h) { - g.buffers.erase(g.buffers.begin() + static_cast(h.value)); - if (h.value == g.buffers.size()) { - return; - } - impl::reindexVectorHandle(g._vertices, h.value); - }, - [&](const impl::ValueHandle& h) { - g.textures.erase(g.textures.begin() + static_cast(h.value)); - if (h.value == g.textures.size()) { - return; - } - impl::reindexVectorHandle(g._vertices, h.value); - }, - [&](const impl::ValueHandle& h) { - g.framebuffers.erase(g.framebuffers.begin() + static_cast(h.value)); - if (h.value == g.framebuffers.size()) { - return; - } - impl::reindexVectorHandle(g._vertices, h.value); - }, - [&](const impl::ValueHandle& h) { - g.swapchains.erase(g.swapchains.begin() + static_cast(h.value)); - if (h.value == g.swapchains.size()) { - return; - } - impl::reindexVectorHandle(g._vertices, h.value); - }), - h); -} - -inline void remove_vertex(ResourceGraph::vertex_descriptor u, ResourceGraph& g) noexcept { // NOLINT - // preserve vertex' iterators - auto& vert = g._vertices[u]; - remove_vertex_value_impl(vert.handle, g); - { // UuidGraph - const auto& key = g.names[u]; - auto num = g.valueIndex.erase(key); - CC_ENSURES(num == 1); - for (auto&& pair : g.valueIndex) { - auto& v = pair.second; - if (v > u) { - --v; - } +inline bool +ancestor(ResourceGraph::vertex_descriptor u, ResourceGraph::vertex_descriptor v, const ResourceGraph& g) noexcept { + CC_EXPECTS(u != v); + bool isAncestor = false; + auto r = parents(v, g); + while (r.first != r.second) { + v = parent(*r.first, g); + if (u == v) { + isAncestor = true; + break; } + r = parents(v, g); } - impl::removeVectorVertex(const_cast(g), u, ResourceGraph::directed_category{}); - - // remove components - g.names.erase(g.names.begin() + static_cast(u)); - g.descs.erase(g.descs.begin() + static_cast(u)); - g.traits.erase(g.traits.begin() + static_cast(u)); - g.states.erase(g.states.begin() + static_cast(u)); - g.samplerInfo.erase(g.samplerInfo.begin() + static_cast(u)); + return isAncestor; } -// MutablePropertyGraph(Vertex) -template -void addVertexImpl( // NOLINT - ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT - std::enable_if_t, ManagedResource>::value>* dummy = nullptr) { // NOLINT - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.resources.size())}; - g.resources.emplace_back(std::forward(val)); +inline std::pair +references(const ResourceGraph& g0) noexcept { + auto& g = const_cast(g0); + return std::make_pair( + ResourceGraph::ownership_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), + ResourceGraph::ownership_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); } -template -void addVertexImpl( // NOLINT - ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT - std::enable_if_t, ManagedBuffer>::value>* dummy = nullptr) { // NOLINT - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.managedBuffers.size())}; - g.managedBuffers.emplace_back(std::forward(val)); -} - -template -void addVertexImpl( // NOLINT - ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT - std::enable_if_t, ManagedTexture>::value>* dummy = nullptr) { // NOLINT - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.managedTextures.size())}; - g.managedTextures.emplace_back(std::forward(val)); -} - -template -void addVertexImpl( // NOLINT - ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT - std::enable_if_t, IntrusivePtr>::value>* dummy = nullptr) { // NOLINT - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.buffers.size())}; - g.buffers.emplace_back(std::forward(val)); -} - -template -void addVertexImpl( // NOLINT - ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT - std::enable_if_t, IntrusivePtr>::value>* dummy = nullptr) { // NOLINT - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.textures.size())}; - g.textures.emplace_back(std::forward(val)); -} - -template -void addVertexImpl( // NOLINT - ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT - std::enable_if_t, IntrusivePtr>::value>* dummy = nullptr) { // NOLINT - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.framebuffers.size())}; - g.framebuffers.emplace_back(std::forward(val)); -} - -template -void addVertexImpl( // NOLINT - ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT - std::enable_if_t, RenderSwapchain>::value>* dummy = nullptr) { // NOLINT - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.swapchains.size())}; - g.swapchains.emplace_back(std::forward(val)); -} - -template -inline ResourceGraph::vertex_descriptor -addVertex(Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, Component4&& c4, ValueT&& val, ResourceGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - auto& vert = g._vertices.back(); - - { // UuidGraph - const auto& uuid = c0; - auto res = g.valueIndex.emplace(uuid, v); - CC_ENSURES(res.second); +inline ResourceGraph::ownerships_size_type +numReferences(const ResourceGraph& g) noexcept { + ResourceGraph::ownerships_size_type numEdges = 0; + auto range = vertices(g); + for (auto iter = range.first; iter != range.second; ++iter) { + numEdges += numChildren(*iter, g); } - g.names.emplace_back(std::forward(c0)); - g.descs.emplace_back(std::forward(c1)); - g.traits.emplace_back(std::forward(c2)); - g.states.emplace_back(std::forward(c3)); - g.samplerInfo.emplace_back(std::forward(c4)); - - // PolymorphicGraph - // if no matching overloaded function is found, Type is not supported by PolymorphicGraph - addVertexImpl(std::forward(val), g, vert); - - return v; -} - -template -void addVertexImpl(ManagedTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { - std::apply( - [&](auto&&... args) { - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.resources.size())}; - g.resources.emplace_back(std::forward(args)...); - }, - std::forward(val)); -} - -template -void addVertexImpl(ManagedBufferTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { - std::apply( - [&](auto&&... args) { - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.managedBuffers.size())}; - g.managedBuffers.emplace_back(std::forward(args)...); - }, - std::forward(val)); -} - -template -void addVertexImpl(ManagedTextureTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { - std::apply( - [&](auto&&... args) { - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.managedTextures.size())}; - g.managedTextures.emplace_back(std::forward(args)...); - }, - std::forward(val)); -} - -template -void addVertexImpl(PersistentBufferTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { - std::apply( - [&](auto&&... args) { - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.buffers.size())}; - g.buffers.emplace_back(std::forward(args)...); - }, - std::forward(val)); -} - -template -void addVertexImpl(PersistentTextureTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { - std::apply( - [&](auto&&... args) { - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.textures.size())}; - g.textures.emplace_back(std::forward(args)...); - }, - std::forward(val)); -} - -template -void addVertexImpl(FramebufferTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { - std::apply( - [&](auto&&... args) { - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.framebuffers.size())}; - g.framebuffers.emplace_back(std::forward(args)...); - }, - std::forward(val)); -} - -template -void addVertexImpl(SwapchainTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { - std::apply( - [&](auto&&... args) { - vert.handle = impl::ValueHandle{ - gsl::narrow_cast(g.swapchains.size())}; - g.swapchains.emplace_back(std::forward(args)...); - }, - std::forward(val)); -} - -template -inline ResourceGraph::vertex_descriptor -addVertex(Tag tag, Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, Component4&& c4, ValueT&& val, ResourceGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - auto& vert = g._vertices.back(); - - { // UuidGraph - std::apply( - [&](const auto&... args) { - auto res = g.valueIndex.emplace(std::piecewise_construct, std::forward_as_tuple(args...), std::forward_as_tuple(v)); - CC_ENSURES(res.second); - }, - c0); - } - - std::apply( - [&](auto&&... args) { - g.names.emplace_back(std::forward(args)...); - }, - std::forward(c0)); - - std::apply( - [&](auto&&... args) { - g.descs.emplace_back(std::forward(args)...); - }, - std::forward(c1)); - - std::apply( - [&](auto&&... args) { - g.traits.emplace_back(std::forward(args)...); - }, - std::forward(c2)); - - std::apply( - [&](auto&&... args) { - g.states.emplace_back(std::forward(args)...); - }, - std::forward(c3)); - - std::apply( - [&](auto&&... args) { - g.samplerInfo.emplace_back(std::forward(args)...); - }, - std::forward(c4)); - - // PolymorphicGraph - // if no matching overloaded function is found, Type is not supported by PolymorphicGraph - addVertexImpl(tag, std::forward(val), g, vert); - - return v; + return numEdges; } // IncidenceGraph @@ -1552,6 +1302,12 @@ id(ResourceGraph::vertex_descriptor u, const ResourceGraph& g) noexcept { }, [](const impl::ValueHandle& h) { return h.value; + }, + [](const impl::ValueHandle& h) { + return h.value; + }, + [](const impl::ValueHandle& h) { + return h.value; }), g._vertices[u].handle); } @@ -1581,6 +1337,12 @@ tag(ResourceGraph::vertex_descriptor u, const ResourceGraph& g) noexcept { }, [](const impl::ValueHandle&) { return ResourceGraph::VertexTag{SwapchainTag{}}; + }, + [](const impl::ValueHandle&) { + return ResourceGraph::VertexTag{FormatViewTag{}}; + }, + [](const impl::ValueHandle&) { + return ResourceGraph::VertexTag{SubresourceViewTag{}}; }), g._vertices[u].handle); } @@ -1610,6 +1372,12 @@ value(ResourceGraph::vertex_descriptor u, ResourceGraph& g) noexcept { }, [&](const impl::ValueHandle& h) { return ResourceGraph::VertexValue{&g.swapchains[h.value]}; + }, + [&](const impl::ValueHandle& h) { + return ResourceGraph::VertexValue{&g.formatViews[h.value]}; + }, + [&](const impl::ValueHandle& h) { + return ResourceGraph::VertexValue{&g.subresourceViews[h.value]}; }), g._vertices[u].handle); } @@ -1639,6 +1407,12 @@ value(ResourceGraph::vertex_descriptor u, const ResourceGraph& g) noexcept { }, [&](const impl::ValueHandle& h) { return ResourceGraph::VertexConstValue{&g.swapchains[h.value]}; + }, + [&](const impl::ValueHandle& h) { + return ResourceGraph::VertexConstValue{&g.formatViews[h.value]}; + }, + [&](const impl::ValueHandle& h) { + return ResourceGraph::VertexConstValue{&g.subresourceViews[h.value]}; }), g._vertices[u].handle); } @@ -1703,6 +1477,22 @@ holds(ResourceGraph::vertex_descriptor v, const ResourceGraph& g) g._vertices[v].handle); } +template <> +inline bool +holds(ResourceGraph::vertex_descriptor v, const ResourceGraph& g) noexcept { + return ccstd::holds_alternative< + impl::ValueHandle>( + g._vertices[v].handle); +} + +template <> +inline bool +holds(ResourceGraph::vertex_descriptor v, const ResourceGraph& g) noexcept { + return ccstd::holds_alternative< + impl::ValueHandle>( + g._vertices[v].handle); +} + template inline bool holds_alternative(ResourceGraph::vertex_descriptor v, const ResourceGraph& g) noexcept; // NOLINT @@ -1763,6 +1553,22 @@ holds_alternative(ResourceGraph::vertex_descriptor v, const Res g._vertices[v].handle); } +template <> +inline bool +holds_alternative(ResourceGraph::vertex_descriptor v, const ResourceGraph& g) noexcept { // NOLINT + return ccstd::holds_alternative< + impl::ValueHandle>( + g._vertices[v].handle); +} + +template <> +inline bool +holds_alternative(ResourceGraph::vertex_descriptor v, const ResourceGraph& g) noexcept { // NOLINT + return ccstd::holds_alternative< + impl::ValueHandle>( + g._vertices[v].handle); +} + template inline ValueT& get(ResourceGraph::vertex_descriptor /*v*/, ResourceGraph& /*g*/); @@ -1830,6 +1636,24 @@ get(ResourceGraph::vertex_descriptor v, ResourceGraph& g) { return g.swapchains[handle.value]; } +template <> +inline FormatView& +get(ResourceGraph::vertex_descriptor v, ResourceGraph& g) { + auto& handle = ccstd::get< + impl::ValueHandle>( + g._vertices[v].handle); + return g.formatViews[handle.value]; +} + +template <> +inline SubresourceView& +get(ResourceGraph::vertex_descriptor v, ResourceGraph& g) { + auto& handle = ccstd::get< + impl::ValueHandle>( + g._vertices[v].handle); + return g.subresourceViews[handle.value]; +} + template inline const ValueT& get(ResourceGraph::vertex_descriptor /*v*/, const ResourceGraph& /*g*/); @@ -1897,6 +1721,24 @@ get(ResourceGraph::vertex_descriptor v, const ResourceGraph& g) return g.swapchains[handle.value]; } +template <> +inline const FormatView& +get(ResourceGraph::vertex_descriptor v, const ResourceGraph& g) { + const auto& handle = ccstd::get< + impl::ValueHandle>( + g._vertices[v].handle); + return g.formatViews[handle.value]; +} + +template <> +inline const SubresourceView& +get(ResourceGraph::vertex_descriptor v, const ResourceGraph& g) { + const auto& handle = ccstd::get< + impl::ValueHandle>( + g._vertices[v].handle); + return g.subresourceViews[handle.value]; +} + inline ManagedResource& get(ManagedTag /*tag*/, ResourceGraph::vertex_descriptor v, ResourceGraph& g) { auto& handle = ccstd::get< @@ -1953,6 +1795,22 @@ get(SwapchainTag /*tag*/, ResourceGraph::vertex_descriptor v, ResourceGraph& g) return g.swapchains[handle.value]; } +inline FormatView& +get(FormatViewTag /*tag*/, ResourceGraph::vertex_descriptor v, ResourceGraph& g) { + auto& handle = ccstd::get< + impl::ValueHandle>( + g._vertices[v].handle); + return g.formatViews[handle.value]; +} + +inline SubresourceView& +get(SubresourceViewTag /*tag*/, ResourceGraph::vertex_descriptor v, ResourceGraph& g) { + auto& handle = ccstd::get< + impl::ValueHandle>( + g._vertices[v].handle); + return g.subresourceViews[handle.value]; +} + inline const ManagedResource& get(ManagedTag /*tag*/, ResourceGraph::vertex_descriptor v, const ResourceGraph& g) { const auto& handle = ccstd::get< @@ -2009,6 +1867,22 @@ get(SwapchainTag /*tag*/, ResourceGraph::vertex_descriptor v, const ResourceGrap return g.swapchains[handle.value]; } +inline const FormatView& +get(FormatViewTag /*tag*/, ResourceGraph::vertex_descriptor v, const ResourceGraph& g) { + const auto& handle = ccstd::get< + impl::ValueHandle>( + g._vertices[v].handle); + return g.formatViews[handle.value]; +} + +inline const SubresourceView& +get(SubresourceViewTag /*tag*/, ResourceGraph::vertex_descriptor v, const ResourceGraph& g) { + const auto& handle = ccstd::get< + impl::ValueHandle>( + g._vertices[v].handle); + return g.subresourceViews[handle.value]; +} + template inline ValueT* get_if(ResourceGraph::vertex_descriptor v, ResourceGraph* pGraph) noexcept; // NOLINT @@ -2132,6 +2006,40 @@ get_if(ResourceGraph::vertex_descriptor v, ResourceGraph* pGrap return ptr; } +template <> +inline FormatView* +get_if(ResourceGraph::vertex_descriptor v, ResourceGraph* pGraph) noexcept { // NOLINT + FormatView* ptr = nullptr; + if (!pGraph) { + return ptr; + } + auto& g = *pGraph; + auto* pHandle = ccstd::get_if< + impl::ValueHandle>( + &g._vertices[v].handle); + if (pHandle) { + ptr = &g.formatViews[pHandle->value]; + } + return ptr; +} + +template <> +inline SubresourceView* +get_if(ResourceGraph::vertex_descriptor v, ResourceGraph* pGraph) noexcept { // NOLINT + SubresourceView* ptr = nullptr; + if (!pGraph) { + return ptr; + } + auto& g = *pGraph; + auto* pHandle = ccstd::get_if< + impl::ValueHandle>( + &g._vertices[v].handle); + if (pHandle) { + ptr = &g.subresourceViews[pHandle->value]; + } + return ptr; +} + template inline const ValueT* get_if(ResourceGraph::vertex_descriptor v, const ResourceGraph* pGraph) noexcept; // NOLINT @@ -2255,6 +2163,40 @@ get_if(ResourceGraph::vertex_descriptor v, const ResourceGraph* return ptr; } +template <> +inline const FormatView* +get_if(ResourceGraph::vertex_descriptor v, const ResourceGraph* pGraph) noexcept { // NOLINT + const FormatView* ptr = nullptr; + if (!pGraph) { + return ptr; + } + const auto& g = *pGraph; + const auto* pHandle = ccstd::get_if< + impl::ValueHandle>( + &g._vertices[v].handle); + if (pHandle) { + ptr = &g.formatViews[pHandle->value]; + } + return ptr; +} + +template <> +inline const SubresourceView* +get_if(ResourceGraph::vertex_descriptor v, const ResourceGraph* pGraph) noexcept { // NOLINT + const SubresourceView* ptr = nullptr; + if (!pGraph) { + return ptr; + } + const auto& g = *pGraph; + const auto* pHandle = ccstd::get_if< + impl::ValueHandle>( + &g._vertices[v].handle); + if (pHandle) { + ptr = &g.subresourceViews[pHandle->value]; + } + return ptr; +} + // Vertex Constant Getter template inline decltype(auto) @@ -2319,6 +2261,413 @@ contains(const KeyLike& key, const ResourceGraph& g) noexcept { return iter != g.valueIndex.end(); } +// MutableGraph(Vertex) +inline void addPathImpl(ResourceGraph::vertex_descriptor u, ResourceGraph::vertex_descriptor v, ResourceGraph& g) { // NOLINT + // add to parent + if (u != ResourceGraph::null_vertex()) { + auto& outEdgeList = g.getChildrenList(u); + outEdgeList.emplace_back(v); + + auto& inEdgeList = g.getParentsList(v); + inEdgeList.emplace_back(u); + } +} + +inline void clear_out_edges(ResourceGraph::vertex_descriptor u, ResourceGraph& g) noexcept { // NOLINT + // Bidirectional (OutEdges) + auto& outEdgeList = g.getOutEdgeList(u); + auto outEnd = outEdgeList.end(); + for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { + auto& inEdgeList = g.getInEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + outEdgeList.clear(); +} + +inline void clear_in_edges(ResourceGraph::vertex_descriptor u, ResourceGraph& g) noexcept { // NOLINT + // Bidirectional (InEdges) + auto& inEdgeList = g.getInEdgeList(u); + auto inEnd = inEdgeList.end(); + for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { + auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + inEdgeList.clear(); +} + +inline void clear_vertex(ResourceGraph::vertex_descriptor u, ResourceGraph& g) noexcept { // NOLINT + clear_out_edges(u, g); + clear_in_edges(u, g); +} + +inline void remove_vertex_value_impl(const ResourceGraph::VertexHandle& h, ResourceGraph& g) noexcept { // NOLINT + using vertex_descriptor = ResourceGraph::vertex_descriptor; + ccstd::visit( + overload( + [&](const impl::ValueHandle& h) { + g.resources.erase(g.resources.begin() + static_cast(h.value)); + if (h.value == g.resources.size()) { + return; + } + impl::reindexVectorHandle(g._vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.managedBuffers.erase(g.managedBuffers.begin() + static_cast(h.value)); + if (h.value == g.managedBuffers.size()) { + return; + } + impl::reindexVectorHandle(g._vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.managedTextures.erase(g.managedTextures.begin() + static_cast(h.value)); + if (h.value == g.managedTextures.size()) { + return; + } + impl::reindexVectorHandle(g._vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.buffers.erase(g.buffers.begin() + static_cast(h.value)); + if (h.value == g.buffers.size()) { + return; + } + impl::reindexVectorHandle(g._vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.textures.erase(g.textures.begin() + static_cast(h.value)); + if (h.value == g.textures.size()) { + return; + } + impl::reindexVectorHandle(g._vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.framebuffers.erase(g.framebuffers.begin() + static_cast(h.value)); + if (h.value == g.framebuffers.size()) { + return; + } + impl::reindexVectorHandle(g._vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.swapchains.erase(g.swapchains.begin() + static_cast(h.value)); + if (h.value == g.swapchains.size()) { + return; + } + impl::reindexVectorHandle(g._vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.formatViews.erase(g.formatViews.begin() + static_cast(h.value)); + if (h.value == g.formatViews.size()) { + return; + } + impl::reindexVectorHandle(g._vertices, h.value); + }, + [&](const impl::ValueHandle& h) { + g.subresourceViews.erase(g.subresourceViews.begin() + static_cast(h.value)); + if (h.value == g.subresourceViews.size()) { + return; + } + impl::reindexVectorHandle(g._vertices, h.value); + }), + h); +} + +inline void remove_vertex(ResourceGraph::vertex_descriptor u, ResourceGraph& g) noexcept { // NOLINT + // preserve vertex' iterators + auto& vert = g._vertices[u]; + remove_vertex_value_impl(vert.handle, g); + { // UuidGraph + const auto& key = g.names[u]; + auto num = g.valueIndex.erase(key); + CC_ENSURES(num == 1); + for (auto&& pair : g.valueIndex) { + auto& v = pair.second; + if (v > u) { + --v; + } + } + } + impl::removeVectorVertex(const_cast(g), u, ResourceGraph::directed_category{}); + + // remove components + g.names.erase(g.names.begin() + static_cast(u)); + g.descs.erase(g.descs.begin() + static_cast(u)); + g.traits.erase(g.traits.begin() + static_cast(u)); + g.states.erase(g.states.begin() + static_cast(u)); + g.samplerInfo.erase(g.samplerInfo.begin() + static_cast(u)); +} + +// MutablePropertyGraph(Vertex) +template +void addVertexImpl( // NOLINT + ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT + std::enable_if_t, ManagedResource>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.resources.size())}; + g.resources.emplace_back(std::forward(val)); +} + +template +void addVertexImpl( // NOLINT + ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT + std::enable_if_t, ManagedBuffer>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.managedBuffers.size())}; + g.managedBuffers.emplace_back(std::forward(val)); +} + +template +void addVertexImpl( // NOLINT + ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT + std::enable_if_t, ManagedTexture>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.managedTextures.size())}; + g.managedTextures.emplace_back(std::forward(val)); +} + +template +void addVertexImpl( // NOLINT + ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT + std::enable_if_t, IntrusivePtr>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.buffers.size())}; + g.buffers.emplace_back(std::forward(val)); +} + +template +void addVertexImpl( // NOLINT + ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT + std::enable_if_t, IntrusivePtr>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.textures.size())}; + g.textures.emplace_back(std::forward(val)); +} + +template +void addVertexImpl( // NOLINT + ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT + std::enable_if_t, IntrusivePtr>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.framebuffers.size())}; + g.framebuffers.emplace_back(std::forward(val)); +} + +template +void addVertexImpl( // NOLINT + ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT + std::enable_if_t, RenderSwapchain>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.swapchains.size())}; + g.swapchains.emplace_back(std::forward(val)); +} + +template +void addVertexImpl( // NOLINT + ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT + std::enable_if_t, FormatView>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.formatViews.size())}; + g.formatViews.emplace_back(std::forward(val)); +} + +template +void addVertexImpl( // NOLINT + ValueT &&val, ResourceGraph &g, ResourceGraph::Vertex &vert, // NOLINT + std::enable_if_t, SubresourceView>::value>* dummy = nullptr) { // NOLINT + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.subresourceViews.size())}; + g.subresourceViews.emplace_back(std::forward(val)); +} + +template +inline ResourceGraph::vertex_descriptor +addVertex(Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, Component4&& c4, ValueT&& val, ResourceGraph& g, ResourceGraph::vertex_descriptor u = ResourceGraph::null_vertex()) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + auto& vert = g._vertices.back(); + + { // UuidGraph + const auto& uuid = c0; + auto res = g.valueIndex.emplace(uuid, v); + CC_ENSURES(res.second); + } + g.names.emplace_back(std::forward(c0)); + g.descs.emplace_back(std::forward(c1)); + g.traits.emplace_back(std::forward(c2)); + g.states.emplace_back(std::forward(c3)); + g.samplerInfo.emplace_back(std::forward(c4)); + + // PolymorphicGraph + // if no matching overloaded function is found, Type is not supported by PolymorphicGraph + addVertexImpl(std::forward(val), g, vert); + + // ReferenceGraph + addPathImpl(u, v, g); + + return v; +} + +template +void addVertexImpl(ManagedTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { + std::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.resources.size())}; + g.resources.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +void addVertexImpl(ManagedBufferTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { + std::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.managedBuffers.size())}; + g.managedBuffers.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +void addVertexImpl(ManagedTextureTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { + std::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.managedTextures.size())}; + g.managedTextures.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +void addVertexImpl(PersistentBufferTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { + std::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.buffers.size())}; + g.buffers.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +void addVertexImpl(PersistentTextureTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { + std::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.textures.size())}; + g.textures.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +void addVertexImpl(FramebufferTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { + std::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.framebuffers.size())}; + g.framebuffers.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +void addVertexImpl(SwapchainTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { + std::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.swapchains.size())}; + g.swapchains.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +void addVertexImpl(FormatViewTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { + std::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.formatViews.size())}; + g.formatViews.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +void addVertexImpl(SubresourceViewTag /*tag*/, Tuple &&val, ResourceGraph &g, ResourceGraph::Vertex &vert) { + std::apply( + [&](auto&&... args) { + vert.handle = impl::ValueHandle{ + gsl::narrow_cast(g.subresourceViews.size())}; + g.subresourceViews.emplace_back(std::forward(args)...); + }, + std::forward(val)); +} + +template +inline ResourceGraph::vertex_descriptor +addVertex(Tag tag, Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, Component4&& c4, ValueT&& val, ResourceGraph& g, ResourceGraph::vertex_descriptor u = ResourceGraph::null_vertex()) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + auto& vert = g._vertices.back(); + + { // UuidGraph + std::apply( + [&](const auto&... args) { + auto res = g.valueIndex.emplace(std::piecewise_construct, std::forward_as_tuple(args...), std::forward_as_tuple(v)); + CC_ENSURES(res.second); + }, + c0); + } + + std::apply( + [&](auto&&... args) { + g.names.emplace_back(std::forward(args)...); + }, + std::forward(c0)); + + std::apply( + [&](auto&&... args) { + g.descs.emplace_back(std::forward(args)...); + }, + std::forward(c1)); + + std::apply( + [&](auto&&... args) { + g.traits.emplace_back(std::forward(args)...); + }, + std::forward(c2)); + + std::apply( + [&](auto&&... args) { + g.states.emplace_back(std::forward(args)...); + }, + std::forward(c3)); + + std::apply( + [&](auto&&... args) { + g.samplerInfo.emplace_back(std::forward(args)...); + }, + std::forward(c4)); + + // PolymorphicGraph + // if no matching overloaded function is found, Type is not supported by PolymorphicGraph + addVertexImpl(tag, std::forward(val), g, vert); + + // ReferenceGraph + addPathImpl(u, v, g); + + return v; +} + // MutableGraph(Vertex) template inline ResourceGraph::vertex_descriptor diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp index e1d7c0b2b1..5550c83a98 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp @@ -196,6 +196,8 @@ ResourceGraph::ResourceGraph(const allocator_type& alloc) noexcept textures(alloc), framebuffers(alloc), swapchains(alloc), + formatViews(alloc), + subresourceViews(alloc), valueIndex(alloc), renderPasses(alloc) {} diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h index 73ff546f76..c8ada0d622 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h @@ -394,6 +394,23 @@ struct PersistentTextureTag {}; struct FramebufferTag {}; struct SwapchainTag {}; struct SamplerTag {}; +struct FormatViewTag {}; +struct SubresourceViewTag {}; + +struct FormatView { + gfx::Format format{gfx::Format::UNKNOWN}; +}; + +struct SubresourceView { + IntrusivePtr textureView; + gfx::Format format{gfx::Format::UNKNOWN}; + uint16_t indexOrFirstMipLevel{0}; + uint16_t numMipLevels{0}; + uint16_t firstArraySlice{0}; + uint16_t numArraySlices{0}; + uint16_t firstPlane{0}; + uint16_t numPlanes{0}; +}; struct ResourceGraph { using allocator_type = boost::container::pmr::polymorphic_allocator; @@ -479,10 +496,42 @@ struct ResourceGraph { using edge_iterator = impl::DirectedEdgeIterator; using edges_size_type = uint32_t; + // AddressableGraph (Alias) + using ownership_descriptor = impl::EdgeDescriptor; + + using ChildEdge = OutEdge; + using children_iterator = impl::OutEdgeIter< + ccstd::pmr::vector::iterator, + vertex_descriptor, ownership_descriptor, int32_t>; + using children_size_type = uint32_t; + + using ParentEdge = InEdge; + using parent_iterator = impl::InEdgeIter< + ccstd::pmr::vector::iterator, + vertex_descriptor, ownership_descriptor, int32_t>; + + using ownership_iterator = impl::DirectedEdgeIterator; + using ownerships_size_type = edges_size_type; + + // AddressableGraph help functions + inline ccstd::pmr::vector& getChildrenList(vertex_descriptor v) noexcept { + return _vertices[v].outEdges; + } + inline const ccstd::pmr::vector& getChildrenList(vertex_descriptor v) const noexcept { + return _vertices[v].outEdges; + } + + inline ccstd::pmr::vector& getParentsList(vertex_descriptor v) noexcept { + return _vertices[v].inEdges; + } + inline const ccstd::pmr::vector& getParentsList(vertex_descriptor v) const noexcept { + return _vertices[v].inEdges; + } + // PolymorphicGraph - using VertexTag = ccstd::variant; - using VertexValue = ccstd::variant*, IntrusivePtr*, IntrusivePtr*, RenderSwapchain*>; - using VertexConstValue = ccstd::variant*, const IntrusivePtr*, const IntrusivePtr*, const RenderSwapchain*>; + using VertexTag = ccstd::variant; + using VertexValue = ccstd::variant*, IntrusivePtr*, IntrusivePtr*, RenderSwapchain*, FormatView*, SubresourceView*>; + using VertexConstValue = ccstd::variant*, const IntrusivePtr*, const IntrusivePtr*, const RenderSwapchain*, const FormatView*, const SubresourceView*>; using VertexHandle = ccstd::variant< impl::ValueHandle, impl::ValueHandle, @@ -490,12 +539,15 @@ struct ResourceGraph { impl::ValueHandle, impl::ValueHandle, impl::ValueHandle, - impl::ValueHandle>; + impl::ValueHandle, + impl::ValueHandle, + impl::ValueHandle>; void validateSwapchains(); void mount(gfx::Device* device, vertex_descriptor vertID); void unmount(uint64_t completedFenceValue); bool isTexture(vertex_descriptor resID) const noexcept; + bool isTextureView(vertex_descriptor resID) const noexcept; gfx::Texture* getTexture(vertex_descriptor resID); gfx::Buffer* getBuffer(vertex_descriptor resID); void invalidatePersistentRenderPassAndFramebuffer(gfx::Texture* pTexture); @@ -546,6 +598,8 @@ struct ResourceGraph { ccstd::pmr::vector> textures; ccstd::pmr::vector> framebuffers; ccstd::pmr::vector swapchains; + ccstd::pmr::vector formatViews; + ccstd::pmr::vector subresourceViews; // UuidGraph PmrUnorderedStringMap valueIndex; // Members diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h index 564eeb093d..a4af4a08ee 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h @@ -62,6 +62,13 @@ class RenderWindow; } // namespace scene +namespace render { + +constexpr bool ENABLE_SUBPASS = false; +constexpr bool ENABLE_GPU_DRIVEN = false; + +} // namespace render + } // namespace cc namespace cc { @@ -232,7 +239,7 @@ public: * @deprecated method will be removed in 3.8.0 */ virtual void addComputeView(const ccstd::string &name, const ComputeView &view) = 0; - virtual RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &layoutName) = 0; + virtual RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &phaseName) = 0; virtual void setViewport(const gfx::Viewport &viewport) = 0; virtual void setVersion(const ccstd::string &name, uint64_t version) = 0; virtual bool getShowStatistics() const = 0; @@ -296,8 +303,8 @@ public: virtual void updateDepthStencil(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) = 0; virtual void beginFrame() = 0; virtual void endFrame() = 0; - virtual BasicRenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &layoutName) = 0; - virtual BasicRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &layoutName) = 0; + virtual BasicRenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &passName) = 0; + virtual BasicRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) = 0; virtual void addResolvePass(const ccstd::vector &resolvePairs) = 0; virtual void addCopyPass(const ccstd::vector ©Pairs) = 0; virtual gfx::DescriptorSetLayout *getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) = 0; @@ -335,7 +342,7 @@ public: */ virtual void addComputeView(const ccstd::string &name, const ComputeView &view) = 0; virtual void setViewport(const gfx::Viewport &viewport) = 0; - virtual RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &layoutName) = 0; + virtual RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &phaseName) = 0; virtual bool getShowStatistics() const = 0; virtual void setShowStatistics(bool enable) = 0; /** @@ -428,7 +435,7 @@ public: * @deprecated method will be removed in 3.8.0 */ virtual void addComputeView(const ccstd::string &name, const ComputeView &view) = 0; - virtual ComputeQueueBuilder *addQueue(const ccstd::string &layoutName) = 0; + virtual ComputeQueueBuilder *addQueue(const ccstd::string &phaseName) = 0; /** * @beta function signature might change */ @@ -450,19 +457,13 @@ public: virtual void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) = 0; virtual void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) = 0; - virtual RenderSubpassBuilder *addRenderSubpass(const ccstd::string &layoutName) = 0; - virtual MultisampleRenderSubpassBuilder *addMultisampleRenderSubpass(uint32_t count, uint32_t quality, const ccstd::string &layoutName) = 0; - virtual ComputeSubpassBuilder *addComputeSubpass(const ccstd::string &layoutName) = 0; + virtual RenderSubpassBuilder *addRenderSubpass(const ccstd::string &subpassName) = 0; + virtual MultisampleRenderSubpassBuilder *addMultisampleRenderSubpass(uint32_t count, uint32_t quality, const ccstd::string &subpassName) = 0; + virtual ComputeSubpassBuilder *addComputeSubpass(const ccstd::string &subpassName) = 0; /** * @beta function signature might change */ virtual void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) = 0; - RenderSubpassBuilder *addRenderSubpass() { - return addRenderSubpass(""); - } - MultisampleRenderSubpassBuilder *addMultisampleRenderSubpass(uint32_t count, uint32_t quality) { - return addMultisampleRenderSubpass(count, quality, ""); - } ComputeSubpassBuilder *addComputeSubpass() { return addComputeSubpass(""); } @@ -479,7 +480,7 @@ public: * @deprecated method will be removed in 3.8.0 */ virtual void addComputeView(const ccstd::string &name, const ComputeView &view) = 0; - virtual ComputeQueueBuilder *addQueue(const ccstd::string &layoutName) = 0; + virtual ComputeQueueBuilder *addQueue(const ccstd::string &phaseName) = 0; /** * @beta function signature might change */ @@ -551,8 +552,8 @@ public: virtual void updateStorageBuffer(const ccstd::string &name, uint32_t size, gfx::Format format) = 0; virtual void updateStorageTexture(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) = 0; virtual void updateShadingRateTexture(const ccstd::string &name, uint32_t width, uint32_t height) = 0; - RenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &layoutName) override = 0 /* covariant */; - virtual ComputePassBuilder *addComputePass(const ccstd::string &layoutName) = 0; + RenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &passName) override = 0 /* covariant */; + virtual ComputePassBuilder *addComputePass(const ccstd::string &passName) = 0; virtual void addUploadPass(ccstd::vector &uploadPairs) = 0; virtual void addMovePass(const ccstd::vector &movePairs) = 0; /** diff --git a/platforms/native/engine/jsb-gfx.js b/platforms/native/engine/jsb-gfx.js index 43c13b9ce4..1fa6926dd4 100644 --- a/platforms/native/engine/jsb-gfx.js +++ b/platforms/native/engine/jsb-gfx.js @@ -148,8 +148,8 @@ descriptorSetProto.bindBuffer = function (binding, buffer, index) { descriptorSetProto.bindSampler = function (binding, sampler, index) { this.dirtyJSB = descriptorSetProto.bindSamplerJSB.call(this, binding, sampler, index || 0); }; -descriptorSetProto.bindTexture = function (bindding, texture, index) { - this.dirtyJSB = descriptorSetProto.bindTextureJSB.call(this, bindding, texture, index || 0); +descriptorSetProto.bindTexture = function (bindding, texture, index, flags) { + this.dirtyJSB = descriptorSetProto.bindTextureJSB.call(this, bindding, texture, index || 0, flags || 0); }; const oldDSUpdate = descriptorSetProto.update; descriptorSetProto.update = function () {