diff --git a/cocos/gfx/base/command-buffer.ts b/cocos/gfx/base/command-buffer.ts index 9472939256..87469e26e7 100644 --- a/cocos/gfx/base/command-buffer.ts +++ b/cocos/gfx/base/command-buffer.ts @@ -88,6 +88,14 @@ export abstract class CommandBuffer extends GFXObject { return this._numTris; } + /** + * @en Number of compute dispatches currently recorded. + * @zh 计算调度(dispatch)次数。 + */ + get numDispatches (): number { + return this._numDispatches; + } + /** @mangle */ protected _queue: Queue | null = null; /** @mangle */ @@ -95,6 +103,8 @@ export abstract class CommandBuffer extends GFXObject { /** @mangle */ protected _numDrawCalls = 0; /** @mangle */ + protected _numDispatches = 0; + /** @mangle */ protected _numInstances = 0; /** @mangle */ protected _numTris = 0; diff --git a/cocos/gfx/base/device.ts b/cocos/gfx/base/device.ts index 93536a4dee..dfa792f722 100644 --- a/cocos/gfx/base/device.ts +++ b/cocos/gfx/base/device.ts @@ -127,6 +127,14 @@ export abstract class Device { return this._numTris; } + /** + * @en Number of compute dispatches currently recorded. + * @zh 计算调度(dispatch)次数。 + */ + get numDispatches (): number { + return this._numDispatches; + } + /** * @en Total memory size currently allocated. * @zh 内存状态。 @@ -168,6 +176,8 @@ export abstract class Device { /** @mangle */ protected _numDrawCalls = 0; /** @mangle */ + protected _numDispatches = 0; + /** @mangle */ protected _numInstances = 0; /** @mangle */ protected _numTris = 0; diff --git a/cocos/gfx/webgpu/webgpu-command-buffer.ts b/cocos/gfx/webgpu/webgpu-command-buffer.ts index 74bf8319ea..44e0c1c798 100644 --- a/cocos/gfx/webgpu/webgpu-command-buffer.ts +++ b/cocos/gfx/webgpu/webgpu-command-buffer.ts @@ -40,6 +40,7 @@ import { TextureBlit, DescriptorSetInfo, Format, + DispatchInfo, } from '../base/define'; import { Framebuffer } from '../base/framebuffer'; import { InputAssembler } from '../base/input-assembler'; @@ -179,6 +180,7 @@ export class WebGPUCommandBuffer extends CommandBuffer { private _wgpuRenderPass!: WebGPURenderPass; private _renderPassFuncQueue: ((renPassEncoder: GPURenderPassEncoder) => void)[] = []; + private _computeFuncQueue: ((computePassEncoder: GPUComputePassEncoder) => void)[] = []; public initialize (info: CommandBufferInfo): boolean { this._type = info.type; @@ -222,13 +224,16 @@ export class WebGPUCommandBuffer extends CommandBuffer { this._curStencilWriteMask = null; this._curStencilCompareMask = null; this._numDrawCalls = 0; + this._numDispatches = 0; this._numInstances = 0; this._numTris = 0; + this._computeFuncQueue.length = 0; } public end (): void { this._isStateValid = false; this._isInRenderPass = false; + this._computeFuncQueue.length = 0; } public beginRenderPass ( @@ -650,22 +655,20 @@ export class WebGPUCommandBuffer extends CommandBuffer { this.cmdPackage.cmds.concat(cmdPackage.cmds.array); this._numDrawCalls += WebGPUCmdBuff._numDrawCalls; + this._numDispatches += WebGPUCmdBuff._numDispatches; this._numInstances += WebGPUCmdBuff._numInstances; this._numTris += WebGPUCmdBuff._numTris; } } - protected bindStates (): void { - if (!this._curGPUPipelineState) { - return; - } - const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout; + private _prepareDescriptorSets (): void { const wgpuPipLayout = (currPipelineState?.pipelineLayout as WebGPUPipelineLayout); const device = WebGPUDeviceManager.instance; for (let i = 0; i < groupSets.length; i++) { const currSetIdx = groupSets[i]; const currDesc = descriptorSets[currSetIdx]; if (currDesc && currDesc.gpuDescriptorSet) { + // prepare() builds the bind group if it was never created, or rebuilds it on resource change. currDesc.prepare(); } else { const currLayout = wgpuPipLayout.setLayouts[currSetIdx]; @@ -675,23 +678,13 @@ export class WebGPUCommandBuffer extends CommandBuffer { newDescSet.prepare(true); } } - const gpuIA = this._curGPUInputAssembler!; - // only 4x MSAA is supported - gpuIA.samples = samples > 1 ? 4 : 1; - this._curWebGPUPipelineState!.prepare(gpuIA); - // ----------------------------wgpu pipline state----------------------------- - const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline; - const pplFunc = (passEncoder: GPURenderPassEncoder): void => { - passEncoder.setPipeline(wgpuPipeline); - }; - this._renderPassFuncQueue.push(pplFunc); - if (this._curGPUPipelineState.pipelineState?.depthStencil) { - const stencilRef = this._curGPUPipelineState.stencilRef; - const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => { - passEncoder.setStencilReference(stencilRef); - }; - this._renderPassFuncQueue.push(stencilRefFunc); - } + } + + /** + * Collect the bind groups and dynamic offsets for the currently bound descriptor sets. + * Shared by the draw (bindStates) and compute (dispatch) paths. + */ + private _collectBindGroups (): { wgpuBindGroups: GPUBindGroup[]; wgpuDynOffsets: number[][] } { const currGPUDescSize = groupSets.length; const wgpuBindGroups = new Array(currGPUDescSize); const wgpuDynOffsets = new Array(currGPUDescSize); @@ -703,7 +696,7 @@ export class WebGPUCommandBuffer extends CommandBuffer { wgpuDynOffsets[currSetIdx] = [...this._curDynamicOffsets[currSetIdx]]; if (!descObj.dynamicOffsetCount) { wgpuDynOffsets[currSetIdx] = []; - } else if (descObj && descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) { + } else if (descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) { wgpuDynOffsets[currSetIdx].length = descObj.dynamicOffsetCount; for (let j = 0; j < descObj.dynamicOffsetCount; j++) { const currOffset = wgpuDynOffsets[currSetIdx][j]; @@ -719,16 +712,84 @@ export class WebGPUCommandBuffer extends CommandBuffer { } } } + return { wgpuBindGroups, wgpuDynOffsets }; + } + + public dispatch (info: DispatchInfo): void { + if (!this._curGPUPipelineState) { + return; + } + // Prepare descriptor sets (same logic as bindStates) + this._prepareDescriptorSets(); + + // Create compute pipeline + this._curWebGPUPipelineState!.prepare(null!); + + const computePipeline = this._curGPUPipelineState.nativePipeline as GPUComputePipeline; + + // Build bind groups for compute pass + const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups(); + + const func = (passEncoder: GPUComputePassEncoder): void => { + passEncoder.setPipeline(computePipeline); + const gpuBindGroupSize = wgpuBindGroups.length; + for (let i = 0; i < gpuBindGroupSize; i++) { + passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]); + } + passEncoder.dispatchWorkgroups(info.groupCountX, info.groupCountY, info.groupCountZ); + }; + this._computeFuncQueue.push(func); + ++this._numDispatches; + this._isStateValid = false; + } + + public submitComputePass (): void { + if (this._computeFuncQueue.length === 0) { + return; + } + const device = WebGPUDeviceManager.instance; + const nativeDevice = device.nativeDevice!; + const cmdEncoder = nativeDevice.createCommandEncoder(); + const computePassEncoder = cmdEncoder.beginComputePass(); + this._computeFuncQueue.forEach((cb) => { + cb(computePassEncoder); + }); + computePassEncoder.end(); + nativeDevice.queue.submit([cmdEncoder.finish()]); + this._computeFuncQueue.length = 0; + } + + protected bindStates (): void { + if (!this._curGPUPipelineState) { + return; + } + const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout; + this._prepareDescriptorSets(); + const gpuIA = this._curGPUInputAssembler!; + // only 4x MSAA is supported + gpuIA.samples = samples > 1 ? 4 : 1; + this._curWebGPUPipelineState!.prepare(gpuIA); + // ----------------------------wgpu pipline state----------------------------- + const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline; + const pplFunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setPipeline(wgpuPipeline); + }; + this._renderPassFuncQueue.push(pplFunc); + const pipelineDesc = this._curGPUPipelineState.pipelineState; + if (pipelineDesc && 'depthStencil' in pipelineDesc && pipelineDesc.depthStencil) { + const stencilRef = this._curGPUPipelineState.stencilRef; + const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setStencilReference(stencilRef); + }; + this._renderPassFuncQueue.push(stencilRefFunc); + } + const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups(); const bgfunc = (passEncoder: GPURenderPassEncoder): void => { const gpuBindGroupSize = wgpuBindGroups.length; for (let i = 0; i < gpuBindGroupSize; i++) { - let currBindGroup = wgpuBindGroups[i]; - if (!currBindGroup) { - currBindGroup = (device.defaultResource.descSet as WebGPUDescriptorSet).gpuDescriptorSet.bindGroup; - } // FIXME: this is a special sentence that 2 in 3 parameters I'm not certain. - passEncoder.setBindGroup(i, currBindGroup, wgpuDynOffsets[i]); + passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]); } }; this._renderPassFuncQueue.push(bgfunc); diff --git a/cocos/gfx/webgpu/webgpu-commands.ts b/cocos/gfx/webgpu/webgpu-commands.ts index 8d9771599b..8907fd1996 100644 --- a/cocos/gfx/webgpu/webgpu-commands.ts +++ b/cocos/gfx/webgpu/webgpu-commands.ts @@ -35,6 +35,7 @@ import { TextureUsageBit, ShaderStageFlags, DescriptorType, + MemoryAccessBit, Color, Rect, Viewport, BufferTextureCopy, SamplerInfo, FormatSize, @@ -1423,11 +1424,15 @@ export function createBindGroupLayoutEntry (currBind: DescriptorSetLayoutBinding case DescriptorType.STORAGE_BUFFER: case DescriptorType.DYNAMIC_STORAGE_BUFFER: - entry.buffer = { - type: 'storage', - hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER, - minBindingSize: undefined, - }; + { + const readOnly = (currBind.access & MemoryAccessBit.READ_ONLY) !== 0 + && (currBind.access & MemoryAccessBit.WRITE_ONLY) === 0; + entry.buffer = { + type: readOnly ? 'read-only-storage' : 'storage', + hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER, + minBindingSize: undefined, + }; + } break; case DescriptorType.SAMPLER_TEXTURE: diff --git a/cocos/gfx/webgpu/webgpu-descriptor-set.ts b/cocos/gfx/webgpu/webgpu-descriptor-set.ts index f7a4492497..1a305b3063 100644 --- a/cocos/gfx/webgpu/webgpu-descriptor-set.ts +++ b/cocos/gfx/webgpu/webgpu-descriptor-set.ts @@ -170,9 +170,17 @@ export class WebGPUDescriptorSet extends DescriptorSet { if (descType & (DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER)) { this._dynamicOffsets.push(bindIdx); } - } else if (descType & DESCRIPTOR_SAMPLER_TYPE) { - if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) { - // texture + } else if (descType & (DESCRIPTOR_SAMPLER_TYPE | DescriptorType.STORAGE_IMAGE)) { + const isStorageImage = (descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE; + if (isStorageImage) { + // storage texture (compute read/write): bind the texture view, no sampler + let currTex = this._textures[i] as WebGPUTexture; + if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) { + currTex = device.defaultResource.texture; + } + this._bindTextureEntry(binding, currTex); + } else if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) { + // sampled texture let currTex = this._textures[i] as WebGPUTexture; // null or destroyed? if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) { @@ -185,9 +193,9 @@ export class WebGPUDescriptorSet extends DescriptorSet { this._bindTextureEntry(binding, currTex); } - if (!((descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE - || (descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT - || (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) { + if (!isStorageImage + && !((descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT + || (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) { // sampler const currSampler = (this._samplers[i] || device.defaultResource.sampler) as WebGPUSampler; this._bindSamplerEntry(binding, currSampler); @@ -219,7 +227,12 @@ export class WebGPUDescriptorSet extends DescriptorSet { } public prepare (force: boolean = false): void { - const breakUpdate = !this._isResourceChange() && !force; + const gpuDescriptorSet = this._gpuDescriptorSet; + if (!gpuDescriptorSet) { + return; + } + // Rebuild when forced, when the bind group has never been built, or when resources changed. + const breakUpdate = gpuDescriptorSet.bindGroup && !this._isResourceChange() && !force; if (breakUpdate) return; this._isDirty = true; this._applyBindGroup(); diff --git a/cocos/gfx/webgpu/webgpu-device.ts b/cocos/gfx/webgpu/webgpu-device.ts index de14429c95..032778d656 100644 --- a/cocos/gfx/webgpu/webgpu-device.ts +++ b/cocos/gfx/webgpu/webgpu-device.ts @@ -560,6 +560,7 @@ export class WebGPUDevice extends Device { this._features[Feature.ELEMENT_INDEX_UINT] = true; this._features[Feature.INSTANCED_ARRAYS] = true; this._features[Feature.MULTIPLE_RENDER_TARGETS] = true; + this._features[Feature.COMPUTE_SHADER] = true; this.initFormatFeatures(features); this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS)); @@ -684,6 +685,7 @@ export class WebGPUDevice extends Device { public present (): void { const queue = (this._queue as unknown as WebGPUQueue); this._numDrawCalls = queue.numDrawCalls; + this._numDispatches = queue.numDispatches; this._numInstances = queue.numInstances; this._numTris = queue.numTris; queue.clear(); diff --git a/cocos/gfx/webgpu/webgpu-gpu-objects.ts b/cocos/gfx/webgpu/webgpu-gpu-objects.ts index 0c3b22f7ba..25acf40f0a 100644 --- a/cocos/gfx/webgpu/webgpu-gpu-objects.ts +++ b/cocos/gfx/webgpu/webgpu-gpu-objects.ts @@ -241,8 +241,8 @@ export interface IWebGPUGPUPipelineState { bs: BlendState; dynamicStates: DynamicStateFlagBit[]; gpuRenderPass: IWebGPUGPURenderPass | null; - pipelineState: GPURenderPipelineDescriptor | undefined; - nativePipeline: GPUPipelineBase | undefined; + pipelineState: GPURenderPipelineDescriptor | GPUComputePipelineDescriptor | undefined; + nativePipeline: GPURenderPipeline | GPUComputePipeline | undefined; } export interface IWebGPUGPUDescriptor { diff --git a/cocos/gfx/webgpu/webgpu-pipeline-state.ts b/cocos/gfx/webgpu/webgpu-pipeline-state.ts index 8f0e25666c..e1259a04ca 100644 --- a/cocos/gfx/webgpu/webgpu-pipeline-state.ts +++ b/cocos/gfx/webgpu/webgpu-pipeline-state.ts @@ -26,7 +26,7 @@ import { PipelineState, PipelineStateInfo } from '../base/pipeline-state'; import { IWebGPUGPUInputAssembler, IWebGPUGPUPipelineState } from './webgpu-gpu-objects'; import { WebGPURenderPass } from './webgpu-render-pass'; import { WebGPUShader } from './webgpu-shader'; -import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PrimitiveMode, ShaderStageFlagBit } from '../base/define'; +import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PipelineBindPoint, PrimitiveMode, ShaderStageFlagBit } from '../base/define'; import { WebGPUPipelineLayout } from './webgpu-pipeline-layout'; import { GFXFormatToWGPUFormat, @@ -81,124 +81,156 @@ export class WebGPUPipelineState extends PipelineState { } } - // colorstates - const colorAttachments = this._renderPass.colorAttachments; - const colorDescs: GPUColorTargetState[] = []; - const colAttachmentSize = colorAttachments.length; - const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout; - for (let i = 0; i < colAttachmentSize; i++) { - const colDesc: GPUColorTargetState = { - format: GFXFormatToWGPUFormat(colorAttachments[i].format), - writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask), - }; - if (this._bs.targets[i].blend) { - colDesc.blend = { - color: { - dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst], - operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq], - srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc], - }, - alpha: { - dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha], - operation: WebGPUBlendOps[this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq], - srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha], - }, - }; - } - colorDescs.push(colDesc); - } - - let vertexStage: GPUProgrammableStage; - let fragmentStage: GPUProgrammableStage; - const shaderStages = (this._shader as WebGPUShader).gpuShader.gpuStages; - const stageSize = shaderStages.length; - for (let i = 0; i < stageSize; i++) { - if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; } - if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; } - } - const gpuShader = info.shader as WebGPUShader; + const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout; + const shaderStages = gpuShader.gpuShader.gpuStages; - const shaderAttrs = gpuShader.attributes; - const attrsSize = shaderAttrs.length; - for (let i = 0; i < attrsSize; i++) { - this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location); - } - const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP); - const renderPplDesc: GPURenderPipelineDescriptor = { - layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout, - vertex: { - module: vertexStage!.module, - entryPoint: 'main', - buffers: [], - }, - primitive: { - topology: WebPUPrimitives[info.primitive], - frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw', - cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back', - }, - - fragment: { - module: fragmentStage!.module, - entryPoint: 'main', - targets: colorDescs, - }, - }; - if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16'; - - // depthstencil states - let stencilRef = 0; - if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) { - const dssDesc = {} as GPUDepthStencilState; - dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format); - dssDesc.depthWriteEnabled = this._dss.depthWrite; - dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always'; - let stencilReadMask = 0; - let stencilWriteMask = 0; - - if (this._dss.stencilTestFront) { - dssDesc.stencilFront = { - compare: WebGPUCompereFunc[this._dss.stencilFuncFront], - depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront], - passOp: WebGPUStencilOp[this._dss.stencilPassOpFront], - failOp: WebGPUStencilOp[this._dss.stencilFailOpFront], - }; - stencilReadMask |= this._dss.stencilReadMaskFront; - stencilWriteMask |= this._dss.stencilWriteMaskFront; - stencilRef |= this._dss.stencilRefFront; + if (info.bindPoint === PipelineBindPoint.COMPUTE) { + // ---- Compute Pipeline ---- + let computeStage: GPUProgrammableStage | undefined; + const stageSize = shaderStages.length; + for (let i = 0; i < stageSize; i++) { + if (shaderStages[i].type === ShaderStageFlagBit.COMPUTE) { + computeStage = shaderStages[i].gpuShader!; + } } - if (this._dss.stencilTestBack) { - dssDesc.stencilBack = { - compare: WebGPUCompereFunc[this._dss.stencilFuncBack], - depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack], - passOp: WebGPUStencilOp[this._dss.stencilPassOpBack], - failOp: WebGPUStencilOp[this._dss.stencilFailOpBack], - }; - stencilReadMask |= this._dss.stencilReadMaskBack; - stencilWriteMask |= this._dss.stencilWriteMaskBack; - stencilRef |= this._dss.stencilRefBack; - } - dssDesc.stencilReadMask = stencilReadMask; - dssDesc.stencilWriteMask = stencilWriteMask; - dssDesc.depthBias = this._rs.depthBias; - dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop; - dssDesc.depthBiasClamp = this._rs.depthBiasClamp; - renderPplDesc.depthStencil = dssDesc; - } - this._gpuPipelineState = { - gpuPrimitive: WebPUPrimitives[info.primitive], - gpuShader: gpuShader.gpuShader, - gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout, - rs: info.rasterizerState, - dss: info.depthStencilState, - stencilRef, - bs: info.blendState, - gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass, - dynamicStates, - pipelineState: renderPplDesc, - nativePipeline: undefined, - }; + const computeDesc: GPUComputePipelineDescriptor = { + layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout, + compute: computeStage!, + }; + + this._gpuPipelineState = { + gpuPrimitive: 'triangle-list' as GPUPrimitiveTopology, + gpuShader: gpuShader.gpuShader, + gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout, + rs: info.rasterizerState, + dss: info.depthStencilState, + stencilRef: 0, + bs: info.blendState, + gpuRenderPass: null, + dynamicStates, + pipelineState: computeDesc, + nativePipeline: undefined, + }; + } else { + // ---- Render Pipeline ---- + // colorstates + const colorAttachments = this._renderPass.colorAttachments; + const colorDescs: GPUColorTargetState[] = []; + const colAttachmentSize = colorAttachments.length; + for (let i = 0; i < colAttachmentSize; i++) { + const colDesc: GPUColorTargetState = { + format: GFXFormatToWGPUFormat(colorAttachments[i].format), + writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask), + }; + if (this._bs.targets[i].blend) { + colDesc.blend = { + color: { + dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst], + operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq], + srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc], + }, + alpha: { + dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha], + operation: WebGPUBlendOps[ + this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq], + srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha], + }, + }; + } + colorDescs.push(colDesc); + } + + let vertexStage: GPUProgrammableStage; + let fragmentStage: GPUProgrammableStage; + const stageSize = shaderStages.length; + for (let i = 0; i < stageSize; i++) { + if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; } + if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; } + } + + const shaderAttrs = gpuShader.attributes; + const attrsSize = shaderAttrs.length; + for (let i = 0; i < attrsSize; i++) { + this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location); + } + const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP); + const renderPplDesc: GPURenderPipelineDescriptor = { + layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout, + vertex: { + module: vertexStage!.module, + entryPoint: 'main', + buffers: [], + }, + primitive: { + topology: WebPUPrimitives[info.primitive], + frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw', + cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back', + }, + + fragment: { + module: fragmentStage!.module, + entryPoint: 'main', + targets: colorDescs, + }, + }; + if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16'; + + // depthstencil states + let stencilRef = 0; + if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) { + const dssDesc = {} as GPUDepthStencilState; + dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format); + dssDesc.depthWriteEnabled = this._dss.depthWrite; + dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always'; + let stencilReadMask = 0; + let stencilWriteMask = 0; + + if (this._dss.stencilTestFront) { + dssDesc.stencilFront = { + compare: WebGPUCompereFunc[this._dss.stencilFuncFront], + depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront], + passOp: WebGPUStencilOp[this._dss.stencilPassOpFront], + failOp: WebGPUStencilOp[this._dss.stencilFailOpFront], + }; + stencilReadMask |= this._dss.stencilReadMaskFront; + stencilWriteMask |= this._dss.stencilWriteMaskFront; + stencilRef |= this._dss.stencilRefFront; + } + if (this._dss.stencilTestBack) { + dssDesc.stencilBack = { + compare: WebGPUCompereFunc[this._dss.stencilFuncBack], + depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack], + passOp: WebGPUStencilOp[this._dss.stencilPassOpBack], + failOp: WebGPUStencilOp[this._dss.stencilFailOpBack], + }; + stencilReadMask |= this._dss.stencilReadMaskBack; + stencilWriteMask |= this._dss.stencilWriteMaskBack; + stencilRef |= this._dss.stencilRefBack; + } + dssDesc.stencilReadMask = stencilReadMask; + dssDesc.stencilWriteMask = stencilWriteMask; + dssDesc.depthBias = this._rs.depthBias; + dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop; + dssDesc.depthBiasClamp = this._rs.depthBiasClamp; + renderPplDesc.depthStencil = dssDesc; + } + + this._gpuPipelineState = { + gpuPrimitive: WebPUPrimitives[info.primitive], + gpuShader: gpuShader.gpuShader, + gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout, + rs: info.rasterizerState, + dss: info.depthStencilState, + stencilRef, + bs: info.blendState, + gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass, + dynamicStates, + pipelineState: renderPplDesc, + nativePipeline: undefined, + }; + } } protected _getShaderLocation (name: string): number | undefined { @@ -215,9 +247,22 @@ export class WebGPUPipelineState extends PipelineState { if (this._gpuPipelineState!.nativePipeline && !forceUpdate) { return; } + const webgpuDevice = (WebGPUDeviceManager.instance); + const nativeDevice = webgpuDevice.nativeDevice; + + const pipelineState = this._gpuPipelineState!.pipelineState!; + // Compute pipeline: no vertex attributes, no multisample + if ('compute' in pipelineState) { + const nativePipeline = nativeDevice?.createComputePipeline( + pipelineState, + ); + this._gpuPipelineState!.nativePipeline = nativePipeline; + return; + } + + // Render pipeline const gpuShader = this.shader; const shaderAttrs = gpuShader.attributes; - const pipelineState = this._gpuPipelineState!.pipelineState!; const vertexAttrs: GPUVertexBufferLayout[] = []; const emptyPushAttr: string[] = []; const streamCount = ia.gpuVertexBuffers.length; @@ -272,8 +317,6 @@ export class WebGPUPipelineState extends PipelineState { pipelineState.vertex.buffers = vertexAttrs; pipelineState.multisample = { count: ia.samples }; - const webgpuDevice = (WebGPUDeviceManager.instance); - const nativeDevice = webgpuDevice.nativeDevice; const nativePipeline = nativeDevice?.createRenderPipeline(pipelineState); this._gpuPipelineState!.nativePipeline = nativePipeline; } diff --git a/cocos/gfx/webgpu/webgpu-queue.ts b/cocos/gfx/webgpu/webgpu-queue.ts index 4df451c765..a093408ade 100644 --- a/cocos/gfx/webgpu/webgpu-queue.ts +++ b/cocos/gfx/webgpu/webgpu-queue.ts @@ -29,6 +29,7 @@ import { QueueInfo } from '../base/define'; export class WebGPUQueue extends Queue { public numDrawCalls = 0; + public numDispatches = 0; public numInstances = 0; public numTris = 0; @@ -51,6 +52,7 @@ export class WebGPUQueue extends Queue { for (let i = 0; i < cmdBuffSize; i++) { const cmdBuff = cmdBuffs[i] as WebGPUCommandBuffer; this.numDrawCalls += cmdBuff.numDrawCalls; + this.numDispatches += cmdBuff.numDispatches; this.numInstances += cmdBuff.numInstances; this.numTris += cmdBuff.numTris; } @@ -59,6 +61,7 @@ export class WebGPUQueue extends Queue { public clear (): void { this.numDrawCalls = 0; + this.numDispatches = 0; this.numInstances = 0; this.numTris = 0; } diff --git a/cocos/profiler/profiler.ts b/cocos/profiler/profiler.ts index 5cca16c3e4..ccc428af4d 100644 --- a/cocos/profiler/profiler.ts +++ b/cocos/profiler/profiler.ts @@ -60,6 +60,7 @@ interface IProfilerState { frame: ICounterOption; fps: ICounterOption; draws: ICounterOption; + dispatches: ICounterOption; instances: ICounterOption; tricount: ICounterOption; logic: ICounterOption; @@ -73,6 +74,7 @@ interface IProfilerState { const _profileInfo = { fps: { desc: `Framerate (FPS)`, below: 30, average: _average, isInteger: true }, draws: { desc: 'Draw call', isInteger: true }, + dispatches: { desc: 'Dispatch call', isInteger: true }, frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: _average }, instances: { desc: 'Instance Count', isInteger: true }, tricount: { desc: 'Triangle', isInteger: true }, @@ -586,6 +588,8 @@ export class Profiler extends System { const device = this._device!; (profilerStats.draws.counter as PerfCounter).value = device.numDrawCalls; + // Native (JSB) devices expose no dispatch stats yet; WebGPU does. Treat missing as 0. + (profilerStats.dispatches.counter as PerfCounter).value = device.numDispatches ?? 0; (profilerStats.instances.counter as PerfCounter).value = device.numInstances; (profilerStats.bufferMemory.counter as PerfCounter).value = device.memoryStatus.bufferSize / (1024 * 1024); (profilerStats.textureMemory.counter as PerfCounter).value = device.memoryStatus.textureSize / (1024 * 1024); diff --git a/cocos/rendering/custom/compiler.ts b/cocos/rendering/custom/compiler.ts index f53c98e425..0f3e87656f 100644 --- a/cocos/rendering/custom/compiler.ts +++ b/cocos/rendering/custom/compiler.ts @@ -231,7 +231,21 @@ class PassVisitor implements RenderGraphVisitor { compute (value: ComputePass): void { this._currPass = value; const rg = context.renderGraph; + if (rg.getValid(this.passID)) { + // Avoid revisiting a valid pass and recursive dependency cycles. + return; + } rg.setValid(this.passID, true); + // Trace READ dependencies only; WRITE dependencies are produced by this pass. + const resourceGraph = this.context.resourceGraph; + for (const [computeName, cViews] of value.computeViews) { + if (!cViews.length || cViews[0].accessType !== AccessType.READ) continue; + const vertID = resourceGraph.find(computeName); + if (vertID !== 0xFFFFFFFF) { + this._resVisitor.resID = vertID; + resourceGraph.visitVertex(this._resVisitor, vertID); + } + } } resolve (value: ResolvePass): void { // noop diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 1013e078e4..52b9721312 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -48,6 +48,7 @@ import { Device, deviceManager, DispatchInfo, + Feature, Format, Framebuffer, FramebufferInfo, @@ -56,9 +57,7 @@ import { InputAssemblerInfo, LoadOp, MemoryUsageBit, - PipelineBindPoint, PipelineState, - PipelineStateInfo, Rect, RenderPass, RenderPassInfo, @@ -1910,26 +1909,23 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { renderScene.preRecord(); } dispatch (value: Dispatch): void { + if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return; let pso: PipelineState | null = null; const devicePass = this.currPass as DeviceComputePass; const pass = value.material?.passes[value.passID]; pass?.update(); const shader = pass?.getShaderVariant(); - if (pass !== null && shader !== null) { - const psoInfo = new PipelineStateInfo( - shader, - pass?.pipelineLayout, - ); - psoInfo.bindPoint = PipelineBindPoint.COMPUTE; - pso = deviceManager.gfxDevice.createPipelineState(psoInfo); + if (pass && shader) { + pso = PipelineStateManager.getOrCreateComputePipelineState(deviceManager.gfxDevice, pass, shader); } const cmdBuff = context.commandBuffer; - if (pso) { + if (pso && pass) { cmdBuff.bindPipelineState(pso); const layoutStage = devicePass.renderLayout; const layoutDesc = layoutStage!.descriptorSet!; cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc); + cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); } const gx = value.threadGroupCountX; @@ -1965,10 +1961,12 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor computeSubpass (value: ComputeSubpass): void { // do nothing } - resolve (value: ResolvePass): void { - // do nothing - } compute (value: ComputePass): void { + if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return; + const cmdBuff = context.commandBuffer; + (cmdBuff as any).submitComputePass(); + } + resolve (value: ResolvePass): void { // do nothing } copy (value: CopyPass): void { diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index 222ee961bb..5f5d7ddb6d 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -864,7 +864,11 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild this._renderGraph.setName(this._vertID, name); } addTexture (name: string, slotName: string, sampler: Sampler | null = null): void { - throw new Error('Method not implemented.'); + this._addComputeResource(name, AccessType.READ, slotName); + if (sampler) { + const descriptorID = this._lg.attributeIndex.get(slotName)!; + this._data.samplers.set(descriptorID, sampler); + } } addStorageBuffer (name: string, accessType: AccessType, slotName: string): void { this._addComputeResource(name, accessType, slotName); diff --git a/cocos/rendering/pipeline-state-manager.ts b/cocos/rendering/pipeline-state-manager.ts index ef7a20f99d..c861abb6fd 100644 --- a/cocos/rendering/pipeline-state-manager.ts +++ b/cocos/rendering/pipeline-state-manager.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo } from '../gfx'; +import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo, PipelineBindPoint } from '../gfx'; import { Pass } from '../render-scene/core/pass'; export class PipelineStateManager { @@ -30,6 +30,8 @@ export class PipelineStateManager { private static _PSOHashMap: Map = new Map(); + private static _computePSOHashMap: Map = new Map(); + // pass is only needed on TS. static getOrCreatePipelineState (device: Device, pass: Pass, shader: Shader, renderPass: RenderPass, ia: InputAssembler): PipelineState { const hash1 = pass.hash; @@ -59,4 +61,33 @@ export class PipelineStateManager { return pso; } + + /** + * @en Get or create a compute pipeline state. + * A compute pipeline only depends on the shader variant and the pipeline layout, + * both carried by the pass, so the cache key is `pass.hash ^ shader.typedID`, + * mirroring the graphics-side hash mechanism without renderPass/inputState factors. + * @zh 获取或创建计算管线状态。 + * 计算管线仅依赖于着色器变体与管线布局(均由 pass 携带), + * 因此缓存键为 `pass.hash ^ shader.typedID`,与图形侧哈希机制一致但不包含 renderPass/顶点布局因子。 + */ + static getOrCreateComputePipelineState (device: Device, pass: Pass, shader: Shader): PipelineState { + const hash1 = pass.hash; + const hash2 = shader.typedID; + + const newHash = hash1 ^ hash2; + let pso = this._computePSOHashMap.get(newHash); + if (!pso) { + const pipelineLayout = pass.pipelineLayout; + const psoInfo = new PipelineStateInfo( + shader, + pipelineLayout, + ); + psoInfo.bindPoint = PipelineBindPoint.COMPUTE; + pso = device.createPipelineState(psoInfo); + this._computePSOHashMap.set(newHash, pso); + } + + return pso; + } }