diff --git a/cocos/3d/reflection-probe/reflection-probe-component.ts b/cocos/3d/reflection-probe/reflection-probe-component.ts index ec66ef564b..9c94934eef 100644 --- a/cocos/3d/reflection-probe/reflection-probe-component.ts +++ b/cocos/3d/reflection-probe/reflection-probe-component.ts @@ -23,7 +23,7 @@ */ import { ccclass, executeInEditMode, menu, playOnFocus, serializable, tooltip, type, visible } from 'cc.decorator'; import { EDITOR, EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; -import { CCBoolean, CCObject, Color, Enum, Vec3 } from '../../core'; +import { CCBoolean, CCObject, Color, Enum, Vec3, warn } from '../../core'; import { TextureCube } from '../../asset/assets'; import { scene } from '../../render-scene'; @@ -127,7 +127,7 @@ export class ReflectionProbe extends Component { * @zh 设置探针类型,环境反射或者平面反射 */ @type(Enum(ProbeType)) - set probeType (value: number) { + set probeType (value: ProbeType) { this.probe.probeType = value; if (value !== this._probeType) { const lastSize = this._size.clone(); @@ -151,7 +151,7 @@ export class ReflectionProbe extends Component { this._objFlags ^= CCObject.Flags.IsRotationLocked; } if (!this._sourceCamera) { - console.warn('the reflection camera is invalid, please set the reflection camera'); + warn('the reflection camera is invalid, please set the reflection camera'); } else { this.probe.switchProbeType(value, this._sourceCamera.camera); } @@ -163,7 +163,7 @@ export class ReflectionProbe extends Component { this.size = this._size; } } - get probeType (): number { + get probeType (): ProbeType { return this._probeType; } diff --git a/cocos/gfx/base/define.ts b/cocos/gfx/base/define.ts index 769ade2ff9..53eeb4062c 100644 --- a/cocos/gfx/base/define.ts +++ b/cocos/gfx/base/define.ts @@ -21,6 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/* eslint-disable no-empty-function */ import { Queue } from './queue'; import { Buffer } from './buffer'; @@ -129,6 +130,7 @@ export enum Feature { SUBPASS_COLOR_INPUT, SUBPASS_DEPTH_STENCIL_INPUT, RASTERIZATION_ORDER_COHERENT, + MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL, COUNT, } @@ -405,6 +407,7 @@ export enum TextureFlagBit { GENERAL_LAYOUT = 0x2, // For inout framebuffer attachments EXTERNAL_OES = 0x4, // External oes texture EXTERNAL_NORMAL = 0x8, // External normal texture + LAZILY_ALLOCATED = 0x10 // Try lazily allocated mode. } export enum FormatFeatureBit { @@ -417,10 +420,13 @@ export enum FormatFeatureBit { } export enum SampleCount { - ONE, // Single sample - MULTIPLE_PERFORMANCE, // Multiple samples prioritizing performance over quality - MULTIPLE_BALANCE, // Multiple samples leveraging both quality and performance - MULTIPLE_QUALITY, // Multiple samples prioritizing quality over performance + X1 = 0x01, + X2 = 0x02, + X4 = 0x04, + X8 = 0x08, + X16 = 0x10, + X32 = 0x20, + X64 = 0x40 } export enum VsyncMode { @@ -1171,7 +1177,7 @@ export class TextureInfo { public flags: TextureFlags = TextureFlagBit.NONE, public layerCount: number = 1, public levelCount: number = 1, - public samples: SampleCount = SampleCount.ONE, + public samples: SampleCount = SampleCount.X1, public depth: number = 1, public externalRes: number = 0, ) {} @@ -1513,7 +1519,7 @@ export class ColorAttachment { constructor ( public format: Format = Format.UNKNOWN, - public sampleCount: SampleCount = SampleCount.ONE, + public sampleCount: SampleCount = SampleCount.X1, public loadOp: LoadOp = LoadOp.CLEAR, public storeOp: StoreOp = StoreOp.STORE, public barrier: GeneralBarrier = null!, @@ -1534,7 +1540,7 @@ export class DepthStencilAttachment { constructor ( public format: Format = Format.UNKNOWN, - public sampleCount: SampleCount = SampleCount.ONE, + public sampleCount: SampleCount = SampleCount.X1, public depthLoadOp: LoadOp = LoadOp.CLEAR, public depthStoreOp: StoreOp = StoreOp.STORE, public stencilLoadOp: LoadOp = LoadOp.CLEAR, @@ -1608,6 +1614,7 @@ export class RenderPassInfo { constructor ( public colorAttachments: ColorAttachment[] = [], public depthStencilAttachment: DepthStencilAttachment = new DepthStencilAttachment(), + public depthStencilResolveAttachment: DepthStencilAttachment = new DepthStencilAttachment(), public subpasses: SubpassInfo[] = [], public dependencies: SubpassDependency[] = [], ) {} @@ -1615,6 +1622,7 @@ export class RenderPassInfo { public copy (info: Readonly): RenderPassInfo { deepCopy(this.colorAttachments, info.colorAttachments, ColorAttachment); this.depthStencilAttachment.copy(info.depthStencilAttachment); + this.depthStencilResolveAttachment.copy(info.depthStencilResolveAttachment); deepCopy(this.subpasses, info.subpasses, SubpassInfo); deepCopy(this.dependencies, info.dependencies, SubpassDependency); return this; @@ -1703,12 +1711,14 @@ export class FramebufferInfo { public renderPass: RenderPass = null!, public colorTextures: Texture[] = [], public depthStencilTexture: Texture | null = null, + public depthStencilResolveTexture: Texture | null = null, ) {} public copy (info: Readonly): FramebufferInfo { this.renderPass = info.renderPass; this.colorTextures = info.colorTextures.slice(); this.depthStencilTexture = info.depthStencilTexture; + this.depthStencilResolveTexture = info.depthStencilResolveTexture; return this; } } @@ -2245,8 +2255,11 @@ export function FormatSize (format: Format, width: number, height: number, depth * @param mips The target mip levels. */ export function FormatSurfaceSize ( - format: Format, width: number, height: number, - depth: number, mips: number, + format: Format, + width: number, + height: number, + depth: number, + mips: number, ): number { let size = 0; diff --git a/cocos/gfx/base/device.ts b/cocos/gfx/base/device.ts index e0272538b2..ff4f113b59 100644 --- a/cocos/gfx/base/device.ts +++ b/cocos/gfx/base/device.ts @@ -28,7 +28,7 @@ import { ShaderInfo, InputAssemblerInfo, RenderPassInfo, FramebufferInfo, DescriptorSetLayoutInfo, PipelineLayoutInfo, QueueInfo, BufferTextureCopy, DeviceInfo, DeviceCaps, GeneralBarrierInfo, TextureBarrierInfo, BufferBarrierInfo, SwapchainInfo, BindingMappingInfo, Format, FormatFeature, TextureType, TextureUsageBit, - TextureFlagBit, Offset, Extent, SampleCount, TextureSubresLayers, + TextureFlagBit, Offset, Extent, SampleCount, TextureSubresLayers, TextureUsage, TextureFlags, } from './define'; import { Buffer } from './buffer'; import { CommandBuffer } from './command-buffer'; @@ -359,6 +359,17 @@ export abstract class Device { * @param format The GFX format to be queried. */ public enableAutoBarrier (en: boolean): void {} + + /** + * @en Get maximum supported sample count. + * @zh 获取最大可支持的 Samples 参数 + * @param format The GFX texture format. + * @param usage The GFX texture usage. + * @param flags The GFX texture create flags. + */ + public getMaxSampleCount (format: Format, usage: TextureUsage, flags: TextureFlags): SampleCount { + return SampleCount.X1; + } } export class DefaultResource { @@ -377,7 +388,8 @@ export class DefaultResource { TextureType.TEX2D, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, - 2, 2, + 2, + 2, TextureFlagBit.NONE, )); const copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 1)); @@ -388,7 +400,8 @@ export class DefaultResource { TextureType.CUBE, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, - 2, 2, + 2, + 2, TextureFlagBit.NONE, 6, )); @@ -410,10 +423,12 @@ export class DefaultResource { TextureType.TEX3D, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, - 2, 2, + 2, + 2, TextureFlagBit.NONE, - 1, 1, - SampleCount.ONE, + 1, + 1, + SampleCount.X1, 2, )); const copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 2), new TextureSubresLayers(0, 0, 1)); @@ -424,7 +439,8 @@ export class DefaultResource { TextureType.TEX2D_ARRAY, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, - 2, 2, + 2, + 2, TextureFlagBit.NONE, 2, )); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 9c4f73c093..f64ea3cc4e 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -179,7 +179,7 @@ export function GFXFormatToWebGLInternalFormat (format: Format, gl: WebGLRenderi case Format.DEPTH_STENCIL: return gl.DEPTH_STENCIL; default: { - console.error('Unsupported Format, convert to WebGL internal format failed.'); + error('Unsupported Format, convert to WebGL internal format failed.'); return gl.RGBA; } } @@ -261,7 +261,7 @@ export function GFXFormatToWebGLFormat (format: Format, gl: WebGLRenderingContex case Format.ASTC_SRGBA_12X12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; default: { - console.error('Unsupported Format, convert to WebGL format failed.'); + error('Unsupported Format, convert to WebGL format failed.'); return gl.RGBA; } } @@ -288,7 +288,7 @@ function GFXTypeToWebGLType (type: Type, gl: WebGLRenderingContext): GLenum { case Type.SAMPLER2D: return gl.SAMPLER_2D; case Type.SAMPLER_CUBE: return gl.SAMPLER_CUBE; default: { - console.error('Unsupported GLType, convert to GL type failed.'); + error('Unsupported GLType, convert to GL type failed.'); return Type.UNKNOWN; } } @@ -315,7 +315,7 @@ function GFXTypeToTypedArrayCtor (type: Type): Int32ArrayConstructor | Float32Ar case Type.MAT4: return Float32Array; default: { - console.error('Unsupported GLType, convert to TypedArrayConstructor failed.'); + error('Unsupported GLType, convert to TypedArrayConstructor failed.'); return Float32Array; } } @@ -342,13 +342,13 @@ function WebGLTypeToGFXType (glType: GLenum, gl: WebGLRenderingContext): Type { case gl.SAMPLER_2D: return Type.SAMPLER2D; case gl.SAMPLER_CUBE: return Type.SAMPLER_CUBE; default: { - console.error('Unsupported GLType, convert to Type failed.'); + error('Unsupported GLType, convert to Type failed.'); return Type.UNKNOWN; } } } -function WebGLGetTypeSize (glType: GLenum, gl: WebGLRenderingContext): Type { +function WebGLGetTypeSize (glType: GLenum, gl: WebGLRenderingContext): number { switch (glType) { case gl.BOOL: return 4; case gl.BOOL_VEC2: return 8; @@ -369,13 +369,13 @@ function WebGLGetTypeSize (glType: GLenum, gl: WebGLRenderingContext): Type { case gl.SAMPLER_2D: return 4; case gl.SAMPLER_CUBE: return 4; default: { - console.error('Unsupported GLType, get type failed.'); + error('Unsupported GLType, get type failed.'); return 0; } } } -function WebGLGetComponentCount (glType: GLenum, gl: WebGLRenderingContext): Type { +function WebGLGetComponentCount (glType: GLenum, gl: WebGLRenderingContext): number { switch (glType) { case gl.FLOAT_MAT2: return 2; case gl.FLOAT_MAT3: return 3; @@ -665,7 +665,7 @@ export function WebGLCmdFuncCreateBuffer (device: WebGLDevice, gpuBuffer: IWebGL } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) { gpuBuffer.glTarget = gl.NONE; } else { - console.error('Unsupported BufferType, create buffer failed.'); + error('Unsupported BufferType, create buffer failed.'); gpuBuffer.glTarget = gl.NONE; } } @@ -764,13 +764,18 @@ export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGL || (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC)) { gpuBuffer.glTarget = gl.NONE; } else { - console.error('Unsupported BufferType, create buffer failed.'); + error('Unsupported BufferType, create buffer failed.'); gpuBuffer.glTarget = gl.NONE; } } -export function WebGLCmdFuncUpdateBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer, buffer: Readonly, - offset: number, size: number): void { +export function WebGLCmdFuncUpdateBuffer ( + device: WebGLDevice, + gpuBuffer: IWebGLGPUBuffer, + buffer: Readonly, + offset: number, + size: number, +): void { if (gpuBuffer.usage & BufferUsageBit.UNIFORM) { if (ArrayBuffer.isView(buffer)) { gpuBuffer.vf32!.set(buffer as Float32Array, offset / Float32Array.BYTES_PER_ELEMENT); @@ -820,7 +825,7 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLDevice, gpuBuffer: IWebGL break; } default: { - console.error('Unsupported BufferType, update buffer failed.'); + error('Unsupported BufferType, update buffer failed.'); return; } } @@ -940,8 +945,17 @@ export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWeb w = gpuTexture.width; h = gpuTexture.height; for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, - gpuTexture.glFormat, gpuTexture.glType, null); + gl.texImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + i, + gpuTexture.glInternalFmt, + w, + h, + 0, + gpuTexture.glFormat, + gpuTexture.glType, + null, + ); w = Math.max(1, w >> 1); h = Math.max(1, h >> 1); } @@ -967,7 +981,7 @@ export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWeb break; } default: { - console.error('Unsupported TextureType, create texture failed.'); + error('Unsupported TextureType, create texture failed.'); gpuTexture.type = TextureType.TEX2D; gpuTexture.glTarget = gl.TEXTURE_2D; } @@ -1084,8 +1098,17 @@ export function WebGLCmdFuncResizeTexture (device: WebGLDevice, gpuTexture: IWeb w = gpuTexture.width; h = gpuTexture.height; for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, - 0, gpuTexture.glFormat, gpuTexture.glType, null); + gl.texImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + i, + gpuTexture.glInternalFmt, + w, + h, + 0, + gpuTexture.glFormat, + gpuTexture.glType, + null, + ); w = Math.max(1, w >> 1); h = Math.max(1, h >> 1); } @@ -1094,7 +1117,7 @@ export function WebGLCmdFuncResizeTexture (device: WebGLDevice, gpuTexture: IWeb break; } default: { - console.error('Unsupported TextureType, create texture failed.'); + error('Unsupported TextureType, create texture failed.'); gpuTexture.type = TextureType.TEX2D; gpuTexture.glTarget = gl.TEXTURE_2D; } @@ -1178,19 +1201,19 @@ export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuff if (status !== gl.FRAMEBUFFER_COMPLETE) { switch (status) { case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); break; } case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); break; } case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); break; } case gl.FRAMEBUFFER_UNSUPPORTED: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); break; } default: @@ -1236,7 +1259,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL break; } default: { - console.error('Unsupported ShaderType.'); + error('Unsupported ShaderType.'); return; } } @@ -1248,9 +1271,9 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL gl.compileShader(gpuStage.glShader); if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) { - console.error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); - console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); - console.error(gl.getShaderInfoLog(gpuStage.glShader)); + error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); + error('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); + error(gl.getShaderInfoLog(gpuStage.glShader)); for (let l = 0; l < gpuShader.gpuStages.length; l++) { const stage = gpuShader.gpuStages[k]; @@ -1294,13 +1317,13 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { debug(`Shader '${gpuShader.name}' compilation succeeded.`); } else { - console.error(`Failed to link shader '${gpuShader.name}'.`); - console.error(gl.getProgramInfoLog(gpuShader.glProgram)); + error(`Failed to link shader '${gpuShader.name}'.`); + error(gl.getProgramInfoLog(gpuShader.glProgram)); return; } // parse inputs - const activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); + const activeAttribCount: number = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); gpuShader.glInputs = new Array(activeAttribCount); for (let i = 0; i < activeAttribCount; ++i) { @@ -1375,9 +1398,9 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL // WebGL doesn't support Framebuffer Fetch for (let i = 0; i < gpuShader.subpassInputs.length; ++i) { const subpassInput = gpuShader.subpassInputs[i]; - gpuShader.samplerTextures.push(new UniformSamplerTexture( - subpassInput.set, subpassInput.binding, subpassInput.name, Type.SAMPLER2D, subpassInput.count, - )); + gpuShader.samplerTextures.push( + new UniformSamplerTexture(subpassInput.set, subpassInput.binding, subpassInput.name, Type.SAMPLER2D, subpassInput.count), + ); } // create uniform sampler textures @@ -2575,24 +2598,38 @@ export function WebGLCmdFuncDraw (device: WebGLDevice, drawInfo: Readonly 0) { const offset = drawInfo.firstIndex * indexBuffer.stride; - ia.drawElementsInstancedANGLE(glPrimitive, drawInfo.indexCount, - gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount); + ia.drawElementsInstancedANGLE( + glPrimitive, + drawInfo.indexCount, + gpuInputAssembler.glIndexType, + offset, + drawInfo.instanceCount, + ); } } else if (drawInfo.vertexCount > 0) { ia.drawArraysInstancedANGLE(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount); @@ -2652,8 +2703,15 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLDevice, cmdPackage: WebGLC switch (cmd) { case WebGLCmd.BEGIN_RENDER_PASS: { const cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId]; - WebGLCmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, - cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil); + WebGLCmdFuncBeginRenderPass( + device, + cmd0.gpuRenderPass, + cmd0.gpuFramebuffer, + cmd0.renderArea, + cmd0.clearColors, + cmd0.clearDepth, + cmd0.clearStencil, + ); break; } /* @@ -2665,8 +2723,14 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLDevice, cmdPackage: WebGLC */ case WebGLCmd.BIND_STATES: { const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; - WebGLCmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, - cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, cmd2.dynamicStates); + WebGLCmdFuncBindStates( + device, + cmd2.gpuPipelineState, + cmd2.gpuInputAssembler, + cmd2.gpuDescriptorSets, + cmd2.dynamicOffsets, + cmd2.dynamicStates, + ); break; } case WebGLCmd.DRAW: { @@ -2715,9 +2779,15 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( for (let i = 0; i < regions.length; i++) { const region = regions[i]; // console.debug('Copying image to texture 2D: ' + region.texExtent.width + ' x ' + region.texExtent.height); - gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, - gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); + gl.texSubImage2D( + gl.TEXTURE_2D, + region.texSubres.mipLevel, + region.texOffset.x, + region.texOffset.y, + gpuTexture.glFormat, + gpuTexture.glType, + texImages[n++], + ); } break; } @@ -2727,15 +2797,21 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( // console.debug('Copying image to texture cube: ' + region.texExtent.width + ' x ' + region.texExtent.height); const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, - gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); + gl.texSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + region.texSubres.mipLevel, + region.texOffset.x, + region.texOffset.y, + gpuTexture.glFormat, + gpuTexture.glType, + texImages[n++], + ); } } break; } default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); + error('Unsupported GL texture type, copy buffer to texture failed.'); } } @@ -2746,11 +2822,13 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( } let stagingBuffer = new Uint8Array(1); -function pixelBufferPick (buffer: ArrayBufferView, +function pixelBufferPick ( + buffer: ArrayBufferView, format: Format, offset: number, stride: Extent, - extent: Extent): ArrayBufferView { + extent: Extent, +): ArrayBufferView { const blockHeight = formatAlignment(format).height; const bufferSize = FormatSize(format, extent.width, extent.height, extent.depth); @@ -2835,22 +2913,38 @@ export function WebGLCmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, - offset.x, offset.y, - destWidth, destHeight, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, - offset.x, offset.y, - destWidth, destHeight, + gl.texSubImage2D( + gl.TEXTURE_2D, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== (WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL as number) && !device.extensions.noCompressedTexSubImage2D) { + gl.compressedTexSubImage2D( + gl.TEXTURE_2D, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, + gl.compressedTexImage2D( + gl.TEXTURE_2D, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, 0, - pixels); + destWidth, + destHeight, + 0, + pixels, + ); } } break; @@ -2884,29 +2978,46 @@ export function WebGLCmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, - offset.x, offset.y, - destWidth, destHeight, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, - offset.x, offset.y, - destWidth, destHeight, + gl.texSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== (WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL as number) + && !device.extensions.noCompressedTexSubImage2D) { + gl.compressedTexSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + gl.compressedTexImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, 0, - pixels); + destWidth, + destHeight, + 0, + pixels, + ); } } } break; } default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); + error('Unsupported GL texture type, copy buffer to texture failed.'); } } @@ -2945,7 +3056,7 @@ export function WebGLCmdFuncCopyTextureToBuffers ( break; } default: { - console.error('Unsupported GL texture type, copy texture to buffers failed.'); + error('Unsupported GL texture type, copy texture to buffers failed.'); } } gl.bindFramebuffer(gl.FRAMEBUFFER, null); @@ -2953,8 +3064,13 @@ export function WebGLCmdFuncCopyTextureToBuffers ( gl.deleteFramebuffer(framebuffer); } -export function WebGLCmdFuncBlitTexture (device: WebGLDevice, - srcTexture: Readonly, dstTexture: IWebGLGPUTexture, regions: Readonly, filter: Filter): void { +export function WebGLCmdFuncBlitTexture ( + device: WebGLDevice, + srcTexture: Readonly, + dstTexture: IWebGLGPUTexture, + regions: Readonly, + filter: Filter, +): void { // logic different from native, because framebuffer map is not implemented in webgl device.blitManager.draw(srcTexture, dstTexture, regions as TextureBlit[], filter); } diff --git a/cocos/gfx/webgl2/webgl2-commands.ts b/cocos/gfx/webgl2/webgl2-commands.ts index 136a6eebfd..80f4caab35 100644 --- a/cocos/gfx/webgl2/webgl2-commands.ts +++ b/cocos/gfx/webgl2/webgl2-commands.ts @@ -304,7 +304,7 @@ export function GFXFormatToWebGLInternalFormat (format: Format, gl: WebGL2Render case Format.ASTC_SRGBA_12X12: return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; default: { - console.error('Unsupported Format, convert to WebGL internal format failed.'); + error('Unsupported Format, convert to WebGL internal format failed.'); return gl.RGBA; } } @@ -423,7 +423,7 @@ export function GFXFormatToWebGLFormat (format: Format, gl: WebGL2RenderingConte case Format.ASTC_SRGBA_12X12: return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; default: { - console.error('Unsupported Format, convert to WebGL format failed.'); + error('Unsupported Format, convert to WebGL format failed.'); return gl.RGBA; } } @@ -458,7 +458,7 @@ function GFXTypeToWebGLType (type: Type, gl: WebGL2RenderingContext): GLenum { case Type.SAMPLER3D: return gl.SAMPLER_3D; case Type.SAMPLER_CUBE: return gl.SAMPLER_CUBE; default: { - console.error('Unsupported GLType, convert to GL type failed.'); + error('Unsupported GLType, convert to GL type failed.'); return Type.UNKNOWN; } } @@ -496,13 +496,13 @@ function WebGLTypeToGFXType (glType: GLenum, gl: WebGL2RenderingContext): Type { case gl.SAMPLER_3D: return Type.SAMPLER3D; case gl.SAMPLER_CUBE: return Type.SAMPLER_CUBE; default: { - console.error('Unsupported GLType, convert to Type failed.'); + error('Unsupported GLType, convert to Type failed.'); return Type.UNKNOWN; } } } -function WebGLGetTypeSize (glType: GLenum, gl: WebGL2RenderingContext): Type { +function WebGLGetTypeSize (glType: GLenum, gl: WebGL2RenderingContext): number { switch (glType) { case gl.BOOL: return 4; case gl.BOOL_VEC2: return 8; @@ -543,7 +543,7 @@ function WebGLGetTypeSize (glType: GLenum, gl: WebGL2RenderingContext): Type { case gl.UNSIGNED_INT_SAMPLER_3D: return 4; case gl.UNSIGNED_INT_SAMPLER_CUBE: return 4; default: { - console.error('Unsupported GLType, get type failed.'); + error('Unsupported GLType, get type failed.'); return 0; } } @@ -855,7 +855,7 @@ export function WebGL2CmdFuncCreateBuffer (device: WebGL2Device, gpuBuffer: IWeb } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) { gpuBuffer.glTarget = gl.NONE; } else { - console.error('Unsupported BufferType, create buffer failed.'); + error('Unsupported BufferType, create buffer failed.'); gpuBuffer.glTarget = gl.NONE; } } @@ -962,13 +962,18 @@ export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWeb || (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC)) { gpuBuffer.glTarget = gl.NONE; } else { - console.error('Unsupported BufferType, create buffer failed.'); + error('Unsupported BufferType, create buffer failed.'); gpuBuffer.glTarget = gl.NONE; } } -export function WebGL2CmdFuncUpdateBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer, buffer: Readonly, - offset: number, size: number): void { +export function WebGL2CmdFuncUpdateBuffer ( + device: WebGL2Device, + gpuBuffer: IWebGL2GPUBuffer, + buffer: Readonly, + offset: number, + size: number, +): void { if (gpuBuffer.usage & BufferUsageBit.INDIRECT) { gpuBuffer.indirects.clearDraws(); const drawInfos = (buffer as IndirectBuffer).drawInfos; @@ -1037,7 +1042,7 @@ export function WebGL2CmdFuncUpdateBuffer (device: WebGL2Device, gpuBuffer: IWeb break; } default: { - console.error('Unsupported BufferType, update buffer failed.'); + error('Unsupported BufferType, update buffer failed.'); } } } @@ -1064,7 +1069,7 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW errorID(9100, maxSize, device.capabilities.maxTextureSize); } - if (gpuTexture.samples === SampleCount.ONE) { + if (gpuTexture.samples === SampleCount.X1) { gpuTexture.glTexture = gl.createTexture(); if (gpuTexture.size > 0) { const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; @@ -1094,8 +1099,13 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; } - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, gpuTexture.samples, - gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height); + gl.renderbufferStorageMultisample( + gl.RENDERBUFFER, + gpuTexture.samples, + gpuTexture.glInternalFmt, + gpuTexture.width, + gpuTexture.height, + ); } } break; @@ -1199,7 +1209,7 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW break; } default: { - console.error('Unsupported TextureType, create texture failed.'); + error('Unsupported TextureType, create texture failed.'); gpuTexture.type = TextureType.TEX2D; gpuTexture.glTarget = gl.TEXTURE_2D; } @@ -1254,7 +1264,7 @@ export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IW errorID(9100, maxSize, device.capabilities.maxTextureSize); } - if (gpuTexture.samples === SampleCount.ONE) { + if (gpuTexture.samples === SampleCount.X1) { const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { @@ -1281,8 +1291,13 @@ export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IW device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; } - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, gpuTexture.samples, - gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height); + gl.renderbufferStorageMultisample( + gl.RENDERBUFFER, + gpuTexture.samples, + gpuTexture.glInternalFmt, + gpuTexture.width, + gpuTexture.height, + ); } break; } @@ -1387,7 +1402,7 @@ export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IW break; } default: { - console.error('Unsupported TextureType, create texture failed.'); + error('Unsupported TextureType, create texture failed.'); gpuTexture.type = TextureType.TEX2D; gpuTexture.glTarget = gl.TEXTURE_2D; } @@ -1521,19 +1536,19 @@ export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebu if (status !== gl.FRAMEBUFFER_COMPLETE) { switch (status) { case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); break; } case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); break; } case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); break; } case gl.FRAMEBUFFER_UNSUPPORTED: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); break; } default: @@ -1579,7 +1594,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb break; } default: { - console.error('Unsupported ShaderType.'); + error('Unsupported ShaderType.'); return; } } @@ -1591,9 +1606,9 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb gl.compileShader(gpuStage.glShader); if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) { - console.error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); - console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); - console.error(gl.getShaderInfoLog(gpuStage.glShader)); + error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); + error('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); + error(gl.getShaderInfoLog(gpuStage.glShader)); for (let l = 0; l < gpuShader.gpuStages.length; l++) { const stage = gpuShader.gpuStages[k]; @@ -1637,13 +1652,13 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { debug(`Shader '${gpuShader.name}' compilation succeeded.`); } else { - console.error(`Failed to link shader '${gpuShader.name}'.`); - console.error(gl.getProgramInfoLog(gpuShader.glProgram)); + error(`Failed to link shader '${gpuShader.name}'.`); + error(gl.getProgramInfoLog(gpuShader.glProgram)); return; } // parse inputs - const activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); + const activeAttribCount: number = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); gpuShader.glInputs = new Array(activeAttribCount); for (let i = 0; i < activeAttribCount; ++i) { @@ -1675,7 +1690,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb } // create uniform blocks - const activeBlockCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORM_BLOCKS); + const activeBlockCount: number = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORM_BLOCKS); let blockName: string; let blockIdx: number; let blockSize: number; @@ -1728,9 +1743,9 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb // WebGL doesn't support Framebuffer Fetch for (let i = 0; i < gpuShader.subpassInputs.length; ++i) { const subpassInput = gpuShader.subpassInputs[i]; - gpuShader.samplerTextures.push(new UniformSamplerTexture( - subpassInput.set, subpassInput.binding, subpassInput.name, Type.SAMPLER2D, subpassInput.count, - )); + gpuShader.samplerTextures.push( + new UniformSamplerTexture(subpassInput.set, subpassInput.binding, subpassInput.name, Type.SAMPLER2D, subpassInput.count), + ); } // create uniform sampler textures @@ -2372,8 +2387,13 @@ export function WebGL2CmdFuncBindStates ( if (cache.glBindUBOs[glBlock.glBinding] !== gpuDescriptor.gpuBuffer.glBuffer || cache.glBindUBOOffsets[glBlock.glBinding] !== offset) { if (offset) { - gl.bindBufferRange(gl.UNIFORM_BUFFER, glBlock.glBinding, gpuDescriptor.gpuBuffer.glBuffer, - offset, gpuDescriptor.gpuBuffer.size); + gl.bindBufferRange( + gl.UNIFORM_BUFFER, + glBlock.glBinding, + gpuDescriptor.gpuBuffer.glBuffer, + offset, + gpuDescriptor.gpuBuffer.size, + ); } else { gl.bindBufferBase(gl.UNIFORM_BUFFER, glBlock.glBinding, gpuDescriptor.gpuBuffer.glBuffer); } @@ -2637,24 +2657,38 @@ export function WebGL2CmdFuncDraw (device: WebGL2Device, drawInfo: Readonly 0) { const offset = drawInfo.firstIndex * indexBuffer.stride; - gl.drawElementsInstanced(glPrimitive, drawInfo.indexCount, - gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount); + gl.drawElementsInstanced( + glPrimitive, + drawInfo.indexCount, + gpuInputAssembler.glIndexType, + offset, + drawInfo.instanceCount, + ); } } else if (drawInfo.vertexCount > 0) { gl.drawArraysInstanced(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount); @@ -2714,8 +2762,15 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2Device, cmdPackage: WebG switch (cmd) { case WebGL2Cmd.BEGIN_RENDER_PASS: { const cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId]; - WebGL2CmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, - cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil); + WebGL2CmdFuncBeginRenderPass( + device, + cmd0.gpuRenderPass, + cmd0.gpuFramebuffer, + cmd0.renderArea, + cmd0.clearColors, + cmd0.clearDepth, + cmd0.clearStencil, + ); break; } /* @@ -2727,8 +2782,14 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2Device, cmdPackage: WebG */ case WebGL2Cmd.BIND_STATES: { const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; - WebGL2CmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, - cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, cmd2.dynamicStates); + WebGL2CmdFuncBindStates( + device, + cmd2.gpuPipelineState, + cmd2.gpuInputAssembler, + cmd2.gpuDescriptorSets, + cmd2.dynamicOffsets, + cmd2.dynamicStates, + ); break; } case WebGL2Cmd.DRAW: { @@ -2789,14 +2850,29 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( switch (gpuTexture.glTarget) { case gl.TEXTURE_2D: { if (toUseTexImage2D(texImages, regions)) { - gl.texImage2D(gl.TEXTURE_2D, regions[0].texSubres.mipLevel, gpuTexture.glInternalFmt, regions[0].texExtent.width, - regions[0].texExtent.height, 0, gpuTexture.glFormat, gpuTexture.glType, texImages[0]); + gl.texImage2D( + gl.TEXTURE_2D, + regions[0].texSubres.mipLevel, + gpuTexture.glInternalFmt, + regions[0].texExtent.width, + regions[0].texExtent.height, + 0, + gpuTexture.glFormat, + gpuTexture.glType, + texImages[0], + ); } else { for (let k = 0; k < regions.length; k++) { const region = regions[k]; - gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, - gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); + gl.texSubImage2D( + gl.TEXTURE_2D, + region.texSubres.mipLevel, + region.texOffset.x, + region.texOffset.y, + gpuTexture.glFormat, + gpuTexture.glType, + texImages[n++], + ); } } break; @@ -2806,15 +2882,21 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( const region = regions[k]; const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, - gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); + gl.texSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + region.texSubres.mipLevel, + region.texOffset.x, + region.texOffset.y, + gpuTexture.glFormat, + gpuTexture.glType, + texImages[n++], + ); } } break; } default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); + error('Unsupported GL texture type, copy buffer to texture failed.'); } } @@ -2824,11 +2906,13 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( } let stagingBuffer = new Uint8Array(1); -function pixelBufferPick (buffer: ArrayBufferView, +function pixelBufferPick ( + buffer: ArrayBufferView, format: Format, offset: number, stride: Extent, - extent: Extent): ArrayBufferView { + extent: Extent, +): ArrayBufferView { const blockHeight = formatAlignment(format).height; const bufferSize = FormatSize(format, extent.width, extent.height, extent.depth); @@ -2913,22 +2997,38 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, - offset.x, offset.y, - destWidth, destHeight, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, - offset.x, offset.y, - destWidth, destHeight, + gl.texSubImage2D( + gl.TEXTURE_2D, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) { + gl.compressedTexSubImage2D( + gl.TEXTURE_2D, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, + gl.compressedTexImage2D( + gl.TEXTURE_2D, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, 0, - pixels); + destWidth, + destHeight, + 0, + pixels, + ); } } break; @@ -2965,22 +3065,43 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, - offset.x, offset.y, offset.z, - destWidth, destHeight, extent.depth, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, - offset.x, offset.y, offset.z, - destWidth, destHeight, extent.depth, + gl.texSubImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, + offset.x, + offset.y, + offset.z, + destWidth, + destHeight, + extent.depth, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) { + gl.compressedTexSubImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, + offset.x, + offset.y, + offset.z, + destWidth, + destHeight, + extent.depth, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + gl.compressedTexImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, extent.depth, 0, - pixels); + destWidth, + destHeight, + extent.depth, + 0, + pixels, + ); } } } @@ -3015,22 +3136,43 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, - offset.x, offset.y, offset.z, - destWidth, destHeight, extent.depth, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, - offset.x, offset.y, offset.z, - destWidth, destHeight, extent.depth, + gl.texSubImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, + offset.x, + offset.y, + offset.z, + destWidth, + destHeight, + extent.depth, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) { + gl.compressedTexSubImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, + offset.x, + offset.y, + offset.z, + destWidth, + destHeight, + extent.depth, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + gl.compressedTexImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, extent.depth, 0, - pixels); + destWidth, + destHeight, + extent.depth, + 0, + pixels, + ); } } break; @@ -3064,29 +3206,45 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, - offset.x, offset.y, - destWidth, destHeight, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, - offset.x, offset.y, - destWidth, destHeight, + gl.texSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) { + gl.compressedTexSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + gl.compressedTexImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, 0, - pixels); + destWidth, + destHeight, + 0, + pixels, + ); } } } break; } default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); + error('Unsupported GL texture type, copy buffer to texture failed.'); } } @@ -3125,7 +3283,7 @@ export function WebGL2CmdFuncCopyTextureToBuffers ( break; } default: { - console.error('Unsupported GL texture type, copy texture to buffers failed.'); + error('Unsupported GL texture type, copy texture to buffers failed.'); } } gl.bindFramebuffer(gl.FRAMEBUFFER, null); @@ -3168,9 +3326,16 @@ export function WebGL2CmdFuncBlitFramebuffer ( const glFilter = (filter === Filter.LINEAR || filter === Filter.ANISOTROPIC) ? gl.LINEAR : gl.NEAREST; gl.blitFramebuffer( - srcRect.x, srcRect.y, srcRect.x + srcRect.width, srcRect.y + srcRect.height, - dstRect.x, dstRect.y, dstRect.x + dstRect.width, dstRect.y + dstRect.height, - mask, glFilter, + srcRect.x, + srcRect.y, + srcRect.x + srcRect.width, + srcRect.y + srcRect.height, + dstRect.x, + dstRect.y, + dstRect.x + dstRect.width, + dstRect.y + dstRect.height, + mask, + glFilter, ); if (rebindFBO) { @@ -3205,7 +3370,7 @@ export function WebGL2CmdFuncBlitTexture ( const blitInfo = (formatInfo: FormatInfo): { mask: number; attachment: number; } => { let mask = 0; - let attachment = gl.COLOR_ATTACHMENT0; + let attachment: number = gl.COLOR_ATTACHMENT0; if (formatInfo.hasStencil) { attachment = gl.DEPTH_STENCIL_ATTACHMENT; @@ -3269,9 +3434,16 @@ export function WebGL2CmdFuncBlitTexture ( } gl.blitFramebuffer( - region.srcOffset.x, region.srcOffset.y, region.srcOffset.x + region.srcExtent.width, region.srcOffset.y + region.srcExtent.height, - region.dstOffset.x, region.dstOffset.y, region.dstOffset.x + region.dstExtent.width, region.dstOffset.y + region.dstExtent.height, - srcMask, glFilter, + region.srcOffset.x, + region.srcOffset.y, + region.srcOffset.x + region.srcExtent.width, + region.srcOffset.y + region.srcExtent.height, + region.dstOffset.x, + region.dstOffset.y, + region.dstOffset.x + region.dstExtent.width, + region.dstOffset.y + region.dstExtent.height, + srcMask, + glFilter, ); } diff --git a/cocos/render-scene/core/pass.ts b/cocos/render-scene/core/pass.ts index a1a7c93ca7..4345d8c500 100644 --- a/cocos/render-scene/core/pass.ts +++ b/cocos/render-scene/core/pass.ts @@ -28,13 +28,15 @@ import { TextureBase } from '../../asset/assets/texture-base'; import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; import { getPhaseID } from '../../rendering/pass-phase'; import { murmurhash2_32_gc, errorID, assertID, cclegacy, warnID } from '../../core'; -import { BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color, +import { + BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color, BlendState, BlendTarget, Buffer, BufferInfo, BufferViewInfo, DepthStencilState, DescriptorSet, DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, Texture, Shader, PipelineLayout, deviceManager, UniformBlock, } from '../../gfx'; import { EffectAsset } from '../../asset/assets/effect-asset'; import { IProgramInfo, programLib } from './program-lib'; -import { MacroRecord, MaterialProperty, customizeType, getBindingFromHandle, getDefaultFromType, getStringFromType, +import { + MacroRecord, MaterialProperty, customizeType, getBindingFromHandle, getDefaultFromType, getStringFromType, getOffsetFromHandle, getTypeFromHandle, type2reader, type2writer, getCountFromHandle, type2validator, } from './pass-utils'; import { RenderPassStage, RenderPriority } from '../../rendering/define'; @@ -182,7 +184,7 @@ export class Pass { protected _shaderInfo: IProgramInfo = null!; protected _defines: MacroRecord = {}; protected _properties: Record = {}; - protected _shader: Shader | null = null + protected _shader: Shader | null = null; protected _bs: BlendState = new BlendState(); protected _dss: DepthStencilState = new DepthStencilState(); protected _rs: RasterizerState = new RasterizerState(); @@ -190,6 +192,7 @@ export class Pass { protected _stage: RenderPassStage = RenderPassStage.DEFAULT; protected _phase = getPhaseID('default'); protected _passID = 0xFFFFFFFF; + protected _subpassID = 0xFFFFFFFF; protected _phaseID = 0xFFFFFFFF; protected _primitive: PrimitiveMode = PrimitiveMode.TRIANGLE_LIST; protected _batchingScheme: BatchingSchemes = BatchingSchemes.NONE; @@ -488,7 +491,10 @@ export class Pass { if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) { const programLib = cclegacy.rendering.programLib as ProgramLibrary; const program = programLib.getProgramVariant( - this._device, this._phaseID, this._programName, this._defines, + this._device, + this._phaseID, + this._programName, + this._defines, ); if (!program) { warnID(12103, this._programName); @@ -576,11 +582,17 @@ export class Pass { const r = cclegacy.rendering; if (typeof info.phase === 'number') { this._passID = (info as Pass)._passID; + this._subpassID = (info as Pass)._subpassID; this._phaseID = (info as Pass)._phaseID; } else { this._passID = r.getPassID(info.pass); if (this._passID !== r.INVALID_ID) { - this._phaseID = r.getPhaseID(this._passID, info.phase); + if (info.subpass) { + this._subpassID = r.getSubpassID(this._passID, info.subpass); + this._phaseID = r.getPhaseID(this._subpassID, info.phase); + } else { + this._phaseID = r.getPhaseID(this._passID, info.phase); + } } } if (this._passID === r.INVALID_ID) { @@ -683,8 +695,11 @@ export class Pass { const bufferView = this._buffers[binding] = device.createBuffer(_bufferViewInfo); // non-builtin UBO data pools, note that the effect compiler // guarantees these bindings to be consecutive, starting from 0 and non-array-typed - this._blocks[binding] = new Float32Array(this._rootBlock!, _bufferViewInfo.offset, - size / Float32Array.BYTES_PER_ELEMENT); + this._blocks[binding] = new Float32Array( + this._rootBlock!, + _bufferViewInfo.offset, + size / Float32Array.BYTES_PER_ELEMENT, + ); this._blocksInt[binding] = new Int32Array(this._blocks[binding].buffer, this._blocks[binding].byteOffset, this._blocks[binding].length); this._descriptorSet.bindBuffer(binding, bufferView); } @@ -728,8 +743,11 @@ export class Pass { const bufferView = this._buffers[binding] = device.createBuffer(_bufferViewInfo); // non-builtin UBO data pools, note that the effect compiler // guarantees these bindings to be consecutive, starting from 0 and non-array-typed - this._blocks[binding] = new Float32Array(this._rootBlock!, _bufferViewInfo.offset, - size / Float32Array.BYTES_PER_ELEMENT); + this._blocks[binding] = new Float32Array( + this._rootBlock!, + _bufferViewInfo.offset, + size / Float32Array.BYTES_PER_ELEMENT, + ); this._blocksInt[binding] = new Int32Array(this._blocks[binding].buffer, this._blocks[binding].byteOffset, this._blocks[binding].length); this._descriptorSet.bindBuffer(binding, bufferView); } @@ -778,7 +796,7 @@ export class Pass { this._blocks = target._blocks; this._blocksInt = target._blocksInt; - this._dynamics = target._dynamics; + this._dynamics = target._dynamics; this._shader = target._shader; diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 574ffff1ba..b5492e7a13 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -20,7 +20,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ + ****************************************************************************/ /** * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= @@ -32,9 +32,43 @@ import { getPhaseID, InstancedBuffer, PipelineStateManager } from '..'; import { assert, cclegacy, RecyclePool } from '../../core'; import intersect from '../../core/geometry/intersect'; import { Sphere } from '../../core/geometry/sphere'; -import { AccessFlagBit, Attribute, Buffer, BufferInfo, BufferUsageBit, BufferViewInfo, Color, ColorAttachment, CommandBuffer, DepthStencilAttachment, DescriptorSet, DescriptorSetInfo, Device, deviceManager, Format, Framebuffer, - FramebufferInfo, GeneralBarrierInfo, InputAssemblerInfo, LoadOp, MemoryUsageBit, PipelineState, Rect, RenderPass, RenderPassInfo, Sampler, SamplerInfo, StoreOp, SurfaceTransform, Swapchain, Texture, TextureInfo, - TextureType, TextureUsageBit, Viewport } from '../../gfx'; +import { + AccessFlagBit, + Attribute, + Buffer, + BufferInfo, + BufferUsageBit, + BufferViewInfo, + Color, + ColorAttachment, + CommandBuffer, + DepthStencilAttachment, + DescriptorSet, + DescriptorSetInfo, + Device, + deviceManager, + Format, + Framebuffer, + FramebufferInfo, + GeneralBarrierInfo, + InputAssembler, + InputAssemblerInfo, + LoadOp, + MemoryUsageBit, + PipelineState, + Rect, + RenderPass, + RenderPassInfo, + Shader, + StoreOp, + SurfaceTransform, + Swapchain, + Texture, + TextureInfo, + TextureType, + TextureUsageBit, + Viewport, +} from '../../gfx'; import { legacyCC } from '../../core/global-exports'; import { Vec3 } from '../../core/math/vec3'; import { Vec4 } from '../../core/math/vec4'; @@ -46,11 +80,47 @@ import { IRenderPass, isEnableEffect, SetIndex, UBODeferredLight, UBOForwardLigh 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, FormatView, ManagedBuffer, ManagedResource, ManagedTexture, MovePass, - RasterPass, RasterSubpass, RaytracePass, RenderData, RenderGraph, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResolvePass, ResourceDesc, - ResourceGraph, ResourceGraphVisitor, ResourceTraits, SceneData, SubresourceView, ComputeView, RasterView } from './render-graph'; -import { AttachmentType, QueueHint, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; +import { BasicPipeline } from './pipeline'; +import { SceneVisitor } from './scene'; +import { + Blit, + ClearView, + ComputePass, + ComputeSubpass, + ComputeView, + CopyPass, + Dispatch, + FormatView, + ManagedBuffer, + ManagedResource, + ManagedTexture, + MovePass, + RasterPass, + RasterSubpass, + RasterView, + RaytracePass, + RenderData, + RenderGraph, + RenderGraphVisitor, + RenderQueue, + RenderSwapchain, + ResolvePass, + ResourceDesc, + ResourceGraph, + ResourceGraphVisitor, + ResourceTraits, + SceneData, + SubresourceView, +} from './render-graph'; +import { + AttachmentType, + QueueHint, + ResourceDimension, + ResourceFlags, + ResourceResidency, + SceneFlags, + UpdateFrequency, +} from './types'; import { PipelineUBO } from '../pipeline-ubo'; import { RenderInfo, RenderObject, WebSceneTask, WebSceneTransversal } from './web-scene'; import { WebSceneVisitor } from './web-scene-visitor'; @@ -59,7 +129,14 @@ import { RenderShadowMapBatchedQueue } from '../render-shadow-map-batched-queue' import { PlanarShadowQueue } from '../planar-shadow-queue'; import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph'; import { VectorGraphColorMap } from './effect'; -import { getDescBindingFromName, getDescriptorSetDataFromLayout, getDescriptorSetDataFromLayoutId, getRenderArea, mergeSrcToTargetDesc, updateGlobalDescBinding } from './define'; +import { + getDescBindingFromName, + getDescriptorSetDataFromLayout, + getDescriptorSetDataFromLayoutId, + getRenderArea, + mergeSrcToTargetDesc, + updateGlobalDescBinding, +} from './define'; import { RenderReflectionProbeQueue } from '../render-reflection-probe-queue'; import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; import { Texture2D } from '../../asset/assets/texture-2d'; @@ -177,6 +254,8 @@ class DeviceTexture extends DeviceResource { if (info.flags & ResourceFlags.INPUT_ATTACHMENT) usageFlags |= TextureUsageBit.INPUT_ATTACHMENT; if (info.flags & ResourceFlags.SAMPLED) usageFlags |= TextureUsageBit.SAMPLED; if (info.flags & ResourceFlags.STORAGE) usageFlags |= TextureUsageBit.STORAGE; + if (info.flags & ResourceFlags.TRANSFER_SRC) usageFlags |= TextureUsageBit.TRANSFER_SRC; + if (info.flags & ResourceFlags.TRANSFER_DST) usageFlags |= TextureUsageBit.TRANSFER_DST; this._texture = context.device.createTexture(new TextureInfo( type, @@ -405,7 +484,7 @@ class DeviceRenderQueue { get renderPhase (): RenderPhaseData | null { return this._renderPhase; } get viewport (): Viewport | null { return this._viewport; } get scissor (): Rect | null { return this._scissor; } - private _sceneVisitor; + private _sceneVisitor!: WebSceneVisitor; private _blitDesc: BlitDesc | null = null; private _queueId = -1; set queueId (val) { this._queueId = val; } @@ -428,8 +507,10 @@ class DeviceRenderQueue { this._devicePass = devicePass; if (isEnableEffect()) this._phaseID = cclegacy.rendering.getPhaseID(devicePass.passID, context.renderGraph.getLayout(id) || 'default'); if (!this._sceneVisitor) { - this._sceneVisitor = new WebSceneVisitor(context.commandBuffer, - context.pipeline.pipelineSceneData); + this._sceneVisitor = new WebSceneVisitor( + context.commandBuffer, + context.pipeline.pipelineSceneData, + ); } } createBlitDesc (blit: Blit): void { @@ -535,7 +616,7 @@ class RenderPassLayoutInfo { protected _layout: PipelineLayoutData; protected _inputName: string; protected _descriptorSet: DescriptorSet | null = null; - constructor (layoutId, input: [string, ComputeView[]]) { + constructor (layoutId: number, input: [string, ComputeView[]]) { this._inputName = input[0]; this._layoutID = layoutId; const lg = context.layoutGraph; @@ -754,9 +835,11 @@ class DeviceRenderPass { // )); // } this._renderPass = device.createRenderPass(new RenderPassInfo(colors, depthStencilAttachment)); - this._framebuffer = framebuffer || device.createFramebuffer(new FramebufferInfo(this._renderPass, + this._framebuffer = framebuffer || device.createFramebuffer(new FramebufferInfo( + this._renderPass, swapchain ? [swapchain.colorTexture] : colorTexs, - swapchain ? swapchain.depthStencilTexture : depthTex)); + swapchain ? swapchain.depthStencilTexture : depthTex, + )); } get layoutName (): string { return this._layoutName; } get passID (): number { return this._passID; } @@ -821,8 +904,13 @@ class DeviceRenderPass { const pass = submodel.passes[0]; const ia = submodel.inputAssembler; const device = context.device; - const pso = PipelineStateManager.getOrCreatePipelineState(device, pass, - submodel.shaders[0], renderPass, ia); + const pso = PipelineStateManager.getOrCreatePipelineState( + device, + pass, + submodel.shaders[0], + renderPass, + ia, + ); const descData = getDescriptorSetDataFromLayoutId(pass.passID)!; mergeSrcToTargetDesc(descData.descriptorSet, context.pipeline.descriptorSet, true); profilerViewport.width = rect.width; @@ -851,10 +939,18 @@ class DeviceRenderPass { renderPassArea.width = tex.width; renderPassArea.height = tex.height; } - cmdBuff.beginRenderPass(this.renderPass, this.framebuffer, renderPassArea, - this.clearColor, this.clearDepth, this.clearStencil); - cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, - context.pipeline.descriptorSet); + cmdBuff.beginRenderPass( + this.renderPass, + this.framebuffer, + renderPassArea, + this.clearColor, + this.clearDepth, + this.clearStencil, + ); + cmdBuff.bindDescriptorSet( + SetIndex.GLOBAL, + context.pipeline.descriptorSet, + ); for (const queue of this._deviceQueues) { queue.record(); } @@ -1014,7 +1110,7 @@ class GraphScene { } this.blit = null; } - init (scene, blit, sceneID): void { + init (scene: SceneData | null, blit: Blit | null, sceneID): void { this._copyScene(scene); this._copyBlit(blit); this.sceneID = sceneID; @@ -1027,8 +1123,12 @@ class DevicePreSceneTask extends WebSceneTask { protected _graphScene: GraphScene; private _cmdBuff: CommandBuffer; constructor (queue: DeviceRenderQueue, graphScene: GraphScene, visitor: SceneVisitor) { - super(context.pipelineSceneData, context.ubo, - graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, visitor); + super( + context.pipelineSceneData, + context.ubo, + graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, + visitor, + ); this._currentQueue = queue; this._graphScene = graphScene; this._renderPass = queue.devicePass.renderPass; @@ -1096,6 +1196,7 @@ class DevicePreSceneTask extends WebSceneTask { const probes = cclegacy.internal.reflectionProbeManager.getProbes(); for (let i = 0; i < probes.length; i++) { if (probes[i].hasFrameBuffer(this._currentQueue.devicePass.framebuffer)) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._submitInfo.reflectionProbe.gatherRenderObjects(probes[i], this.camera, this._cmdBuff); break; } @@ -1162,7 +1263,7 @@ class DevicePreSceneTask extends WebSceneTask { protected _insertRenderList (ro: RenderObject, subModelIdx: number, passIdx: number, isTransparent = false): void { const subModel = ro.model.subModels[subModelIdx]; - const pass = subModel.passes[passIdx]; + const pass: Pass = subModel.passes[passIdx]; const shader = subModel.shaders[passIdx]; const currTransparent = pass.blendState.targets[0].blend; const devicePass = this._currentQueue.devicePass; @@ -1172,7 +1273,7 @@ class DevicePreSceneTask extends WebSceneTask { if (currTransparent !== isTransparent || !(pass.phaseID & (isTransparent ? phase : this._currentQueue.phaseID))) { return; } - const hash = (0 << 30) | pass.priority << 16 | subModel.priority << 8 | passIdx; + const hash = (0 << 30) | pass.priority as number << 16 | subModel.priority as number << 8 | passIdx; const rp = context.pools.addPassInfo(); rp.priority = ro.model.priority; rp.hash = hash; @@ -1233,8 +1334,12 @@ class DeviceSceneTask extends WebSceneTask { protected _renderPass: RenderPass; protected _graphScene: GraphScene; constructor (queue: DeviceRenderQueue, graphScene: GraphScene, visitor: SceneVisitor) { - super(context.pipelineSceneData, context.ubo, - graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, visitor); + super( + context.pipelineSceneData, + context.ubo, + graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, + visitor, + ); this._currentQueue = queue; this._renderPass = this._currentQueue.devicePass.renderPass; this._graphScene = graphScene; @@ -1258,14 +1363,20 @@ class DeviceSceneTask extends WebSceneTask { : currSubmitInfo.opaqueList; for (let i = 0; i < renderList.length; ++i) { const { subModel, passIdx } = renderList[i]; - const { inputAssembler } = subModel; - const pass = subModel.passes[passIdx]; - const shader = subModel.shaders[passIdx]; - const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, - pass, shader, this._renderPass, inputAssembler); + const inputAssembler: InputAssembler = subModel.inputAssembler; + const pass: Pass = subModel.passes[passIdx]; + const shader: Shader = subModel.shaders[passIdx]; + const descriptorSet: DescriptorSet = subModel.descriptorSet; + const pso = PipelineStateManager.getOrCreatePipelineState( + deviceManager.gfxDevice, + pass, + shader, + this._renderPass, + inputAssembler, + ); this.visitor.bindPipelineState(pso); this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); - this.visitor.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet); + this.visitor.bindDescriptorSet(SetIndex.LOCAL, descriptorSet); this.visitor.bindInputAssembler(inputAssembler); this.visitor.draw(inputAssembler); } @@ -1289,13 +1400,18 @@ class DeviceSceneTask extends WebSceneTask { const instance = instances[b]; if (!instance.count) { continue; } const shader = instance.shader!; - const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, pass, - shader, this._renderPass, instance.ia); + const pso = PipelineStateManager.getOrCreatePipelineState( + deviceManager.gfxDevice, + pass, + shader, + this._renderPass, + instance.ia, + ); if (lastPSO !== pso) { this.visitor.bindPipelineState(pso); lastPSO = pso; } - const ia: any = instance.ia; + const ia: InputAssembler = instance.ia; this.visitor.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, res.value.dynamicOffsets); this.visitor.bindInputAssembler(ia); this.visitor.draw(ia); @@ -1320,7 +1436,7 @@ class DeviceSceneTask extends WebSceneTask { const pass = batch.passes[j]; if (((isEnableEffect()) ? pass.phaseID : pass.phase) !== this._currentQueue.phaseID) continue; const shader = batch.shaders[j]; - const inputAssembler: any = batch.inputAssembler!; + const inputAssembler: InputAssembler = batch.inputAssembler!; const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, pass, shader, this._renderPass, inputAssembler); this.visitor.bindPipelineState(pso); this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); @@ -1337,14 +1453,22 @@ class DeviceSceneTask extends WebSceneTask { protected _recordShadowMap (): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.shadowMap.get(this.graphScene.sceneID)!.recordCommandBuffer(context.device, - this._renderPass, context.commandBuffer); + currSubmitInfo.shadowMap.get(this.graphScene.sceneID)!.recordCommandBuffer( + context.device, + this._renderPass, + + context.commandBuffer, + ); } protected _recordReflectionProbe (): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.reflectionProbe?.recordCommandBuffer(context.device, - this._renderPass, context.commandBuffer); + currSubmitInfo.reflectionProbe?.recordCommandBuffer( + context.device, + this._renderPass, + + context.commandBuffer, + ); } private _clearExtBlitDesc (desc, extResId: number[]): void { @@ -1371,12 +1495,17 @@ class DeviceSceneTask extends WebSceneTask { pass.update(); const shader = pass.getShaderVariant(); const devicePass = this._currentQueue.devicePass; - const screenIa: any = this._currentQueue.blitDesc!.screenQuad!.quadIA; + const screenIa: InputAssembler = this._currentQueue.blitDesc!.screenQuad!.quadIA!; const globalDesc = context.pipeline.descriptorSet; - let pso; + let pso: PipelineState | null = null; if (pass !== null && shader !== null && screenIa !== null) { - pso = PipelineStateManager.getOrCreatePipelineState(context.device, pass, shader, - devicePass.renderPass, screenIa); + pso = PipelineStateManager.getOrCreatePipelineState( + context.device, + pass, + shader, + devicePass.renderPass, + screenIa, + ); } if (pso) { this.visitor.bindPipelineState(pso); @@ -1397,18 +1526,22 @@ class DeviceSceneTask extends WebSceneTask { const devicePass = this._currentQueue.devicePass; const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.additiveLight?.recordCommandBuffer(context.device, + currSubmitInfo.additiveLight?.recordCommandBuffer( + context.device, this._renderPass, - context.commandBuffer); + context.commandBuffer, + ); } private _recordPlanarShadows (): void { const devicePass = this._currentQueue.devicePass; const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.planarQueue?.recordCommandBuffer(context.device, + currSubmitInfo.planarQueue?.recordCommandBuffer( + context.device, this._renderPass, - context.commandBuffer); + context.commandBuffer, + ); } protected _updateGlobal (data: RenderData): void { const devicePass = this._currentQueue.devicePass; @@ -1495,8 +1628,10 @@ class DeviceSceneTask extends WebSceneTask { if (graphSceneData.flags & SceneFlags.DEFAULT_LIGHTING) { this._recordAdditiveLights(); } - this.visitor.bindDescriptorSet(SetIndex.GLOBAL, - context.pipeline.descriptorSet); + this.visitor.bindDescriptorSet( + SetIndex.GLOBAL, + context.pipeline.descriptorSet, + ); if (graphSceneData.flags & SceneFlags.PLANAR_SHADOW) { this._recordPlanarShadows(); } @@ -1504,8 +1639,12 @@ class DeviceSceneTask extends WebSceneTask { this._recordTransparentList(); } if (graphSceneData.flags & SceneFlags.GEOMETRY) { - this.camera!.geometryRenderer?.render(devicePass.renderPass, - context.commandBuffer, context.pipeline.pipelineSceneData); + this.camera!.geometryRenderer?.render( + devicePass.renderPass, + context.commandBuffer, + + context.pipeline.pipelineSceneData, + ); } if (graphSceneData.flags & SceneFlags.UI) { this._recordUI(); @@ -1692,7 +1831,7 @@ class BlitInfo { const vbStride = Float32Array.BYTES_PER_ELEMENT * 4; const vbSize = vbStride * 4; const device = cclegacy.director.root.device; - const quadVB = device.createBuffer(new BufferInfo( + const quadVB: Buffer = device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE | MemoryUsageBit.HOST, vbSize, @@ -1707,7 +1846,7 @@ class BlitInfo { const ibStride = Uint8Array.BYTES_PER_ELEMENT; const ibSize = ibStride * 6; - const quadIB = device.createBuffer(new BufferInfo( + const quadIB: Buffer = device.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, @@ -1744,14 +1883,16 @@ class BlitInfo { } class ExecutorContext { - constructor (pipeline: BasicPipeline, + constructor ( + pipeline: BasicPipeline, ubo: PipelineUBO, device: Device, resourceGraph: ResourceGraph, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, width: number, - height: number) { + height: number, + ) { this.pipeline = pipeline; this.device = device; this.commandBuffer = device.commandBuffer; @@ -1804,12 +1945,15 @@ class ExecutorContext { } export class Executor { - constructor (pipeline: BasicPipeline, + constructor ( + pipeline: BasicPipeline, ubo: PipelineUBO, device: Device, resourceGraph: ResourceGraph, layoutGraph: LayoutGraphData, - width: number, height: number) { + width: number, + height: number, + ) { context = this._context = new ExecutorContext( pipeline, ubo, diff --git a/cocos/rendering/custom/index.jsb.ts b/cocos/rendering/custom/index.jsb.ts index ce9a0e531f..7aa8b0d0a2 100644 --- a/cocos/rendering/custom/index.jsb.ts +++ b/cocos/rendering/custom/index.jsb.ts @@ -25,7 +25,7 @@ declare const render: any; import { Pipeline, PipelineBuilder, RenderingModule } from './pipeline'; -import { DeferredPipelineBuilder, ForwardPipelineBuilder } from './builtin-pipelines'; +import { DeferredPipelineBuilder } from './builtin-pipelines'; import { CustomPipelineBuilder, TestPipelineBuilder } from './custom-pipeline'; import { Device } from '../../gfx'; import { PostProcessBuilder } from '../post-process/post-process-builder'; @@ -92,11 +92,15 @@ export function getPassID (name: string | undefined): number { return _renderModule.getPassID(name); } +export function getSubpassID (passID: number, name: string): number { + return _renderModule.getSubpassID(passID, name); +} + export function getPhaseID (passID: number, name: string | number | undefined): number { if (name === undefined) { return _renderModule.getPhaseID(passID, 'default'); } - if (typeof(name) === 'number') { + if (typeof (name) === 'number') { return _renderModule.getPhaseID(passID, name.toString()); } return _renderModule.getPhaseID(passID, name); diff --git a/cocos/rendering/custom/index.ts b/cocos/rendering/custom/index.ts index cfbd706696..ab1c8fa240 100644 --- a/cocos/rendering/custom/index.ts +++ b/cocos/rendering/custom/index.ts @@ -32,7 +32,7 @@ import { LayoutGraphData, loadLayoutGraphData } from './layout-graph'; import { BinaryInputArchive } from './binary-archive'; import { WebProgramLibrary } from './web-program-library'; import { Device } from '../../gfx'; -import { initializeLayoutGraphData, terminateLayoutGraphData, getCustomPassID, getCustomPhaseID } from './layout-graph-utils'; +import { initializeLayoutGraphData, terminateLayoutGraphData, getCustomPassID, getCustomPhaseID, getCustomSubpassID } from './layout-graph-utils'; import { ProgramLibrary } from './private'; import { PostProcessBuilder } from '../post-process/post-process-builder'; @@ -101,6 +101,10 @@ export function getPassID (name: string | undefined): number { return getCustomPassID(defaultLayoutGraph, name); } +export function getSubpassID (passID: number, name: string): number { + return getCustomSubpassID(defaultLayoutGraph, passID, name); +} + export function getPhaseID (passID: number, name: string | number | undefined): number { return getCustomPhaseID(defaultLayoutGraph, passID, name); } diff --git a/cocos/rendering/custom/pipeline.ts b/cocos/rendering/custom/pipeline.ts index 7bdabfe198..c679c5796d 100644 --- a/cocos/rendering/custom/pipeline.ts +++ b/cocos/rendering/custom/pipeline.ts @@ -30,15 +30,17 @@ /* eslint-disable max-len */ import { Material } from '../../asset/assets'; import { Camera } from '../../render-scene/scene/camera'; +import { DirectionalLight } from '../../render-scene/scene/directional-light'; import { GeometryRenderer } from '../geometry-renderer'; -import { Buffer, BufferInfo, ClearFlagBit, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, DrawInfo, Format, InputAssembler, LoadOp, PipelineState, Rect, ResolveMode, Sampler, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureInfo, Viewport } from '../../gfx'; +import { Buffer, BufferInfo, ClearFlagBit, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, Format, LoadOp, ResolveMode, SampleCount, Sampler, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureInfo, Viewport } from '../../gfx'; import { GlobalDSManager } from '../global-descriptor-set-manager'; import { Mat4, Quat, Vec2, Vec4 } from '../../core/math'; import { MacroRecord } from '../../render-scene/core/pass-utils'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { AccessType, CopyPair, LightInfo, MovePair, QueueHint, ResolvePair, ResourceResidency, SceneFlags, TaskType, UpdateFrequency, UploadPair } from './types'; +import { AccessType, CopyPair, LightInfo, MovePair, QueueHint, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency, UploadPair } from './types'; import { RenderWindow } from '../../render-scene/core/render-window'; -import { Model } from '../../render-scene/scene'; +import { Light, Model } from '../../render-scene/scene'; +import { SpotLight } from '../../render-scene/scene/spot-light'; /** * @engineInternal @@ -249,6 +251,11 @@ export enum SubpassCapabilities { * @zh 支持读取当前像素任意颜色值 */ INPUT_COLOR_MRT = 1 << 2, + /** + * @en Each subpass has its own sample count. + * @zh 每个Subpass拥有不同的采样数 + */ + HETEROGENEOUS_SAMPLE_COUNT = 1 << 3, } /** @@ -368,6 +375,10 @@ export interface Setter extends RenderNode { * @param name @en descriptor name in shader. @zh 填写着色器中的描述符(descriptor)名字 */ setSampler (name: string, sampler: Sampler): void; + setBuiltinCameraConstants (camera: Camera): void; + setBuiltinShadowMapConstants (light: DirectionalLight): void; + setBuiltinDirectionalLightViewConstants (light: DirectionalLight, level?: number): void; + setBuiltinSpotLightViewConstants (light: SpotLight): void; } /** @@ -391,6 +402,16 @@ export interface RenderQueueBuilder extends Setter { camera: Camera, light: LightInfo, sceneFlags?: SceneFlags): void; + addScene (camera: Camera, sceneFlags: SceneFlags): void; + addSceneCulledByDirectionalLight ( + camera: Camera, + sceneFlags: SceneFlags, + light: DirectionalLight, + level: number): void; + addSceneCulledBySpotLight ( + camera: Camera, + sceneFlags: SceneFlags, + light: SpotLight): void; /** * @en Render a full-screen quad. * @zh 渲染全屏四边形 @@ -528,6 +549,15 @@ export interface BasicRenderPassBuilder extends Setter { showStatistics: boolean; } +export interface BasicMultisampleRenderPassBuilder extends BasicRenderPassBuilder { + resolveRenderTarget (source: string, target: string): void; + resolveDepthStencil ( + source: string, + target: string, + depthMode?: ResolveMode, + stencilMode?: ResolveMode): void; +} + /** * @en BasicPipeline * Basic pipeline provides basic rendering features which are supported on all platforms. @@ -643,6 +673,27 @@ export interface BasicPipeline extends PipelineRuntime { width: number, height: number, format?: Format): void; + addResource ( + name: string, + dimension: ResourceDimension, + format: Format, + width: number, + height: number, + depth: number, + arraySize: number, + mipLevels: number, + sampleCount: SampleCount, + flags: ResourceFlags, + residency: ResourceResidency): number; + updateResource ( + name: string, + format: Format, + width: number, + height: number, + depth: number, + arraySize: number, + mipLevels: number, + sampleCount: SampleCount): void; /** * @engineInternal * @en Begin rendering one frame @@ -690,7 +741,7 @@ export interface BasicPipeline extends PipelineRuntime { height: number, count: number, quality: number, - passName?: string): BasicRenderPassBuilder; + passName?: string): BasicMultisampleRenderPassBuilder; /** * @deprecated Method will be removed in 3.9.0 */ @@ -1054,6 +1105,17 @@ export interface RenderPassBuilder extends BasicRenderPassBuilder { setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void; } +export interface MultisampleRenderPassBuilder extends BasicMultisampleRenderPassBuilder { + addStorageBuffer ( + name: string, + accessType: AccessType, + slotName: string): void; + addStorageImage ( + name: string, + accessType: AccessType, + slotName: string): void; +} + /** * @en Compute pass * @zh 计算通道 @@ -1133,38 +1195,6 @@ export interface ComputePassBuilder extends Setter { setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void; } -/** - * @deprecated @en Not used @zh 未使用 - */ -export interface SceneVisitor { - readonly pipelineSceneData: PipelineSceneData; - setViewport (vp: Viewport): void; - setScissor (rect: Rect): void; - bindPipelineState (pso: PipelineState): void; - bindInputAssembler (ia: InputAssembler): void; - draw (info: DrawInfo): void; - - bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: number[]): void; - updateBuffer (buffer: Buffer, data: ArrayBuffer, size?: number): void; -} - -/** - * @deprecated @en Not used @zh 未使用 - */ -export interface SceneTask { - readonly taskType: TaskType; - start (): void; - join (): void; - submit (): void; -} - -/** - * @deprecated @en Not used @zh 未使用 - */ -export interface SceneTransversal { - transverse (visitor: SceneVisitor): SceneTask; -} - /** * @en Render pipeline. * @zh 渲染管线 @@ -1259,6 +1289,12 @@ export interface Pipeline extends BasicPipeline { width: number, height: number, passName: string): RenderPassBuilder; + addMultisampleRenderPass ( + width: number, + height: number, + count: number, + quality: number, + passName: string): MultisampleRenderPassBuilder; /** * @en Add compute pass * @zh 添加计算通道 @@ -1308,6 +1344,11 @@ export interface Pipeline extends BasicPipeline { * @param movePairs @en Array of move source and target @zh 移动来源与目标的数组 */ addMovePass (movePairs: MovePair[]): void; + addBuiltinGpuCullingPass ( + camera: Camera, + hzbName?: string, + light?: Light | null): void; + addBuiltinHzbGenerationPass (sourceDepthStencilName: string, targetHzbName: string): void; /** * @experimental */ diff --git a/cocos/rendering/custom/render-graph.ts b/cocos/rendering/custom/render-graph.ts index afbb675ef8..4107887139 100644 --- a/cocos/rendering/custom/render-graph.ts +++ b/cocos/rendering/custom/render-graph.ts @@ -114,7 +114,7 @@ export class ResourceDesc { depthOrArraySize = 0; mipLevels = 0; format: Format = Format.UNKNOWN; - sampleCount: SampleCount = SampleCount.ONE; + sampleCount: SampleCount = SampleCount.X1; textureFlags: TextureFlagBit = TextureFlagBit.NONE; flags: ResourceFlags = ResourceFlags.NONE; } @@ -164,6 +164,7 @@ export class ManagedResource { export class Subpass { readonly rasterViews: Map = new Map(); readonly computeViews: Map = new Map(); + readonly resolvePairs: ResolvePair[] = []; } //================================================================= @@ -171,8 +172,6 @@ export class Subpass { //================================================================= // Graph Concept export class SubpassGraphVertex { - constructor () { - } readonly _outEdges: OutE[] = []; readonly _inEdges: OutE[] = []; } @@ -1656,6 +1655,7 @@ export class RenderGraph implements BidirectionalGraph clear (): void { // Members this.index.clear(); + this.sortedVertices.length = 0; // ComponentGraph this._names.length = 0; this._layoutNodes.length = 0; @@ -2267,4 +2267,5 @@ export class RenderGraph implements BidirectionalGraph readonly _data: RenderData[] = []; readonly _valid: boolean[] = []; readonly index: Map = new Map(); + readonly sortedVertices: number[] = []; } diff --git a/cocos/rendering/custom/scene.ts b/cocos/rendering/custom/scene.ts new file mode 100644 index 0000000000..d46cf08a27 --- /dev/null +++ b/cocos/rendering/custom/scene.ts @@ -0,0 +1,34 @@ +import { + Buffer, + DescriptorSet, + DrawInfo, + InputAssembler, + PipelineState, + Rect, + Viewport, +} from '../../gfx'; +import { PipelineSceneData } from '../pipeline-scene-data'; +import { TaskType } from './types'; + +export interface SceneVisitor { + readonly pipelineSceneData: PipelineSceneData; + setViewport (vp: Viewport): void; + setScissor (rect: Rect): void; + bindPipelineState (pso: PipelineState): void; + bindInputAssembler (ia: InputAssembler): void; + draw (info: DrawInfo | InputAssembler): void; + + bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: number[]): void; + updateBuffer (buffer: Buffer, data: ArrayBuffer, size?: number): void; +} + +export interface SceneTask { + readonly taskType: TaskType; + start (): void; + join (): void; + submit (): void; +} + +export interface SceneTransversal { + transverse (visitor: SceneVisitor): SceneTask; +} diff --git a/cocos/rendering/custom/types.ts b/cocos/rendering/custom/types.ts index c964335b4f..d09e3b8a9f 100644 --- a/cocos/rendering/custom/types.ts +++ b/cocos/rendering/custom/types.ts @@ -168,6 +168,8 @@ export enum ResourceFlags { DEPTH_STENCIL_ATTACHMENT = 0x20, INPUT_ATTACHMENT = 0x40, SHADING_RATE = 0x80, + TRANSFER_SRC = 0x100, + TRANSFER_DST = 0x200, } export enum TaskType { @@ -205,6 +207,7 @@ export enum SceneFlags { DRAW_INSTANCING = 0x800, DRAW_NON_INSTANCING = 0x1000, REFLECTION_PROBE = 0x2000, + GPU_DRIVEN = 0x4000, ALL = 0xFFFFFFFF, } diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index ec05c6e9ee..c1bac8ca45 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -25,11 +25,11 @@ /* eslint-disable max-len */ import { systemInfo } from 'pal/system-info'; import { DEBUG } from 'internal:constants'; -import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address, DescriptorSetInfo, LoadOp, StoreOp, ShaderStageFlagBit, BufferInfo, TextureInfo, UniformBlock } from '../../gfx'; -import { Mat4, Quat, toRadian, Vec2, Vec3, Vec4, assert, macro, cclegacy } from '../../core'; +import { Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address, DescriptorSetInfo, LoadOp, StoreOp, ShaderStageFlagBit, BufferInfo, TextureInfo, UniformBlock, ResolveMode, SampleCount, Color } from '../../gfx'; +import { Mat4, Quat, toRadian, Vec2, Vec3, Vec4, assert, macro, cclegacy, IVec4Like, IMat4Like, IVec2Like, Color as CoreColor } from '../../core'; import { AccessType, AttachmentType, CopyPair, LightInfo, LightingMode, MovePair, QueueHint, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; import { ComputeView, RasterView, Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedBuffer, ManagedResource, MovePass, RasterPass, RasterSubpass, RenderData, RenderGraph, RenderGraphComponent, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData, Subpass } from './render-graph'; -import { ComputePassBuilder, ComputeQueueBuilder, ComputeSubpassBuilder, BasicPipeline, PipelineBuilder, RenderPassBuilder, RenderQueueBuilder, RenderSubpassBuilder, PipelineType, BasicRenderPassBuilder, PipelineCapabilities } from './pipeline'; +import { ComputePassBuilder, ComputeQueueBuilder, ComputeSubpassBuilder, BasicPipeline, PipelineBuilder, RenderPassBuilder, RenderQueueBuilder, RenderSubpassBuilder, PipelineType, BasicRenderPassBuilder, PipelineCapabilities, BasicMultisampleRenderPassBuilder } from './pipeline'; import { PipelineSceneData } from '../pipeline-scene-data'; import { Model, Camera, ShadowType, CSMLevel, DirectionalLight, SpotLight, PCFType, Shadows } from '../../render-scene/scene'; import { Light, LightType } from '../../render-scene/scene/light'; @@ -54,6 +54,9 @@ import { getUBOTypeCount } from './utils'; import { initGlobalDescBinding } from './define'; import { createGfxDescriptorSetsAndPipelines } from './layout-graph-utils'; import { Root } from '../../root'; +import { CSMLayers, CSMShadowLayer } from '../shadow/csm-layers'; +import { Scene } from '../../scene-graph'; +import { Director } from '../../game'; const _uboVec = new Vec4(); const _uboVec3 = new Vec3(); @@ -75,32 +78,34 @@ export class WebSetter { this._lg = lg; } - protected _copyToBuffer (target: any, offset: number, type: Type): void { + protected _copyToBuffer (target: IVec4Like | Quat | IVec2Like | IMat4Like | number, offset: number, type: Type): void { assert(offset !== -1); const arr = this.getCurrConstant(); switch (type) { case Type.FLOAT4: - Vec4.toArray(arr, target, offset); + Vec4.toArray(arr, target as IVec4Like, offset); break; case Type.MAT4: - Mat4.toArray(arr, target, offset); + Mat4.toArray(arr, target as IMat4Like, offset); break; case Type.FLOAT: - arr[offset] = target; + arr[offset] = target as number; break; case Type.SAMPLER2D: break; case Type.TEXTURE2D: break; - case Type.FLOAT2: - arr[offset + 0] = target.x; - arr[offset + 1] = target.y; + case Type.FLOAT2: { + const vec2Val = target as IVec2Like; + arr[offset + 0] = vec2Val.x; + arr[offset + 1] = vec2Val.y; + } break; default: } } - protected _applyCurrConstantBuffer (name: string, target: any, type: Type, idx = 0): void { + protected _applyCurrConstantBuffer (name: string, target: IVec4Like | Quat | IVec2Like | IMat4Like | number, type: Type, idx = 0): void { const offset = this.getUniformOffset(name, type, idx); this._copyToBuffer(target, offset, type); } @@ -189,7 +194,7 @@ export class WebSetter { this._currCount += getUBOTypeCount(uniform.type) * uniform.count; } if (!this._data.constants.get(num)) { - const value = new Array(this._currCount); + const value: number[] = new Array(this._currCount); value.fill(0); this._data.constants.set(num, value); } @@ -211,7 +216,7 @@ export class WebSetter { public setColor (name: string, color: Color, idx = 0): void { this._applyCurrConstantBuffer(name, color, Type.FLOAT4, idx); } - public offsetColor (color: Color, offset: number): void { + public offsetColor (color: Color | CoreColor, offset: number): void { this._copyToBuffer(color, offset, Type.FLOAT4); } public setVec4 (name: string, vec: Vec4, idx = 0): void { @@ -249,18 +254,18 @@ export class WebSetter { const num = this._lg.attributeIndex.get(name)!; this._data.samplers.set(num, sampler); } - // public setCameraConstants (camera: Camera): void { + public setBuiltinCameraConstants (camera: Camera): void { - // } - // public setDirectionalLightProjectionConstants (light: DirectionalLight): void { + } + public setBuiltinShadowMapConstants (light: Light, numLevels?: number): void { - // } - // public setSpotLightProjectionConstants (light: SpotLight): void { + } + public setBuiltinDirectionalLightViewConstants (light: DirectionalLight): void { - // } - // public setShadowMapConstants (light: Light, numLevels?: number): void { + } + public setBuiltinSpotLightViewConstants (light: SpotLight): void { - // } + } public hasSampler (name: string): boolean { const id = this._lg.attributeIndex.get(name); if (id === undefined) { @@ -283,16 +288,18 @@ export class WebSetter { protected _data: RenderData; protected _lg: LayoutGraphData; protected _currBlock; - protected _currStage; + protected _currStage: string = ''; protected _currCount; protected _currConstant: number[] = []; } -function setShadowUBOLightView (setter: WebSetter, +function setShadowUBOLightView ( + setter: WebSetter, camera: Camera, light: Light, level: number, - layout = 'default'): void { + layout = 'default', +): void { const director = cclegacy.director; const pipeline = (director.root as Root).pipeline; const device = pipeline.device; @@ -319,9 +326,9 @@ function setShadowUBOLightView (setter: WebSetter, if (shadowInfo.type === ShadowType.ShadowMap) { let near = 0.1; let far = 0; - let matShadowView; - let matShadowProj; - let matShadowViewProj; + let matShadowView: Mat4; + let matShadowProj: Mat4; + let matShadowViewProj: Mat4; let levelCount = 0; if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { matShadowView = csmLayers.specialLayer.matShadowView; @@ -394,12 +401,21 @@ function setShadowUBOLightView (setter: WebSetter, const matViewOffset = setter.getUniformOffset('cc_matLightView', Type.MAT4); const matViewProOffset = setter.getUniformOffset('cc_matLightViewProj', Type.MAT4); if (setter.hasUniform(matViewOffset) || setter.hasUniform(matViewProOffset)) { - Mat4.invert(_matView, (light as any).node.getWorldMatrix()); + Mat4.invert(_matView, spotLight.node!.getWorldMatrix()); } if (setter.hasUniform(matViewOffset)) setter.offsetMat4(_matView, matViewOffset); if (setter.hasUniform(matViewProOffset)) { - Mat4.perspective(_mulMatView, (light as any).angle, 1.0, 0.001, (light as any).range, - true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0); + Mat4.perspective( + _mulMatView, + spotLight.angle, + 1.0, + 0.001, + spotLight.range, + true, + cap.clipSpaceMinZ, + cap.clipSpaceSignY, + 0, + ); Mat4.multiply(_matView, _mulMatView, _matView); setter.offsetMat4(_matView, matViewProOffset); } @@ -449,12 +465,12 @@ function getPCFRadius (shadowInfo: Shadows, mainLight: DirectionalLight): number function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'default'): void { const director = cclegacy.director; const pipeline = director.root.pipeline; - const device = pipeline.device; + const device: Device = pipeline.device; const scene = director.getScene(); - const mainLight = camera && camera.scene ? camera.scene.mainLight : scene ? scene.renderScene.mainLight : null; + const mainLight: DirectionalLight = camera && camera.scene ? camera.scene.mainLight : scene ? scene.renderScene.mainLight : null; const sceneData = pipeline.pipelineSceneData; - const shadowInfo = sceneData.shadows; - const csmLayers = sceneData.csmLayers; + const shadowInfo: Shadows = sceneData.shadows; + const csmLayers: CSMLayers = sceneData.csmLayers; const csmSupported = sceneData.csmSupported; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; const hasCCShadow = setter.addConstant('CCShadow', layout); @@ -465,11 +481,11 @@ function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'd if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) { if (hasCCShadow) { setter.setCurrConstant('CCShadow', layout); - const matShadowView = csmLayers.specialLayer.matShadowView; - const matShadowProj = csmLayers.specialLayer.matShadowProj; - const matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; - const near = mainLight.shadowNear; - const far = mainLight.shadowFar; + const matShadowView: Mat4 = csmLayers.specialLayer.matShadowView; + const matShadowProj: Mat4 = csmLayers.specialLayer.matShadowProj; + const matShadowViewProj: Mat4 = csmLayers.specialLayer.matShadowViewProj; + const near: number = mainLight.shadowNear; + const far: number = mainLight.shadowFar; uniformOffset = setter.getUniformOffset('cc_matLightView', Type.MAT4); if (setter.hasUniform(uniformOffset)) { setter.offsetMat4(matShadowView, uniformOffset); @@ -504,8 +520,8 @@ function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'd const layerThreshold = getPCFRadius(shadowInfo, mainLight); setter.setCurrConstant('CCCSM', layout); for (let i = 0; i < mainLight.csmLevel; i++) { - const layer = csmLayers.layers[i]; - const matShadowView = layer.matShadowView; + const layer: CSMShadowLayer = csmLayers.layers[i]; + const matShadowView: Mat4 = layer.matShadowView; uniformOffset = setter.getUniformOffset('cc_csmViewDir0', Type.FLOAT4, i); if (setter.hasUniform(uniformOffset)) { _uboVec.set(matShadowView.m00, matShadowView.m04, matShadowView.m08, layerThreshold); @@ -591,10 +607,13 @@ function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'd } } -function setCameraUBOValues (setter: WebSetter, - camera: Readonly | null, cfg: Readonly, - scene: Readonly, - layoutName = 'default'): void { +function setCameraUBOValues ( + setter: WebSetter, + camera: Readonly | null, + cfg: Readonly, + scene: RenderScene | null, + layoutName = 'default', +): void { const director = cclegacy.director; const root = director.root; const pipeline = root.pipeline as WebPipeline; @@ -741,14 +760,14 @@ function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Reado const root = director.root; if (skybox.reflectionMap) { const texture = skybox.reflectionMap.getGFXTexture()!; - const sampler = root.device.getSampler(skybox.reflectionMap.getSamplerInfo()); + const sampler: Sampler = root.device.getSampler(skybox.reflectionMap.getSamplerInfo()); setter.setTexture('cc_environment', texture); setter.setSampler('cc_environment', sampler); } else { const envmap = skybox.envmap ? skybox.envmap : builtinResMgr.get('default-cube-texture'); if (envmap) { const texture = envmap.getGFXTexture()!; - const sampler = root.device.getSampler(envmap.getSamplerInfo()); + const sampler: Sampler = root.device.getSampler(envmap.getSamplerInfo()); setter.setTexture('cc_environment', texture); setter.setSampler('cc_environment', sampler); } @@ -756,11 +775,11 @@ function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Reado const diffuseMap = skybox.diffuseMap ? skybox.diffuseMap : builtinResMgr.get('default-cube-texture'); if (diffuseMap) { const texture = diffuseMap.getGFXTexture()!; - const sampler = root.device.getSampler(diffuseMap.getSamplerInfo()); + const sampler: Sampler = root.device.getSampler(diffuseMap.getSamplerInfo()); setter.setTexture('cc_diffuseMap', texture); setter.setSampler('cc_diffuseMap', sampler); } - const pointSampler = root.device.getSampler(_samplerPointInfo); + const pointSampler: Sampler = root.device.getSampler(_samplerPointInfo); if (!setter.hasSampler('cc_shadowMap')) { setter.setSampler('cc_shadowMap', pointSampler); } @@ -779,7 +798,7 @@ function getFirstChildLayoutName (lg: LayoutGraphData, parentID: number): string if (lg.numVertices() && parentID !== 0xFFFFFFFF && lg.numChildren(parentID)) { const childNodes = lg.children(parentID); if (childNodes.next().value && childNodes.next().value.target !== lg.nullVertex()) { - const ququeLayoutID = childNodes.next().value.target; + const ququeLayoutID: number = childNodes.next().value.target; return lg.getName(ququeLayoutID); } } @@ -812,14 +831,16 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags = SceneFlags.NONE, name = 'Camera'): void { const sceneData = new SceneData(camera.scene, camera, sceneFlags, light); - this._renderGraph.addVertex( - RenderGraphValue.Scene, sceneData, name, '', new RenderData(), false, this._vertID, - ); + this._renderGraph.addVertex(RenderGraphValue.Scene, sceneData, name, '', new RenderData(), false, this._vertID); const layoutName = this.getLayoutName(); - const scene = cclegacy.director.getScene(); - setCameraUBOValues(this, camera, this._pipeline, - camera.scene ? camera.scene : scene ? scene.renderScene : null, - layoutName); + const scene: Scene = cclegacy.director.getScene(); + setCameraUBOValues( + this, + camera, + this._pipeline, + camera.scene || (scene ? scene.renderScene : null), + layoutName, + ); if (sceneFlags & SceneFlags.SHADOW_CASTER) { setShadowUBOLightView(this, camera, light.light!, light.level, layoutName); } else { @@ -828,33 +849,37 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild setTextureUBOView(this, camera, this._pipeline); initGlobalDescBinding(this._data, layoutName); } - // addScene (camera: Camera, sceneFlags = SceneFlags.NONE): void { - // const sceneData = new SceneData(camera.scene, camera, sceneFlags); - // this._renderGraph.addVertex( - // RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID, - // ); - // } - // addSceneCulledByDirectionalLight (camera: Camera, sceneFlags: SceneFlags, light: DirectionalLight, level: number): void { - // const sceneData = new SceneData(camera.scene, camera, sceneFlags, new LightInfo(light, level)); - // this._renderGraph.addVertex( - // RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID, - // ); - // } - // addSceneCulledBySpotLight (camera: Camera, sceneFlags: SceneFlags, light: SpotLight): void { - // const sceneData = new SceneData(camera.scene, camera, sceneFlags, new LightInfo(light, 0)); - // this._renderGraph.addVertex( - // RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID, - // ); - // } + addScene (camera: Camera, sceneFlags = SceneFlags.NONE): void { + const sceneData = new SceneData(camera.scene, camera, sceneFlags); + this._renderGraph.addVertex(RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID); + } + addSceneCulledByDirectionalLight (camera: Camera, sceneFlags: SceneFlags, light: DirectionalLight, level: number): void { + const sceneData = new SceneData(camera.scene, camera, sceneFlags, new LightInfo(light, level)); + this._renderGraph.addVertex(RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID); + } + addSceneCulledBySpotLight (camera: Camera, sceneFlags: SceneFlags, light: SpotLight): void { + const sceneData = new SceneData(camera.scene, camera, sceneFlags, new LightInfo(light, 0)); + this._renderGraph.addVertex(RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID); + } addFullscreenQuad (material: Material, passID: number, sceneFlags = SceneFlags.NONE, name = 'Quad'): void { this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, null), - name, '', new RenderData(), false, this._vertID, + RenderGraphValue.Blit, + new Blit(material, passID, sceneFlags, null), + name, + '', + new RenderData(), + false, + this._vertID, ); const layoutName = this.getLayoutName(); - const scene = cclegacy.director.getScene(); - setCameraUBOValues(this, null, this._pipeline, - scene ? scene.renderScene : null, layoutName); + const scene: Scene | null = cclegacy.director.getScene(); + setCameraUBOValues( + this, + null, + this._pipeline, + scene ? scene.renderScene : null, + layoutName, + ); if (sceneFlags & SceneFlags.SHADOW_CASTER) { // setShadowUBOLightView(this, light.light!, light.level); } else { @@ -865,13 +890,23 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild } addCameraQuad (camera: Camera, material: Material, passID: number, sceneFlags = SceneFlags.NONE): void { this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, camera), - 'CameraQuad', '', new RenderData(), false, this._vertID, + RenderGraphValue.Blit, + new Blit(material, passID, sceneFlags, camera), + 'CameraQuad', + '', + new RenderData(), + false, + this._vertID, ); const layoutName = this.getLayoutName(); - const scene = cclegacy.director.getScene(); - setCameraUBOValues(this, camera, this._pipeline, - camera.scene ? camera.scene : scene ? scene.renderScene : null, layoutName); + const scene: Scene = cclegacy.director.getScene(); + setCameraUBOValues( + this, + camera, + this._pipeline, + camera.scene || (scene ? scene.renderScene : null), + layoutName, + ); if (sceneFlags & SceneFlags.SHADOW_CASTER) { // setShadowUBOLightView(this, light.light!, light.level); } else { @@ -882,8 +917,13 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild } clearRenderTarget (name: string, color: Color = new Color()): void { this._renderGraph.addVertex( - RenderGraphValue.Clear, [new ClearView(name, ClearFlagBit.COLOR, color)], - 'ClearRenderTarget', '', new RenderData(), false, this._vertID, + RenderGraphValue.Clear, + [new ClearView(name, ClearFlagBit.COLOR, color)], + 'ClearRenderTarget', + '', + new RenderData(), + false, + this._vertID, ); } setViewport (viewport: Viewport): void { @@ -899,8 +939,14 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild } export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassBuilder { - constructor (data: RenderData, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, - vertID: number, subpass: RasterSubpass, pipeline: PipelineSceneData) { + constructor ( + data: RenderData, + renderGraph: RenderGraph, + layoutGraph: LayoutGraphData, + vertID: number, + subpass: RasterSubpass, + pipeline: PipelineSceneData, + ) { super(data, layoutGraph); this._renderGraph = renderGraph; this._layoutGraph = layoutGraph; @@ -908,11 +954,12 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB this._subpass = subpass; this._pipeline = pipeline; - const layoutName = this._renderGraph.component( - RenderGraphComponent.Layout, this._vertID, - ); + const layoutName = this._renderGraph.component(RenderGraphComponent.Layout, this._vertID); this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } + addRenderTarget (name: string, accessType: AccessType, slotName?: string | undefined, loadOp?: LoadOp | undefined, storeOp?: StoreOp | undefined, color?: Color | undefined): void { + throw new Error('Method not implemented.'); + } setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void { throw new Error('Method not implemented.'); } @@ -925,9 +972,7 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB set name (name: string) { this._renderGraph.setName(this._vertID, name); } - addRenderTarget (name: string, accessType: AccessType, slotName: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()): void { - throw new Error('Method not implemented.'); - } + addDepthStencil (name: string, accessType: AccessType, depthSlotName = '', stencilSlotName = '', loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { throw new Error('Method not implemented.'); } @@ -950,9 +995,7 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB } const queue = new RenderQueue(hint); const data = new RenderData(); - const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID, - ); + const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebRenderQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); } get showStatistics (): boolean { @@ -970,7 +1013,7 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB private readonly _layoutGraph: LayoutGraphData; } -export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBuilder { +export class WebRenderPassBuilder extends WebSetter implements BasicMultisampleRenderPassBuilder { constructor (data: RenderData, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, resourceGraph: ResourceGraph, vertID: number, pass: RasterPass, pipeline: PipelineSceneData) { super(data, layoutGraph); this._renderGraph = renderGraph; @@ -980,9 +1023,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu this._pass = pass; this._pipeline = pipeline; - const layoutName = this._renderGraph.component( - RenderGraphComponent.Layout, this._vertID, - ); + const layoutName = this._renderGraph.component(RenderGraphComponent.Layout, this._vertID); this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void { @@ -1009,25 +1050,44 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu if (loadOp === LoadOp.LOAD) { clearFlag = ClearFlagBit.NONE; } - const view = new RasterView('', - AccessType.WRITE, AttachmentType.RENDER_TARGET, + const view = new RasterView( + '', + AccessType.WRITE, + + AttachmentType.RENDER_TARGET, loadOp, storeOp, clearFlag, - clearColor); + clearColor, + ); this._pass.rasterViews.set(name, view); } addDepthStencil (name: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { if (DEBUG) { assert(Boolean(name && this._resourceGraph.contains(name))); } - const view = new RasterView('', - AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + const view = new RasterView( + '', + AccessType.WRITE, + + AttachmentType.DEPTH_STENCIL, loadOp, storeOp, clearFlag, - new Color(depth, stencil, 0, 0)); + new Color(depth, stencil, 0, 0), + ); this._pass.rasterViews.set(name, view); + } + resolveRenderTarget (source: string, target: string): void { + + } + resolveDepthStencil ( + source: string, + target: string, + depthMode?: ResolveMode, + stencilMode?: ResolveMode, + ): void { + } private _addComputeResource (name: string, accessType: AccessType, slotName: string): void { const view = new ComputeView(slotName); @@ -1064,9 +1124,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu this._pass.subpassGraph.addVertex(name, new Subpass()); const subpass = new RasterSubpass(subpassID, 1, 0); const data = new RenderData(); - const vertID = this._renderGraph.addVertex( - RenderGraphValue.RasterSubpass, subpass, name, layoutName, data, false, - ); + const vertID = this._renderGraph.addVertex(RenderGraphValue.RasterSubpass, subpass, name, layoutName, data, false); const result = new WebRenderSubpassBuilder(data, this._renderGraph, this._layoutGraph, vertID, subpass, this._pipeline); return result; } @@ -1077,34 +1135,51 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu } const queue = new RenderQueue(hint); const data = new RenderData(); - const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID, - ); + const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebRenderQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); } addFullscreenQuad (material: Material, passID: number, sceneFlags = SceneFlags.NONE, name = 'FullscreenQuad'): void { const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); const queueId = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, - 'Queue', '', new RenderData(), - false, this._vertID, + RenderGraphValue.Queue, + queue, + 'Queue', + '', + new RenderData(), + false, + this._vertID, ); this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, null), - name, '', new RenderData(), false, queueId, + RenderGraphValue.Blit, + new Blit(material, passID, sceneFlags, null), + name, + '', + new RenderData(), + false, + queueId, ); } addCameraQuad (camera: Camera, material: Material, passID: number, sceneFlags: SceneFlags, name = 'CameraQuad'): void { const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); const queueId = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, - 'Queue', '', new RenderData(), false, this._vertID, + RenderGraphValue.Queue, + queue, + 'Queue', + '', + new RenderData(), + false, + this._vertID, ); this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, camera), - name, '', new RenderData(), false, queueId, + RenderGraphValue.Blit, + new Blit(material, passID, sceneFlags, camera), + name, + '', + new RenderData(), + false, + queueId, ); } setViewport (viewport: Viewport): void { @@ -1153,7 +1228,15 @@ export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBui this._renderGraph.addVertex( RenderGraphValue.Dispatch, new Dispatch(material, passID, threadGroupCountX, threadGroupCountY, threadGroupCountZ), - name, '', new RenderData(), false, this._vertID, + name, + + '', + + new RenderData(), + + false, + + this._vertID, ); } private readonly _renderGraph: RenderGraph; @@ -1172,9 +1255,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild this._pass = pass; this._pipeline = pipeline; - const layoutName = this._renderGraph.component( - RenderGraphComponent.Layout, this._vertID, - ); + const layoutName = this._renderGraph.component(RenderGraphComponent.Layout, this._vertID); this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void { @@ -1208,9 +1289,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild } const queue = new RenderQueue(); const data = new RenderData(); - const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID, - ); + const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebComputeQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); } private readonly _renderGraph: RenderGraph; @@ -1302,10 +1381,13 @@ export class WebPipeline implements BasicPipeline { if (renderWindow.swapchain === null) { assert(renderWindow.framebuffer.colorTextures.length === 1 && renderWindow.framebuffer.colorTextures[0] !== null); + desc.sampleCount = renderWindow.framebuffer.colorTextures[0].info.samples; return this._resourceGraph.addVertex( ResourceGraphValue.Framebuffer, renderWindow.framebuffer, - name, desc, + name, + + desc, new ResourceTraits(ResourceResidency.EXTERNAL), new ResourceStates(), new SamplerInfo(), @@ -1314,7 +1396,9 @@ export class WebPipeline implements BasicPipeline { return this._resourceGraph.addVertex( ResourceGraphValue.Swapchain, new RenderSwapchain(renderWindow.swapchain), - name, desc, + name, + + desc, new ResourceTraits(ResourceResidency.BACKBUFFER), new ResourceStates(), new SamplerInfo(), @@ -1365,6 +1449,39 @@ export class WebPipeline implements BasicPipeline { desc.width = width; desc.height = height; } + addResource (name: string, dimension: ResourceDimension, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount, flags: ResourceFlags, residency: ResourceResidency): number { + const desc = new ResourceDesc(); + desc.dimension = dimension; + desc.width = width; + desc.height = height; + desc.depthOrArraySize = dimension === ResourceDimension.TEXTURE3D ? depth : arraySize; + desc.mipLevels = mipLevels; + desc.format = format; + desc.sampleCount = sampleCount; + desc.flags = flags; + return this._resourceGraph.addVertex( + ResourceGraphValue.Managed, + new ManagedResource(), + name, + + desc, + new ResourceTraits(residency), + new ResourceStates(), + new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), + ); + } + updateResource (name: string, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount): void { + const resId = this.resourceGraph.vertex(name); + const desc = this.resourceGraph.getDesc(resId); + desc.width = width; + desc.height = height; + desc.depthOrArraySize = desc.dimension === ResourceDimension.TEXTURE3D ? depth : arraySize; + desc.mipLevels = mipLevels; + if (format !== Format.UNKNOWN) { + desc.format = format; + } + desc.sampleCount = sampleCount; + } public containsResource (name: string): boolean { return this._resourceGraph.contains(name); } @@ -1618,7 +1735,9 @@ export class WebPipeline implements BasicPipeline { return this._resourceGraph.addVertex( ResourceGraphValue.ManagedBuffer, new ManagedBuffer(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(), @@ -1632,12 +1751,15 @@ export class WebPipeline implements BasicPipeline { desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; + desc.sampleCount = SampleCount.X1; desc.flags = ResourceFlags.COLOR_ATTACHMENT | ResourceFlags.SAMPLED; return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), @@ -1651,11 +1773,14 @@ export class WebPipeline implements BasicPipeline { desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; + desc.sampleCount = SampleCount.X1; desc.flags = ResourceFlags.DEPTH_STENCIL_ATTACHMENT | ResourceFlags.SAMPLED; return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(Filter.POINT, Filter.POINT, Filter.NONE), @@ -1673,7 +1798,9 @@ export class WebPipeline implements BasicPipeline { return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(Filter.POINT, Filter.POINT, Filter.NONE), @@ -1692,7 +1819,9 @@ export class WebPipeline implements BasicPipeline { return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), @@ -1724,8 +1853,15 @@ export class WebPipeline implements BasicPipeline { throw new Error('Cannot run without creating rendergraph'); } if (!this._executor) { - this._executor = new Executor(this, this._pipelineUBO, this._device, - this._resourceGraph, this.layoutGraph, this.width, this.height); + this._executor = new Executor( + this, + this._pipelineUBO, + this._device, + this._resourceGraph, + this.layoutGraph, + this.width, + this.height, + ); } this._executor.resize(this.width, this.height); this._executor.execute(this._renderGraph); @@ -1762,7 +1898,7 @@ export class WebPipeline implements BasicPipeline { this.execute(); this.endFrame(); } - addRenderPassImpl (width: number, height: number, layoutName: string, count = 1, quality = 0): BasicRenderPassBuilder { + addRenderPassImpl (width: number, height: number, layoutName: string, count = 1, quality = 0): BasicMultisampleRenderPassBuilder { if (DEBUG) { const stageId = this.layoutGraph.locateChild(this.layoutGraph.nullVertex(), layoutName); assert(stageId !== 0xFFFFFFFF); @@ -1778,9 +1914,7 @@ export class WebPipeline implements BasicPipeline { pass.quality = quality; const data = new RenderData(); - const vertID = this._renderGraph!.addVertex( - RenderGraphValue.RasterPass, pass, name, layoutName, data, false, - ); + const vertID = this._renderGraph!.addVertex(RenderGraphValue.RasterPass, pass, name, layoutName, data, false); const result = new WebRenderPassBuilder(data, this._renderGraph!, this._layoutGraph, this._resourceGraph, vertID, pass, this._pipelineSceneData); this._updateRasterPassConstants(result, width, height, isEnableEffect() ? layoutName : 'default'); initGlobalDescBinding(data, layoutName); @@ -1789,7 +1923,7 @@ export class WebPipeline implements BasicPipeline { addRenderPass (width: number, height: number, layoutName = 'default'): BasicRenderPassBuilder { return this.addRenderPassImpl(width, height, layoutName); } - addMultisampleRenderPass (width: number, height: number, count: number, quality: number, layoutName = 'default'): BasicRenderPassBuilder { + addMultisampleRenderPass (width: number, height: number, count: number, quality: number, layoutName = 'default'): BasicMultisampleRenderPassBuilder { assert(count > 1); return this.addRenderPassImpl(width, height, layoutName, count, quality); } @@ -1815,8 +1949,8 @@ export class WebPipeline implements BasicPipeline { } protected _updateRasterPassConstants (setter: WebSetter, width: number, height: number, layoutName = 'default'): void { - const director = cclegacy.director; - const root = director.root; + const director: Director = cclegacy.director; + const root: Root = director.root!; const shadingWidth = width; const shadingHeight = height; const pipeline = root.pipeline as WebPipeline; @@ -1843,7 +1977,7 @@ export class WebPipeline implements BasicPipeline { if (debugView) { if (setter.hasUniform(uniformOffset)) { const debugPackVec: number[] = [debugView.singleMode as number, 0.0, 0.0, 0.0]; - for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { + for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < (DebugViewCompositeType.MAX_BIT_COUNT as number); i++) { const idx = i >> 3; const bit = i % 8; debugPackVec[idx + 1] += (debugView.isCompositeModeEnabled(i) ? 1.0 : 0.0) * (10.0 ** bit); diff --git a/cocos/rendering/custom/web-scene-visitor.ts b/cocos/rendering/custom/web-scene-visitor.ts index 81f3d187c1..04f4e94bb1 100644 --- a/cocos/rendering/custom/web-scene-visitor.ts +++ b/cocos/rendering/custom/web-scene-visitor.ts @@ -24,7 +24,7 @@ import { PipelineState, DescriptorSet, InputAssembler, DrawInfo, Buffer, CommandBuffer, Rect, Viewport } from '../../gfx'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { SceneVisitor } from './pipeline'; +import { SceneVisitor } from './scene'; export class WebSceneVisitor implements SceneVisitor { protected _pipelineSceneData: PipelineSceneData; @@ -51,7 +51,7 @@ export class WebSceneVisitor implements SceneVisitor { public bindInputAssembler (ia: InputAssembler): void { this._commandBuffer.bindInputAssembler(ia); } - public draw (info: DrawInfo): void { + public draw (info: DrawInfo | InputAssembler): void { this._commandBuffer.draw(info); } public updateBuffer (buffer: Buffer, data: ArrayBuffer, size?: number): void { diff --git a/cocos/rendering/custom/web-scene.ts b/cocos/rendering/custom/web-scene.ts index 7a4c6a6150..ea0272151d 100644 --- a/cocos/rendering/custom/web-scene.ts +++ b/cocos/rendering/custom/web-scene.ts @@ -28,7 +28,7 @@ import { RenderScene, scene } from '../../render-scene'; import { Camera, Model, ShadowType, SKYBOX_FLAG } from '../../render-scene/scene'; import { IRenderObject, IRenderPass, UBOShadow } from '../define'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { SceneTask, SceneTransversal, SceneVisitor } from './pipeline'; +import { SceneTask, SceneTransversal, SceneVisitor } from './scene'; import { TaskType } from './types'; import { PipelineUBO } from '../pipeline-ubo'; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 4e9a2c3d98..bf1218beb9 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1410,7 +1410,8 @@ cocos_source_files( cocos/renderer/pipeline/custom/LayoutGraphTypes.h cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp cocos/renderer/pipeline/custom/LayoutGraphUtils.h - cocos/renderer/pipeline/custom/NativeDefaultScene.cpp + cocos/renderer/pipeline/custom/NativeBuiltinUtils.cpp + cocos/renderer/pipeline/custom/NativeBuiltinUtils.h cocos/renderer/pipeline/custom/NativeExecutor.cpp cocos/renderer/pipeline/custom/NativeFactory.cpp cocos/renderer/pipeline/custom/NativeFwd.h @@ -1422,10 +1423,13 @@ cocos_source_files( cocos/renderer/pipeline/custom/NativePools.cpp cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp cocos/renderer/pipeline/custom/NativeRenderGraph.cpp + cocos/renderer/pipeline/custom/NativeRenderGraphUtils.cpp + cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h cocos/renderer/pipeline/custom/NativeRenderQueue.cpp cocos/renderer/pipeline/custom/NativeRenderingModule.cpp cocos/renderer/pipeline/custom/NativeResourceGraph.cpp cocos/renderer/pipeline/custom/NativeSceneCulling.cpp + cocos/renderer/pipeline/custom/NativeSetter.cpp cocos/renderer/pipeline/custom/NativeTypes.cpp cocos/renderer/pipeline/custom/NativeTypes.h cocos/renderer/pipeline/custom/NativeUtils.cpp diff --git a/native/cocos/core/assets/RenderTexture.cpp b/native/cocos/core/assets/RenderTexture.cpp index 79224297f7..564e94cb92 100644 --- a/native/cocos/core/assets/RenderTexture.cpp +++ b/native/cocos/core/assets/RenderTexture.cpp @@ -36,7 +36,7 @@ gfx::RenderPassInfo getDefaultRenderPassInfo(gfx::Device *device) { gfx::RenderPassInfo info; info.colorAttachments.push_back({ gfx::Format::RGBA8, - gfx::SampleCount::ONE, + gfx::SampleCount::X1, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, device->getGeneralBarrier({ diff --git a/native/cocos/renderer/frame-graph/FrameGraph.cpp b/native/cocos/renderer/frame-graph/FrameGraph.cpp index 25b14f79e0..594d16a0c9 100644 --- a/native/cocos/renderer/frame-graph/FrameGraph.cpp +++ b/native/cocos/renderer/frame-graph/FrameGraph.cpp @@ -426,7 +426,7 @@ void FrameGraph::computeStoreActionAndMemoryless() { const gfx::TextureInfo &textureDesc = static_cast *>(renderTarget)->get().getDesc(); renderTarget->_memoryless = renderTarget->_neverLoaded && renderTarget->_neverStored; - renderTarget->_memorylessMSAA = textureDesc.samples != gfx::SampleCount::ONE && renderTarget->_writerCount < 2; + renderTarget->_memorylessMSAA = textureDesc.samples != gfx::SampleCount::X1 && renderTarget->_writerCount < 2; } } diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 204df36faf..7689387fd3 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -383,6 +383,27 @@ void CommandBufferAgent::updateBuffer(Buffer *buff, const void *data, uint32_t s }); } +void CommandBufferAgent::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + Texture *actorSrcTexture = nullptr; + Texture *actorDstTexture = nullptr; + if (srcTexture) actorSrcTexture = static_cast(srcTexture)->getActor(); + if (dstTexture) actorDstTexture = static_cast(dstTexture)->getActor(); + + auto *actorRegions = _messageQueue->allocate(count); + memcpy(actorRegions, regions, count * sizeof(TextureCopy)); + + ENQUEUE_MESSAGE_5( + _messageQueue, CommandBufferBlitTexture, + actor, getActor(), + srcTexture, actorSrcTexture, + dstTexture, actorDstTexture, + regions, actorRegions, + count, count, + { + actor->resolveTexture(srcTexture, dstTexture, regions, count); + }); +} + void CommandBufferAgent::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { Texture *actorSrcTexture = nullptr; Texture *actorDstTexture = nullptr; diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h index 95ddf92a57..b3cf37ff0e 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h @@ -61,6 +61,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index 16fe3f531e..872fb3bf84 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp @@ -455,5 +455,9 @@ void DeviceAgent::frameSync() { }); } +SampleCount DeviceAgent::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + return _actor->getMaxSampleCount(format, usage, flags); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.h b/native/cocos/renderer/gfx-agent/DeviceAgent.h index cbbb969346..ce11e0feb5 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.h +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.h @@ -106,7 +106,7 @@ public: void presentSignal(); void enableAutoBarrier(bool en) override; - + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static DeviceAgent *instance; diff --git a/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp b/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp index 0c54378d08..8b3f019140 100644 --- a/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp @@ -57,6 +57,9 @@ void FramebufferAgent::doInit(const FramebufferInfo &info) { if (info.depthStencilTexture) { actorInfo.depthStencilTexture = static_cast(info.depthStencilTexture)->getActor(); } + if (info.depthStencilResolveTexture) { + actorInfo.depthStencilResolveTexture = static_cast(info.depthStencilResolveTexture)->getActor(); + } actorInfo.renderPass = static_cast(info.renderPass)->getActor(); ENQUEUE_MESSAGE_2( diff --git a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h index c16065c74b..00a6d46e2a 100644 --- a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h +++ b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h @@ -63,6 +63,7 @@ public: virtual void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) = 0; virtual void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) = 0; virtual void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) = 0; + virtual void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) = 0; virtual void execute(CommandBuffer *const *cmdBuffs, uint32_t count) = 0; virtual void dispatch(const DispatchInfo &info) = 0; virtual void beginQuery(QueryPool *queryPool, uint32_t id) = 0; diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 943cc1242c..ab5c7bd810 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -175,9 +175,12 @@ enum class Feature : uint32_t { COMPUTE_SHADER, // @deprecated INPUT_ATTACHMENT_BENEFIT, + SUBPASS_COLOR_INPUT, SUBPASS_DEPTH_STENCIL_INPUT, RASTERIZATION_ORDER_NOCOHERENT, + + MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL, // resolve depth stencil COUNT, }; CC_ENUM_CONVERSION_OPERATOR(Feature); @@ -472,9 +475,10 @@ CC_ENUM_BITWISE_OPERATORS(TextureUsageBit); enum class TextureFlagBit : uint32_t { NONE = 0, GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter - GENERAL_LAYOUT = 0x2, // For inout framebuffer attachments + GENERAL_LAYOUT = 0x2, // @deprecated, For inout framebuffer attachments EXTERNAL_OES = 0x4, // External oes texture EXTERNAL_NORMAL = 0x8, // External normal texture + LAZILY_ALLOCATED = 0x10 // Try lazily allocated mode. }; using TextureFlags = TextureFlagBit; CC_ENUM_BITWISE_OPERATORS(TextureFlagBit); @@ -492,10 +496,13 @@ using FormatFeature = FormatFeatureBit; CC_ENUM_BITWISE_OPERATORS(FormatFeatureBit); enum class SampleCount : uint32_t { - ONE, // Single sample - MULTIPLE_PERFORMANCE, // Multiple samples prioritizing performance over quality - MULTIPLE_BALANCE, // Multiple samples leveraging both quality and performance - MULTIPLE_QUALITY, // Multiple samples prioritizing quality over performance + X1 = 0x01, + X2 = 0x02, + X4 = 0x04, + X8 = 0x08, + X16 = 0x10, + X32 = 0x20, + X64 = 0x40 }; CC_ENUM_CONVERSION_OPERATOR(SampleCount); @@ -1064,7 +1071,7 @@ struct ALIGNAS(8) TextureInfo { TextureFlags flags{TextureFlagBit::NONE}; uint32_t layerCount{1}; uint32_t levelCount{1}; - SampleCount samples{SampleCount::ONE}; + SampleCount samples{SampleCount::X1}; uint32_t depth{1}; void *externalRes{nullptr}; // CVPixelBuffer for Metal, EGLImage for GLES #if CC_CPU_ARCH == CC_CPU_ARCH_32 @@ -1272,7 +1279,7 @@ struct InputAssemblerInfo { struct ALIGNAS(8) ColorAttachment { Format format{Format::UNKNOWN}; - SampleCount sampleCount{SampleCount::ONE}; + SampleCount sampleCount{SampleCount::X1}; LoadOp loadOp{LoadOp::CLEAR}; StoreOp storeOp{StoreOp::STORE}; GeneralBarrier *barrier{nullptr}; @@ -1284,7 +1291,7 @@ using ColorAttachmentList = ccstd::vector; struct ALIGNAS(8) DepthStencilAttachment { Format format{Format::UNKNOWN}; - SampleCount sampleCount{SampleCount::ONE}; + SampleCount sampleCount{SampleCount::X1}; LoadOp depthLoadOp{LoadOp::CLEAR}; StoreOp depthStoreOp{StoreOp::STORE}; LoadOp stencilLoadOp{LoadOp::CLEAR}; @@ -1327,6 +1334,7 @@ using SubpassDependencyList = ccstd::vector; struct RenderPassInfo { ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; + DepthStencilAttachment depthStencilResolveAttachment; SubpassInfoList subpasses; SubpassDependencyList dependencies; @@ -1386,6 +1394,7 @@ struct FramebufferInfo { RenderPass *renderPass{nullptr}; TextureList colorTextures; Texture *depthStencilTexture{nullptr}; // @ts-nullable + Texture *depthStencilResolveTexture{nullptr}; // @ts-nullable EXPOSE_COPY_FN(FramebufferInfo) }; diff --git a/native/cocos/renderer/gfx-base/GFXDef.cpp b/native/cocos/renderer/gfx-base/GFXDef.cpp index c7e35253f4..00a9bc6873 100644 --- a/native/cocos/renderer/gfx-base/GFXDef.cpp +++ b/native/cocos/renderer/gfx-base/GFXDef.cpp @@ -107,6 +107,7 @@ ccstd::hash_t Hasher::operator()(const RenderPassInfo &info) con ccstd::hash_t seed = 4; ccstd::hash_combine(seed, info.colorAttachments); ccstd::hash_combine(seed, info.depthStencilAttachment); + ccstd::hash_combine(seed, info.depthStencilResolveAttachment); ccstd::hash_combine(seed, info.subpasses); ccstd::hash_combine(seed, info.dependencies); return seed; @@ -115,6 +116,7 @@ ccstd::hash_t Hasher::operator()(const RenderPassInfo &info) con bool operator==(const RenderPassInfo &lhs, const RenderPassInfo &rhs) { return lhs.colorAttachments == rhs.colorAttachments && lhs.depthStencilAttachment == rhs.depthStencilAttachment && + lhs.depthStencilResolveAttachment == rhs.depthStencilResolveAttachment && lhs.subpasses == rhs.subpasses && lhs.dependencies == rhs.dependencies; } @@ -122,19 +124,17 @@ bool operator==(const RenderPassInfo &lhs, const RenderPassInfo &rhs) { template <> ccstd::hash_t Hasher::operator()(const FramebufferInfo &info) const { // render pass is mostly irrelevant - ccstd::hash_t seed; + ccstd::hash_t seed = static_cast(info.colorTextures.size()) + + static_cast(info.depthStencilTexture != nullptr) + + static_cast(info.depthStencilResolveTexture != nullptr); if (info.depthStencilTexture) { - seed = (static_cast(info.colorTextures.size()) + 1) * 3 + 1; - ccstd::hash_combine(seed, info.depthStencilTexture); - ccstd::hash_combine(seed, info.depthStencilTexture->getRaw()); - ccstd::hash_combine(seed, info.depthStencilTexture->getHash()); - } else { - seed = static_cast(info.colorTextures.size()) * 3 + 1; + ccstd::hash_combine(seed, info.depthStencilTexture->getObjectID()); + } + if (info.depthStencilResolveTexture) { + ccstd::hash_combine(seed, info.depthStencilResolveTexture->getObjectID()); } for (auto *colorTexture : info.colorTextures) { - ccstd::hash_combine(seed, colorTexture); - ccstd::hash_combine(seed, colorTexture->getRaw()); - ccstd::hash_combine(seed, colorTexture->getHash()); + ccstd::hash_combine(seed, colorTexture->getObjectID()); } ccstd::hash_combine(seed, info.renderPass->getHash()); return seed; @@ -149,6 +149,10 @@ bool operator==(const FramebufferInfo &lhs, const FramebufferInfo &rhs) { res = lhs.depthStencilTexture == rhs.depthStencilTexture; } + if (res) { + res = lhs.depthStencilResolveTexture == rhs.depthStencilResolveTexture; + } + if (res) { for (size_t i = 0; i < lhs.colorTextures.size(); ++i) { res = lhs.colorTextures[i]->getRaw() == rhs.colorTextures[i]->getRaw() && diff --git a/native/cocos/renderer/gfx-base/GFXDevice.cpp b/native/cocos/renderer/gfx-base/GFXDevice.cpp index c8e8805d26..a19e4da519 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.cpp +++ b/native/cocos/renderer/gfx-base/GFXDevice.cpp @@ -154,7 +154,7 @@ DefaultResource::DefaultResource(Device *device) { if (device->getCapabilities().max3DTextureSize >= 2) { _texture3D = device->createTexture({TextureType::TEX3D, TextureUsageBit::STORAGE | TextureUsageBit::SAMPLED | TextureUsageBit::TRANSFER_DST, - Format::RGBA8, 2, 2, TextureFlagBit::NONE, 1, 1, SampleCount::ONE, 2}); + Format::RGBA8, 2, 2, TextureFlagBit::NONE, 1, 1, SampleCount::X1, 2}); BufferTextureCopy region = {0, 0, 0, {0, 0, 0}, {2, 2, 2}, {0, 0, 1}}; device->copyBuffersToTexture(&bufferData, _texture3D, ®ion, 1); } diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index 9ab7df8555..e59e8c5041 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -122,6 +122,12 @@ public: void registerOnAcquireCallback(ExecuteMethod &&execute); virtual void enableAutoBarrier(bool en) { _options.enableBarrierDeduce = en; } + virtual SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + std::ignore = format; + std::ignore = usage; + std::ignore = flags; + return SampleCount::X1; + }; protected: static Device *instance; diff --git a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp index 1fd8b6cce1..dfbdd20430 100644 --- a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp +++ b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp @@ -44,6 +44,7 @@ void Framebuffer::initialize(const FramebufferInfo &info) { _renderPass = info.renderPass; _colorTextures = info.colorTextures; _depthStencilTexture = info.depthStencilTexture; + _depthStencilResolveTexture = info.depthStencilResolveTexture; doInit(info); } @@ -54,6 +55,7 @@ void Framebuffer::destroy() { _renderPass = nullptr; _colorTextures.clear(); _depthStencilTexture = nullptr; + _depthStencilResolveTexture = nullptr; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXFramebuffer.h b/native/cocos/renderer/gfx-base/GFXFramebuffer.h index 01a8b3a925..21125fc160 100644 --- a/native/cocos/renderer/gfx-base/GFXFramebuffer.h +++ b/native/cocos/renderer/gfx-base/GFXFramebuffer.h @@ -45,6 +45,7 @@ public: inline RenderPass *getRenderPass() const { return _renderPass; } inline const TextureList &getColorTextures() const { return _colorTextures; } inline Texture *getDepthStencilTexture() const { return _depthStencilTexture; } + inline Texture *getDepthStencilResolveTexture() const { return _depthStencilResolveTexture; } protected: virtual void doInit(const FramebufferInfo &info) = 0; @@ -56,6 +57,7 @@ protected: TextureList _colorTextures; // weak reference Texture *_depthStencilTexture{nullptr}; + Texture *_depthStencilResolveTexture{nullptr}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp index 7dff13380d..91cb468c24 100644 --- a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp +++ b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp @@ -44,8 +44,8 @@ ccstd::hash_t RenderPass::computeHash() { for (const ColorAttachment &ca : _colorAttachments) { ccstd::hash_combine(seed, ca); } - const auto &ds = _depthStencilAttachment; - ccstd::hash_combine(seed, ds); + ccstd::hash_combine(seed, _depthStencilAttachment); + ccstd::hash_combine(seed, _depthStencilResolveAttachment); ccstd::hash_combine(seed, _subpasses); return seed; @@ -58,6 +58,7 @@ ccstd::hash_t RenderPass::computeHash(const RenderPassInfo &info) { void RenderPass::initialize(const RenderPassInfo &info) { _colorAttachments = info.colorAttachments; _depthStencilAttachment = info.depthStencilAttachment; + _depthStencilResolveAttachment = info.depthStencilResolveAttachment; _subpasses = info.subpasses; _dependencies = info.dependencies; _hash = computeHash(); diff --git a/native/cocos/renderer/gfx-base/GFXRenderPass.h b/native/cocos/renderer/gfx-base/GFXRenderPass.h index 12d606ecf6..f51502c632 100644 --- a/native/cocos/renderer/gfx-base/GFXRenderPass.h +++ b/native/cocos/renderer/gfx-base/GFXRenderPass.h @@ -42,6 +42,7 @@ public: inline const ColorAttachmentList &getColorAttachments() const { return _colorAttachments; } inline const DepthStencilAttachment &getDepthStencilAttachment() const { return _depthStencilAttachment; } + inline const DepthStencilAttachment &getDepthStencilResolveAttachment() const { return _depthStencilResolveAttachment; } inline const SubpassInfoList &getSubpasses() const { return _subpasses; } inline const SubpassDependencyList &getDependencies() const { return _dependencies; } inline ccstd::hash_t getHash() const { return _hash; } @@ -54,6 +55,7 @@ protected: ColorAttachmentList _colorAttachments; DepthStencilAttachment _depthStencilAttachment; + DepthStencilAttachment _depthStencilResolveAttachment; SubpassInfoList _subpasses; SubpassDependencyList _dependencies; ccstd::hash_t _hash = 0; diff --git a/native/cocos/renderer/gfx-base/GFXTexture.cpp b/native/cocos/renderer/gfx-base/GFXTexture.cpp index d8b6a7cde0..0f1a7c2c14 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.cpp +++ b/native/cocos/renderer/gfx-base/GFXTexture.cpp @@ -128,11 +128,11 @@ void Texture::updateTextureInfo(const SwapchainTextureInfo &info, Texture *out) out->_info.layerCount = 1; out->_info.levelCount = 1; out->_info.depth = 1; - out->_info.samples = SampleCount::ONE; + out->_info.samples = SampleCount::X1; out->_info.flags = TextureFlagBit::NONE; - out->_info.usage = GFX_FORMAT_INFOS[toNumber(info.format)].hasDepth + out->_info.usage = TextureUsageBit::SAMPLED | (GFX_FORMAT_INFOS[toNumber(info.format)].hasDepth ? TextureUsageBit::DEPTH_STENCIL_ATTACHMENT - : TextureUsageBit::COLOR_ATTACHMENT; + : TextureUsageBit::COLOR_ATTACHMENT); out->_swapchain = info.swapchain; out->_size = formatSize(info.format, info.width, info.height, 1); out->_hash = computeHash(out); diff --git a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp index 8db04e5f6f..8c2e17a36b 100644 --- a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp @@ -99,6 +99,9 @@ void EmptyCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, c void EmptyCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { } +void EmptyCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { +} + void EmptyCommandBuffer::dispatch(const DispatchInfo &info) { } diff --git a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h index f83d684b09..d429d23f61 100644 --- a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h +++ b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h @@ -52,6 +52,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp index 5ee07a69a7..daaf4efc6e 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp @@ -316,6 +316,10 @@ void GLES2CommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, c // should not copy texture in a secondary command buffer } +void GLES2CommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + // should not copy texture in a secondary command buffer +} + void GLES2CommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) { GLES2CmdBlitTexture *cmd = _cmdAllocator->blitTextureCmdPool.alloc(); if (srcTexture) cmd->gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h index 20e948ecbc..0618586189 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h @@ -64,6 +64,7 @@ public: void updateBuffer(Buffer *buff, const void *data, uint32_t size) override; void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override {} diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp index 2d7b38666f..1d9ca68f44 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp @@ -574,22 +574,13 @@ void cmdFuncGLES2CreateTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) gpuTexture->glFormat = mapGLFormat(gpuTexture->format); gpuTexture->glType = formatToGLType(gpuTexture->format); gpuTexture->glInternalFmt = mapGLInternalFormat(gpuTexture->format); + gpuTexture->glSamples = static_cast(gpuTexture->samples); - if (gpuTexture->samples > SampleCount::ONE) { - if (device->constantRegistry()->mMSRT != MSRTSupportLevel::NONE) { - GLint maxSamples; - glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); - - auto requestedSampleCount = static_cast(gpuTexture->samples); - gpuTexture->glSamples = std::min(maxSamples, requestedSampleCount); - - // skip multi-sampled attachment resources if we can use auto resolve - if (gpuTexture->usage == TextureUsageBit::COLOR_ATTACHMENT) { - gpuTexture->memoryless = true; - return; - } - } else { - gpuTexture->glSamples = 1; // fallback to single sample if the extensions is not available + if (gpuTexture->samples > SampleCount::X1) { + if (device->constantRegistry()->mMSRT != MSRTSupportLevel::NONE && + hasFlag(gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED)) { + gpuTexture->memoryAllocated = false; + return; } } @@ -810,7 +801,7 @@ void cmdFuncGLES2DestroyTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture } void cmdFuncGLES2ResizeTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) { - if (gpuTexture->memoryless || gpuTexture->glTarget == GL_TEXTURE_EXTERNAL_OES) return; + if (!gpuTexture->memoryAllocated || gpuTexture->glTarget == GL_TEXTURE_EXTERNAL_OES) return; if (gpuTexture->glSamples <= 1) { switch (gpuTexture->type) { @@ -3042,6 +3033,12 @@ void cmdFuncGLES2ExecuteCmds(GLES2Device *device, GLES2CmdPackage *cmdPackage) { } } +GLint cmdFuncGLES2GetMaxSampleCount() { + GLint maxSamples = 1; + GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples)); + return maxSamples; +} + void GLES2GPUBlitManager::initialize() { _gpuShader.name = "Blit Pass"; _gpuShader.blocks.push_back({ diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.h b/native/cocos/renderer/gfx-gles2/GLES2Commands.h index e87736708f..670b8e3ae3 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.h @@ -246,5 +246,7 @@ void cmdFuncGLES2BlitTexture(GLES2Device *device, void cmdFuncGLES2ExecuteCmds(GLES2Device *device, GLES2CmdPackage *cmdPackage); +GLint cmdFuncGLES2GetMaxSampleCount(); + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index 77404c2c06..38d0864da4 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -176,6 +176,7 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { } } #endif + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = false; // not implement yet. ccstd::string compressedFmts; if (getFormatFeatures(Format::ETC_RGB8) != FormatFeature::NONE) { @@ -534,5 +535,12 @@ void GLES2Device::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, co cmdFuncGLES2CopyTextureToBuffers(this, static_cast(src)->gpuTexture(), buffers, region, count); } +SampleCount GLES2Device::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + std::ignore = format; + std::ignore = usage; + std::ignore = flags; + return static_cast(cmdFuncGLES2GetMaxSampleCount()); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.h b/native/cocos/renderer/gfx-gles2/GLES2Device.h index 44867f653a..0b7269005f 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.h @@ -95,7 +95,7 @@ public: // check the specified format is texture-exclusive (no renderbuffers allowed) inline bool isTextureExclusive(const Format &format) { return _textureExclusive[static_cast(format)]; }; - + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static GLES2Device *instance; diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h index 31057eec95..99ce522f08 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h @@ -118,10 +118,10 @@ struct GLES2GPUTexture { uint32_t size{0}; uint32_t arrayLayer{1}; uint32_t mipLevel{1}; - SampleCount samples{SampleCount::ONE}; + SampleCount samples{SampleCount::X1}; TextureFlags flags{TextureFlagBit::NONE}; bool isPowerOf2{false}; - bool memoryless{false}; + bool memoryAllocated{true}; // false if swapchain image or implicit ms render buffer. GLenum glTarget{0}; GLenum glInternalFmt{0}; GLenum glFormat{0}; diff --git a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp index 6336745e10..1c3832849a 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp @@ -149,6 +149,10 @@ void GLES2PrimaryCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffe } } +void GLES2PrimaryCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + copyTexture(srcTexture, dstTexture, regions, count); +} + void GLES2PrimaryCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { GLES2GPUTexture *gpuTextureSrc = nullptr; GLES2GPUTexture *gpuTextureDst = nullptr; diff --git a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h index 358b3de968..2a3411c9ee 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h @@ -46,6 +46,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; protected: diff --git a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp index ad127f1557..2656dff1b4 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp @@ -59,7 +59,7 @@ void GLES2Texture::doInit(const TextureInfo & /*info*/) { cmdFuncGLES2CreateTexture(GLES2Device::getInstance(), _gpuTexture); - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES2Device::getInstance()->getMemoryStatus().textureSize += _size; CC_PROFILE_MEMORY_INC(Texture, _size); } @@ -72,7 +72,7 @@ void GLES2Texture::doInit(const TextureViewInfo &info) { void GLES2Texture::doDestroy() { if (_gpuTexture) { if (!_isTextureView) { - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES2Device::getInstance()->getMemoryStatus().textureSize -= _size; CC_PROFILE_MEMORY_DEC(Texture, _size); } @@ -85,7 +85,7 @@ void GLES2Texture::doDestroy() { } void GLES2Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES2Device::getInstance()->getMemoryStatus().textureSize -= _size; CC_PROFILE_MEMORY_DEC(Texture, _size); } @@ -97,7 +97,7 @@ void GLES2Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { GLES2Device::getInstance()->framebufferHub()->update(_gpuTexture); - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES2Device::getInstance()->getMemoryStatus().textureSize += size; CC_PROFILE_MEMORY_INC(Texture, size); } @@ -135,7 +135,7 @@ void GLES2Texture::doInit(const SwapchainTextureInfo & /*info*/) { _gpuTexture->samples = _info.samples; _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; - _gpuTexture->memoryless = true; + _gpuTexture->memoryAllocated = false; _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); } diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp index 6066660b98..706dd795a5 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp @@ -303,6 +303,10 @@ void GLES3CommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, c // should not copy texture in a secondary command buffer } +void GLES3CommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + // should not resolve texture in a secondary command buffer +} + void GLES3CommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) { GLES3CmdBlitTexture *cmd = _cmdAllocator->blitTextureCmdPool.alloc(); if (srcTexture) cmd->gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h index 594a8e059f..d42b50d43b 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h @@ -64,6 +64,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const * /*buffers*/, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const * /*textures*/, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index a4ba060a41..afddfc2d1a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -491,6 +491,18 @@ GLenum formatToGLType(Format format) { } } +GLenum getTextureTarget(TextureType type) { + switch (type) { + case TextureType::TEX2D: return GL_TEXTURE_2D; + case TextureType::TEX2D_ARRAY: return GL_TEXTURE_2D_ARRAY; + case TextureType::TEX3D: return GL_TEXTURE_3D; + case TextureType::CUBE: return GL_TEXTURE_CUBE_MAP; + default: + CC_ABORT(); + return GL_NONE; + } +} + uint32_t glComponentCount(GLenum glType) { switch (glType) { case GL_FLOAT_MAT2: @@ -575,17 +587,6 @@ const GLenum GL_MEMORY_ACCESS[] = { GL_WRITE_ONLY, GL_READ_WRITE, }; - -const GLint GL_SAMPLE_COUNT[] = { - 1, - 2, -#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_IOS - 4, -#else - 8, -#endif - 16, -}; } // namespace void cmdFuncGLES3CreateBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { @@ -800,31 +801,77 @@ void cmdFuncGLES3ResizeBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { } } -void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { - static ccstd::vector supportedSampleCounts; +static void renderBufferStorage(GLES3Device *device, GLES3GPUTexture *gpuTexture) { + CC_ASSERT(gpuTexture->type == TextureType::TEX2D); + GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; + if (gpuTexture->glRenderbuffer != glRenderbuffer) { + GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); + glRenderbuffer = gpuTexture->glRenderbuffer; + } + if (gpuTexture->glSamples > 1) { + GL_CHECK(glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); + } else { + GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); + } +} +static void textureStorage(GLES3Device *device, GLES3GPUTexture *gpuTexture) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(gpuTexture->glTarget, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; + } + uint32_t w = gpuTexture->width; + uint32_t h = gpuTexture->height; + uint32_t d = gpuTexture->type == TextureType::TEX2D_ARRAY ? gpuTexture->arrayLayer : gpuTexture->depth; + + switch (gpuTexture->type) { + case TextureType::CUBE: + CC_ASSERT(gpuTexture->glSamples <= 1); + case TextureType::TEX2D: + if (gpuTexture->glSamples > 1 && !gpuTexture->immutable && device->constantRegistry()->glMinorVersion >= 1) { + gpuTexture->glTarget = GL_TEXTURE_2D_MULTISAMPLE; + GL_CHECK(glTexStorage2DMultisample(gpuTexture->glTarget, gpuTexture->glSamples, gpuTexture->glInternalFmt, w, h, GL_FALSE)); + } else { + GL_CHECK(glTexStorage2D(gpuTexture->glTarget, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); + } + break; + case TextureType::TEX3D: + CC_ASSERT(gpuTexture->glSamples <= 1); + case TextureType::TEX2D_ARRAY: + if (gpuTexture->glSamples > 1 && !gpuTexture->immutable && device->constantRegistry()->glMinorVersion >= 1) { + gpuTexture->glTarget = GL_TEXTURE_2D_MULTISAMPLE_ARRAY; + GL_CHECK(glTexStorage3DMultisample(gpuTexture->glTarget, gpuTexture->glSamples, gpuTexture->glInternalFmt, w, h, d, GL_FALSE)); + } else { + GL_CHECK(glTexStorage3D(gpuTexture->glTarget, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h, d)); + } + break; + default: + break; + } +} + +static bool useRenderBuffer(const GLES3Device *device, Format format, TextureUsage usage) { + return !device->isTextureExclusive(format) && + hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::DEPTH_STENCIL_ATTACHMENT, usage); +} + +void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { gpuTexture->glInternalFmt = mapGLInternalFormat(gpuTexture->format); gpuTexture->glFormat = mapGLFormat(gpuTexture->format); gpuTexture->glType = formatToGLType(gpuTexture->format); - if (gpuTexture->samples > SampleCount::ONE) { - GLint supportedSampleCountCount = 0; - GL_CHECK(glGetInternalformativ(GL_RENDERBUFFER, gpuTexture->glInternalFmt, GL_SAMPLES, 1, &supportedSampleCountCount)); - supportedSampleCounts.resize(supportedSampleCountCount); - GL_CHECK(glGetInternalformativ(GL_RENDERBUFFER, gpuTexture->glInternalFmt, GL_SAMPLES, supportedSampleCountCount, supportedSampleCounts.data())); + bool supportRenderBufferMS = device->constantRegistry()->mMSRT > MSRTSupportLevel::NONE; + gpuTexture->useRenderBuffer = useRenderBuffer(device, gpuTexture->format, gpuTexture->usage) && + (gpuTexture->glSamples <= 1 || supportRenderBufferMS); - auto requestedSampleCount = GL_SAMPLE_COUNT[toNumber(gpuTexture->samples)]; - for (GLint sampleCount : supportedSampleCounts) { - if (sampleCount <= requestedSampleCount) { - gpuTexture->glSamples = sampleCount; - break; - } - } - - // skip multi-sampled attachment resources if we can use auto resolve - if (device->constantRegistry()->mMSRT != MSRTSupportLevel::NONE && - gpuTexture->usage == TextureUsageBit::COLOR_ATTACHMENT) { - gpuTexture->memoryless = true; + if (gpuTexture->glSamples > 1) { + // Allocate render buffer when binding a framebuffer if the MSRT extension is not present. + if (gpuTexture->useRenderBuffer && + hasFlag(gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED)) { + gpuTexture->glTarget = GL_RENDERBUFFER; + gpuTexture->memoryAllocated = false; return; } } @@ -838,97 +885,18 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) return; } - if (!device->isTextureExclusive(gpuTexture->format) && (gpuTexture->glSamples > 1 || hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::DEPTH_STENCIL_ATTACHMENT, gpuTexture->usage))) { - switch (gpuTexture->type) { - case TextureType::TEX2D: { - gpuTexture->glTarget = GL_RENDERBUFFER; - GL_CHECK(glGenRenderbuffers(1, &gpuTexture->glRenderbuffer)); - if (gpuTexture->size > 0) { - GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; - if (gpuTexture->glRenderbuffer != glRenderbuffer) { - GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); - glRenderbuffer = gpuTexture->glRenderbuffer; - } - if (gpuTexture->glSamples > 1) { - GL_CHECK(glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); - } else { - GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); - } - } - break; - } - default: - CC_ABORT(); - break; - } + if (gpuTexture->size == 0) { + return; + } + + if (gpuTexture->useRenderBuffer) { + gpuTexture->glTarget = GL_RENDERBUFFER; + GL_CHECK(glGenRenderbuffers(1, &gpuTexture->glRenderbuffer)); + renderBufferStorage(device, gpuTexture); } else { - switch (gpuTexture->type) { - case TextureType::TEX2D: { - gpuTexture->glTarget = GL_TEXTURE_2D; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint32_t w = gpuTexture->width; - uint32_t h = gpuTexture->height; - GL_CHECK(glTexStorage2D(GL_TEXTURE_2D, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); - } - break; - } - case TextureType::TEX2D_ARRAY: { - gpuTexture->glTarget = GL_TEXTURE_2D_ARRAY; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_2D_ARRAY, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint32_t w = gpuTexture->width; - uint32_t h = gpuTexture->height; - uint32_t d = gpuTexture->arrayLayer; - GL_CHECK(glTexStorage3D(GL_TEXTURE_2D_ARRAY, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h, d)); - } - break; - } - case TextureType::TEX3D: { - gpuTexture->glTarget = GL_TEXTURE_3D; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_3D, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint32_t w = gpuTexture->width; - uint32_t h = gpuTexture->height; - uint32_t d = gpuTexture->depth; - GL_CHECK(glTexStorage3D(GL_TEXTURE_3D, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h, d)); - } - break; - } - case TextureType::CUBE: { - gpuTexture->glTarget = GL_TEXTURE_CUBE_MAP; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint32_t w = gpuTexture->width; - uint32_t h = gpuTexture->height; - GL_CHECK(glTexStorage2D(GL_TEXTURE_CUBE_MAP, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); - } - break; - } - default: - CC_ABORT(); - break; - } + gpuTexture->glTarget = getTextureTarget(gpuTexture->type); + GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); + textureStorage(device, gpuTexture); } } @@ -957,36 +925,18 @@ void cmdFuncGLES3DestroyTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture } void cmdFuncGLES3ResizeTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { - if (gpuTexture->memoryless || hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_OES) || + if (!gpuTexture->memoryAllocated || + hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_OES) || hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_NORMAL)) { return; } - if (gpuTexture->glSamples <= 1) { + if (!gpuTexture->useRenderBuffer) { // immutable by default cmdFuncGLES3DestroyTexture(device, gpuTexture); cmdFuncGLES3CreateTexture(device, gpuTexture); - } else { - switch (gpuTexture->type) { - case TextureType::TEX2D: { - if (gpuTexture->size > 0) { - GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; - if (gpuTexture->glRenderbuffer != glRenderbuffer) { - GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); - glRenderbuffer = gpuTexture->glRenderbuffer; - } - if (gpuTexture->glSamples > 1) { - GL_CHECK(glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); - } else { - GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); - } - } - break; - } - default: - CC_ABORT(); - break; - } + } else if (gpuTexture->size > 0){ + renderBufferStorage(device, gpuTexture); } } @@ -1450,6 +1400,10 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * } for (auto &resolve : sub.resolves) { + if (resolve == INVALID_BINDING) { + gpuRenderPass->resolves.emplace_back(resolve); + continue; + } auto &index = gpuRenderPass->indices[resolve]; if (index == INVALID_BINDING) { index = static_cast(gpuRenderPass->resolves.size()); @@ -1458,6 +1412,7 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * } gpuRenderPass->depthStencil = sub.depthStencil; + gpuRenderPass->depthStencilResolve = sub.depthStencilResolve; } } @@ -1514,187 +1469,168 @@ void cmdFuncGLES3DestroyInputAssembler(GLES3Device *device, GLES3GPUInputAssembl gpuInputAssembler->glVAOs.clear(); } -static GLES3GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES3Device *device, - const ccstd::vector &attachments, const uint32_t *colors, size_t colorCount, - const GLES3GPUTextureView *depthStencilView, - const uint32_t *resolves = nullptr, - const GLES3GPUTextureView *depthStencilResolveView = nullptr, - GLbitfield *resolveMask = nullptr) { - static ccstd::vector drawBuffers; - GLES3GPUStateCache *cache = device->stateCache(); - GLES3GPUFramebuffer::GLFramebufferInfo res; - - GL_CHECK(glGenFramebuffers(1, &res.glFramebuffer)); - if (cache->glDrawFramebuffer != res.glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, res.glFramebuffer)); - cache->glDrawFramebuffer = res.glFramebuffer; - } - - drawBuffers.clear(); - - auto supportLevel = device->constantRegistry()->mMSRT; - bool autoResolve = supportLevel > MSRTSupportLevel::LEVEL1 || (supportLevel != MSRTSupportLevel::NONE && colorCount <= 1); - - for (size_t j = 0; j < colorCount; ++j) { - GLES3GPUTextureView *gpuColorTextureView = attachments[colors[j]]; - GLES3GPUTextureView *gpuResolveTextureView = resolves ? attachments[resolves[j]] : nullptr; - GLES3GPUTexture *gpuColorTexture = gpuColorTextureView->gpuTexture; - GLES3GPUTexture *gpuResolveTexture = resolves ? gpuResolveTextureView->gpuTexture : nullptr; - - drawBuffers.push_back(static_cast(GL_COLOR_ATTACHMENT0 + j)); - - if (gpuResolveTexture) { - if (autoResolve) { - GL_CHECK(glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), - gpuResolveTexture->glTarget, gpuResolveTexture->glTexture, - gpuResolveTextureView->baseLevel, gpuColorTexture->glSamples)); - continue; - } - *resolveMask |= GL_COLOR_BUFFER_BIT; // fallback to blit-based manual resolve - } - if (gpuColorTexture) { - if (gpuColorTexture->glTexture) { - GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), - gpuColorTexture->glTarget, gpuColorTexture->glTexture, gpuColorTextureView->baseLevel)); - } else { - GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), - gpuColorTexture->glTarget, gpuColorTexture->glRenderbuffer)); - } - } - res.width = std::min(res.width, gpuColorTexture->width); - res.height = std::min(res.height, gpuColorTexture->height); - } - - GLES3GPUTexture *depthStencil = depthStencilView ? depthStencilView->gpuTexture : nullptr; - GLES3GPUTexture *depthStencilResolve = depthStencilResolveView ? depthStencilResolveView->gpuTexture : nullptr; - if (depthStencil) { - bool hasStencil = GFX_FORMAT_INFOS[static_cast(depthStencil->format)].hasStencil; - GLenum glAttachment = hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT; - if (depthStencil->glTexture) { - GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, glAttachment, depthStencil->glTarget, depthStencil->glTexture, depthStencilView->baseLevel)); - } else if (depthStencil->glRenderbuffer) { - GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, glAttachment, depthStencil->glTarget, depthStencil->glRenderbuffer)); - } - - // fallback to blit-based manual resolve - if (depthStencilResolve) *resolveMask |= hasStencil ? GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT : GL_DEPTH_BUFFER_BIT; - res.width = std::min(res.width, depthStencil->width >> depthStencilView->baseLevel); - res.height = std::min(res.height, depthStencil->height >> depthStencilView->baseLevel); - } - - // register to framebuffer caches - if (colorCount == 1) device->framebufferCacheMap()->registerExternal(res.glFramebuffer, attachments[colors[0]]->gpuTexture, 0); - if (depthStencil) device->framebufferCacheMap()->registerExternal(res.glFramebuffer, depthStencilView->gpuTexture, 0); - - GL_CHECK(glDrawBuffers(utils::toUint(drawBuffers.size()), drawBuffers.data())); - - GLenum status; - GL_CHECK(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); - if (status != GL_FRAMEBUFFER_COMPLETE) { - switch (status) { - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); - break; - default: - CC_LOG_ERROR("checkFramebufferStatus() - %x", status); - break; - } - } - - return res; -} - static GLES3GPUSwapchain *getSwapchainIfExists(const ccstd::vector &textureViews, const uint32_t *indices, size_t count) { GLES3GPUSwapchain *swapchain{nullptr}; if (indices) { - size_t offscreenCount{0}; for (size_t i = 0; i < count; ++i) { + if (indices[i] == INVALID_BINDING) { + continue; + } auto *colorTexture = textureViews[indices[i]]->gpuTexture; if (colorTexture->swapchain) { swapchain = colorTexture->swapchain; - } else { - ++offscreenCount; } } - CC_ASSERT(!offscreenCount || offscreenCount == count); } return swapchain; } -static void doCreateFramebufferInstance(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO, const ccstd::vector &colors, - uint32_t depthStencil, GLES3GPUFramebuffer::Framebuffer *outFBO, - const uint32_t *resolves = nullptr, uint32_t depthStencilResolve = INVALID_BINDING) { - GLES3GPUSwapchain *swapchain{getSwapchainIfExists(gpuFBO->gpuColorViews, colors.data(), colors.size())}; - if (!swapchain) { - const GLES3GPUTextureView *depthStencilTextureView = nullptr; - if (depthStencil != INVALID_BINDING) { - depthStencilTextureView = depthStencil < gpuFBO->gpuColorViews.size() - ? gpuFBO->gpuColorViews[depthStencil] - : gpuFBO->gpuDepthStencilView; - } - const GLES3GPUTextureView *depthStencilResolveTextureView = nullptr; - if (depthStencilResolve != INVALID_BINDING) { - depthStencilResolveTextureView = depthStencilResolve < gpuFBO->gpuColorViews.size() - ? gpuFBO->gpuColorViews[depthStencilResolve] - : gpuFBO->gpuDepthStencilView; - } - - outFBO->framebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorViews, colors.data(), utils::toUint(colors.size()), - depthStencilTextureView, resolves, depthStencilResolveTextureView, &outFBO->resolveMask)); - if (outFBO->resolveMask) { - size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? utils::toUint(colors.size()) : 0U; - GLES3GPUSwapchain *resolveSwapchain{getSwapchainIfExists(gpuFBO->gpuColorViews, resolves, resolveCount)}; - if (!resolveSwapchain) { - outFBO->resolveFramebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorViews, resolves, resolveCount, depthStencilResolveTextureView)); - } else { - outFBO->resolveFramebuffer.initialize(resolveSwapchain); - } - } +static GLbitfield getColorBufferMask(Format format) { + GLbitfield mask = 0U; + const FormatInfo &info = GFX_FORMAT_INFOS[toNumber(format)]; + if (info.hasDepth || info.hasStencil) { + if (info.hasDepth) mask |= GL_DEPTH_BUFFER_BIT; + if (info.hasStencil) mask |= GL_STENCIL_BUFFER_BIT; } else { - outFBO->framebuffer.initialize(swapchain); + mask = GL_COLOR_BUFFER_BIT; } + return mask; +} + +static void doResolve(GLES3Device *device, GLES3GPUFramebuffer *gpuFbo) { + device->context()->makeCurrent(gpuFbo->resolveFramebuffer.swapchain, gpuFbo->framebuffer.swapchain); + auto *cache = device->stateCache(); + auto width = gpuFbo->width; + auto height = gpuFbo->height; + + if (cache->glReadFramebuffer != gpuFbo->framebuffer.handle) { + GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, gpuFbo->framebuffer.handle)); + cache->glReadFramebuffer = gpuFbo->framebuffer.handle; + } + + if (cache->glDrawFramebuffer != gpuFbo->resolveFramebuffer.handle) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, gpuFbo->resolveFramebuffer.handle)); + cache->glDrawFramebuffer = gpuFbo->resolveFramebuffer.handle; + } + + gpuFbo->resolveFramebuffer.processLoad(GL_DRAW_FRAMEBUFFER); + + if (!gpuFbo->colorBlitPairs.empty()) { + auto resolveColorNum = gpuFbo->resolveFramebuffer.colors.size(); + std::vector drawBuffers(resolveColorNum, GL_NONE); + for (auto &[src, dst] : gpuFbo->colorBlitPairs) { + drawBuffers[dst] = GL_COLOR_ATTACHMENT0 + dst; + GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0 + src)); + if (gpuFbo->resolveFramebuffer.handle != 0) { + GL_CHECK(glDrawBuffers(resolveColorNum, drawBuffers.data())); + } + + GL_CHECK(glBlitFramebuffer( + 0, 0, width, height, + 0, 0, width, height, + GL_COLOR_BUFFER_BIT, GL_NEAREST)); + drawBuffers[dst] = GL_NONE; + } + } + if (gpuFbo->dsResolveMask != 0 && gpuFbo->resolveFramebuffer.handle != 0) { + GL_CHECK(glBlitFramebuffer( + 0, 0, width, height, + 0, 0, width, height, + gpuFbo->dsResolveMask, GL_NEAREST)); + } + + gpuFbo->framebuffer.processStore(GL_READ_FRAMEBUFFER); + gpuFbo->resolveFramebuffer.processStore(GL_DRAW_FRAMEBUFFER); } void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { - const auto &colors = gpuFBO->gpuRenderPass->colors; - const auto &resolves = gpuFBO->gpuRenderPass->resolves; - const auto &depthStencil = gpuFBO->gpuRenderPass->depthStencil; + const auto *renderPass = gpuFBO->gpuRenderPass; + const auto &colors = renderPass->colors; + const auto &resolves = renderPass->resolves; + const auto &indices = renderPass->indices; + const auto depthStencil = renderPass->depthStencil; + const auto depthStencilResolve = renderPass->depthStencilResolve; - doCreateFramebufferInstance(device, gpuFBO, colors, depthStencil, &gpuFBO->frameBuffer, resolves.empty() ? nullptr : resolves.data()); -} + gpuFBO->framebuffer.initialize(getSwapchainIfExists(gpuFBO->gpuColorViews, colors.data(), colors.size())); + gpuFBO->resolveFramebuffer.initialize(getSwapchainIfExists(gpuFBO->gpuColorViews, resolves.data(), resolves.size())); -void GLES3GPUFramebuffer::GLFramebuffer::destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap) { - if (swapchain) { - swapchain = nullptr; - } else { - if (cache->glDrawFramebuffer == _glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); - cache->glDrawFramebuffer = 0; + auto supportLevel = device->constantRegistry()->mMSRT; + /* + * LEVEL0 does ont support on-chip resolve + * LEVEL1 only support COLOR_ATTACHMENT0 + * LEVEL2 support COLOR_ATTACHMENT(i) + DEPTH_STENCIL + */ + uint32_t supportCount = supportLevel > MSRTSupportLevel::LEVEL1 ? 255 : static_cast(supportLevel); + constexpr bool useDsResolve = true; + + uint32_t resolveColorIndex = 0; + for (uint32_t i = 0; i < colors.size(); ++i) { + const auto &attachmentIndex = colors[i]; + const auto &colorIndex = indices[attachmentIndex]; + const auto &resolveIndex = resolves.empty() ? INVALID_BINDING : resolves[attachmentIndex]; + + const auto &desc = renderPass->colorAttachments[attachmentIndex]; + const auto *view = gpuFBO->gpuColorViews[attachmentIndex]; + CC_ASSERT(view != nullptr); + + // need to resolve + if (view->gpuTexture->glSamples > 1 && resolveIndex != INVALID_BINDING) { + const auto &resolveDesc = renderPass->colorAttachments[resolveIndex]; + const auto *resolveView = gpuFBO->gpuColorViews[resolveIndex]; + CC_ASSERT(resolveView != nullptr); + bool lazilyAllocated = hasFlag(view->gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED); + + if (lazilyAllocated && // MS attachment should be memoryless + resolveView->gpuTexture->swapchain == nullptr && // not back buffer + i < supportCount) { // extension limit + gpuFBO->framebuffer.bindColorMultiSample(resolveView, colorIndex, view->gpuTexture->glSamples, resolveDesc); + } else { + // implicit MS not supported, fallback to MS Renderbuffer + gpuFBO->colorBlitPairs.emplace_back(colorIndex, resolveColorIndex); + gpuFBO->framebuffer.bindColor(view, colorIndex, desc); + gpuFBO->resolveFramebuffer.bindColor(resolveView, resolveColorIndex++, resolveDesc); + } + continue; } - GL_CHECK(glDeleteFramebuffers(1, &_glFramebuffer)); - framebufferCacheMap->unregisterExternal(_glFramebuffer); - _glFramebuffer = 0U; + gpuFBO->framebuffer.bindColor(view, colorIndex, desc); } + + if (depthStencil != INVALID_BINDING) { + const auto &desc = renderPass->depthStencilAttachment; + const auto *view = gpuFBO->gpuDepthStencilView; + CC_ASSERT(view != nullptr); + + if (view->gpuTexture->glSamples > 1 && depthStencilResolve != INVALID_BINDING) { + const auto &resolveDesc = renderPass->depthStencilResolveAttachment; + const auto *resolveView = gpuFBO->gpuDepthStencilResolveView; + bool lazilyAllocated = hasFlag(view->gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED); + + if (lazilyAllocated && // MS attachment should be memoryless + resolveView->gpuTexture->swapchain == nullptr && // not back buffer + supportCount > 1 && // extension limit + useDsResolve) { // enable ds resolve + gpuFBO->framebuffer.bindDepthStencilMultiSample(resolveView, view->gpuTexture->glSamples, resolveDesc); + } else { + // implicit MS not supported, fallback to MS Renderbuffer + gpuFBO->dsResolveMask = getColorBufferMask(desc.format); + gpuFBO->framebuffer.bindDepthStencil(view, desc); + gpuFBO->resolveFramebuffer.bindDepthStencil(resolveView, resolveDesc); + } + } else { + gpuFBO->framebuffer.bindDepthStencil(view, desc); + } + } + + gpuFBO->framebuffer.finalize(device->stateCache()); + gpuFBO->resolveFramebuffer.finalize(device->stateCache()); } void cmdFuncGLES3DestroyFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { auto *cache = device->stateCache(); auto *framebufferCacheMap = device->framebufferCacheMap(); - gpuFBO->frameBuffer.framebuffer.destroy(cache, framebufferCacheMap); - gpuFBO->frameBuffer.resolveFramebuffer.destroy(cache, framebufferCacheMap); + gpuFBO->framebuffer.destroy(cache, framebufferCacheMap); + gpuFBO->resolveFramebuffer.destroy(cache, framebufferCacheMap); } void completeBarrier(GLES3GPUGeneralBarrier *barrier) { @@ -1856,7 +1792,6 @@ void cmdFuncGLES3Query(GLES3Device * /*device*/, GLES3QueryPool *queryPool, GLES void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRenderPass, GLES3GPUFramebuffer *gpuFramebuffer, const Rect *renderArea, const Color *clearColors, float clearDepth, uint32_t clearStencil) { - ccstd::vector invalidAttachments; GLES3GPUStateCache *cache = device->stateCache(); GLES3ObjectCache &gfxStateCache = cache->gfxStateCache; gfxStateCache.subpassIdx = 0; @@ -1868,14 +1803,18 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen gfxStateCache.clearStencil = clearStencil; if (gpuFramebuffer && gpuRenderPass) { - auto &instance = gpuFramebuffer->frameBuffer; + auto &framebuffer = gpuFramebuffer->framebuffer; + auto &resolveFramebuffer = gpuFramebuffer->resolveFramebuffer; + if (gpuFramebuffer->resolveFramebuffer.isActive()) { + device->context()->makeCurrent(resolveFramebuffer.swapchain, framebuffer.swapchain); + } else { + device->context()->makeCurrent(framebuffer.swapchain); + } - GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); - device->context()->makeCurrent(instance.framebuffer.swapchain, instance.framebuffer.swapchain); - if (cache->glDrawFramebuffer != glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glFramebuffer)); - cache->glDrawFramebuffer = glFramebuffer; + if (cache->glDrawFramebuffer != framebuffer.handle) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer.handle)); + cache->glDrawFramebuffer = framebuffer.handle; } if (cache->viewport.left != renderArea->x || @@ -1895,38 +1834,27 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen } GLbitfield glClears = 0; - invalidAttachments.clear(); - float fColors[4]{}; bool maskSet = false; auto performLoadOp = [&](uint32_t attachmentIndex, uint32_t glAttachmentIndex) { const ColorAttachment &colorAttachment = gpuRenderPass->colorAttachments[attachmentIndex]; - if (colorAttachment.format != Format::UNKNOWN) { - switch (colorAttachment.loadOp) { - case LoadOp::LOAD: break; // GL default behaviour - case LoadOp::CLEAR: { - if (!maskSet && cache->bs.targets[0].blendColorMask != ColorMask::ALL) { - GL_CHECK(glColorMask(true, true, true, true)); - maskSet = true; - } + if (colorAttachment.format != Format::UNKNOWN && colorAttachment.loadOp == LoadOp::CLEAR) { + if (!maskSet && cache->bs.targets[0].blendColorMask != ColorMask::ALL) { + GL_CHECK(glColorMask(true, true, true, true)); + maskSet = true; + } - const Color &color = clearColors[attachmentIndex]; - if (glFramebuffer) { - fColors[0] = color.x; - fColors[1] = color.y; - fColors[2] = color.z; - fColors[3] = color.w; - GL_CHECK(glClearBufferfv(GL_COLOR, glAttachmentIndex, fColors)); - } else { - GL_CHECK(glClearColor(color.x, color.y, color.z, color.w)); - glClears |= GL_COLOR_BUFFER_BIT; - } - } break; - case LoadOp::DISCARD: - // invalidate fbo - invalidAttachments.push_back(glFramebuffer ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); - break; + const Color &color = clearColors[attachmentIndex]; + if (framebuffer.handle) { + fColors[0] = color.x; + fColors[1] = color.y; + fColors[2] = color.z; + fColors[3] = color.w; + GL_CHECK(glClearBufferfv(GL_COLOR, glAttachmentIndex, fColors)); + } else { + GL_CHECK(glClearColor(color.x, color.y, color.z, color.w)); + glClears |= GL_COLOR_BUFFER_BIT; } } }; @@ -1940,41 +1868,23 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen depthLoadOp = stencilLoadOp = gpuRenderPass->colorAttachments[attachmentIndex].loadOp; hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; } - switch (gpuRenderPass->depthStencilAttachment.depthLoadOp) { - case LoadOp::LOAD: break; // GL default behaviour - case LoadOp::CLEAR: - if (!cache->dss.depthWrite) { - GL_CHECK(glDepthMask(true)); - } - GL_CHECK(glClearDepthf(clearDepth)); - glClears |= GL_DEPTH_BUFFER_BIT; - break; - case LoadOp::DISCARD: - invalidAttachments.push_back(glFramebuffer ? GL_DEPTH_ATTACHMENT : GL_DEPTH); - break; - } - if (hasStencils) { - switch (gpuRenderPass->depthStencilAttachment.depthLoadOp) { - case LoadOp::LOAD: break; // GL default behaviour - case LoadOp::CLEAR: { - if (!cache->dss.stencilWriteMaskFront) { - GL_CHECK(glStencilMaskSeparate(GL_FRONT, 0xffffffff)); - } - if (!cache->dss.stencilWriteMaskBack) { - GL_CHECK(glStencilMaskSeparate(GL_BACK, 0xffffffff)); - } - GL_CHECK(glClearStencil(clearStencil)); - glClears |= GL_STENCIL_BUFFER_BIT; - } break; - case LoadOp::DISCARD: - invalidAttachments.push_back(glFramebuffer ? GL_STENCIL_ATTACHMENT : GL_STENCIL); - break; + if (gpuRenderPass->depthStencilAttachment.depthLoadOp == LoadOp::CLEAR) { + if (!cache->dss.depthWrite) { + GL_CHECK(glDepthMask(true)); } + GL_CHECK(glClearDepthf(clearDepth)); + glClears |= GL_DEPTH_BUFFER_BIT; + } + if (hasStencils && gpuRenderPass->depthStencilAttachment.depthLoadOp == LoadOp::CLEAR) { + if (!cache->dss.stencilWriteMaskFront) { + GL_CHECK(glStencilMaskSeparate(GL_FRONT, 0xffffffff)); + } + if (!cache->dss.stencilWriteMaskBack) { + GL_CHECK(glStencilMaskSeparate(GL_BACK, 0xffffffff)); + } + GL_CHECK(glClearStencil(clearStencil)); + glClears |= GL_STENCIL_BUFFER_BIT; } - } - - if (!invalidAttachments.empty()) { - GL_CHECK(glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, utils::toUint(invalidAttachments.size()), invalidAttachments.data())); } if (glClears) { @@ -2010,6 +1920,8 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen performLoadOp(i, indices[i]); } performDepthStencilLoadOp(gpuRenderPass->depthStencil); + + framebuffer.processLoad(GL_DRAW_FRAMEBUFFER); } } @@ -2031,113 +1943,14 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { GLES3GPUStateCache *cache = device->stateCache(); GLES3ObjectCache &gfxStateCache = cache->gfxStateCache; - GLES3GPURenderPass *gpuRenderPass = gfxStateCache.gpuRenderPass; GLES3GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; - const auto &instance = gpuFramebuffer->frameBuffer; - const SubpassInfo &subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; - GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); - GLuint glResolveFramebuffer = instance.resolveFramebuffer.getFramebuffer(); - GLenum invalidateTarget = GL_DRAW_FRAMEBUFFER; - - auto performStoreOp = [&](uint32_t attachmentIndex, uint32_t glAttachmentIndex) { - const ColorAttachment &colorAttachment = gpuRenderPass->colorAttachments[attachmentIndex]; - if (colorAttachment.format != Format::UNKNOWN) { - switch (colorAttachment.storeOp) { - case StoreOp::STORE: break; - case StoreOp::DISCARD: - // invalidate fbo - invalidAttachments.push_back(glFramebuffer ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); - break; - } - } - }; - - auto performDepthStencilStoreOp = [&](uint32_t attachmentIndex) { - if (attachmentIndex != INVALID_BINDING) { - StoreOp depthStoreOp = gpuRenderPass->depthStencilAttachment.depthStoreOp; - StoreOp stencilStoreOp = gpuRenderPass->depthStencilAttachment.stencilStoreOp; - bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; - if (attachmentIndex < gpuRenderPass->colorAttachments.size()) { - depthStoreOp = stencilStoreOp = gpuRenderPass->colorAttachments[attachmentIndex].storeOp; - hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; - } - - switch (gpuRenderPass->depthStencilAttachment.depthStoreOp) { - case StoreOp::STORE: break; - case StoreOp::DISCARD: - invalidAttachments.push_back(glFramebuffer ? GL_DEPTH_ATTACHMENT : GL_DEPTH); - break; - } - if (hasStencils) { - switch (gpuRenderPass->depthStencilAttachment.stencilStoreOp) { - case StoreOp::STORE: break; - case StoreOp::DISCARD: - invalidAttachments.push_back(glFramebuffer ? GL_STENCIL_ATTACHMENT : GL_STENCIL); - break; - } - } - } - - if (!invalidAttachments.empty()) { - GL_CHECK(glInvalidateFramebuffer(invalidateTarget, utils::toUint(invalidAttachments.size()), invalidAttachments.data())); - } - }; - - if (instance.resolveMask) { - device->context()->makeCurrent(instance.resolveFramebuffer.swapchain, instance.framebuffer.swapchain); - - if (cache->glReadFramebuffer != glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, glFramebuffer)); - cache->glReadFramebuffer = glFramebuffer; - } - - if (cache->glDrawFramebuffer != glResolveFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glResolveFramebuffer)); - cache->glDrawFramebuffer = glResolveFramebuffer; - } - - if (instance.resolveMask & GL_COLOR_BUFFER_BIT) { - for (uint32_t i = 0; i < subpass.colors.size(); ++i) { - auto attachment = static_cast(GL_COLOR_ATTACHMENT0 + i); - GL_CHECK(glReadBuffer(attachment)); - GL_CHECK(glDrawBuffers(1, &attachment)); - - GLES3GPUTexture *srcTex = gpuFramebuffer->gpuColorViews[subpass.colors[i]]->gpuTexture; - GLES3GPUTexture *dstTex = gpuFramebuffer->gpuColorViews[subpass.resolves[i]]->gpuTexture; - - ensureScissorRect(cache, 0, 0, dstTex->width, dstTex->height); - GL_CHECK(glBlitFramebuffer( - 0, 0, srcTex->width, srcTex->height, - 0, 0, dstTex->width, dstTex->height, - GL_COLOR_BUFFER_BIT, GL_NEAREST)); - } - } - - if (instance.resolveMask & GL_DEPTH_BUFFER_BIT) { - GLES3GPUTexture *srcTex = subpass.depthStencil < gpuFramebuffer->gpuColorViews.size() - ? gpuFramebuffer->gpuColorViews[subpass.depthStencil]->gpuTexture - : gpuFramebuffer->gpuDepthStencilView->gpuTexture; - GLES3GPUTexture *dstTex = subpass.depthStencilResolve < gpuFramebuffer->gpuColorViews.size() - ? gpuFramebuffer->gpuColorViews[subpass.depthStencilResolve]->gpuTexture - : gpuFramebuffer->gpuDepthStencilView->gpuTexture; - - ensureScissorRect(cache, 0, 0, dstTex->width, dstTex->height); - GL_CHECK(glBlitFramebuffer( - 0, 0, srcTex->width, srcTex->height, - 0, 0, dstTex->width, dstTex->height, - instance.resolveMask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT), GL_NEAREST)); - } - - invalidateTarget = GL_READ_FRAMEBUFFER; + if (gpuFramebuffer->resolveFramebuffer.isActive()) { + doResolve(device, gpuFramebuffer); + } else { + gpuFramebuffer->framebuffer.processStore(GL_DRAW_FRAMEBUFFER); } - const auto &attachments = gpuRenderPass->colorAttachments; - const auto &indices = gpuRenderPass->indices; - for (uint32_t i = 0; i < attachments.size(); ++i) { - performStoreOp(i, indices[i]); - } - performDepthStencilStoreOp(gpuRenderPass->depthStencil); // if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_EXT) { // GL_CHECK(glFramebufferFetchBarrierEXT()); // } else if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { @@ -2362,6 +2175,10 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli const GLES3GPUUniformBuffer &glBuffer = gpuPipelineState->gpuShader->glBuffers[j]; const GLES3GPUDescriptorSet *gpuDescriptorSet = gpuDescriptorSets[glBuffer.set]; + if (gpuDescriptorSet == nullptr) { + continue; + } + const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glBuffer.binding); const GLES3GPUDescriptor &gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; @@ -2817,7 +2634,7 @@ uint8_t *funcGLES3PixelBufferPick(const uint8_t *buffer, Format format, uint32_t } void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const *buffers, GLES3GPUTexture *gpuTexture, const BufferTextureCopy *regions, uint32_t count) { - if (gpuTexture->memoryless) return; + if (!gpuTexture->memoryAllocated) return; GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; if (glTexture != gpuTexture->glTexture) { @@ -3065,15 +2882,7 @@ void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTexture *gpuTextureSrc const TextureBlit *regions, uint32_t count, Filter filter) { GLES3GPUStateCache *cache = device->stateCache(); - GLbitfield mask = 0U; - const FormatInfo &info = GFX_FORMAT_INFOS[toNumber(gpuTextureSrc->format)]; - if (info.hasDepth || info.hasStencil) { - if (info.hasDepth) mask |= GL_DEPTH_BUFFER_BIT; - if (info.hasStencil) mask |= GL_STENCIL_BUFFER_BIT; - } else { - mask = GL_COLOR_BUFFER_BIT; - } - + GLbitfield mask = getColorBufferMask(gpuTextureSrc->format); for (uint32_t i = 0U; i < count; ++i) { const TextureBlit ®ion = regions[i]; @@ -3184,6 +2993,180 @@ void cmdFuncGLES3ExecuteCmds(GLES3Device *device, GLES3CmdPackage *cmdPackage) { } } +void GLES3GPUFramebufferObject::initialize(GLES3GPUSwapchain *swc) { + swapchain = swc; +} + +void GLES3GPUFramebufferObject::bindColor(const GLES3GPUTextureView *texture, uint32_t colorIndex, const ColorAttachment &attachment) { + bindColorMultiSample(texture, colorIndex, 1, attachment); +} + +void GLES3GPUFramebufferObject::bindColorMultiSample(const GLES3GPUTextureView *texture, uint32_t colorIndex, GLint samples, const ColorAttachment &attachment) { + if (colorIndex >= colors.size()) { + colors.resize(colorIndex + 1); + } + bool isDefaultFb = swapchain != nullptr; + + if (attachment.loadOp == LoadOp::DISCARD) { + loadInvalidates.emplace_back(isDefaultFb ? GL_COLOR : GL_COLOR_ATTACHMENT0 + colorIndex); + } + if (attachment.storeOp == StoreOp::DISCARD) { + storeInvalidates.emplace_back(isDefaultFb ? GL_COLOR : GL_COLOR_ATTACHMENT0 + colorIndex); + } + colors[colorIndex] = {texture, samples}; +} + +void GLES3GPUFramebufferObject::bindDepthStencil(const GLES3GPUTextureView *texture, const DepthStencilAttachment &attachment) { + bindDepthStencilMultiSample(texture, 1, attachment); +} + +void GLES3GPUFramebufferObject::bindDepthStencilMultiSample(const GLES3GPUTextureView *texture, GLint samples, const DepthStencilAttachment &attachment) { + const FormatInfo &info = GFX_FORMAT_INFOS[toNumber(texture->gpuTexture->format)]; + + bool isDefaultFb = swapchain != nullptr; + bool hasDepth = info.hasDepth; + bool hasStencil = info.hasStencil; + + dsAttachment = hasDepth && hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : + hasDepth ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT; + + if (hasDepth) { + auto att = isDefaultFb ? GL_DEPTH : GL_DEPTH_ATTACHMENT; + if (attachment.depthLoadOp == LoadOp::DISCARD) { + loadInvalidates.emplace_back(att); + } + if (attachment.depthStoreOp == StoreOp::DISCARD) { + storeInvalidates.emplace_back(att); + } + } + if (hasStencil) { + auto att = isDefaultFb ? GL_STENCIL : GL_STENCIL_ATTACHMENT; + if (attachment.stencilLoadOp == LoadOp::DISCARD) { + loadInvalidates.emplace_back(att); + } + if (attachment.stencilStoreOp == StoreOp::DISCARD) { + storeInvalidates.emplace_back(att); + } + } + + depthStencil.first = texture; + depthStencil.second = samples; +} + +bool GLES3GPUFramebufferObject::isActive() const { + return swapchain != nullptr || (handle != 0); +} + +void GLES3GPUFramebufferObject::processLoad(GLenum target) { + if (!loadInvalidates.empty()) { + GL_CHECK(glInvalidateFramebuffer(target, utils::toUint(loadInvalidates.size()), loadInvalidates.data())); + } +} + +void GLES3GPUFramebufferObject::processStore(GLenum target) { + if (!storeInvalidates.empty()) { + GL_CHECK(glInvalidateFramebuffer(target, utils::toUint(storeInvalidates.size()), storeInvalidates.data())); + } +} + +void GLES3GPUFramebufferObject::finalize(GLES3GPUStateCache *cache) { + if (swapchain != nullptr) { + return; + } + + if (colors.empty() && dsAttachment == GL_NONE) { + return; + } + + GL_CHECK(glGenFramebuffers(1, &handle)); + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, handle)); + cache->glDrawFramebuffer = handle; + + auto bindAttachment = [](GLenum attachment, GLint samples, const GLES3GPUTextureView *view) { + auto *texture = view->gpuTexture; + if (samples > 1) { + CC_ASSERT(view->gpuTexture->glTexture != 0); + GL_CHECK(glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, + attachment, + GL_TEXTURE_2D, + texture->glTexture, + view->baseLevel, + static_cast(samples))); + return; + } + + if (texture->useRenderBuffer) { + /* + * Renderbuffer is not allocated if using lazily allocated flag. + * If the attachment does not meet the implicit MS condition, renderbuffer should be allocated here. + */ + if (view->gpuTexture->glRenderbuffer == 0) { + GL_CHECK(glGenRenderbuffers(1, &view->gpuTexture->glRenderbuffer)); + renderBufferStorage(GLES3Device::getInstance(), texture); + } + GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, attachment, texture->glTarget, texture->glRenderbuffer)); + } else { + GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachment, texture->glTarget, texture->glTexture, view->baseLevel)); + } + }; + + ccstd::vector drawBuffers(colors.size(), GL_NONE); + for (uint32_t i = 0; i < colors.size(); ++i) { + const auto &[view, samples] = colors[i]; + auto att = static_cast(GL_COLOR_ATTACHMENT0 + i); + drawBuffers[i] = att; + bindAttachment(att, samples, view); + } + + if (depthStencil.first != nullptr) { + const auto &[view, samples] = depthStencil; + bindAttachment(dsAttachment, samples, view); + } + + if (!drawBuffers.empty()) { + GL_CHECK(glDrawBuffers(drawBuffers.size(), drawBuffers.data())); + } + + GLenum status; + GL_CHECK(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); + if (status != GL_FRAMEBUFFER_COMPLETE) { + switch (status) { + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); + break; + case GL_FRAMEBUFFER_UNSUPPORTED: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); + break; + default: + CC_LOG_ERROR("checkFramebufferStatus() - %x", status); + break; + } + } +} + +void GLES3GPUFramebufferObject::destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap) { + if (swapchain) { + swapchain = nullptr; + } else { + if (cache->glDrawFramebuffer == handle) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); + cache->glDrawFramebuffer = 0; + } + GL_CHECK(glDeleteFramebuffers(1, &handle)); + framebufferCacheMap->unregisterExternal(handle); + handle = 0U; + } +} + void GLES3GPUFramebufferHub::update(GLES3GPUTexture *texture) { auto &pool = _framebuffers[texture]; for (auto *framebuffer : pool) { @@ -3192,5 +3175,16 @@ void GLES3GPUFramebufferHub::update(GLES3GPUTexture *texture) { } } +GLint cmdFuncGLES3GetMaxSampleCount(const GLES3Device *device, Format format, TextureUsage usage, TextureFlags flags) { + std::ignore = flags; + + auto internalFormat = mapGLInternalFormat(format); + auto target = useRenderBuffer(device, format, usage) ? GL_RENDERBUFFER : GL_TEXTURE_2D_MULTISAMPLE; + + GLint maxSamples = 1; + GL_CHECK(glGetInternalformativ(target, internalFormat, GL_SAMPLES, 1, &maxSamples)); + return maxSamples; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.h b/native/cocos/renderer/gfx-gles3/GLES3Commands.h index 7108e4ecee..c9d612550d 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.h @@ -312,5 +312,7 @@ void cmdFuncGLES3Dispatch(GLES3Device *device, const GLES3GPUDispatchInfo &info) void cmdFuncGLES3MemoryBarrier(GLES3Device *device, GLbitfield barriers, GLbitfield barriersByRegion); +GLint cmdFuncGLES3GetMaxSampleCount(const GLES3Device *device, Format format, TextureUsage usage, TextureFlags flags); + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index c8de3ad8f3..79bc6937af 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -121,7 +121,6 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { ccstd::string fbfLevelStr = "NONE"; // PVRVFrame has issues on their support -//#if CC_PLATFORM != CC_PLATFORM_WINDOWS if (checkExtension("framebuffer_fetch")) { ccstd::string nonCoherent = "framebuffer_fetch_non"; @@ -153,17 +152,20 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = true; fbfLevelStr += "_DEPTH_STENCIL"; } -//#endif + ccstd::string msaaLevelStr = "NONE"; #if CC_PLATFORM != CC_PLATFORM_WINDOWS || ALLOW_MULTISAMPLED_RENDER_TO_TEXTURE_ON_DESKTOP if (checkExtension("multisampled_render_to_texture")) { + msaaLevelStr = "MSRT1"; if (checkExtension("multisampled_render_to_texture2")) { _gpuConstantRegistry->mMSRT = MSRTSupportLevel::LEVEL2; + msaaLevelStr = "MSRT2"; } else { _gpuConstantRegistry->mMSRT = MSRTSupportLevel::LEVEL1; } } #endif + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = true; ccstd::string compressedFmts; @@ -242,6 +244,7 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { CC_LOG_INFO("VERSION: %s", _version.c_str()); CC_LOG_INFO("COMPRESSED_FORMATS: %s", compressedFmts.c_str()); CC_LOG_INFO("FRAMEBUFFER_FETCH: %s", fbfLevelStr.c_str()); + CC_LOG_INFO("MULTI_SAMPLE_RENDER_TO_TEXTURE: %s", msaaLevelStr.c_str()); if (_xr) { _xr->initializeGLESData(pfnGLES3wLoadProc(), GLES3Device::getInstance()->context()); @@ -610,5 +613,9 @@ void GLES3Device::getQueryPoolResults(QueryPool *queryPool) { cmdBuff->getQueryPoolResults(queryPool); } +SampleCount GLES3Device::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + return static_cast(cmdFuncGLES3GetMaxSampleCount(this, format, usage, flags)); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.h b/native/cocos/renderer/gfx-gles3/GLES3Device.h index 5eed7ca400..cba5ba99a0 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.h @@ -95,8 +95,8 @@ public: return _stagingBuffer; } - inline bool isTextureExclusive(const Format &format) { return _textureExclusive[static_cast(format)]; }; - + inline bool isTextureExclusive(const Format &format) const { return _textureExclusive[static_cast(format)]; }; + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static GLES3Device *instance; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp index 0eb96c3b3c..1b4b8e0f19 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp @@ -41,10 +41,25 @@ GLES3Framebuffer::~GLES3Framebuffer() { destroy(); } +void GLES3Framebuffer::updateExtent() { + if (!_colorTextures.empty()) { + const auto *tex = _colorTextures[0]; + _gpuFBO->width = tex->getWidth(); + _gpuFBO->height = tex->getHeight(); + return; + } + if (_depthStencilTexture != nullptr) { + _gpuFBO->width = _depthStencilTexture->getWidth(); + _gpuFBO->height = _depthStencilTexture->getHeight(); + return; + } +} + void GLES3Framebuffer::doInit(const FramebufferInfo & /*info*/) { _gpuFBO = ccnew GLES3GPUFramebuffer; - _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); + updateExtent(); + _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); _gpuFBO->gpuColorViews.resize(_colorTextures.size()); for (size_t i = 0; i < _colorTextures.size(); ++i) { auto *colorTexture = static_cast(_colorTextures.at(i)); @@ -58,6 +73,12 @@ void GLES3Framebuffer::doInit(const FramebufferInfo & /*info*/) { GLES3Device::getInstance()->framebufferHub()->connect(depthTexture->gpuTexture(), _gpuFBO); } + if (_depthStencilResolveTexture) { + auto *depthTexture = static_cast(_depthStencilResolveTexture); + _gpuFBO->gpuDepthStencilResolveView = depthTexture->gpuTextureView(); + GLES3Device::getInstance()->framebufferHub()->connect(depthTexture->gpuTexture(), _gpuFBO); + } + cmdFuncGLES3CreateFramebuffer(GLES3Device::getInstance(), _gpuFBO); } @@ -73,6 +94,10 @@ void GLES3Framebuffer::doDestroy() { auto *depthTexture = static_cast(_depthStencilTexture); GLES3Device::getInstance()->framebufferHub()->disengage(depthTexture->gpuTexture(), _gpuFBO); } + if (_depthStencilResolveTexture) { + auto *depthTexture = static_cast(_depthStencilResolveTexture); + GLES3Device::getInstance()->framebufferHub()->disengage(depthTexture->gpuTexture(), _gpuFBO); + } delete _gpuFBO; _gpuFBO = nullptr; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h index 50abda51bc..15620265e8 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h @@ -42,6 +42,7 @@ public: protected: void doInit(const FramebufferInfo &info) override; void doDestroy() override; + void updateExtent(); GLES3GPUFramebuffer *_gpuFBO = nullptr; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 7c1317f284..169767fe08 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -130,10 +130,11 @@ struct GLES3GPUTexture { uint32_t size{0}; uint32_t arrayLayer{1}; uint32_t mipLevel{1}; - SampleCount samples{SampleCount::ONE}; TextureFlags flags{TextureFlagBit::NONE}; + bool immutable{true}; bool isPowerOf2{false}; - bool memoryless{false}; + bool useRenderBuffer{false}; + bool memoryAllocated{true}; // false if swapchain image or implicit ms render buffer. GLenum glTarget{0}; GLenum glInternalFmt{0}; GLenum glFormat{0}; @@ -320,63 +321,63 @@ struct GLES3GPUGeneralBarrier { GLbitfield glBarriersByRegion = 0U; }; -using DrawBuffer = std::vector; +using DrawBuffer = ccstd::vector; struct GLES3GPURenderPass { ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; + DepthStencilAttachment depthStencilResolveAttachment; SubpassInfoList subpasses; SubpassDependencyList dependencies; - std::vector colors; - std::vector resolves; + ccstd::vector colors; + ccstd::vector resolves; uint32_t depthStencil = INVALID_BINDING; - std::vector indices; // offsets to GL_COLOR_ATTACHMENT_0 - std::vector drawBuffers; + uint32_t depthStencilResolve = INVALID_BINDING; + ccstd::vector indices; // offsets to GL_COLOR_ATTACHMENT_0 + ccstd::vector drawBuffers; }; class GLES3GPUFramebufferCacheMap; +struct GLES3GPUFramebufferObject { + void initialize(GLES3GPUSwapchain *swc = nullptr); + + void bindColor(const GLES3GPUTextureView *texture, uint32_t colorIndex, const ColorAttachment &attachment); + void bindColorMultiSample(const GLES3GPUTextureView *texture, uint32_t colorIndex, GLint samples, const ColorAttachment &attachment); + void bindDepthStencil(const GLES3GPUTextureView *texture, const DepthStencilAttachment &attachment); + void bindDepthStencilMultiSample(const GLES3GPUTextureView *texture, GLint samples, const DepthStencilAttachment &attachment); + + bool isActive() const; + void finalize(GLES3GPUStateCache *cache); + void processLoad(GLenum target); + void processStore(GLenum target); + void destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap); + + using Reference = std::pair; + + GLuint handle{0}; + GLES3GPUSwapchain *swapchain{nullptr}; + + ccstd::vector colors; + Reference depthStencil{nullptr, 1}; + GLenum dsAttachment{GL_NONE}; + + ccstd::vector loadInvalidates; + ccstd::vector storeInvalidates; +}; + class GLES3GPUFramebuffer final { public: GLES3GPURenderPass *gpuRenderPass{nullptr}; GLES3GPUTextureViewList gpuColorViews; GLES3GPUTextureView *gpuDepthStencilView{nullptr}; + GLES3GPUTextureView *gpuDepthStencilResolveView{nullptr}; - struct GLFramebufferInfo { - GLuint glFramebuffer{0U}; - uint32_t width{UINT_MAX}; - uint32_t height{UINT_MAX}; - }; - struct GLFramebuffer { - inline void initialize(GLES3GPUSwapchain *sc) { swapchain = sc; } - inline void initialize(const GLFramebufferInfo &info) { - _glFramebuffer = info.glFramebuffer; - _width = info.width; - _height = info.height; - } - inline GLuint getFramebuffer() const { return swapchain ? swapchain->glFramebuffer : _glFramebuffer; } - inline uint32_t getWidth() const { return swapchain ? swapchain->gpuColorTexture->width : _width; } - inline uint32_t getHeight() const { return swapchain ? swapchain->gpuColorTexture->height : _height; } - - void destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap); - - GLES3GPUSwapchain *swapchain{nullptr}; - - private: - GLuint _glFramebuffer{0U}; - uint32_t _width{0U}; - uint32_t _height{0U}; - }; - - struct Framebuffer { - GLFramebuffer framebuffer; - - // for blit-based manual resolving - GLbitfield resolveMask{0U}; - GLFramebuffer resolveFramebuffer; - }; - - // one per subpass, if not using FBF - Framebuffer frameBuffer; + uint32_t width{UINT_MAX}; + uint32_t height{UINT_MAX}; + GLbitfield dsResolveMask = 0; + std::vector> colorBlitPairs; + GLES3GPUFramebufferObject framebuffer; + GLES3GPUFramebufferObject resolveFramebuffer; }; struct GLES3GPUDescriptorSetLayout { diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp index a489267092..c409f6023a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp @@ -138,6 +138,10 @@ void GLES3PrimaryCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffe } } +void GLES3PrimaryCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + copyTexture(srcTexture, dstTexture, regions, count); +} + void GLES3PrimaryCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { GLES3GPUTexture *gpuTextureSrc = nullptr; GLES3GPUTexture *gpuTextureDst = nullptr; diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h index 79d82f6bd3..3ae0973530 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h @@ -49,6 +49,7 @@ public: void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const * /*buffers*/, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const * /*textures*/, uint32_t textureBarrierCount) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void beginQuery(QueryPool *queryPool, uint32_t id) override; void endQuery(QueryPool *queryPool, uint32_t id) override; void resetQueryPool(QueryPool *queryPool) override; diff --git a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp index 2029f901eb..76f8328171 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp @@ -44,6 +44,7 @@ void GLES3RenderPass::doInit(const RenderPassInfo & /*info*/) { _gpuRenderPass = ccnew GLES3GPURenderPass; _gpuRenderPass->colorAttachments = _colorAttachments; _gpuRenderPass->depthStencilAttachment = _depthStencilAttachment; + _gpuRenderPass->depthStencilResolveAttachment = _depthStencilResolveAttachment; _gpuRenderPass->subpasses = _subpasses; _gpuRenderPass->dependencies = _dependencies; @@ -59,14 +60,17 @@ void GLES3RenderPass::doInit(const RenderPassInfo & /*info*/) { if (_depthStencilAttachment.format != Format::UNKNOWN) { subpass.depthStencil = colorCount; } + if (_depthStencilResolveAttachment.format != Format::UNKNOWN) { + subpass.depthStencil = colorCount + 1; + } } else { // unify depth stencil index for (auto &subpass : _gpuRenderPass->subpasses) { - if (subpass.depthStencil != INVALID_BINDING && subpass.depthStencil > colorCount) { + if (subpass.depthStencil != INVALID_BINDING && subpass.depthStencil >= colorCount) { subpass.depthStencil = colorCount; } - if (subpass.depthStencilResolve != INVALID_BINDING && subpass.depthStencilResolve > colorCount) { - subpass.depthStencilResolve = colorCount; + if (subpass.depthStencilResolve != INVALID_BINDING && subpass.depthStencil >= colorCount) { + subpass.depthStencilResolve = colorCount + 1; } } } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp index a4c729b678..286ef62b78 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp @@ -52,7 +52,7 @@ void GLES3Texture::doInit(const TextureInfo & /*info*/) { _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayer = _info.layerCount; _gpuTexture->mipLevel = _info.levelCount; - _gpuTexture->samples = _info.samples; + _gpuTexture->glSamples = static_cast(_info.samples); _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; _gpuTexture->isPowerOf2 = math::isPowerOfTwo(_info.width) && math::isPowerOfTwo(_info.height); @@ -71,7 +71,7 @@ void GLES3Texture::doInit(const TextureInfo & /*info*/) { cmdFuncGLES3CreateTexture(GLES3Device::getInstance(), _gpuTexture); - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES3Device::getInstance()->getMemoryStatus().textureSize += _size; CC_PROFILE_MEMORY_INC(Texture, _size); } @@ -101,7 +101,7 @@ void GLES3Texture::doDestroy() { CC_SAFE_DELETE(_gpuTextureView); if (_gpuTexture) { if (!_isTextureView) { - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES3Device::getInstance()->getMemoryStatus().textureSize -= _size; CC_PROFILE_MEMORY_DEC(Texture, _size); } @@ -115,7 +115,7 @@ void GLES3Texture::doDestroy() { } void GLES3Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { - if (!_isTextureView && !_gpuTexture->memoryless) { + if (!_isTextureView && _gpuTexture->memoryAllocated) { GLES3Device::getInstance()->getMemoryStatus().textureSize -= _size; CC_PROFILE_MEMORY_DEC(Texture, _size); } @@ -129,7 +129,7 @@ void GLES3Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { GLES3Device::getInstance()->framebufferHub()->update(_gpuTexture); - if (!_isTextureView && !_gpuTexture->memoryless) { + if (!_isTextureView && _gpuTexture->memoryAllocated) { GLES3Device::getInstance()->getMemoryStatus().textureSize += size; CC_PROFILE_MEMORY_INC(Texture, size); } @@ -164,10 +164,10 @@ void GLES3Texture::doInit(const SwapchainTextureInfo & /*info*/) { _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayer = _info.layerCount; _gpuTexture->mipLevel = _info.levelCount; - _gpuTexture->samples = _info.samples; + _gpuTexture->glSamples = static_cast(_info.samples); _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; - _gpuTexture->memoryless = true; + _gpuTexture->memoryAllocated = false; _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); _gpuTextureView = ccnew GLES3GPUTextureView; createTextureView(); diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h index 7567af5316..bb38f1530c 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h @@ -73,6 +73,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index 0779591c60..84cd6f958e 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -237,6 +237,15 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb if(color >= colorAttachments.size()) { continue; // depthStencil as output } + if (subpasses[i].resolves.size() > j) { + uint32_t resolve = subpasses[i].resolves[j]; + auto *resolveTex = static_cast(colorTextures[resolve]); + mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); + mtlRenderPassDescriptor.colorAttachments[color].resolveLevel = 0; + mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; + mtlRenderPassDescriptor.colorAttachments[color].resolveDepthPlane = 0; + mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; + } if (visited[color]) continue; auto *ccMtlTexture = static_cast(colorTextures[color]); @@ -255,17 +264,6 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore; visited[color] = true; _colorAppearedBefore.set(color); - if (subpasses[i].resolves.size() > j) { - uint32_t resolve = subpasses[i].resolves[j]; - auto *resolveTex = static_cast(colorTextures[resolve]); - if (resolveTex->textureInfo().samples == SampleCount::ONE) - continue; - mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); - mtlRenderPassDescriptor.colorAttachments[color].resolveLevel = 0; - mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; - mtlRenderPassDescriptor.colorAttachments[color].resolveDepthPlane = 0; - mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; - } } } updateDepthStencilState(ccMtlRenderPass->getCurrentSubpassIndex(), mtlRenderPassDescriptor); @@ -388,19 +386,13 @@ void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDe } if (subpass.depthStencilResolve != INVALID_BINDING) { - const CCMTLTexture *dsResolveTex = nullptr; - if (subpass.depthStencilResolve >= colorTextures.size()) { - dsResolveTex = static_cast(curFBO->getDepthStencilTexture()); - } else { - dsResolveTex = static_cast(colorTextures[subpass.depthStencilResolve]); - } - descriptor.depthAttachment.resolveTexture = dsResolveTex->getMTLTexture(); + descriptor.depthAttachment.resolveTexture = static_cast(curFBO->getDepthStencilTexture())->getMTLTexture(); descriptor.depthAttachment.resolveLevel = 0; descriptor.depthAttachment.resolveSlice = 0; descriptor.depthAttachment.resolveDepthPlane = 0; descriptor.depthAttachment.storeAction = subpass.depthResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; - descriptor.stencilAttachment.resolveTexture = dsResolveTex->getMTLTexture(); + descriptor.stencilAttachment.resolveTexture = static_cast(curFBO->getDepthStencilResolveTexture())->getMTLTexture(); descriptor.stencilAttachment.resolveLevel = 0; descriptor.stencilAttachment.resolveSlice = 0; descriptor.stencilAttachment.resolveDepthPlane = 0; @@ -919,6 +911,10 @@ void CCMTLCommandBuffer::bindDescriptorSets() { } } +void CCMTLCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + // not supported. +} + void CCMTLCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { ccstd::vector blitRegions(count); for (uint32_t i = 0; i < count; ++i) { diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.h b/native/cocos/renderer/gfx-metal/MTLDevice.h index b76443f1bd..14064a3f30 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.h +++ b/native/cocos/renderer/gfx-metal/MTLDevice.h @@ -62,7 +62,7 @@ public: using Device::createRenderPass; using Device::createShader; using Device::createTexture; - + void frameSync() override; void acquire(Swapchain *const *swapchains, uint32_t count) override; @@ -88,6 +88,8 @@ public: _swapchains.erase(iter); } } + + inline CCMTLGPUDeviceObject* gpuObject() const { return _gpuDeviceObj; } protected: static CCMTLDevice *_instance; @@ -114,6 +116,7 @@ protected: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; void getQueryPoolResults(QueryPool *queryPool) override; + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; void onMemoryWarning(); void initFormatFeatures(uint32_t family); diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index db0ceef627..186a152bcd 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -73,7 +73,7 @@ CCMTLDevice::~CCMTLDevice() { bool CCMTLDevice::doInit(const DeviceInfo &info) { _gpuDeviceObj = ccnew CCMTLGPUDeviceObject; - + _currentFrameIndex = 0; id mtlDevice = MTLCreateSystemDefaultDevice(); @@ -87,7 +87,7 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { } _mtlFeatureSet = mu::highestSupportedFeatureSet(mtlDevice); _version = std::to_string(_mtlFeatureSet); - + const auto gpuFamily = mu::getGPUFamily(MTLFeatureSet(_mtlFeatureSet)); _indirectDrawSupported = mu::isIndirectDrawSupported(gpuFamily); _caps.maxVertexAttributes = mu::getMaxVertexAttributes(gpuFamily); @@ -139,13 +139,15 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = false; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = [mtlDevice supportsFamily: MTLGPUFamilyApple3]; + QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; _queue = createQueue(queueInfo); QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS, true}; _queryPool = createQueryPool(queryPoolInfo); - + CommandBufferInfo cmdBuffInfo; cmdBuffInfo.type = CommandBufferType::PRIMARY; cmdBuffInfo.queue = _queue; @@ -527,5 +529,22 @@ void CCMTLDevice::initFormatFeatures(uint32_t gpuFamily) { _formatFeatures[toNumber(Format::RGB10A2)] |= FormatFeature::VERTEX_ATTRIBUTE; } +SampleCount CCMTLDevice::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + const SampleCount sampleCounts[] = { + SampleCount::X64, + SampleCount::X32, + SampleCount::X16, + SampleCount::X8, + SampleCount::X4, + SampleCount::X2, + }; + for (auto sampleCount : sampleCounts) { + if ([_mtlDevice supportsTextureSampleCount: static_cast(sampleCount)]) { + return sampleCount; + } + } + return SampleCount::X1; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm index 7bd26adbae..447ca460e1 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm @@ -333,7 +333,7 @@ bool CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor * } } - SampleCount sample = SampleCount::ONE; + SampleCount sample = SampleCount::X1; Format depthStencilFormat; if (depthStencilTexIndex != INVALID_BINDING && depthStencilTexIndex < _renderPass->getColorAttachments().size()) { sample = _renderPass->getColorAttachments()[depthStencilTexIndex].sampleCount; diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.h b/native/cocos/renderer/gfx-metal/MTLTexture.h index 65eaf60e10..38a48205a5 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.h +++ b/native/cocos/renderer/gfx-metal/MTLTexture.h @@ -72,6 +72,8 @@ protected: bool _isArray = false; bool _isPVRTC = false; + bool _allocateMemory = true; // allocate device memory by metal driver. + id _mtlTexture = nil; id _mtlTextureView = nil; }; diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.mm b/native/cocos/renderer/gfx-metal/MTLTexture.mm index 5812ca53e1..edab24a636 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.mm +++ b/native/cocos/renderer/gfx-metal/MTLTexture.mm @@ -144,8 +144,10 @@ void CCMTLTexture::doInit(const TextureInfo &info) { return; } - CCMTLDevice::getInstance()->getMemoryStatus().textureSize += _size; - CC_PROFILE_MEMORY_INC(Texture, _size); + if (_allocateMemory) { + CCMTLDevice::getInstance()->getMemoryStatus().textureSize += _size; + CC_PROFILE_MEMORY_INC(Texture, _size); + } } void CCMTLTexture::doInit(const TextureViewInfo &info) { @@ -223,27 +225,15 @@ bool CCMTLTexture::createMTLTexture() { descriptor.mipmapLevelCount = _info.levelCount; descriptor.arrayLength = _info.type == TextureType::CUBE ? 1 : _info.layerCount; - if (hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::INPUT_ATTACHMENT, _info.usage) && mu::isImageBlockSupported()) { -#if MEMLESS_ON - // mac SDK mem_less unavailable before 11.0 - #if MAC_MEMORY_LESS_TEXTURE_SUPPORT || CC_PLATFORM == CC_PLATFORM_IOS - //xcode OS version warning - if (@available(macOS 11.0, *)) { + descriptor.storageMode = MTLStorageModePrivate; + if (@available(macos 11.0, ios 10.0, *)) { + bool memoryless = hasFlag(_info.flags, TextureFlagBit::LAZILY_ALLOCATED) && + hasFlag(_info.usage, TextureUsageBit::COLOR_ATTACHMENT) && + hasFlag(_info.usage, TextureUsageBit::DEPTH_STENCIL_ATTACHMENT); + if (memoryless) { descriptor.storageMode = MTLStorageModeMemoryless; - } else { - descriptor.storageMode = MTLStorageModePrivate; + _allocateMemory = false; } - #else - descriptor.storageMode = MTLStorageModePrivate; - #endif -#else - descriptor.storageMode = MTLStorageModePrivate; -#endif - } else if (hasFlag(_info.usage, TextureUsage::COLOR_ATTACHMENT) || - hasFlag(_info.usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT) || - hasFlag(_info.usage, TextureUsage::INPUT_ATTACHMENT) || - hasFlag(_info.usage, TextureUsage::STORAGE)) { - descriptor.storageMode = MTLStorageModePrivate; } id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); @@ -262,8 +252,9 @@ const TextureInfo &CCMTLTexture::textureInfo() { void CCMTLTexture::doDestroy() { //decrease only non-swapchain tex and have had been inited. - if (!_swapchain && _mtlTexture) { + if (!_swapchain && _mtlTexture && _allocateMemory) { CCMTLDevice::getInstance()->getMemoryStatus().textureSize -= _size; + CC_PROFILE_MEMORY_DEC(Texture, _size); } if (_swapchain) { @@ -281,8 +272,6 @@ void CCMTLTexture::doDestroy() { _mtlTexture = nil; } - CC_PROFILE_MEMORY_DEC(Texture, _size); - std::function destroyFunc = [mtlTexure]() { if (mtlTexure) { //TODO_Zeqiang: [mac12 | ios15, ...) validate here @@ -319,7 +308,7 @@ void CCMTLTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { // texture is a wrapper of drawable when _swapchain is active, drawable is not a resource alloc by gfx, // but the system so skip here. - if (!_swapchain) { + if (!_swapchain && _allocateMemory) { CCMTLDevice::getInstance()->getMemoryStatus().textureSize -= oldSize; CCMTLDevice::getInstance()->getMemoryStatus().textureSize += size; CC_PROFILE_MEMORY_DEC(Texture, oldSize); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index 18869415bb..d2864e9b91 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -847,17 +847,7 @@ MTLTextureType mu::toMTLTextureType(TextureType type) { } NSUInteger mu::toMTLSampleCount(SampleCount count) { - //TODO_Zeqiang: query from device. - switch (count) { - case SampleCount::ONE: return 1; - case SampleCount::MULTIPLE_PERFORMANCE: return 2; - case SampleCount::MULTIPLE_BALANCE: return 4; - case SampleCount::MULTIPLE_QUALITY: - return 8; - // case SampleCount::X16: return 16; - // case SampleCount::X32: return 32; - // case SampleCount::X64: return 64; - } + return static_cast(count); } MTLSamplerAddressMode mu::toMTLSamplerAddressMode(Address mode) { diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp index abae179830..bab7e3c6ca 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp @@ -418,6 +418,41 @@ void CommandBufferValidator::copyBuffersToTexture(const uint8_t *const *buffers, _actor->copyBuffersToTexture(buffers, textureValidator->getActor(), regions, count); } +void CommandBufferValidator::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + CC_ASSERT(isInited()); + CC_ASSERT(srcTexture && static_cast(srcTexture)->isInited()); + CC_ASSERT(dstTexture && static_cast(dstTexture)->isInited()); + const auto &srcInfo = srcTexture->getInfo(); + const auto &dstInfo = dstTexture->getInfo(); + + CC_ASSERT(srcInfo.format == dstInfo.format); + CC_ASSERT(srcInfo.format != Format::DEPTH_STENCIL && + srcInfo.format != Format::DEPTH); + + CC_ASSERT(srcInfo.samples > SampleCount::X1 && + dstInfo.samples == SampleCount::X1); + + CC_ASSERT(!_insideRenderPass); + + for (uint32_t i = 0; i < count; ++i) { + const auto ®ion = regions[i]; + CC_ASSERT(region.srcOffset.x + region.extent.width <= srcInfo.width); + CC_ASSERT(region.srcOffset.y + region.extent.height <= srcInfo.height); + CC_ASSERT(region.srcOffset.z + region.extent.depth <= srcInfo.depth); + + CC_ASSERT(region.dstOffset.x + region.extent.width <= dstInfo.width); + CC_ASSERT(region.dstOffset.y + region.extent.height <= dstInfo.height); + CC_ASSERT(region.dstOffset.z + region.extent.depth <= dstInfo.depth); + } + + Texture *actorSrcTexture = nullptr; + Texture *actorDstTexture = nullptr; + if (srcTexture) actorSrcTexture = static_cast(srcTexture)->getActor(); + if (dstTexture) actorDstTexture = static_cast(dstTexture)->getActor(); + + _actor->resolveTexture(actorSrcTexture, actorDstTexture, regions, count); +} + void CommandBufferValidator::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { CC_ASSERT(isInited()); CC_ASSERT(srcTexture && static_cast(srcTexture)->isInited()); @@ -453,9 +488,9 @@ void CommandBufferValidator::blitTexture(Texture *srcTexture, Texture *dstTextur CC_ASSERT(srcTexture && static_cast(srcTexture)->isInited()); CC_ASSERT(dstTexture && static_cast(dstTexture)->isInited()); // Blit on multisampled texture is not allowed. - CC_ASSERT(srcTexture->getInfo().samples == SampleCount::ONE); + CC_ASSERT(srcTexture->getInfo().samples == SampleCount::X1); // blit on multisampled texture is not allowed. - CC_ASSERT(dstTexture->getInfo().samples == SampleCount::ONE); + CC_ASSERT(dstTexture->getInfo().samples == SampleCount::X1); // Command 'blitTexture' must be recorded outside render passes. CC_ASSERT(!_insideRenderPass); diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h index f7b0ee5274..3ec70240be 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h @@ -58,6 +58,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp index f44d42aee1..ff97a9910a 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp @@ -352,5 +352,9 @@ void DeviceValidator::frameSync() { _actor->frameSync(); } +SampleCount DeviceValidator::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + return _actor->getMaxSampleCount(format, usage, flags); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.h b/native/cocos/renderer/gfx-validator/DeviceValidator.h index 111737a086..4122d715e7 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.h +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.h @@ -95,7 +95,7 @@ public: inline uint64_t currentFrame() const { return _currentFrame; } void enableAutoBarrier(bool enable) override; - + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static DeviceValidator *instance; diff --git a/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp b/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp index bf6c868d47..8c4166bbb8 100644 --- a/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp @@ -54,6 +54,9 @@ void FramebufferValidator::doInit(const FramebufferInfo &info) { if (info.renderPass->getDepthStencilAttachment().format != Format::UNKNOWN) { CC_ASSERT(info.depthStencilTexture); } + if (info.renderPass->getDepthStencilResolveAttachment().format != Format::UNKNOWN) { + CC_ASSERT(info.depthStencilResolveTexture); + } for (uint32_t i = 0U; i < info.colorTextures.size(); ++i) { const auto &desc = info.renderPass->getColorAttachments()[i]; @@ -67,6 +70,11 @@ void FramebufferValidator::doInit(const FramebufferInfo &info) { CC_ASSERT(hasFlag(info.depthStencilTexture->getInfo().usage, TextureUsageBit::DEPTH_STENCIL_ATTACHMENT)); CC_ASSERT(info.depthStencilTexture->getFormat() == info.renderPass->getDepthStencilAttachment().format); } + if (info.depthStencilResolveTexture) { + CC_ASSERT(static_cast(info.depthStencilResolveTexture)->isInited()); + CC_ASSERT(hasFlag(info.depthStencilResolveTexture->getInfo().usage, TextureUsageBit::DEPTH_STENCIL_ATTACHMENT)); + CC_ASSERT(info.depthStencilResolveTexture->getFormat() == info.renderPass->getDepthStencilResolveAttachment().format); + } /////////// execute /////////// @@ -79,6 +87,9 @@ void FramebufferValidator::doInit(const FramebufferInfo &info) { if (info.depthStencilTexture) { actorInfo.depthStencilTexture = static_cast(info.depthStencilTexture)->getActor(); } + if (info.depthStencilResolveTexture) { + actorInfo.depthStencilResolveTexture = static_cast(info.depthStencilResolveTexture)->getActor(); + } actorInfo.renderPass = static_cast(info.renderPass)->getActor(); _actor->initialize(actorInfo); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index fb62c102e0..7aefa9312f 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -168,15 +168,17 @@ void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo } ccstd::vector &clearValues = _curGPURenderPass->clearValues; - bool depthEnabled = _curGPURenderPass->depthStencilAttachment.format != Format::UNKNOWN; - size_t attachmentCount = depthEnabled ? clearValues.size() - 1 : clearValues.size(); - + size_t attachmentCount = _curGPURenderPass->colorAttachments.size(); for (size_t i = 0U; i < attachmentCount; ++i) { clearValues[i].color = {{colors[i].x, colors[i].y, colors[i].z, colors[i].w}}; } - if (depthEnabled) { + + if (_curGPURenderPass->depthStencilAttachment.format != Format::UNKNOWN) { clearValues[attachmentCount].depthStencil = {depth, stencil}; } + if (_curGPURenderPass->depthStencilResolveAttachment.format != Format::UNKNOWN) { + clearValues[attachmentCount + 1].depthStencil = {depth, stencil}; + } Rect safeArea{ std::min(renderArea.x, static_cast(_curGPUFBO->width)), @@ -516,6 +518,50 @@ void CCVKCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Text cmdFuncCCVKCopyBuffersToTexture(CCVKDevice::getInstance(), buffers, static_cast(texture)->gpuTexture(), regions, count, _gpuCommandBuffer); } +void CCVKCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + VkImageAspectFlags srcAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + VkImageAspectFlags dstAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + VkImage srcImage = VK_NULL_HANDLE; + VkImage dstImage = VK_NULL_HANDLE; + + auto getImage = [](Texture * texture) -> auto { + CCVKGPUTexture *gpuTexture = static_cast(texture)->gpuTexture(); + return gpuTexture->swapchain ? std::pair{gpuTexture->aspectMask, gpuTexture->swapchainVkImages[gpuTexture->swapchain->curImageIndex]} : std::pair{gpuTexture->aspectMask, gpuTexture->vkImage}; + }; + + std::tie(srcAspectMask, srcImage) = getImage(srcTexture); + std::tie(dstAspectMask, dstImage) = getImage(dstTexture); + + ccstd::vector resolveRegions(count); + for (uint32_t i = 0U; i < count; ++i) { + const TextureCopy ®ion = regions[i]; + auto &resolveRegion = resolveRegions[i]; + + resolveRegion.srcSubresource.aspectMask = srcAspectMask; + resolveRegion.srcSubresource.mipLevel = region.srcSubres.mipLevel; + resolveRegion.srcSubresource.baseArrayLayer = region.srcSubres.baseArrayLayer; + resolveRegion.srcSubresource.layerCount = region.srcSubres.layerCount; + + resolveRegion.dstSubresource.aspectMask = dstAspectMask; + resolveRegion.dstSubresource.mipLevel = region.dstSubres.mipLevel; + resolveRegion.dstSubresource.baseArrayLayer = region.dstSubres.baseArrayLayer; + resolveRegion.dstSubresource.layerCount = region.dstSubres.layerCount; + + resolveRegion.srcOffset.x = region.srcOffset.x; + resolveRegion.srcOffset.y = region.srcOffset.y; + resolveRegion.srcOffset.z = region.srcOffset.z; + + resolveRegion.dstOffset.x = region.dstOffset.x; + resolveRegion.dstOffset.y = region.dstOffset.y; + resolveRegion.dstOffset.z = region.dstOffset.z; + + resolveRegion.extent.width = region.extent.width; + resolveRegion.extent.height = region.extent.height; + resolveRegion.extent.depth = region.extent.depth; + } + vkCmdResolveImage(_gpuCommandBuffer->vkCommandBuffer, srcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dstImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, count, resolveRegions.data()); +} + void CCVKCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { VkImageAspectFlags srcAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; VkImageAspectFlags dstAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h index 3438684cbe..1eae85158e 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h @@ -58,6 +58,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index 4d65e96f6c..cf09829838 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -119,11 +119,6 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { if (!gpuTexture->size) return; gpuTexture->aspectMask = mapVkImageAspectFlags(gpuTexture->format); - // storage images has to be in general layout - // if (hasFlag(gpuTexture->usage, TextureUsageBit::STORAGE)) gpuTexture->flags |= TextureFlagBit::GENERAL_LAYOUT; - // remove stencil aspect for depth textures with sampled usage - if (hasFlag(gpuTexture->usage, TextureUsageBit::SAMPLED)) gpuTexture->aspectMask &= ~VK_IMAGE_ASPECT_STENCIL_BIT; - auto createFn = [device, gpuTexture](VkImage *pVkImage, VmaAllocation *pVmaAllocation) { VkFormat vkFormat = mapVkFormat(gpuTexture->format, device->gpuDevice()); VkFormatFeatureFlags features = mapVkFormatFeatureFlags(gpuTexture->usage); @@ -135,10 +130,7 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { return; } - VkImageUsageFlags usageFlags = mapVkImageUsageFlagBits(gpuTexture->usage); - if (hasFlag(gpuTexture->flags, TextureFlags::GEN_MIPMAP)) { - usageFlags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - } + VkImageUsageFlags usageFlags = mapVkImageUsageFlags(gpuTexture->usage, gpuTexture->flags); VkImageCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; createInfo.flags = mapVkImageCreateFlags(gpuTexture->type); @@ -147,7 +139,7 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { createInfo.extent = {gpuTexture->width, gpuTexture->height, gpuTexture->depth}; createInfo.mipLevels = gpuTexture->mipLevels; createInfo.arrayLayers = gpuTexture->arrayLayers; - createInfo.samples = device->gpuContext()->getSampleCountForAttachments(gpuTexture->format, vkFormat, gpuTexture->samples); + createInfo.samples = static_cast(gpuTexture->samples); createInfo.tiling = VK_IMAGE_TILING_OPTIMAL; createInfo.usage = usageFlags; createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; @@ -156,23 +148,25 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; VmaAllocationInfo res; - - if (ENABLE_LAZY_ALLOCATION && hasAllFlags(TEXTURE_USAGE_TRANSIENT, gpuTexture->usage)) { - createInfo.usage = usageFlags | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; + const VkFlags lazilyAllocatedFilterFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | + VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT | + VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; + if (hasFlag(gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED) && + (lazilyAllocatedFilterFlags & usageFlags) == usageFlags) { allocInfo.usage = VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED; VkResult result = vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, pVkImage, pVmaAllocation, &res); if (!result) { - gpuTexture->memoryless = true; + gpuTexture->memoryAllocated = false; return; } - // feature not present, fallback - createInfo.usage = usageFlags; + // feature not present, fallback to device memory allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; } - gpuTexture->memoryless = false; + gpuTexture->memoryAllocated = true; VK_CHECK(vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, pVkImage, pVmaAllocation, &res)); }; @@ -190,7 +184,7 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { gpuTexture->swapchainVkImages[i] = gpuTexture->swapchain->swapchainImages[i]; } } - gpuTexture->memoryless = true; + gpuTexture->memoryAllocated = false; } else if (hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_OES) || hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_NORMAL)) { gpuTexture->vkImage = gpuTexture->externalVKImage; } else { @@ -382,11 +376,18 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende ccstd::vector shadingRateReferences; const size_t colorAttachmentCount = gpuRenderPass->colorAttachments.size(); - const size_t hasDepth = gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN ? 1 : 0; - attachmentDescriptions.assign(colorAttachmentCount + hasDepth, {VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2}); - gpuRenderPass->clearValues.resize(colorAttachmentCount + hasDepth); - beginAccessInfos.resize(colorAttachmentCount + hasDepth); - endAccessInfos.resize(colorAttachmentCount + hasDepth); + const size_t hasDepthStencil = gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN ? 1 : 0; + const size_t hasDepthResolve = gpuRenderPass->depthStencilResolveAttachment.format != Format::UNKNOWN ? 1 : 0; + auto attachmentCount = static_cast(colorAttachmentCount + hasDepthStencil + hasDepthResolve); + uint32_t depthIndex = colorAttachmentCount; + uint32_t stencilIndex = colorAttachmentCount + 1; + + const bool hasStencil = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; + + attachmentDescriptions.assign(attachmentCount, {VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2}); + gpuRenderPass->clearValues.resize(attachmentCount); + beginAccessInfos.resize(attachmentCount); + endAccessInfos.resize(attachmentCount); shadingRateReferences.resize(gpuRenderPass->subpasses.size(), {VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR}); for (size_t i = 0U; i < colorAttachmentCount; ++i) { @@ -395,34 +396,43 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende getInitialFinalLayout(device, static_cast(attachment.barrier), false); VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); - bool hasStencil = GFX_FORMAT_INFOS[toNumber(attachment.format)].hasStencil; - VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(attachment.format, vkFormat, attachment.sampleCount); - attachmentDescriptions[i].format = vkFormat; - attachmentDescriptions[i].samples = samples; + attachmentDescriptions[i].samples = static_cast(attachment.sampleCount); attachmentDescriptions[i].loadOp = mapVkLoadOp(attachment.loadOp); 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].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[i].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachmentDescriptions[i].initialLayout = attachment.loadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : initialLayout; attachmentDescriptions[i].finalLayout = finalLayout; } - if (hasDepth) { - const DepthStencilAttachment &depthStencilAttachment = gpuRenderPass->depthStencilAttachment; - auto [initialLayout, finalLayout] = getInitialFinalLayout(device, static_cast(depthStencilAttachment.barrier), true); + if (hasDepthStencil) { + const DepthStencilAttachment &attachment = gpuRenderPass->depthStencilAttachment; + auto [initialLayout, finalLayout] = getInitialFinalLayout(device, static_cast(attachment.barrier), true); - VkFormat vkFormat = mapVkFormat(depthStencilAttachment.format, device->gpuDevice()); - bool hasStencil = GFX_FORMAT_INFOS[toNumber(depthStencilAttachment.format)].hasStencil; - VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(depthStencilAttachment.format, vkFormat, depthStencilAttachment.sampleCount); + VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); + attachmentDescriptions[depthIndex].format = vkFormat; + attachmentDescriptions[depthIndex].samples = static_cast(attachment.sampleCount); + attachmentDescriptions[depthIndex].loadOp = mapVkLoadOp(attachment.depthLoadOp); + attachmentDescriptions[depthIndex].storeOp = mapVkStoreOp(attachment.depthStoreOp); + attachmentDescriptions[depthIndex].stencilLoadOp = hasStencil ? mapVkLoadOp(attachment.stencilLoadOp) : VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[depthIndex].stencilStoreOp = hasStencil ? mapVkStoreOp(attachment.stencilStoreOp) : VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachmentDescriptions[depthIndex].initialLayout = attachment.depthLoadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : initialLayout; + attachmentDescriptions[depthIndex].finalLayout = finalLayout; + } + if (hasDepthResolve) { + const DepthStencilAttachment &attachment = gpuRenderPass->depthStencilResolveAttachment; + auto [initialLayout, finalLayout] = getInitialFinalLayout(device, static_cast(attachment.barrier), true); - attachmentDescriptions[colorAttachmentCount].format = vkFormat; - attachmentDescriptions[colorAttachmentCount].samples = samples; - attachmentDescriptions[colorAttachmentCount].loadOp = mapVkLoadOp(depthStencilAttachment.depthLoadOp); - 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 : initialLayout; - attachmentDescriptions[colorAttachmentCount].finalLayout = finalLayout; + VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); + + attachmentDescriptions[stencilIndex].format = vkFormat; + attachmentDescriptions[stencilIndex].samples = VK_SAMPLE_COUNT_1_BIT; + attachmentDescriptions[stencilIndex].loadOp = mapVkLoadOp(attachment.depthLoadOp); + attachmentDescriptions[stencilIndex].storeOp = mapVkStoreOp(attachment.depthStoreOp); + attachmentDescriptions[stencilIndex].stencilLoadOp = hasStencil ? mapVkLoadOp(attachment.stencilLoadOp) : VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[stencilIndex].stencilStoreOp = hasStencil ? mapVkStoreOp(attachment.stencilStoreOp) : VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachmentDescriptions[stencilIndex].initialLayout = attachment.depthLoadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : initialLayout; + attachmentDescriptions[stencilIndex].finalLayout = finalLayout; } size_t subpassCount = gpuRenderPass->subpasses.size(); @@ -433,62 +443,41 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkSampleCountFlagBits sampleCount = VK_SAMPLE_COUNT_1_BIT; for (uint32_t input : subpassInfo.inputs) { + bool appearsInOutput = std::find(subpassInfo.colors.begin(), subpassInfo.colors.end(), input) != subpassInfo.colors.end(); if (input == gpuRenderPass->colorAttachments.size()) { - VkImageLayout layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; + VkImageLayout layout = subpassInfo.depthStencil != INVALID_BINDING ? VK_IMAGE_LAYOUT_GENERAL : 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 = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + VkImageLayout layout = appearsInOutput ? VK_IMAGE_LAYOUT_GENERAL : 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]; 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 = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + for (uint32_t resolveIn : subpassInfo.resolves) { + VkImageLayout layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + auto resolve = resolveIn == gfx::INVALID_BINDING ? VK_ATTACHMENT_UNUSED : resolveIn; + CC_ASSERT(INVALID_BINDING == VK_ATTACHMENT_UNUSED); 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}; - if (subpassInfo.depthStencil >= colorAttachmentCount) { - const DepthStencilAttachment &desc = gpuRenderPass->depthStencilAttachment; - const VkAttachmentDescription2 &attachment = attachmentDescriptions.back(); - dsFormat = desc.format; - sampleCount = std::max(sampleCount, attachment.samples); - } else { - const ColorAttachment &desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencil]; - const VkAttachmentDescription2 &attachment = attachmentDescriptions[subpassInfo.depthStencil]; - dsFormat = desc.format; - sampleCount = std::max(sampleCount, attachment.samples); - } + const VkAttachmentDescription2 &attachment = attachmentDescriptions[subpassInfo.depthStencil]; + 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; + VkImageAspectFlags aspect = hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; 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}; - if (subpassInfo.depthStencilResolve >= colorAttachmentCount) { - const DepthStencilAttachment &desc = gpuRenderPass->depthStencilAttachment; - dsFormat = desc.format; - } else { - const ColorAttachment &desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencilResolve]; - 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; + VkImageAspectFlags aspect = hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; VkImageLayout layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, subpassInfo.depthStencilResolve, layout, aspect}); } @@ -547,8 +536,14 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkResolveModeFlagBits depthResolveMode = VK_RESOLVE_MODES[toNumber(subpassInfo.depthResolveMode)]; VkResolveModeFlagBits stencilResolveMode = VK_RESOLVE_MODES[toNumber(subpassInfo.stencilResolveMode)]; - if ((depthResolveMode & prop.supportedDepthResolveModes) == 0) depthResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; - if ((stencilResolveMode & prop.supportedStencilResolveModes) == 0) stencilResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; + if ((depthResolveMode & prop.supportedDepthResolveModes) == 0) { + depthResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; + CC_LOG_WARNING("render pass depth resolve mode [%u] not supported, use Sample0 instead.", toNumber(subpassInfo.depthResolveMode)); + } + if ((stencilResolveMode & prop.supportedStencilResolveModes) == 0) { + stencilResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; + CC_LOG_WARNING("render pass stencil resolve mode [%u] not supported, use Sample0 instead.", toNumber(subpassInfo.stencilResolveMode)); + } if (!prop.independentResolveNone && stencilResolveMode != depthResolveMode) { stencilResolveMode = depthResolveMode; @@ -572,6 +567,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende } size_t dependencyCount = gpuRenderPass->dependencies.size(); + gpuRenderPass->hasSelfDependency.resize(subpassCount, false); dependencyManager.clear(); bool manuallyDeduce = true; @@ -584,8 +580,6 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende if (!manuallyDeduce) { // 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}; @@ -669,8 +663,8 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende } } }; - attachmentStatistics.resize(colorAttachmentCount + hasDepth); - for (uint32_t i = 0U; i < utils ::toUint(colorAttachmentCount + hasDepth); ++i) { + attachmentStatistics.resize(attachmentCount); + for (uint32_t i = 0U; i < utils ::toUint(attachmentCount); ++i) { attachmentStatistics[i].clear(); calculateLifeCycle(i, attachmentStatistics[i]); CC_ASSERT(attachmentStatistics[i].loadSubpass != VK_SUBPASS_EXTERNAL && @@ -697,7 +691,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkSubpassDependency2 beginDependency; uint32_t lastLoadSubpass{VK_SUBPASS_EXTERNAL}; bool beginDependencyValid{false}; - for (uint32_t i = 0U; i < utils ::toUint(colorAttachmentCount + hasDepth); ++i) { + for (uint32_t i = 0U; i < attachmentCount; ++i) { auto &statistics = attachmentStatistics[i]; if (lastLoadSubpass != statistics.loadSubpass) { if (beginDependencyValid) dependencyManager.append(beginDependency); @@ -729,7 +723,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkSubpassDependency2 endDependency; uint32_t lastStoreSubpass{VK_SUBPASS_EXTERNAL}; bool endDependencyValid{false}; - for (uint32_t i = 0U; i < utils ::toUint(colorAttachmentCount + hasDepth); ++i) { + for (uint32_t i = 0U; i < attachmentCount; ++i) { auto &statistics = attachmentStatistics[i]; if (lastStoreSubpass != statistics.storeSubpass) { if (endDependencyValid) dependencyManager.append(endDependency); @@ -759,7 +753,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; return dependency; }; - for (size_t i = 0U; i < colorAttachmentCount + hasDepth; ++i) { + for (size_t i = 0U; i < attachmentCount; ++i) { auto &statistics{attachmentStatistics[i]}; const AttachmentStatistics::SubpassRef *prevRef{nullptr}; @@ -788,8 +782,12 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFramebuffer) { size_t colorViewCount = gpuFramebuffer->gpuColorViews.size(); - bool hasDepth = gpuFramebuffer->gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN; - ccstd::vector attachments(colorViewCount + hasDepth); + const auto *gpuRenderPass = gpuFramebuffer->gpuRenderPass.get(); + const size_t hasDepthStencil = gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN ? 1 : 0; + const size_t hasDepthResolve = gpuRenderPass->depthStencilResolveAttachment.format != Format::UNKNOWN ? 1 : 0; + auto attachmentCount = static_cast(colorViewCount + hasDepthStencil + hasDepthResolve); + + ccstd::vector attachments(attachmentCount); VkFramebufferCreateInfo createInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; createInfo.width = createInfo.height = UINT_MAX; @@ -809,14 +807,20 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra createInfo.height = std::min(createInfo.height, std::max(1U, gpuFramebuffer->gpuColorViews[i]->gpuTexture->height >> gpuFramebuffer->gpuColorViews[i]->baseLevel)); } } - if (hasDepth) { + if (hasDepthStencil) { if (gpuFramebuffer->gpuDepthStencilView->gpuTexture->swapchain) { gpuFramebuffer->swapchain = gpuFramebuffer->gpuDepthStencilView->gpuTexture->swapchain; swapchainImageIndices |= (1 << colorViewCount); } else { attachments[colorViewCount] = gpuFramebuffer->gpuDepthStencilView->vkImageView; } + createInfo.width = std::min(createInfo.width, std::max(1U, gpuFramebuffer->gpuDepthStencilView->gpuTexture->width >> gpuFramebuffer->gpuDepthStencilView->baseLevel)); + createInfo.height = std::min(createInfo.height, std::max(1U, gpuFramebuffer->gpuDepthStencilView->gpuTexture->height >> gpuFramebuffer->gpuDepthStencilView->baseLevel)); } + if (hasDepthResolve) { + attachments[colorViewCount + 1] = gpuFramebuffer->gpuDepthStencilResolveView->vkImageView; + } + gpuFramebuffer->isOffscreen = !swapchainImageIndices; gpuFramebuffer->width = createInfo.width; gpuFramebuffer->height = createInfo.height; @@ -1590,33 +1594,6 @@ bool CCVKGPURenderPass::hasShadingAttachment(uint32_t subPassId) const { return subpasses[subPassId].shadingRate != INVALID_BINDING; } -VkSampleCountFlagBits CCVKGPUContext::getSampleCountForAttachments(Format format, VkFormat vkFormat, SampleCount sampleCount) const { - if (sampleCount <= SampleCount::ONE) return VK_SAMPLE_COUNT_1_BIT; - - static ccstd::unordered_map cacheMap; - if (!cacheMap.count(format)) { - bool hasDepth = GFX_FORMAT_INFOS[toNumber(format)].hasDepth; - VkImageUsageFlags usages = hasDepth ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - - VkImageFormatProperties properties; - vkGetPhysicalDeviceImageFormatProperties(physicalDevice, vkFormat, VK_IMAGE_TYPE_2D, - VK_IMAGE_TILING_OPTIMAL, usages, 0, &properties); - cacheMap[format] = properties.sampleCounts; - } - - VkSampleCountFlags availableSampleCounts = cacheMap[format]; - - auto requestedSampleCount = VK_SAMPLE_COUNT_FLAGS[toNumber(sampleCount)]; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_64_BIT) return VK_SAMPLE_COUNT_64_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_32_BIT) return VK_SAMPLE_COUNT_32_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_16_BIT) return VK_SAMPLE_COUNT_16_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_8_BIT) return VK_SAMPLE_COUNT_8_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_4_BIT) return VK_SAMPLE_COUNT_4_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_2_BIT) return VK_SAMPLE_COUNT_2_BIT; - - return VK_SAMPLE_COUNT_1_BIT; -} - void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { if (_buffersToBeChecked.empty() && _texturesToBeChecked.empty()) return; diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index acc577be13..85d9bacdfc 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -768,6 +768,7 @@ void CCVKDevice::initDeviceFeature() { _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = true; _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = true; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = checkExtension("VK_KHR_depth_stencil_resolve"); } void CCVKDevice::initFormatFeature() { @@ -1084,5 +1085,23 @@ static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( return vkCreateRenderPass(device, &renderPassCreateInfo, pAllocator, pRenderPass); } +SampleCount CCVKDevice::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + auto vkFormat = mapVkFormat(format, gpuDevice()); + auto usages = mapVkImageUsageFlags(usage, flags); + + VkImageFormatProperties imageFormatProperties = {}; + vkGetPhysicalDeviceImageFormatProperties(_gpuContext->physicalDevice, vkFormat, VK_IMAGE_TYPE_2D, + VK_IMAGE_TILING_OPTIMAL, usages, 0, &imageFormatProperties); + + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_64_BIT) return SampleCount::X64; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_32_BIT) return SampleCount::X32; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_16_BIT) return SampleCount::X16; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_8_BIT) return SampleCount::X8; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_4_BIT) return SampleCount::X4; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_2_BIT) return SampleCount::X2; + + return SampleCount::X1; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.h b/native/cocos/renderer/gfx-vulkan/VKDevice.h index c53f6cb20a..4d7d9c938a 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.h +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.h @@ -105,7 +105,7 @@ public: void waitAllFences(); void updateBackBufferCount(uint32_t backBufferCount); - + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static CCVKDevice *instance; diff --git a/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp index efb463ba46..7bf4d5d288 100644 --- a/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp @@ -54,6 +54,11 @@ void CCVKFramebuffer::doInit(const FramebufferInfo & /*info*/) { _gpuFBO->gpuDepthStencilView = depthTex->gpuTextureView(); } + if (_depthStencilResolveTexture) { + auto *depthTex = static_cast(_depthStencilResolveTexture); + _gpuFBO->gpuDepthStencilResolveView = depthTex->gpuTextureView(); + } + cmdFuncCCVKCreateFramebuffer(CCVKDevice::getInstance(), _gpuFBO); } diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index c47e4a76fa..cb386223c6 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -71,8 +71,6 @@ public: return std::strcmp(ext, extension.c_str()) == 0; }); } - - VkSampleCountFlagBits getSampleCountForAttachments(Format format, VkFormat vkFormat, SampleCount sampleCount) const; }; struct CCVKAccessInfo { @@ -119,6 +117,7 @@ public: ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; + DepthStencilAttachment depthStencilResolveAttachment; SubpassInfoList subpasses; SubpassDependencyList dependencies; @@ -148,10 +147,19 @@ struct CCVKGPUTexture : public CCVKGPUDeviceObject { uint32_t size = 0U; uint32_t arrayLayers = 1U; uint32_t mipLevels = 1U; - SampleCount samples = SampleCount::ONE; + SampleCount samples = SampleCount::X1; TextureFlags flags = TextureFlagBit::NONE; VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - bool memoryless = false; + + /* + * allocate and bind memory by Texture. + * If any of the following conditions are met, then the statement is false + * 1. Texture is a swapchain image. + * 2. Texture has flag LAZILY_ALLOCATED. + * 3. Memory bound manually bound. + * 4. Sparse Image. + */ + bool memoryAllocated = true; VkImage vkImage = VK_NULL_HANDLE; VmaAllocation vmaAllocation = VK_NULL_HANDLE; @@ -258,6 +266,7 @@ struct CCVKGPUFramebuffer : public CCVKGPUDeviceObject { ConstPtr gpuRenderPass; ccstd::vector> gpuColorViews; ConstPtr gpuDepthStencilView; + ConstPtr gpuDepthStencilResolveView; VkFramebuffer vkFramebuffer = VK_NULL_HANDLE; std::vector vkFrameBuffers; CCVKGPUSwapchain *swapchain = nullptr; diff --git a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp index 8597bf22a8..ce705b9ee8 100644 --- a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp @@ -41,6 +41,7 @@ void CCVKRenderPass::doInit(const RenderPassInfo & /*info*/) { _gpuRenderPass = ccnew CCVKGPURenderPass; _gpuRenderPass->colorAttachments = _colorAttachments; _gpuRenderPass->depthStencilAttachment = _depthStencilAttachment; + _gpuRenderPass->depthStencilResolveAttachment = _depthStencilResolveAttachment; _gpuRenderPass->subpasses = _subpasses; _gpuRenderPass->dependencies = _dependencies; @@ -56,14 +57,17 @@ void CCVKRenderPass::doInit(const RenderPassInfo & /*info*/) { if (_depthStencilAttachment.format != Format::UNKNOWN) { subpass.depthStencil = colorCount; } + if (_depthStencilResolveAttachment.format != Format::UNKNOWN) { + subpass.depthStencilResolve = colorCount + 1; + } } else { // unify depth stencil index for (auto &subpass : _gpuRenderPass->subpasses) { - if (subpass.depthStencil != INVALID_BINDING && subpass.depthStencil > colorCount) { + if (subpass.depthStencil != INVALID_BINDING && subpass.depthStencil >= colorCount) { subpass.depthStencil = colorCount; } - if (subpass.depthStencilResolve != INVALID_BINDING && subpass.depthStencilResolve > colorCount) { - subpass.depthStencilResolve = colorCount; + if (subpass.depthStencilResolve != INVALID_BINDING && subpass.depthStencilResolve >= colorCount) { + subpass.depthStencilResolve = colorCount + 1; } } } diff --git a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp index 8af0555a99..5f0a3e85b4 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp @@ -60,7 +60,7 @@ void CCVKTexture::createTexture(uint32_t width, uint32_t height, uint32_t size, if (_swapchain != nullptr) { _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); - _gpuTexture->memoryless = true; + _gpuTexture->memoryAllocated = false; } _gpuTexture->type = _info.type; @@ -121,14 +121,14 @@ void CCVKTexture::doInit(const SwapchainTextureInfo & /*info*/) { void CCVKGPUTexture::init() { cmdFuncCCVKCreateTexture(CCVKDevice::getInstance(), this); - if (!memoryless) { + if (memoryAllocated) { CCVKDevice::getInstance()->getMemoryStatus().textureSize += size; CC_PROFILE_MEMORY_INC(Texture, size); } } void CCVKGPUTexture::shutdown() { - if (!memoryless) { + if (memoryAllocated) { CCVKDevice::getInstance()->getMemoryStatus().textureSize -= size; CC_PROFILE_MEMORY_DEC(Texture, size); } diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp index 2b328b47e1..4d9c78dfc6 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp @@ -229,8 +229,8 @@ VkFormatFeatureFlags mapVkFormatFeatureFlags(TextureUsage usage) { return static_cast(flags); } -VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage) { - uint32_t flags = 0U; +VkImageUsageFlags mapVkImageUsageFlags(TextureUsage usage, TextureFlags textureFlags) { + VkImageUsageFlags flags = 0; if (hasFlag(usage, TextureUsage::TRANSFER_SRC)) flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; if (hasFlag(usage, TextureUsage::TRANSFER_DST)) flags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (hasFlag(usage, TextureUsage::SAMPLED)) flags |= VK_IMAGE_USAGE_SAMPLED_BIT; @@ -239,7 +239,14 @@ VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage) { if (hasFlag(usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT)) flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; if (hasFlag(usage, TextureUsage::INPUT_ATTACHMENT)) flags |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; if (hasFlag(usage, TextureUsage::SHADING_RATE)) flags |= VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR; - return static_cast(flags); + + if (hasFlag(textureFlags, TextureFlags::GEN_MIPMAP)) { + flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + } + if (hasFlag(textureFlags, TextureFlags::LAZILY_ALLOCATED)) { + flags |= VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; + } + return flags; } VkImageAspectFlags mapVkImageAspectFlags(Format format) { @@ -493,17 +500,6 @@ const VkStencilFaceFlags VK_STENCIL_FACE_FLAGS[] = { VK_STENCIL_FACE_FRONT_AND_BACK, }; -const VkSampleCountFlags VK_SAMPLE_COUNT_FLAGS[] = { - VK_SAMPLE_COUNT_1_BIT, - VK_SAMPLE_COUNT_2_BIT, -#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_IOS - VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_2_BIT, -#else // desktop platforms - VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_2_BIT, -#endif - VK_SAMPLE_COUNT_16_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_2_BIT, -}; - const VkAccessFlags FULL_ACCESS_FLAGS = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_INDEX_READ_BIT | diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.h b/native/cocos/renderer/gfx-vulkan/VKUtils.h index 4b7ac04abe..26bf88d35e 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.h +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.h @@ -58,7 +58,7 @@ VkAttachmentStoreOp mapVkStoreOp(StoreOp storeOp); VkBufferUsageFlagBits mapVkBufferUsageFlagBits(BufferUsage usage); VkImageType mapVkImageType(TextureType type); VkFormatFeatureFlags mapVkFormatFeatureFlags(TextureUsage usage); -VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage); +VkImageUsageFlags mapVkImageUsageFlags(TextureUsage usage, TextureFlags textureFlags); VkImageAspectFlags mapVkImageAspectFlags(Format format); VkImageCreateFlags mapVkImageCreateFlags(TextureType type); VkImageViewType mapVkImageViewType(TextureType viewType); @@ -94,7 +94,6 @@ extern const VkPipelineBindPoint VK_PIPELINE_BIND_POINTS[]; extern const VkResolveModeFlagBits VK_RESOLVE_MODES[]; extern const VkImageLayout VK_IMAGE_LAYOUTS[]; extern const VkStencilFaceFlags VK_STENCIL_FACE_FLAGS[]; -extern const VkSampleCountFlags VK_SAMPLE_COUNT_FLAGS[]; extern const VkAccessFlags FULL_ACCESS_FLAGS; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp index b9f2c8b070..432b1ad9ef 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp @@ -169,7 +169,7 @@ void CCWGPUDescriptorSetLayout::updateTextureLayout(uint8_t binding, const CCWGP const CCWGPUTexture *ccTex = static_cast(texture->isTextureView() ? texture->getViewInfo().texture : texture); TextureType type = ccTex->getViewInfo().type; (*iter).texture.viewDimension = toWGPUTextureViewDimension(type); - (*iter).texture.multisampled = ccTex->getInfo().samples != SampleCount::ONE; + (*iter).texture.multisampled = ccTex->getInfo().samples != SampleCount::X1; } } else { (*iter).texture.nextInChain = nullptr; diff --git a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp index 467e0f1639..dc425a1ae6 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp @@ -36,13 +36,13 @@ using namespace emscripten; class CCWGPURenderPassHelper { public: explicit CCWGPURenderPassHelper(const RenderPassInfo &info) { - SampleCount samples = SampleCount::ONE; + SampleCount samples = SampleCount::X1; for (size_t i = 0; i < info.colorAttachments.size(); i++) { colors[i].loadOp = toWGPULoadOp(info.colorAttachments[i].loadOp); colors[i].storeOp = toWGPUStoreOp(info.colorAttachments[i].storeOp); colors[i].clearValue = defaultClearColor; // TODO_Zeqaing : subpass - if (info.colorAttachments[i].sampleCount != SampleCount::ONE) + if (info.colorAttachments[i].sampleCount != SampleCount::X1) samples = info.colorAttachments[i].sampleCount; } @@ -54,7 +54,7 @@ public: depthStencils[0].depthClearValue = defaultClearDepth; depthStencils[0].depthReadOnly = false; depthStencils[0].stencilReadOnly = false; - if (samples == SampleCount::ONE) + if (samples == SampleCount::X1) samples = info.depthStencilAttachment.sampleCount; renderPassDesc = ccnew WGPURenderPassDescriptor; @@ -106,4 +106,4 @@ void CCWGPURenderPass::doDestroy() { } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp index d3f486c99b..77f723e0c1 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp @@ -234,7 +234,7 @@ CCWGPUTexture *CCWGPUTexture::defaultCommonTexture() { .flags = TextureFlagBit::NONE, .layerCount = 1, .levelCount = 1, - .samples = SampleCount::ONE, + .samples = SampleCount::X1, .depth = 1, .externalRes = nullptr, }; @@ -256,7 +256,7 @@ CCWGPUTexture *CCWGPUTexture::defaultStorageTexture() { .flags = TextureFlagBit::NONE, .layerCount = 1, .levelCount = 1, - .samples = SampleCount::ONE, + .samples = SampleCount::X1, .depth = 1, .externalRes = nullptr, }; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUUtils.h b/native/cocos/renderer/gfx-wgpu/WGPUUtils.h index 1ab82fb8fc..f79f50c489 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUUtils.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUUtils.h @@ -395,21 +395,7 @@ static WGPUShaderStageFlags toWGPUShaderStageFlag(ShaderStageFlagBit flag) { // TODO_Zeqiang: more flexible strategy static uint32_t toWGPUSampleCount(SampleCount sampleCount) { - // TODO_Zeqiang: msaa - return 1; - switch (sampleCount) { - case SampleCount::ONE: - return 1; - case SampleCount::MULTIPLE_PERFORMANCE: - return 4; - case SampleCount::MULTIPLE_BALANCE: - return 4; - case SampleCount::MULTIPLE_QUALITY: - return 4; - default: - printf("unsupport sampleCount %d.", sampleCount); - return 1; - } + return static_cast(sampleCount); } // NONE = 0, diff --git a/native/cocos/renderer/pipeline/RenderPipeline.cpp b/native/cocos/renderer/pipeline/RenderPipeline.cpp index 7cbecfdf11..4dc96a4742 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.cpp +++ b/native/cocos/renderer/pipeline/RenderPipeline.cpp @@ -40,7 +40,7 @@ #if CC_USE_DEBUG_RENDERER #include "profiler/DebugRenderer.h" #endif -#include "custom/NativeUtils.h" +#include "custom/NativeBuiltinUtils.h" #include "scene/Camera.h" #include "scene/Skybox.h" diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index f89f2c4aa2..0ac3830c64 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -114,7 +114,10 @@ struct LayoutAccess { struct FGRenderPassInfo { std::vector colorAccesses; LayoutAccess dsAccess; + LayoutAccess dsResolveAccess; gfx::RenderPassInfo rpInfo; + std::vector orderedViews; + bool needResolve{false}; }; struct ResourceAccessGraph { diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index 7ea920e513..1a2cffac76 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include "FGDispatcherGraphs.h" #include "FGDispatcherTypes.h" @@ -494,6 +495,9 @@ struct BarrierVisitor : public boost::bfs_visitor<> { dependency.srcSubpass = INVALID_ID; dependency.dstSubpass = subpassIdx; for (const auto &barrier : barriers.frontBarriers) { + if (barrier.beginStatus.accessFlag == gfx::AccessFlagBit::NONE) { + continue; + } auto resID = barrier.resourceID; auto findBarrierByResID = [resID](const Barrier &barrier) { return barrier.resourceID == resID; @@ -1034,7 +1038,8 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { if (batchedBarriers.find(i) == batchedBarriers.end()) { batchedBarriers.emplace(i, BarrierNode{}); auto &rpInfo = rag.rpInfos[i].rpInfo; - if (rpInfo.subpasses.size() > 1) { + // NOLINTNEXTLINE (readability-container-size-empty) + if (rpInfo.subpasses.size() >= 1) { batchedBarriers[i].subpassBarriers.resize(rpInfo.subpasses.size()); } } @@ -1097,8 +1102,9 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { // external res barrier for next frame for (const auto &externalPair : externalResMap) { + const auto &resName = externalPair.first; const auto &transition = externalPair.second; - auto resID = resourceGraph.valueIndex.at(externalPair.first); + auto resID = resourceGraph.valueIndex.at(resName); const auto &resTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, resID); auto &rescStates = get(ResourceGraph::StatesTag{}, resourceGraph, resID); @@ -1107,7 +1113,7 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { // 1. resource been written in this frame; // 2. first meet in this frame (no idea if any writes in next frame) // 3. backbuffer present - bool needNextBarrier = (namesSet.find(externalPair.first) != namesSet.end()) || (rescStates.states == gfx::AccessFlagBit::NONE); + bool needNextBarrier = (namesSet.find(resName) != namesSet.end()) || (rescStates.states == gfx::AccessFlagBit::NONE); // persistant resource states cached here rescStates.states = transition.currStatus.accessFlag; @@ -1144,21 +1150,13 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { bool hasSubpass = !(batchedBarriers[passID].subpassBarriers.size() <= 1); if (hasSubpass) { - auto &subpassBarriers = batchedBarriers[passID].subpassBarriers; - for (int i = static_cast(subpassBarriers.size()) - 1; i >= 0; --i) { - auto findBarrierByResID = [resID](const Barrier &barrier) { - return barrier.resourceID == resID; - }; - - const auto &frontBarriers = subpassBarriers[i].frontBarriers; - auto &rearBarriers = subpassBarriers[i].rearBarriers; - auto found = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID) != frontBarriers.end() || - std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID) != rearBarriers.end(); - if (found) { - rearBarriers.push_back(nextFrameResBarrier); - break; - } - } + // rpinfo instead + auto &fgRenderPassInfo = rag.rpInfos.at(passID); + auto iter = std::find(fgRenderPassInfo.orderedViews.begin(), fgRenderPassInfo.orderedViews.end(), resName.c_str()); + CC_ASSERT(iter != fgRenderPassInfo.orderedViews.end()); + auto index = std::distance(fgRenderPassInfo.orderedViews.begin(), iter); + index -= fgRenderPassInfo.rpInfo.depthStencilAttachment.format != gfx::Format::UNKNOWN; + fgRenderPassInfo.colorAccesses[index].nextAccess = nextFrameResBarrier.endStatus.accessFlag; } else { auto &rearBarriers = batchedBarriers[passID].blockBarrier.rearBarriers; rearBarriers.emplace_back(nextFrameResBarrier); @@ -1235,6 +1233,11 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { const auto &dsAccess = fgRenderpassInfo.dsAccess; dsAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); } + auto &dsResolveAttachment = fgRenderpassInfo.rpInfo.depthStencilResolveAttachment; + if (dsResolveAttachment.format != gfx::Format::UNKNOWN) { + const auto &dsAccess = fgRenderpassInfo.dsResolveAccess; + dsResolveAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); + } } } } @@ -1860,13 +1863,15 @@ auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAcce gfx::TextureUsage texUsage = gfx::TextureUsage::NONE; // TODO(Zeqiang): visbility of slot name "_" not found - if (memAccess == gfx::MemoryAccess::READ_ONLY) { + if (hasFlag(memAccess, gfx::MemoryAccess::READ_ONLY)) { if ((desc.flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE && rasterized) { texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::INPUT_ATTACHMENT)); } else { texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::SAMPLED | gfx::TextureUsage::STORAGE | gfx::TextureUsage::SHADING_RATE | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT)); } - } else { + } + + if (hasFlag(memAccess, gfx::MemoryAccess::WRITE_ONLY)) { texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::STORAGE)); } @@ -2092,23 +2097,65 @@ bool checkComputeViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, P return dependent; } -void fillRenderPassInfo(const RasterView &view, gfx::RenderPassInfo &rpInfo, uint32_t index, const ResourceDesc &viewDesc) { - if (view.attachmentType != AttachmentType::DEPTH_STENCIL) { +bool checkResolveResource(const Graphs &graphs, uint32_t vertID, uint32_t /*passID*/, ResourceAccessNode &node, const ccstd::pmr::vector &resolves) { + const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + bool dependent = false; + for (const auto &pair : resolves) { + const auto &resolveTargetName = pair.target; + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, vertex(resolveTargetName, resourceGraph)); + gfx::AccessFlags accessFlag = gfx::AccessFlags::COLOR_ATTACHMENT_WRITE; + gfx::TextureUsage usage = gfx::TextureUsage::COLOR_ATTACHMENT; + if (desc.format == gfx::Format::DEPTH_STENCIL) { + accessFlag = gfx::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE; + usage = gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT; + } + ViewStatus viewStatus{resolveTargetName, + PassType::RASTER, + gfx::ShaderStageFlags::FRAGMENT, + gfx::MemoryAccess::WRITE_ONLY, + accessFlag, usage}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); + auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, viewStatus); + if (lastVertId != INVALID_ID) { + tryAddEdge(lastVertId, vertID, resourceAccessGraph); + tryAddEdge(lastVertId, vertID, relationGraph); + dependent = true; + } + } + // sort for vector intersection + std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); + + return dependent; +} + +void fillRenderPassInfo(gfx::LoadOp loadOp, gfx::StoreOp storeOp, AttachmentType attachmentType, gfx::RenderPassInfo &rpInfo, uint32_t index, const ResourceDesc &viewDesc, bool resolve) { + if (attachmentType != AttachmentType::DEPTH_STENCIL) { auto &colorAttachment = rpInfo.colorAttachments[index]; - colorAttachment.format = viewDesc.format; - colorAttachment.loadOp = view.loadOp; - colorAttachment.storeOp = view.storeOp; - colorAttachment.sampleCount = viewDesc.sampleCount; - // colorAttachment.barrier = getGeneralBarrier(gfx::Device::getInstance(), view, prevAccess, nextAccess); + if (colorAttachment.format == gfx::Format::UNKNOWN) { + colorAttachment.format = viewDesc.format; + colorAttachment.loadOp = loadOp; + colorAttachment.storeOp = storeOp; + colorAttachment.sampleCount = viewDesc.sampleCount; + } else { + colorAttachment.storeOp = storeOp; + } + } else { - auto &depthStencilAttachment = rpInfo.depthStencilAttachment; - depthStencilAttachment.format = viewDesc.format; - depthStencilAttachment.depthLoadOp = view.loadOp; - depthStencilAttachment.depthStoreOp = view.storeOp; - depthStencilAttachment.stencilLoadOp = view.loadOp; - depthStencilAttachment.stencilStoreOp = view.storeOp; - depthStencilAttachment.sampleCount = viewDesc.sampleCount; - // depthStencilAttachment.barrier = getGeneralBarrier(gfx::Device::getInstance(), view, prevAccess, nextAccess); + auto &depthStencilAttachment = resolve ? + rpInfo.depthStencilResolveAttachment : + rpInfo.depthStencilAttachment; + if (depthStencilAttachment.format == gfx::Format::UNKNOWN) { + depthStencilAttachment.format = viewDesc.format; + depthStencilAttachment.depthLoadOp = loadOp; + depthStencilAttachment.depthStoreOp = storeOp; + depthStencilAttachment.stencilLoadOp = loadOp; + depthStencilAttachment.stencilStoreOp = storeOp; + depthStencilAttachment.sampleCount = viewDesc.sampleCount; + } else { + // TODO(Zeqiang): separate ds + depthStencilAttachment.depthStoreOp = storeOp; + depthStencilAttachment.stencilStoreOp = storeOp; + } } } @@ -2153,7 +2200,6 @@ void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass & const auto &view = pass.rasterViews.at(name); const auto &viewDesc = get(ResourceGraph::DescTag{}, resourceGraph, resID); auto prevAccess = pair.second; - CC_ASSERT(slotID < node.attachmentStatus.size()); // TD:remove find auto nodeIter = std::find_if(node.attachmentStatus.begin(), node.attachmentStatus.end(), [resID](const AccessStatus &status) { return status.vertID == resID; @@ -2182,10 +2228,27 @@ void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass & fgRenderpassInfo.dsAccess.prevAccess = prevAccess; fgRenderpassInfo.dsAccess.nextAccess = nextAccess; } - fillRenderPassInfo(view, rpInfo, slotID, viewDesc); + fillRenderPassInfo(view.loadOp, view.storeOp, view.attachmentType, rpInfo, slotID, viewDesc, false); + fgRenderpassInfo.orderedViews.emplace_back(name); } } else { - auto colorSize = pass.attachmentIndexMap.size(); + auto colorSize = pass.rasterViews.size(); + bool hasDS = std::any_of(pass.rasterViews.begin(), pass.rasterViews.end(), [](const auto &pair) { + return pair.second.attachmentType == AttachmentType::DEPTH_STENCIL; + }); + colorSize -= hasDS; + const auto &subpasses = pass.subpassGraph.subpasses; + uint32_t count = 0; + const auto &resg = resourceGraph; + auto resolveNum = std::accumulate(subpasses.begin(), subpasses.end(), 0, [&resg](uint32_t initVal, const Subpass &subpass) { + auto iter = std::find_if(subpass.resolvePairs.begin(), subpass.resolvePairs.end(), [&resg](const auto &pair) { + auto resID = vertex(pair.target, resg); + const auto& desc = get(ResourceGraph::DescTag{}, resg, resID); + return desc.format == gfx::Format::DEPTH_STENCIL || desc.format == gfx::Format::DEPTH; + }); + return initVal + subpass.resolvePairs.size() - (iter != subpass.resolvePairs.end()); + }); + colorSize += resolveNum; rpInfo.colorAttachments.resize(colorSize); fgRenderpassInfo.colorAccesses.resize(colorSize); } @@ -2266,6 +2329,7 @@ void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSub uint32_t accessType; uint32_t attachmentType; std::string_view slotName; + uint32_t samplesReverseWeight; }; using RasterViewSortKey = std::tuple; struct SubpassRasterViewData { @@ -2274,15 +2338,35 @@ void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSub gfx::AccessFlags access; }; + bool hasDS{false}; ccstd::vector viewIndex; for (const auto &[name, view] : pass.rasterViews) { auto resIter = rag.resourceIndex.find(name); + const auto &resID = vertex(name, resourceGraph); + const auto &desc = get(ResourceGraph::DescTag{}, resg, resID); gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; viewIndex.emplace_back(SubpassRasterViewData{ - {ACCESS_TYPE_WEIGHT[static_cast(view.accessType)], ATTACHMENT_TYPE_WEIGHT[static_cast(view.attachmentType)], view.slotName}, name, prevAccess}); + {ACCESS_TYPE_WEIGHT[static_cast(view.accessType)], ATTACHMENT_TYPE_WEIGHT[static_cast(view.attachmentType)], view.slotName, static_cast(desc.sampleCount)}, + name, + prevAccess, + }); + hasDS |= view.attachmentType == AttachmentType::DEPTH_STENCIL; + } + + for (const auto &resolve : pass.resolvePairs) { + auto resIter = rag.resourceIndex.find(resolve.target); + gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; + viewIndex.emplace_back(SubpassRasterViewData{ + {ACCESS_TYPE_WEIGHT[static_cast(AccessType::WRITE)], ATTACHMENT_TYPE_WEIGHT[static_cast(AttachmentType::RENDER_TARGET)], "_", 0xFFFFFFFF}, + resolve.target, + prevAccess, + }); } std::sort(viewIndex.begin(), viewIndex.end(), [](const SubpassRasterViewData &lhs, const SubpassRasterViewData &rhs) { + if (lhs.sortKey.samplesReverseWeight != rhs.sortKey.samplesReverseWeight) { + return lhs.sortKey.samplesReverseWeight < rhs.sortKey.samplesReverseWeight; + } if (lhs.sortKey.accessType != rhs.sortKey.accessType) { return lhs.sortKey.accessType < rhs.sortKey.accessType; } @@ -2308,49 +2392,94 @@ void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSub bool dependent{false}; dependent |= checkRasterViews(graphs, parentRagVert, passID, PassType::RASTER, *head, pass.rasterViews); dependent |= checkComputeViews(graphs, parentRagVert, passID, PassType::RASTER, *head, pass.computeViews); + dependent |= checkResolveResource(graphs, parentRagVert, passID, *head, pass.resolvePairs); if (!dependent) { tryAddEdge(EXPECT_START_ID, parentRagVert, resourceAccessGraph); tryAddEdge(EXPECT_START_ID, parentRagVert, relationGraph); } + if (!pass.resolvePairs.empty()) { + // ds resolve stores in depthStencilResolve + subpassInfo.resolves.resize(pass.rasterViews.size() - hasDS, gfx::INVALID_BINDING); + } + uint32_t localSlot = 0; + bool dsAppeared{false}; for (const auto &[sortKey, name, access] : viewIndex) { const auto *const resName = name.data(); auto findByResID = [&](const AccessStatus &status) { return status.vertID == rag.resourceIndex.at(resName); }; auto iter = std::find_if(node.attachmentStatus.begin(), node.attachmentStatus.end(), findByResID); - const auto &view = pass.rasterViews.at(resName); + + // TODO(Zeqiang): remove find + const auto &targetName = name; auto resID = rag.resourceIndex.at(resName); const auto &viewDesc = get(ResourceGraph::DescTag{}, resg, rag.resourceIndex.at(resName)); - uint32_t slot = uberPass.attachmentIndexMap.size(); - if (view.attachmentType != AttachmentType::DEPTH_STENCIL) { + AttachmentType attachmentType{AttachmentType::RENDER_TARGET}; + AccessType accessType{AccessType::WRITE}; + gfx::LoadOp loadOp{gfx::LoadOp::DISCARD}; + gfx::StoreOp storeOp{gfx::StoreOp::STORE}; + + uint32_t slot = dsAppeared ? localSlot - 1 : localSlot; + // std::distance(uberPass.rasterViews.begin(), uberPass.rasterViews.find(resName)); + // slot = dsAppeared ? slot - 1 : slot; + /*if (attachmentType != AttachmentType::DEPTH_STENCIL) { CC_ASSERT(uberPass.attachmentIndexMap.count(resName)); slot = uberPass.attachmentIndexMap.at(resName); - } + }*/ // TD:remove find auto nodeIter = std::find_if(head->attachmentStatus.begin(), head->attachmentStatus.end(), [resID](const AccessStatus &status) { return status.vertID == resID; }); auto nextAccess = nodeIter->accessFlag; - if (view.attachmentType != AttachmentType::DEPTH_STENCIL) { - if (view.attachmentType == AttachmentType::SHADING_RATE) { - subpassInfo.shadingRate = slot; + + auto resolveIter = std::find_if(pass.resolvePairs.begin(), pass.resolvePairs.end(), [&targetName](const ResolvePair &resolve) { + return strcmp(resolve.target.c_str(), targetName.data()) == 0; + }); + bool resolveView = resolveIter != pass.resolvePairs.end(); + if (resolveView) { + attachmentType = viewDesc.format == gfx::Format::DEPTH_STENCIL ? AttachmentType::DEPTH_STENCIL : AttachmentType::RENDER_TARGET; + if (attachmentType == AttachmentType::DEPTH_STENCIL) { + subpassInfo.depthStencilResolve = slot; + subpassInfo.depthResolveMode = gfx::ResolveMode::SAMPLE_ZERO; // resolveiter->mode; + subpassInfo.stencilResolveMode = gfx::ResolveMode::SAMPLE_ZERO; // resolveiter->mode1; + fgRenderpassInfo.dsResolveAccess.nextAccess = nextAccess; } else { - if (view.accessType != AccessType::READ) { - subpassInfo.colors.emplace_back(slot); - } - if (view.accessType != AccessType::WRITE) { - subpassInfo.inputs.emplace_back(slot); - } + auto indexIter = std::find(fgRenderpassInfo.orderedViews.begin(), fgRenderpassInfo.orderedViews.end(), resolveIter->source.c_str()); + auto srcIndex = indexIter == fgRenderpassInfo.orderedViews.end() ? fgRenderpassInfo.orderedViews.size() + : std::distance(fgRenderpassInfo.orderedViews.begin(), indexIter); + subpassInfo.resolves[srcIndex] = slot; + fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; } - fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; + accessType = AccessType::WRITE; } else { - fgRenderpassInfo.dsAccess.nextAccess = nextAccess; - subpassInfo.depthStencil = rpInfo.colorAttachments.size(); + const auto &view = pass.rasterViews.at(resName); + attachmentType = view.attachmentType; + accessType = view.accessType; + loadOp = view.loadOp; + storeOp = view.storeOp; + + if (attachmentType != AttachmentType::DEPTH_STENCIL) { + if (attachmentType == AttachmentType::SHADING_RATE) { + subpassInfo.shadingRate = slot; + } else { + if (accessType != AccessType::READ) { + subpassInfo.colors.emplace_back(slot); + } + if (accessType != AccessType::WRITE) { + subpassInfo.inputs.emplace_back(slot); + } + } + fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; + } else { + fgRenderpassInfo.dsAccess.nextAccess = nextAccess; + subpassInfo.depthStencil = rpInfo.colorAttachments.size(); + dsAppeared = true; + } } if (iter == node.attachmentStatus.end()) { @@ -2360,13 +2489,19 @@ void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSub CC_ASSERT(head->attachmentStatus.size() > localSlot); auto nextAccess = head->attachmentStatus[localSlot].accessFlag; - if (view.attachmentType == AttachmentType::DEPTH_STENCIL) { - fgRenderpassInfo.dsAccess.prevAccess = prevAccess; + if (attachmentType == AttachmentType::DEPTH_STENCIL) { + if (resolveView) { + fgRenderpassInfo.dsResolveAccess.prevAccess = prevAccess; + } else { + fgRenderpassInfo.dsAccess.prevAccess = prevAccess; + } } else { fgRenderpassInfo.colorAccesses[slot].prevAccess = prevAccess; } - fillRenderPassInfo(view, rpInfo, slot, viewDesc); + fgRenderpassInfo.orderedViews.emplace_back(resName); } + fillRenderPassInfo(loadOp, storeOp, attachmentType, rpInfo, slot, viewDesc, resolveView); + fgRenderpassInfo.needResolve |= resolveView; ++localSlot; } diff --git a/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.cpp b/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.cpp new file mode 100644 index 0000000000..07c7d0aaa3 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.cpp @@ -0,0 +1,557 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "NativeBuiltinUtils.h" +#include "cocos/application/ApplicationManager.h" +#include "cocos/renderer/gfx-base/GFXDef-common.h" +#include "cocos/renderer/gfx-base/GFXDevice.h" +#include "cocos/renderer/pipeline/PipelineSceneData.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" +#include "cocos/renderer/pipeline/custom/NativeTypes.h" +#include "cocos/renderer/pipeline/custom/NativeUtils.h" +#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" +#include "cocos/scene/Camera.h" +#include "cocos/scene/Fog.h" +#include "cocos/scene/Skybox.h" +#include "cocos/scene/SpotLight.h" + +namespace cc { + +namespace render { + +void setupQuadVertexBuffer(gfx::Device &device, const Vec4 &viewport, float vbData[16]) { + auto minX = static_cast(viewport.x); + auto maxX = static_cast(viewport.x + viewport.z); + auto minY = static_cast(viewport.y); + auto maxY = static_cast(viewport.y + viewport.w); + if (device.getCapabilities().screenSpaceSignY > 0) { + std::swap(minY, maxY); + } + int n = 0; + vbData[n++] = -1.0F; + vbData[n++] = -1.0F; + vbData[n++] = minX; // uv + vbData[n++] = maxY; + vbData[n++] = 1.0F; + vbData[n++] = -1.0F; + vbData[n++] = maxX; + vbData[n++] = maxY; + vbData[n++] = -1.0F; + vbData[n++] = 1.0F; + vbData[n++] = minX; + vbData[n++] = minY; + vbData[n++] = 1.0F; + vbData[n++] = 1.0F; + vbData[n++] = maxX; + vbData[n++] = minY; +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters) +void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter) { + const auto &root = *Root::getInstance(); + const auto shadingWidth = static_cast(width); + const auto shadingHeight = static_cast(height); + setter.setVec4( + "cc_time", + Vec4( + root.getCumulativeTime(), + root.getFrameTime(), + static_cast(CC_CURRENT_ENGINE()->getTotalFrames()), + 0.0F)); + + setter.setVec4( + "cc_screenSize", + Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); + setter.setVec4( + "cc_nativeSize", + Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); +#if 0 + const auto *debugView = root.getDebugView(); + if (debugView) { + setter.setVec4( + "cc_debug_view_mode", + Vec4(static_cast(debugView->getSingleMode()), + debugView->isLightingWithAlbedo() ? 1.0F : 0.0F, + debugView->isCsmLayerColoration() ? 1.0F : 0.0F, + 0.0F)); + Vec4 debugPackVec{}; + for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); + i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + const auto idx = i % 4; + (&debugPackVec.x)[idx] = debugView->isCompositeModeEnabled(i) ? 1.0F : 0.0F; + const auto packIdx = static_cast(floor(static_cast(i) / 4.0F)); + if (idx == 3) { + std::string name("cc_debug_view_composite_pack_"); + name.append(std::to_string(packIdx + 1)); + setter.setVec4(name, debugPackVec); + } + } + } else { + setter.setVec4("cc_debug_view_mode", Vec4(0.0F, 1.0F, 0.0F, 0.0F)); + Vec4 debugPackVec{}; + for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); + i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + const auto idx = i % 4; + (&debugPackVec.x)[idx] = 1.0F; + const auto packIdx = static_cast(floor(i / 4.0)); + if (idx == 3) { + std::string name("cc_debug_view_composite_pack_"); + name.append(std::to_string(packIdx + 1)); + setter.setVec4(name, debugPackVec); + } + } + } +#endif +} + +namespace { + +uint8_t getCombineSignY(gfx::Device *device) { + // 0: vk, 1: metal, 2: none, 3: gl-like + static int8_t combineSignY{-1}; + if (combineSignY < 0) { + const float screenSpaceSignY = device->getCapabilities().screenSpaceSignY * 0.5F + 0.5F; + const float clipSpaceSignY = device->getCapabilities().clipSpaceSignY * 0.5F + 0.5F; + combineSignY = static_cast(static_cast(screenSpaceSignY) << 1 | static_cast(clipSpaceSignY)); + } + return static_cast(combineSignY); +} + +} // namespace + +void setCameraUBOValues( + const scene::Camera &camera, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &cfg, + const scene::DirectionalLight *mainLight, + RenderData &data) { + CC_EXPECTS(camera.getNode()); + CC_EXPECTS(cfg.getSkybox()); + const auto &skybox = *cfg.getSkybox(); + const auto &shadingScale = cfg.getShadingScale(); + // Camera + setMat4Impl(data, layoutGraph, "cc_matView", camera.getMatView()); + setMat4Impl(data, layoutGraph, "cc_matViewInv", camera.getNode()->getWorldMatrix()); + setMat4Impl(data, layoutGraph, "cc_matProj", camera.getMatProj()); + setMat4Impl(data, layoutGraph, "cc_matProjInv", camera.getMatProjInv()); + setMat4Impl(data, layoutGraph, "cc_matViewProj", camera.getMatViewProj()); + setMat4Impl(data, layoutGraph, "cc_matViewProjInv", camera.getMatViewProjInv()); + setVec4Impl(data, layoutGraph, "cc_cameraPos", + Vec4( + camera.getPosition().x, + camera.getPosition().y, + camera.getPosition().z, + getCombineSignY(cc::gfx::Device::getInstance()))); + setVec4Impl(data, layoutGraph, "cc_surfaceTransform", + Vec4( + static_cast(camera.getSurfaceTransform()), + static_cast(camera.getCameraUsage()), + cosf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))), + sinf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))))); + setVec4Impl(data, layoutGraph, "cc_screenScale", + Vec4( + cfg.getShadingScale(), + cfg.getShadingScale(), + 1.0F / cfg.getShadingScale(), + 1.0F / cfg.getShadingScale())); + setVec4Impl(data, layoutGraph, "cc_exposure", + Vec4( + camera.getExposure(), + 1.0F / camera.getExposure(), + cfg.isHDR() ? 1.0F : 0.0F, + 1.0F / scene::Camera::getStandardExposureValue())); + + if (mainLight) { + const auto &shadowInfo = *cfg.getShadows(); + const bool shadowEnable = (mainLight->isShadowEnabled() && + shadowInfo.getType() == scene::ShadowType::SHADOW_MAP); + setVec4Impl(data, layoutGraph, "cc_mainLitDir", + Vec4( + mainLight->getDirection().x, + mainLight->getDirection().y, + mainLight->getDirection().z, + shadowEnable)); + auto r = mainLight->getColor().x; + auto g = mainLight->getColor().y; + auto b = mainLight->getColor().z; + if (mainLight->isUseColorTemperature()) { + r *= mainLight->getColorTemperatureRGB().x; + g *= mainLight->getColorTemperatureRGB().y; + b *= mainLight->getColorTemperatureRGB().z; + } + auto w = mainLight->getIlluminance(); + if (cfg.isHDR()) { + w *= camera.getExposure(); + } + setVec4Impl(data, layoutGraph, "cc_mainLitColor", Vec4(r, g, b, w)); + } else { + setVec4Impl(data, layoutGraph, "cc_mainLitDir", Vec4(0, 0, 1, 0)); + setVec4Impl(data, layoutGraph, "cc_mainLitColor", Vec4(0, 0, 0, 0)); + } + + CC_EXPECTS(cfg.getAmbient()); + auto &ambient = *cfg.getAmbient(); + auto &skyColor = ambient.getSkyColor(); + if (cfg.isHDR()) { + skyColor.w = ambient.getSkyIllum() * camera.getExposure(); + } else { + skyColor.w = ambient.getSkyIllum(); + } + setVec4Impl(data, layoutGraph, "cc_ambientSky", + Vec4(skyColor.x, skyColor.y, skyColor.z, skyColor.w)); + setVec4Impl(data, layoutGraph, "cc_ambientGround", + Vec4( + ambient.getGroundAlbedo().x, + ambient.getGroundAlbedo().y, + ambient.getGroundAlbedo().z, + skybox.getEnvmap() ? static_cast(skybox.getEnvmap()->mipmapLevel()) : 1.0F)); + + CC_EXPECTS(cfg.getFog()); + const auto &fog = *cfg.getFog(); + + const auto &colorTempRGB = fog.getColorArray(); + setVec4Impl(data, layoutGraph, "cc_fogColor", + Vec4(colorTempRGB.x, colorTempRGB.y, colorTempRGB.z, colorTempRGB.z)); + setVec4Impl(data, layoutGraph, "cc_fogBase", + Vec4(fog.getFogStart(), fog.getFogEnd(), fog.getFogDensity(), 0.0F)); + setVec4Impl(data, layoutGraph, "cc_fogAdd", + Vec4(fog.getFogTop(), fog.getFogRange(), fog.getFogAtten(), 0.0F)); + setVec4Impl(data, layoutGraph, "cc_nearFar", + Vec4(camera.getNearClip(), camera.getFarClip(), camera.getClipSpaceMinz(), 0.0F)); + setVec4Impl(data, layoutGraph, "cc_viewPort", + Vec4( + camera.getViewport().x, + camera.getViewport().y, + shadingScale * static_cast(camera.getWindow()->getWidth()) * camera.getViewport().z, + shadingScale * static_cast(camera.getWindow()->getHeight()) * camera.getViewport().w)); +} + +namespace { + +float getPCFRadius( + const scene::Shadows &shadowInfo, + const scene::DirectionalLight &mainLight) { + const auto &shadowMapSize = shadowInfo.getSize().x; + switch (mainLight.getShadowPcf()) { + case scene::PCFType::HARD: + return 0.0F; + case scene::PCFType::SOFT: + return 1.0F / (shadowMapSize * 0.5F); + case scene::PCFType::SOFT_2X: + return 2.0F / (shadowMapSize * 0.5F); + case scene::PCFType::SOFT_4X: + return 3.0F / (shadowMapSize * 0.5F); + default: + break; + } + return 0.0F; +} + +} // namespace + +void setShadowUBOView( + gfx::Device &device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + const scene::DirectionalLight &mainLight, + RenderData &data) { + const auto &shadowInfo = *sceneData.getShadows(); + const auto &csmLayers = *sceneData.getCSMLayers(); + const auto &csmSupported = sceneData.getCSMSupported(); + const auto &packing = pipeline::supportsR32FloatTexture(&device) ? 0.0F : 1.0F; + Vec4 vec4ShadowInfo{}; + if (shadowInfo.isEnabled()) { + if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { + if (mainLight.isShadowEnabled()) { + if (mainLight.isShadowFixedArea() || + mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1 || !csmSupported) { + // Shadow + const auto &matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); + const auto &matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); + const auto &matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); + const auto &near = mainLight.getShadowNear(); + const auto &far = mainLight.getShadowFar(); + + setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); + setVec4Impl(data, layoutGraph, "cc_shadowProjDepthInfo", + Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15])); + + setVec4Impl(data, layoutGraph, "cc_shadowProjInfo", + Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05])); + setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); + vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); + setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set(static_cast(scene::LightType::DIRECTIONAL), packing, mainLight.getShadowNormalBias(), 0); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); + } else { + { // CSM + const auto layerThreshold = getPCFRadius(shadowInfo, mainLight); + const auto numCascades = static_cast(mainLight.getCSMLevel()); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir0", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir1", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir2", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmAtlas", numCascades); + setMat4ArraySizeImpl(data, layoutGraph, "cc_matCSMViewProj", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmProjDepthInfo", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmProjInfo", numCascades); + + Vec4 csmSplitsInfo{}; + for (uint32_t i = 0; i < numCascades; ++i) { + const auto &layer = *csmLayers.getLayers()[i]; + + const auto &matShadowView = layer.getMatShadowView(); + vec4ShadowInfo.set(matShadowView.m[0], matShadowView.m[4], matShadowView.m[8], layerThreshold); + setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir0", vec4ShadowInfo, i); + vec4ShadowInfo.set(matShadowView.m[1], matShadowView.m[5], matShadowView.m[9], layer.getSplitCameraNear()); + setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir1", vec4ShadowInfo, i); + vec4ShadowInfo.set(matShadowView.m[2], matShadowView.m[6], matShadowView.m[10], layer.getSplitCameraFar()); + setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir2", vec4ShadowInfo, i); + + const auto &csmAtlas = layer.getCSMAtlas(); + setVec4ArrayElemImpl(data, layoutGraph, "cc_csmAtlas", csmAtlas, i); + + const auto &matShadowViewProj = layer.getMatShadowViewProj(); + setMat4ArrayElemImpl(data, layoutGraph, "cc_matCSMViewProj", matShadowViewProj, i); + + const auto &matShadowProj = layer.getMatShadowProj(); + setVec4ArrayElemImpl(data, layoutGraph, + "cc_csmProjDepthInfo", + Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15]), + i); + + setVec4ArrayElemImpl(data, layoutGraph, + "cc_csmProjInfo", + Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05]), + i); + + (&csmSplitsInfo.x)[i] = layer.getSplitCameraFar() / mainLight.getShadowDistance(); + } + setVec4Impl(data, layoutGraph, "cc_csmSplitsInfo", csmSplitsInfo); + } + { // Shadow + vec4ShadowInfo.set(0, 0, 0, 1.0F - mainLight.getShadowSaturation()); + setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set( + static_cast(scene::LightType::DIRECTIONAL), + packing, + mainLight.getShadowNormalBias(), + static_cast(mainLight.getCSMLevel())); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); + } + } + { // Shadow + vec4ShadowInfo.set( + shadowInfo.getSize().x, shadowInfo.getSize().y, + static_cast(mainLight.getShadowPcf()), mainLight.getShadowBias()); + setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); + } + } + } else { + Vec3 tempVec3 = shadowInfo.getNormal().getNormalized(); + setVec4Impl(data, layoutGraph, + "cc_planarNDInfo", + Vec4(tempVec3.x, tempVec3.y, tempVec3.z, -shadowInfo.getDistance())); + } + { + const auto &color = shadowInfo.getShadowColor4f(); + setColorImpl(data, layoutGraph, "cc_shadowColor", + gfx::Color{color[0], color[1], color[2], color[3]}); + } + } +} + +void setShadowUBOLightView( + gfx::Device *device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + const scene::Light &light, + uint32_t level, + RenderData &data) { + const auto &shadowInfo = *sceneData.getShadows(); + const auto &csmLayers = *sceneData.getCSMLayers(); + const auto &packing = pipeline::supportsR32FloatTexture(device) ? 0.0F : 1.0F; + const auto &cap = device->getCapabilities(); + Vec4 vec4ShadowInfo{}; + + // ShadowMap + switch (light.getType()) { + case scene::LightType::DIRECTIONAL: { + const auto &mainLight = dynamic_cast(light); + if (shadowInfo.isEnabled() && mainLight.isShadowEnabled()) { + if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { + float near = 0.1F; + float far = 0.0F; + Mat4 matShadowView; + Mat4 matShadowProj; + Mat4 matShadowViewProj; + scene::CSMLevel levelCount{}; + if (mainLight.isShadowFixedArea() || mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1) { + matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); + matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); + matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); + if (mainLight.isShadowFixedArea()) { + near = mainLight.getShadowNear(); + far = mainLight.getShadowFar(); + levelCount = static_cast(0); + } else { + near = 0.1F; + far = csmLayers.getSpecialLayer()->getShadowCameraFar(); + levelCount = scene::CSMLevel::LEVEL_1; + } + vec4ShadowInfo.set(static_cast(scene::LightType::DIRECTIONAL), packing, mainLight.getShadowNormalBias(), 0); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); + } else { + const auto &layer = *csmLayers.getLayers()[level]; + matShadowView = layer.getMatShadowView(); + matShadowProj = layer.getMatShadowProj(); + matShadowViewProj = layer.getMatShadowViewProj(); + + near = layer.getSplitCameraNear(); + far = layer.getSplitCameraFar(); + levelCount = mainLight.getCSMLevel(); + } + setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); + setVec4Impl(data, layoutGraph, "cc_shadowProjDepthInfo", + Vec4( + matShadowProj.m[10], + matShadowProj.m[14], + matShadowProj.m[11], + matShadowProj.m[15])); + setVec4Impl(data, layoutGraph, "cc_shadowProjInfo", + Vec4( + matShadowProj.m[00], + matShadowProj.m[05], + 1.0F / matShadowProj.m[00], + 1.0F / matShadowProj.m[05])); + setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); + vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); + setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set( + static_cast(scene::LightType::DIRECTIONAL), + packing, + mainLight.getShadowNormalBias(), + static_cast(levelCount)); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); + vec4ShadowInfo.set( + shadowInfo.getSize().x, + shadowInfo.getSize().y, + static_cast(mainLight.getShadowPcf()), + mainLight.getShadowBias()); + setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); + } + } + break; + } + case scene::LightType::SPOT: { + const auto &spotLight = dynamic_cast(light); + if (shadowInfo.isEnabled() && spotLight.isShadowEnabled()) { + const auto &matShadowCamera = spotLight.getNode()->getWorldMatrix(); + const auto matShadowView = matShadowCamera.getInversed(); + setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); + + Mat4 matShadowViewProj{}; + Mat4::createPerspective(spotLight.getAngle(), 1.0F, 0.001F, + spotLight.getRange(), true, + cap.clipSpaceMinZ, cap.clipSpaceSignY, 0, &matShadowViewProj); + matShadowViewProj.multiply(matShadowView); + setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); + + const Vec4 shadowNFLSInfos(0.01F, spotLight.getRange(), 0.0F, 0.0F); + setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", shadowNFLSInfos); + + const Vec4 shadowWHPBInfos( + shadowInfo.getSize().x, + shadowInfo.getSize().y, + spotLight.getShadowPcf(), + spotLight.getShadowBias()); + setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", shadowWHPBInfos); + + const Vec4 shadowLPNNInfos(static_cast(scene::LightType::SPOT), packing, spotLight.getShadowNormalBias(), 0.0F); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", shadowLPNNInfos); + } + break; + } + default: + break; + } + + const auto &color = shadowInfo.getShadowColor4f(); + setColorImpl(data, layoutGraph, "cc_shadowColor", gfx::Color{color[0], color[1], color[2], color[3]}); +} + +void setLegacyTextureUBOView( + gfx::Device &device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + RenderData &data) { + const auto &skybox = *sceneData.getSkybox(); + if (skybox.getReflectionMap()) { + auto &texture = *skybox.getReflectionMap()->getGFXTexture(); + auto *sampler = device.getSampler(skybox.getReflectionMap()->getSamplerInfo()); + setTextureImpl(data, layoutGraph, "cc_environment", &texture); + setSamplerImpl(data, layoutGraph, "cc_environment", sampler); + } else { + const auto *envmap = + skybox.getEnvmap() + ? skybox.getEnvmap() + : BuiltinResMgr::getInstance()->get("default-cube-texture"); + if (envmap) { + auto *texture = envmap->getGFXTexture(); + auto *sampler = device.getSampler(envmap->getSamplerInfo()); + setTextureImpl(data, layoutGraph, "cc_environment", texture); + setSamplerImpl(data, layoutGraph, "cc_environment", sampler); + } + } + const auto *diffuseMap = + skybox.getDiffuseMap() + ? skybox.getDiffuseMap() + : BuiltinResMgr::getInstance()->get("default-cube-texture"); + if (diffuseMap) { + auto *texture = diffuseMap->getGFXTexture(); + auto *sampler = device.getSampler(diffuseMap->getSamplerInfo()); + setTextureImpl(data, layoutGraph, "cc_diffuseMap", texture); + setSamplerImpl(data, layoutGraph, "cc_diffuseMap", sampler); + } + gfx::SamplerInfo samplerPointInfo{ + gfx::Filter::POINT, + gfx::Filter::POINT, + gfx::Filter::NONE, + gfx::Address::CLAMP, + gfx::Address::CLAMP, + gfx::Address::CLAMP}; + auto *pointSampler = device.getSampler(samplerPointInfo); + setSamplerImpl(data, layoutGraph, "cc_shadowMap", pointSampler); + // setTextureImpl(data, layoutGraph, "cc_shadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); + setSamplerImpl(data, layoutGraph, "cc_spotShadowMap", pointSampler); + // setTextureImpl(data, layoutGraph, "cc_spotShadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.h b/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.h new file mode 100644 index 0000000000..b123a5332a --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.h @@ -0,0 +1,86 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once +#include +#include "cocos/renderer/pipeline/custom/LayoutGraphFwd.h" +#include "cocos/renderer/pipeline/custom/NativeFwd.h" +#include "cocos/renderer/pipeline/custom/RenderGraphFwd.h" + +namespace cc { + +namespace scene { +class Camera; +class DirectionalLight; +} // namespace scene + +namespace gfx { +class Device; +} // namespace gfx + +namespace pipeline { +class PipelineSceneData; +} // namespace pipeline + +namespace render { + +void setCameraUBOValues( + const scene::Camera &camera, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &cfg, + const scene::DirectionalLight *mainLight, + RenderData &data); + +void setLegacyTextureUBOView( + gfx::Device &device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + RenderData &data); + +// For use shadow map +void setShadowUBOView( + gfx::Device &device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + const scene::DirectionalLight &mainLight, + RenderData &data); + +// For build shadow map +void setShadowUBOLightView( + gfx::Device *device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + const scene::Light &light, + uint32_t level, + RenderData &data); + +// Render graph +void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter); + +// Geometry +void setupQuadVertexBuffer(gfx::Device &device, const Vec4 &viewport, float vbData[16]); + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeDefaultScene.cpp b/native/cocos/renderer/pipeline/custom/NativeDefaultScene.cpp deleted file mode 100644 index 219ef6690e..0000000000 --- a/native/cocos/renderer/pipeline/custom/NativeDefaultScene.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/**************************************************************************** - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "NativePipelineTypes.h" - -namespace cc { - -namespace render { - -const pipeline::PipelineSceneData *DefaultSceneVisitor::getPipelineSceneData() const { - return nullptr; -} - -void DefaultSceneVisitor::setViewport(const gfx::Viewport &vp) {} -void DefaultSceneVisitor::setScissor(const gfx::Rect &rect) {} -void DefaultSceneVisitor::bindPipelineState(gfx::PipelineState *pso) {} -void DefaultSceneVisitor::bindDescriptorSet(uint32_t set, gfx::DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) {} -void DefaultSceneVisitor::bindInputAssembler(gfx::InputAssembler *ia) {} -void DefaultSceneVisitor::updateBuffer(gfx::Buffer *buff, const void *data, uint32_t size) {} -void DefaultSceneVisitor::draw(const gfx::DrawInfo &info) {} - -SceneTask *DefaultForwardLightingTransversal::transverse(SceneVisitor *visitor) const { - std::ignore = visitor; - return nullptr; -} - -} // namespace render - -} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index c044f4204a..23fdda466b 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -97,6 +97,7 @@ struct RenderGraphVisitorContext { void clear(gfx::RenderPassInfo& info) { info.colorAttachments.clear(); info.depthStencilAttachment = {}; + info.depthStencilResolveAttachment = {}; info.subpasses.clear(); info.dependencies.clear(); } @@ -177,25 +178,34 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( fbInfo.colorTextures.reserve(pass.rasterViews.size()); PmrFlatSet set(scratch); - auto fillFrameBufferInfo = [&](const auto& pass) { - auto numTotalAttachments = static_cast(pass.rasterViews.size()); - - PmrFlatMap viewIndex(scratch); - for (const auto& [name, view] : pass.rasterViews) { - if (set.emplace(name).second) { - viewIndex.emplace(view.slotID, name); - } - } + auto fillFrameBufferInfo = [&](const ccstd::vector& passViews, bool hasResolve) { + std::ignore = hasResolve; + const auto& uberPass = pass; + auto numTotalAttachments = static_cast(passViews.size()); // uint32_t dsvCount = 0; uint32_t index = 0; - for (const auto& [slotID, name] : viewIndex) { - const auto& view = pass.rasterViews.at(name); - const auto resID = vertex(name, ctx.resourceGraph); - const auto& desc = get(ResourceGraph::DescTag{}, ctx.resourceGraph, resID); + for (const auto& nameIn : passViews) { + const char* name = nameIn.c_str(); + bool colorLikeView{true}; + bool dsResolveAttachment{false}; + auto clearColor = gfx::Color{}; + auto iter = pass.rasterViews.find(name); + if(iter != pass.rasterViews.end()) { + const auto& view = iter->second; + colorLikeView = view.attachmentType == AttachmentType::RENDER_TARGET || view.attachmentType == AttachmentType::SHADING_RATE; + clearColor = view.clearColor; + } else { + // resolves + const auto resID = vertex(name, ctx.resourceGraph); + const auto& desc = get(ResourceGraph::DescTag{}, ctx.resourceGraph, resID); + CC_ASSERT(hasResolve && desc.sampleCount == gfx::SampleCount::X1); + colorLikeView = desc.format != gfx::Format::DEPTH_STENCIL && desc.format != gfx::Format::DEPTH; + dsResolveAttachment = !colorLikeView; + } - if (view.attachmentType == AttachmentType::RENDER_TARGET || view.attachmentType == AttachmentType::SHADING_RATE) { // RenderTarget - data.clearColors.emplace_back(view.clearColor); + if (colorLikeView) { // RenderTarget + data.clearColors.emplace_back(clearColor); auto resID = findVertex(name, resg); visitObject( @@ -239,22 +249,23 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( std::ignore = view; CC_EXPECTS(false); }); - } else if (view.attachmentType == AttachmentType::DEPTH_STENCIL) { // DepthStencil - data.clearDepth = view.clearColor.x; - data.clearStencil = static_cast(view.clearColor.y); + } else { // DepthStencil + if (!dsResolveAttachment) { + data.clearDepth = clearColor.x; + data.clearStencil = static_cast(clearColor.y); + } - if (!fbInfo.depthStencilTexture) { - auto resID = findVertex(name, resg); - visitObject( + auto &dsAttachment = dsResolveAttachment ? fbInfo.depthStencilResolveTexture : fbInfo.depthStencilTexture; + + auto resID = findVertex(name, resg); + visitObject( resID, resg, [&](const ManagedTexture& tex) { CC_EXPECTS(tex.texture); - CC_EXPECTS(!fbInfo.depthStencilTexture); - fbInfo.depthStencilTexture = tex.texture.get(); + dsAttachment = tex.texture.get(); }, [&](const IntrusivePtr& tex) { - CC_EXPECTS(!fbInfo.depthStencilTexture); - fbInfo.depthStencilTexture = tex.get(); + dsAttachment = tex.get(); }, [&](const FormatView& view) { std::ignore = view; @@ -267,7 +278,6 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( [](const auto& /*unused*/) { CC_EXPECTS(false); }); - } } ++index; } @@ -281,14 +291,14 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( // persistent cache data.clearColors.reserve(numColors); - rpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID).rpInfo; - fillFrameBufferInfo(pass); + const auto& fgdRpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID); + rpInfo = fgdRpInfo.rpInfo; + fillFrameBufferInfo(fgdRpInfo.orderedViews, false); } else { - rpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID).rpInfo; - for (const auto& subpass : pass.subpassGraph.subpasses) { - fillFrameBufferInfo(subpass); - } + const auto& fgdRpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID); + rpInfo = fgdRpInfo.rpInfo; + fillFrameBufferInfo(fgdRpInfo.orderedViews, fgdRpInfo.needResolve); } CC_ENSURES(rpInfo.colorAttachments.size() == data.clearColors.size()); CC_ENSURES(rpInfo.colorAttachments.size() == fbInfo.colorTextures.size()); @@ -923,6 +933,9 @@ getComputeViews(RenderGraph::vertex_descriptor passID, const RenderGraph& rg) { if (holds(passID, rg)) { return get(RasterPassTag{}, passID, rg).computeViews; } + if (holds(passID, rg)) { + return get(RasterSubpassTag{}, passID, rg).computeViews; + } CC_EXPECTS(holds(passID, rg)); return get(ComputeTag{}, passID, rg).computeViews; } @@ -1135,7 +1148,17 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { const auto& subpass = get(RasterSubpassTag{}, vertID, ctx.g); // render pass const auto& layoutName = get(RenderGraph::LayoutTag{}, ctx.g, vertID); - const auto& layoutID = locate(LayoutGraphData::null_vertex(), layoutName, ctx.lg); + + auto parentLayoutID = ctx.currentPassLayoutID; + auto layoutID = parentLayoutID; + if (!layoutName.empty()) { + auto parentID = parent(ctx.currentPassLayoutID, ctx.lg); + if (parentID != LayoutGraphData::null_vertex()) { + parentLayoutID = parentID; + } + layoutID = locate(parentLayoutID, layoutName, ctx.lg); + } + ctx.currentPassLayoutID = layoutID; // get layout auto& layout = get(LayoutGraphData::LayoutTag{}, ctx.lg, layoutID); @@ -1241,7 +1264,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } const auto& nodeID = iter->second; auto iter2 = ctx.barrierMap.find(nodeID); - if (iter2 != ctx.barrierMap.end() && iter2->second.subpassBarriers.empty()) { + if (iter2 != ctx.barrierMap.end()) { submitBarriers(iter2->second.blockBarrier.frontBarriers); } } @@ -1252,7 +1275,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } const auto& nodeID = iter->second; auto iter2 = ctx.barrierMap.find(nodeID); - if (iter2 != ctx.barrierMap.end() && iter2->second.subpassBarriers.empty()) { + if (iter2 != ctx.barrierMap.end()) { submitBarriers(iter2->second.blockBarrier.rearBarriers); } } @@ -1741,6 +1764,11 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { CC_EXPECTS(resID != ResourceGraph::null_vertex()); resg.mount(ctx.device, resID); } + for (const auto& resolve : pass.resolvePairs) { + auto resID = findVertex(resolve.target, resg); + CC_EXPECTS(resID != ResourceGraph::null_vertex()); + resg.mount(ctx.device, resID); + } } void mountResources(const RasterPass& pass) const { @@ -2212,7 +2240,12 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { scratch}; RenderGraphVisitor visitor{{}, ctx}; - boost::depth_first_search(fg, visitor, get(colors, rg)); + auto colors = rg.colors(scratch); + for (const auto vertID : ctx.g.sortedVertices) { + if (holds(vertID, ctx.g) || holds(vertID, ctx.g) || holds(vertID, ctx.g)) { + boost::depth_first_visit(fg, vertID, visitor, get(colors, ctx.g)); + } + } } // collect statistics diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index 2d736168d4..ff89a8cd6d 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -22,44 +22,18 @@ THE SOFTWARE. ****************************************************************************/ -#include -#include -#include "LayoutGraphFwd.h" -#include "LayoutGraphGraphs.h" -#include "LayoutGraphNames.h" -#include "LayoutGraphTypes.h" -#include "LayoutGraphUtils.h" -#include "NativePipelineFwd.h" -#include "NativePipelineTypes.h" -#include "NativeUtils.h" -#include "RenderCommonTypes.h" -#include "RenderGraphGraphs.h" -#include "RenderGraphTypes.h" -#include "RenderInterfaceFwd.h" -#include "RenderInterfaceTypes.h" -#include "RenderingModule.h" -#include "cocos/base/Macros.h" -#include "cocos/base/Ptr.h" -#include "cocos/base/StringUtil.h" -#include "cocos/base/std/container/string.h" -#include "cocos/math/Mat4.h" -#include "cocos/renderer/gfx-base/GFXBuffer.h" -#include "cocos/renderer/gfx-base/GFXDef-common.h" -#include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" -#include "cocos/renderer/gfx-base/GFXDevice.h" -#include "cocos/renderer/gfx-base/GFXInputAssembler.h" -#include "cocos/renderer/gfx-base/GFXSwapchain.h" -#include "cocos/renderer/gfx-base/states/GFXSampler.h" -#include "cocos/renderer/pipeline/Enum.h" -#include "cocos/renderer/pipeline/GlobalDescriptorSetManager.h" #include "cocos/renderer/pipeline/PipelineSceneData.h" #include "cocos/renderer/pipeline/PipelineStateManager.h" -#include "cocos/renderer/pipeline/RenderPipeline.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphUtils.h" +#include "cocos/renderer/pipeline/custom/NativeBuiltinUtils.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/RenderingModule.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" #include "cocos/scene/RenderScene.h" #include "cocos/scene/RenderWindow.h" -#include "details/DebugUtils.h" -#include "details/GslUtils.h" - #if CC_USE_DEBUG_RENDERER #include "profiler/DebugRenderer.h" #endif @@ -68,11 +42,6 @@ namespace cc { namespace render { -SceneTask *NativeSceneTransversal::transverse(SceneVisitor *visitor) const { - std::ignore = visitor; - return nullptr; -} - NativePipeline::NativePipeline(const allocator_type &alloc) noexcept : device(gfx::Device::getInstance()), globalDSManager(std::make_unique()), @@ -118,15 +87,17 @@ uint32_t NativePipeline::addRenderWindow(const ccstd::string &name, gfx::Format desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED | + ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; CC_EXPECTS(renderWindow); if (!renderWindow->getSwapchain()) { CC_ASSERT(renderWindow->getFramebuffer()->getColorTextures().size() == 1); CC_ASSERT(renderWindow->getFramebuffer()->getColorTextures().at(0)); + desc.sampleCount = renderWindow->getFramebuffer()->getColorTextures().at(0)->getInfo().samples; return addVertex( FramebufferTag{}, std::forward_as_tuple(name.c_str()), @@ -163,9 +134,9 @@ uint32_t NativePipeline::addStorageBuffer(const ccstd::string &name, gfx::Format desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::STORAGE; + desc.flags = ResourceFlags::STORAGE | ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; return addVertex( ManagedBufferTag{}, @@ -187,9 +158,10 @@ uint32_t NativePipeline::addRenderTarget(const ccstd::string &name, gfx::Format desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED | + ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; return addVertex( ManagedTextureTag{}, @@ -211,9 +183,10 @@ uint32_t NativePipeline::addDepthStencil(const ccstd::string &name, gfx::Format desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::DEPTH_STENCIL_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::DEPTH_STENCIL_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED | + ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; CC_EXPECTS(residency == ResourceResidency::MANAGED || residency == ResourceResidency::MEMORYLESS); @@ -232,6 +205,67 @@ uint32_t NativePipeline::addDepthStencil(const ccstd::string &name, gfx::Format resourceGraph); } +uint32_t NativePipeline::addResource(const ccstd::string& name, ResourceDimension dimension, + gfx::Format format, + uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, + gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) { + ResourceDesc desc{ + dimension, + 0, + width, + height, + static_cast(dimension == ResourceDimension::TEXTURE3D ? depth : arraySize), + static_cast(mipLevels), + format, + sampleCount, + residency == ResourceResidency::MEMORYLESS ? gfx::TextureFlagBit::LAZILY_ALLOCATED : gfx::TextureFlagBit::NONE, + flags, + }; + return addVertex( + ManagedTextureTag{}, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple(desc), + std::forward_as_tuple(ResourceTraits{residency}), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + resourceGraph); +} + +void NativePipeline::updateResource(const ccstd::string& name, gfx::Format format, + uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, // NOLINT(bugprone-easily-swappable-parameters) + gfx::SampleCount sampleCount) { + auto resID = findVertex(ccstd::pmr::string(name, get_allocator()), resourceGraph); + if (resID == ResourceGraph::null_vertex()) { + return; + } + auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + + // update format + if (format == gfx::Format::UNKNOWN) { + format = desc.format; + } + visitObject( + resID, resourceGraph, + [&](ManagedTexture &tex) { + uint32_t depthOrArraySize = static_cast( + desc.dimension == ResourceDimension::TEXTURE3D ? depth : arraySize); + bool invalidate = + std::forward_as_tuple(desc.width, desc.height, desc.depthOrArraySize, desc.mipLevels, desc.format, desc.sampleCount) != + std::forward_as_tuple(width, height, depthOrArraySize, mipLevels, format, sampleCount); + if (invalidate) { + desc.width = width; + desc.height = height; + desc.depthOrArraySize = depthOrArraySize; + desc.mipLevels = mipLevels; + desc.format = format; + desc.sampleCount = sampleCount; + resourceGraph.invalidatePersistentRenderPassAndFramebuffer(tex.texture.get()); + } + }, + [](const auto & /*res*/) {}); +} + // NOLINTNEXTLINE uint32_t NativePipeline::addStorageTexture(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) { ResourceDesc desc{}; @@ -241,9 +275,9 @@ uint32_t NativePipeline::addStorageTexture(const ccstd::string &name, gfx::Forma desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::STORAGE | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::STORAGE | ResourceFlags::SAMPLED | ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST;; CC_EXPECTS(residency == ResourceResidency::MANAGED || residency == ResourceResidency::MEMORYLESS); @@ -270,9 +304,9 @@ uint32_t NativePipeline::addShadingRateTexture(const ccstd::string &name, uint32 desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = gfx::Format::R8UI; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::SHADING_RATE | ResourceFlags::STORAGE | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::SHADING_RATE | ResourceFlags::STORAGE | ResourceFlags::SAMPLED | ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; CC_EXPECTS(residency == ResourceResidency::MANAGED || residency == ResourceResidency::MEMORYLESS); @@ -306,7 +340,7 @@ uint32_t NativePipeline::addCustomBuffer( desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = gfx::Format::UNKNOWN; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; desc.flags = ResourceFlags::NONE; @@ -338,7 +372,7 @@ uint32_t NativePipeline::addCustomTexture( desc.depthOrArraySize = info.layerCount; desc.mipLevels = info.levelCount; desc.format = info.format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = info.flags; desc.flags = ResourceFlags::NONE; @@ -504,6 +538,7 @@ void NativePipeline::updateShadingRateTexture( } void NativePipeline::beginFrame() { + // noop } void NativePipeline::update(const scene::Camera *camera) { @@ -516,59 +551,52 @@ void NativePipeline::update(const scene::Camera *camera) { } void NativePipeline::endFrame() { + // noop } -namespace { - -RenderPassBuilder *addRenderPassImpl( - const PipelineRuntime *ppl, - 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) +RenderPassBuilder *NativePipeline::addRenderPass( + uint32_t width, uint32_t height, const ccstd::string &passName) { - RasterPass pass(renderGraph.get_allocator()); - pass.width = width; - pass.height = height; - pass.viewport.width = width; - pass.viewport.height = height; - pass.count = count; - pass.quality = quality; + const auto &layoutGraph = programLibrary->layoutGraph; - auto passID = addVertex( - RasterPassTag{}, - 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(), passName, lib.layoutGraph); - CC_EXPECTS(passLayoutID != LayoutGraphData::null_vertex()); + auto [passID, passLayoutID] = addRenderPassVertex( + renderGraph, layoutGraph, + width, height, 1, 0, passName); auto *builder = ccnew NativeRenderPassBuilder( - ppl, &renderGraph, passID, &lib.layoutGraph, passLayoutID); + this, &renderGraph, passID, &layoutGraph, passLayoutID); + updateRasterPassConstants(width, height, *builder); return builder; } -} // namespace - -RenderPassBuilder *NativePipeline::addRenderPass( - uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) - const ccstd::string &passName) { - return addRenderPassImpl( - this, renderGraph, *programLibrary, width, height, 1, 0, passName); -} - -BasicRenderPassBuilder *NativePipeline::addMultisampleRenderPass( - uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) +MultisampleRenderPassBuilder *NativePipeline::addMultisampleRenderPass( + uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) { CC_EXPECTS(count > 1); - return addRenderPassImpl( - this, renderGraph, *programLibrary, width, height, count, quality, passName); + const auto &layoutGraph = programLibrary->layoutGraph; + + auto [passID, passLayoutID] = addRenderPassVertex( + renderGraph, layoutGraph, + width, height, count, quality, passName); + + auto &pass = get(RasterPassTag{}, passID, renderGraph); + + auto [subpassID, subpassLayoutID] = addRenderSubpassVertex( + pass, renderGraph, passID, + layoutGraph, passLayoutID, + "", // subpassName is empty + count, quality); + + auto *builder = ccnew NativeMultisampleRenderPassBuilder( + this, &renderGraph, passID, &layoutGraph, passLayoutID, + subpassID, subpassLayoutID); + + updateRasterPassConstants(pass.width, pass.height, *builder); + + return builder; } void NativePipeline::addResolvePass(const ccstd::vector &resolvePairs) { @@ -578,7 +606,7 @@ void NativePipeline::addResolvePass(const ccstd::vector &resolvePai pass.resolvePairs.emplace_back(pair); } std::string_view name("Resolve"); - addVertex( + addVertex2( ResolveTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -590,7 +618,7 @@ void NativePipeline::addResolvePass(const ccstd::vector &resolvePai // NOLINTNEXTLINE ComputePassBuilder *NativePipeline::addComputePass(const ccstd::string &passName) { - auto passID = addVertex( + auto passID = addVertex2( ComputeTag{}, std::forward_as_tuple(passName), std::forward_as_tuple(passName), @@ -611,7 +639,7 @@ void NativePipeline::addMovePass(const ccstd::vector &movePairs) { pass.movePairs.emplace_back(pair); } std::string_view name("Move"); - addVertex( + addVertex2( MoveTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -621,6 +649,180 @@ void NativePipeline::addMovePass(const ccstd::vector &movePairs) { renderGraph); } +namespace { + +void setupGpuDrivenResources( + NativePipeline& ppl, uint32_t cullingID, ResourceGraph& resg, const std::string &hzbName) { + ccstd::pmr::string name(resg.get_allocator()); + { // init resource + name = "_GpuInit"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = addVertex( + PersistentBufferTag{}, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple(), + std::forward_as_tuple(ResourceTraits{ResourceResidency::EXTERNAL}), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(/*xxx*/), + resg); + } else { + CC_EXPECTS(holds(resID, resg)); + // get(PersistentBufferTag{}, resID, resg) = xxx; + } + } + { + name = "CCObjectBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + { + name = "CCInstanceBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + { + name = "CCDrawIndirectBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + { + name = "CCDrawInstanceBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + { + name = "CCVisibilityBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + if (!hzbName.empty()) { + + } +} + +} // namespace + +void NativePipeline::addBuiltinGpuCullingPass( + const scene::Camera *camera, const std::string &hzbName, const scene::Light *light) { + std::ignore = camera; + const uint32_t cullingID = ++nativeContext.sceneCulling.gpuCullingPassID; + setupGpuDrivenResources(*this, cullingID, resourceGraph, hzbName); + + if (light) { + // build light culling pass + return; + } + + const std::string objectBuffer = "CCObjectBuffer" + std::to_string(cullingID); + const std::string instanceBuffer = "CCInstanceBuffer" + std::to_string(cullingID); + const std::string drawIndirectBuffer = "CCDrawIndirectBuffer" + std::to_string(cullingID); + const std::string drawInstanceBuffer = "CCDrawInstanceBuffer" + std::to_string(cullingID); + const std::string visibilityBuffer = "CCVisibilityBuffer" + std::to_string(cullingID); + + // init indirected buffers + { + CopyPass copyPass{renderGraph.get_allocator()}; + { + CopyPair copyPair{renderGraph.get_allocator()}; + copyPair.source = "xxx"; + copyPair.target = drawIndirectBuffer; + copyPair.mipLevels = 1; + copyPair.numSlices = 1; + copyPass.copyPairs.emplace_back(std::move(copyPair)); + } + + auto copyID = addVertex2(CopyTag{}, + std::forward_as_tuple("CopyInitialIndirectBuffer"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(copyPass)), + renderGraph); + CC_ENSURES(copyID != RenderGraph::null_vertex()); + } + // run compute cullling pass + { + ComputePass computePass{renderGraph.get_allocator()}; + { + auto res = computePass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(drawIndirectBuffer), + std::forward_as_tuple()); + auto& view = res.first->second.emplace_back(); + view.name = "CCDrawIndirectBuffer"; + view.accessType = AccessType::WRITE; + view.shaderStageFlags = gfx::ShaderStageFlagBit::COMPUTE; + } + { + auto res = computePass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(drawInstanceBuffer), + std::forward_as_tuple()); + auto& view = res.first->second.emplace_back(); + view.name = "CCDrawInstanceBuffer"; + view.accessType = AccessType::WRITE; + view.shaderStageFlags = gfx::ShaderStageFlagBit::COMPUTE; + } + { + auto res = computePass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(visibilityBuffer), + std::forward_as_tuple()); + auto& view = res.first->second.emplace_back(); + view.name = "CCVisibilityBuffer"; + view.accessType = AccessType::WRITE; + view.shaderStageFlags = gfx::ShaderStageFlagBit::COMPUTE; + } + + auto computePassID = addVertex2(ComputeTag{}, + std::forward_as_tuple("Scene"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(computePass)), + renderGraph); + CC_ENSURES(computePassID != RenderGraph::null_vertex()); + } +} + +void NativePipeline::addBuiltinHzbGenerationPass( + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) + const std::string &sourceDepthStencilName, const std::string &targetHzbName) { +} + void NativePipeline::addCopyPass(const ccstd::vector ©Pairs) { CopyPass pass(renderGraph.get_allocator()); pass.copyPairs.reserve(copyPairs.size()); @@ -628,7 +830,7 @@ void NativePipeline::addCopyPass(const ccstd::vector ©Pairs) { pass.copyPairs.emplace_back(pair); } std::string_view name("Copy"); - addVertex( + addVertex2( CopyTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -646,7 +848,7 @@ void NativePipeline::addUploadPass(ccstd::vector &uploadPairs) { } uploadPairs.clear(); std::string_view name("Upload"); - addVertex( + addVertex2( CopyTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h index 13635e3aff..846d97ac32 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h @@ -46,15 +46,13 @@ class NativeRenderSubpassBuilder; class NativeMultisampleRenderSubpassBuilder; class NativeComputeSubpassBuilder; class NativeRenderPassBuilder; +class NativeMultisampleRenderPassBuilder; class NativeComputeQueueBuilder; class NativeComputePassBuilder; -class NativeSceneTransversal; struct RenderInstancingQueue; struct DrawInstance; struct RenderDrawQueue; struct NativeRenderQueue; -class DefaultSceneVisitor; -class DefaultForwardLightingTransversal; struct ResourceGroup; struct BufferPool; struct DescriptorSetPool; diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp index cf5285f441..d8de417ef4 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp @@ -80,12 +80,6 @@ NativeRenderQueue::NativeRenderQueue(NativeRenderQueue&& rhs, const allocator_ty sceneFlags(rhs.sceneFlags), subpassOrPassLayoutID(rhs.subpassOrPassLayoutID) {} -DefaultSceneVisitor::DefaultSceneVisitor(const allocator_type& alloc) noexcept -: name(alloc) {} - -DefaultForwardLightingTransversal::DefaultForwardLightingTransversal(const allocator_type& alloc) noexcept -: name(alloc) {} - ResourceGroup::ResourceGroup(const allocator_type& alloc) noexcept : instancingBuffers(alloc) {} @@ -186,7 +180,8 @@ SceneCulling::SceneCulling(SceneCulling&& rhs, const allocator_type& alloc) renderQueues(std::move(rhs.renderQueues), alloc), sceneQueryIndex(std::move(rhs.sceneQueryIndex), alloc), numCullingQueries(rhs.numCullingQueries), - numRenderQueues(rhs.numRenderQueues) {} + numRenderQueues(rhs.numRenderQueues), + gpuCullingPassID(rhs.gpuCullingPassID) {} NativeRenderContext::NativeRenderContext(std::unique_ptr defaultResourceIn, const allocator_type& alloc) noexcept : defaultResource(std::move(defaultResourceIn)), diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index 97ee431bc0..b21235bc46 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -86,6 +86,10 @@ public: void setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) /*implements*/; void setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) /*implements*/; void setSampler(const ccstd::string &name, gfx::Sampler *sampler) /*implements*/; + void setBuiltinCameraConstants(const scene::Camera *camera) /*implements*/; + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) /*implements*/; + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) /*implements*/; + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) /*implements*/; void setVec4ArraySize(const ccstd::string& name, uint32_t sz); void setVec4ArrayElem(const ccstd::string& name, const cc::Vec4& vec, uint32_t id); @@ -165,8 +169,23 @@ public: void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) override; + void addScene(const scene::Camera *camera, SceneFlags sceneFlags) override; + void addSceneCulledByDirectionalLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::DirectionalLight *light, uint32_t level) override; + void addSceneCulledBySpotLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::SpotLight *light) override; void addFullscreenQuad(Material *material, uint32_t passID, SceneFlags sceneFlags) override; void addCameraQuad(scene::Camera *camera, Material *material, uint32_t passID, SceneFlags sceneFlags) override; void clearRenderTarget(const ccstd::string &name, const gfx::Color &color) override; @@ -225,6 +244,18 @@ public: void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addRenderTarget(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override { NativeRenderSubpassBuilderImpl::addRenderTarget(name, accessType, slotName, loadOp, storeOp, color); @@ -309,6 +340,18 @@ public: void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addRenderTarget(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override { NativeRenderSubpassBuilderImpl::addRenderTarget(name, accessType, slotName, loadOp, storeOp, color); @@ -396,6 +439,18 @@ public: void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addRenderTarget(const ccstd::string &name, const ccstd::string &slotName) override; void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; @@ -456,6 +511,18 @@ public: void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addRenderTarget(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override; void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) override; @@ -475,6 +542,91 @@ public: void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) override; }; +class NativeMultisampleRenderPassBuilder final : public MultisampleRenderPassBuilder, public NativeSetter { +public: + NativeMultisampleRenderPassBuilder(const PipelineRuntime* pipelineRuntimeIn, RenderGraph* renderGraphIn, uint32_t nodeIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn, uint32_t subpassIDIn, uint32_t subpassLayoutIDIn) noexcept // NOLINT + : NativeSetter(pipelineRuntimeIn, renderGraphIn, nodeIDIn, layoutGraphIn, layoutIDIn), + subpassID(subpassIDIn), + subpassLayoutID(subpassLayoutIDIn) {} + + ccstd::string getName() const override { + return NativeRenderNode::getName(); + } + void setName(const ccstd::string &name) override { + NativeRenderNode::setName(name); + } + void setCustomBehavior(const ccstd::string &name) override { + NativeRenderNode::setCustomBehavior(name); + } + + void setMat4(const ccstd::string &name, const Mat4 &mat) override { + NativeSetter::setMat4(name, mat); + } + void setQuaternion(const ccstd::string &name, const Quaternion &quat) override { + NativeSetter::setQuaternion(name, quat); + } + void setColor(const ccstd::string &name, const gfx::Color &color) override { + NativeSetter::setColor(name, color); + } + void setVec4(const ccstd::string &name, const Vec4 &vec) override { + NativeSetter::setVec4(name, vec); + } + void setVec2(const ccstd::string &name, const Vec2 &vec) override { + NativeSetter::setVec2(name, vec); + } + void setFloat(const ccstd::string &name, float v) override { + NativeSetter::setFloat(name, v); + } + void setArrayBuffer(const ccstd::string &name, const ArrayBuffer *arrayBuffer) override { + NativeSetter::setArrayBuffer(name, arrayBuffer); + } + void setBuffer(const ccstd::string &name, gfx::Buffer *buffer) override { + NativeSetter::setBuffer(name, buffer); + } + void setTexture(const ccstd::string &name, gfx::Texture *texture) override { + NativeSetter::setTexture(name, texture); + } + void setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) override { + NativeSetter::setReadWriteBuffer(name, buffer); + } + void setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) override { + NativeSetter::setReadWriteTexture(name, texture); + } + void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { + NativeSetter::setSampler(name, sampler); + } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } + + void addRenderTarget(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override; + void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) override; + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) 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; + void setShowStatistics(bool enable) override; + + void resolveRenderTarget(const ccstd::string &source, const ccstd::string &target) override; + void resolveDepthStencil(const ccstd::string &source, const ccstd::string &target, gfx::ResolveMode depthMode, gfx::ResolveMode stencilMode) override; + + 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; + + uint32_t subpassID{RenderGraph::null_vertex()}; + uint32_t subpassLayoutID{RenderGraph::null_vertex()}; +}; + class NativeComputeQueueBuilder final : public ComputeQueueBuilder, public NativeSetter { public: NativeComputeQueueBuilder(const PipelineRuntime* pipelineRuntimeIn, RenderGraph* renderGraphIn, uint32_t nodeIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn) noexcept @@ -526,6 +678,18 @@ public: void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addDispatch(uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, Material *material, uint32_t passID) override; }; @@ -581,6 +745,18 @@ public: void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; @@ -590,19 +766,6 @@ public: void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) override; }; -class NativeSceneTransversal final : public SceneTransversal { -public: - NativeSceneTransversal() = default; - NativeSceneTransversal(const scene::Camera* cameraIn, const scene::RenderScene* sceneIn) noexcept - : camera(cameraIn), - scene(sceneIn) {} - - SceneTask *transverse(SceneVisitor *visitor) const override; - - const scene::Camera* camera{nullptr}; - const scene::RenderScene* scene{nullptr}; -}; - struct RenderInstancingQueue { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -694,41 +857,6 @@ struct NativeRenderQueue { uint32_t subpassOrPassLayoutID{0xFFFFFFFF}; }; -class DefaultSceneVisitor final : public SceneVisitor { -public: - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {name.get_allocator().resource()}; - } - - DefaultSceneVisitor(const allocator_type& alloc) noexcept; // NOLINT - - const pipeline::PipelineSceneData *getPipelineSceneData() const override; - void setViewport(const gfx::Viewport &vp) override; - void setScissor(const gfx::Rect &rect) override; - void bindPipelineState(gfx::PipelineState *pso) override; - void bindDescriptorSet(uint32_t set, gfx::DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; - void bindInputAssembler(gfx::InputAssembler *ia) override; - void updateBuffer(gfx::Buffer *buff, const void *data, uint32_t size) override; - void draw(const gfx::DrawInfo &info) override; - - ccstd::pmr::string name; -}; - -class DefaultForwardLightingTransversal final : public SceneTransversal { -public: - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {name.get_allocator().resource()}; - } - - DefaultForwardLightingTransversal(const allocator_type& alloc) noexcept; // NOLINT - - SceneTask *transverse(SceneVisitor *visitor) const override; - - ccstd::pmr::string name; -}; - struct ResourceGroup { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -968,6 +1096,7 @@ public: PmrFlatMap sceneQueryIndex; uint32_t numCullingQueries{0}; uint32_t numRenderQueues{0}; + uint32_t gpuCullingPassID{0xFFFFFFFF}; }; struct NativeRenderContext { @@ -1109,10 +1238,11 @@ public: uint32_t addDepthStencil(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) override; void updateRenderTarget(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; void updateDepthStencil(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; + uint32_t addResource(const ccstd::string &name, ResourceDimension dimension, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) override; + void updateResource(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount) override; void beginFrame() override; void update(const scene::Camera *camera) override; void endFrame() 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; @@ -1124,9 +1254,12 @@ public: 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 &passName) override; + MultisampleRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, 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; + void addBuiltinGpuCullingPass(const scene::Camera *camera, const std::string &hzbName, const scene::Light *light) override; + void addBuiltinHzbGenerationPass(const std::string &sourceDepthStencilName, const std::string &targetHzbName) override; uint32_t addCustomBuffer(const ccstd::string &name, const gfx::BufferInfo &info, const std::string &type) override; uint32_t addCustomTexture(const ccstd::string &name, const gfx::TextureInfo &info, const std::string &type) override; diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp index c5ddc48835..528c95d5ce 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp @@ -22,31 +22,14 @@ THE SOFTWARE. ****************************************************************************/ -#include -#include -#include "LayoutGraphGraphs.h" -#include "NativePipelineGraphs.h" -#include "NativePipelineTypes.h" -#include "NativeUtils.h" -#include "RenderCommonNames.h" -#include "RenderCommonTypes.h" -#include "RenderGraphFwd.h" -#include "RenderGraphGraphs.h" -#include "RenderGraphTypes.h" -#include "RenderingModule.h" -#include "cocos/math/Utils.h" -#include "cocos/renderer/pipeline/Define.h" -#include "cocos/renderer/pipeline/PipelineUBO.h" +#include "cocos/renderer/pipeline/custom/NativeBuiltinUtils.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h" +#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" #include "cocos/scene/DirectionalLight.h" -#include "cocos/scene/Fog.h" -#include "cocos/scene/Skybox.h" +#include "cocos/scene/RenderScene.h" #include "cocos/scene/SpotLight.h" -#include "details/DebugUtils.h" -#include "details/GraphView.h" -#include "details/GslUtils.h" -#include "gfx-base/GFXDef-common.h" -#include "gfx-base/GFXDevice.h" -#include "pipeline/PipelineSceneData.h" namespace cc { @@ -64,300 +47,17 @@ void NativeRenderNode::setCustomBehavior(const ccstd::string &name) { // NOLINT( get(RenderGraph::DataTag{}, *renderGraph, nodeID).custom = std::string_view{name}; } -void NativeSetter::setMat4(const ccstd::string &name, const Mat4 &mat) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setMat4Impl(data, *layoutGraph, name, mat); -} - -void NativeSetter::setQuaternion(const ccstd::string &name, const Quaternion &quat) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setQuaternionImpl(data, *layoutGraph, name, quat); -} - -void NativeSetter::setColor(const ccstd::string &name, const gfx::Color &color) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setColorImpl(data, *layoutGraph, name, color); -} - -void NativeSetter::setVec4(const ccstd::string &name, const Vec4 &vec) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setVec4Impl(data, *layoutGraph, name, vec); -} - -void NativeSetter::setVec2(const ccstd::string &name, const Vec2 &vec) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setVec2Impl(data, *layoutGraph, name, vec); -} - -void NativeSetter::setFloat(const ccstd::string &name, float v) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setFloatImpl(data, *layoutGraph, name, v); -} - -void NativeSetter::setArrayBuffer(const ccstd::string &name, const ArrayBuffer *buffer) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setArrayBufferImpl(data, *layoutGraph, name, *buffer); -} - -void NativeSetter::setBuffer(const ccstd::string &name, gfx::Buffer *buffer) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setBufferImpl(data, *layoutGraph, name, buffer); -} - -void NativeSetter::setTexture(const ccstd::string &name, gfx::Texture *texture) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setTextureImpl(data, *layoutGraph, name, texture); -} - -void NativeSetter::setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setReadWriteBufferImpl(data, *layoutGraph, name, buffer); -} - -void NativeSetter::setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setReadWriteTextureImpl(data, *layoutGraph, name, texture); -} - -void NativeSetter::setSampler(const ccstd::string &name, gfx::Sampler *sampler) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setSamplerImpl(data, *layoutGraph, name, sampler); -} - -void NativeSetter::setVec4ArraySize(const ccstd::string &name, uint32_t sz) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setVec4ArraySizeImpl(data, *layoutGraph, name, sz); -} - -void NativeSetter::setVec4ArrayElem(const ccstd::string &name, const cc::Vec4 &vec, uint32_t id) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setVec4ArrayElemImpl(data, *layoutGraph, name, vec, id); -} - -void NativeSetter::setMat4ArraySize(const ccstd::string &name, uint32_t sz) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setMat4ArraySizeImpl(data, *layoutGraph, name, sz); -} - -void NativeSetter::setMat4ArrayElem(const ccstd::string &name, const cc::Mat4 &mat, uint32_t id) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setMat4ArrayElemImpl(data, *layoutGraph, name, mat, id); -} - -namespace { - -uint8_t getCombineSignY(gfx::Device *device) { - // 0: vk, 1: metal, 2: none, 3: gl-like - static int8_t combineSignY{-1}; - if (combineSignY < 0) { - const float screenSpaceSignY = device->getCapabilities().screenSpaceSignY * 0.5F + 0.5F; - const float clipSpaceSignY = device->getCapabilities().clipSpaceSignY * 0.5F + 0.5F; - combineSignY = static_cast(static_cast(screenSpaceSignY) << 1 | static_cast(clipSpaceSignY)); +RenderGraph::vertex_descriptor RenderGraph::getPassID(vertex_descriptor nodeID) const { + CC_EXPECTS(nodeID != null_vertex()); + for (auto parentID = nodeID; + parentID != RenderGraph::null_vertex(); + parentID = parent(nodeID, *this)) { + nodeID = parentID; } - return static_cast(combineSignY); + CC_ENSURES(nodeID != null_vertex()); + return nodeID; } -void setCameraUBOValues( - const scene::Camera &camera, - const LayoutGraphData &layoutGraph, - const pipeline::PipelineSceneData &cfg, - const scene::DirectionalLight *mainLight, - RenderData &data) { - CC_EXPECTS(camera.getNode()); - CC_EXPECTS(cfg.getSkybox()); - const auto &skybox = *cfg.getSkybox(); - const auto &shadingScale = cfg.getShadingScale(); - // Camera - setMat4Impl(data, layoutGraph, "cc_matView", camera.getMatView()); - setMat4Impl(data, layoutGraph, "cc_matViewInv", camera.getNode()->getWorldMatrix()); - setMat4Impl(data, layoutGraph, "cc_matProj", camera.getMatProj()); - setMat4Impl(data, layoutGraph, "cc_matProjInv", camera.getMatProjInv()); - setMat4Impl(data, layoutGraph, "cc_matViewProj", camera.getMatViewProj()); - setMat4Impl(data, layoutGraph, "cc_matViewProjInv", camera.getMatViewProjInv()); - setVec4Impl(data, layoutGraph, "cc_cameraPos", - Vec4( - camera.getPosition().x, - camera.getPosition().y, - camera.getPosition().z, - getCombineSignY(cc::gfx::Device::getInstance()))); - setVec4Impl(data, layoutGraph, "cc_surfaceTransform", - Vec4( - static_cast(camera.getSurfaceTransform()), - static_cast(camera.getCameraUsage()), - cosf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))), - sinf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))))); - setVec4Impl(data, layoutGraph, "cc_screenScale", - Vec4( - cfg.getShadingScale(), - cfg.getShadingScale(), - 1.0F / cfg.getShadingScale(), - 1.0F / cfg.getShadingScale())); - setVec4Impl(data, layoutGraph, "cc_exposure", - Vec4( - camera.getExposure(), - 1.0F / camera.getExposure(), - cfg.isHDR() ? 1.0F : 0.0F, - 1.0F / scene::Camera::getStandardExposureValue())); - - if (mainLight) { - const auto &shadowInfo = *cfg.getShadows(); - const bool shadowEnable = (mainLight->isShadowEnabled() && - shadowInfo.getType() == scene::ShadowType::SHADOW_MAP); - setVec4Impl(data, layoutGraph, "cc_mainLitDir", - Vec4( - mainLight->getDirection().x, - mainLight->getDirection().y, - mainLight->getDirection().z, - shadowEnable)); - auto r = mainLight->getColor().x; - auto g = mainLight->getColor().y; - auto b = mainLight->getColor().z; - if (mainLight->isUseColorTemperature()) { - r *= mainLight->getColorTemperatureRGB().x; - g *= mainLight->getColorTemperatureRGB().y; - b *= mainLight->getColorTemperatureRGB().z; - } - auto w = mainLight->getIlluminance(); - if (cfg.isHDR()) { - w *= camera.getExposure(); - } - setVec4Impl(data, layoutGraph, "cc_mainLitColor", Vec4(r, g, b, w)); - } else { - setVec4Impl(data, layoutGraph, "cc_mainLitDir", Vec4(0, 0, 1, 0)); - setVec4Impl(data, layoutGraph, "cc_mainLitColor", Vec4(0, 0, 0, 0)); - } - - CC_EXPECTS(cfg.getAmbient()); - auto &ambient = *cfg.getAmbient(); - auto &skyColor = ambient.getSkyColor(); - if (cfg.isHDR()) { - skyColor.w = ambient.getSkyIllum() * camera.getExposure(); - } else { - skyColor.w = ambient.getSkyIllum(); - } - setVec4Impl(data, layoutGraph, "cc_ambientSky", - Vec4(skyColor.x, skyColor.y, skyColor.z, skyColor.w)); - setVec4Impl(data, layoutGraph, "cc_ambientGround", - Vec4( - ambient.getGroundAlbedo().x, - ambient.getGroundAlbedo().y, - ambient.getGroundAlbedo().z, - skybox.getEnvmap() ? static_cast(skybox.getEnvmap()->mipmapLevel()) : 1.0F)); - - CC_EXPECTS(cfg.getFog()); - const auto &fog = *cfg.getFog(); - - const auto &colorTempRGB = fog.getColorArray(); - setVec4Impl(data, layoutGraph, "cc_fogColor", - Vec4(colorTempRGB.x, colorTempRGB.y, colorTempRGB.z, colorTempRGB.z)); - setVec4Impl(data, layoutGraph, "cc_fogBase", - Vec4(fog.getFogStart(), fog.getFogEnd(), fog.getFogDensity(), 0.0F)); - setVec4Impl(data, layoutGraph, "cc_fogAdd", - Vec4(fog.getFogTop(), fog.getFogRange(), fog.getFogAtten(), 0.0F)); - setVec4Impl(data, layoutGraph, "cc_nearFar", - Vec4(camera.getNearClip(), camera.getFarClip(), camera.getClipSpaceMinz(), 0.0F)); - setVec4Impl(data, layoutGraph, "cc_viewPort", - Vec4( - camera.getViewport().x, - camera.getViewport().y, - shadingScale * static_cast(camera.getWindow()->getWidth()) * camera.getViewport().z, - shadingScale * static_cast(camera.getWindow()->getHeight()) * camera.getViewport().w)); -} - -} // namespace - -// void NativeSetter::setCameraConstants(const scene::Camera *camera) { -// auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); -// setCameraUBOValues( -// *camera, -// *layoutGraph, -// *pipelineRuntime->getPipelineSceneData(), -// camera->getScene()->getMainLight(), data); -// } - -// void NativeSetter::setDirectionalLightProjectionConstants( -// const scene::DirectionalLight* light, uint32_t level) { -// CC_EXPECTS(light); -// const auto *device = pipelineRuntime->getDevice(); -// const auto &mainLight = *light; -// const auto& pplScenData = *pipelineRuntime->getPipelineSceneData(); -// const auto &shadowInfo = *pplScenData.getShadows(); -// const auto &csmLayers = *pplScenData.getCSMLayers(); -// const auto packing = pipeline::supportsR32FloatTexture(device) ? 0.0F : 1.0F; - -// auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - -// float near = 0.1; -// float far = 0; -// Mat4 matShadowView; -// Mat4 matShadowProj; -// Mat4 matShadowViewProj; -// Vec4 vec4ShadowInfo{}; - -// scene::CSMLevel levelCount{}; -// if (mainLight.isShadowFixedArea() || mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1) { -// matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); -// matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); -// matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); -// if (mainLight.isShadowFixedArea()) { -// near = mainLight.getShadowNear(); -// far = mainLight.getShadowFar(); -// levelCount = static_cast(0); -// } else { -// near = 0.1; -// far = csmLayers.getSpecialLayer()->getShadowCameraFar(); -// levelCount = scene::CSMLevel::LEVEL_1; -// } -// vec4ShadowInfo.set(0.0F, packing, mainLight.getShadowNormalBias(), 0); -// setVec4Impl(data, *layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); -// } else { -// const auto &layer = *csmLayers.getLayers()[level]; -// matShadowView = layer.getMatShadowView(); -// matShadowProj = layer.getMatShadowProj(); -// matShadowViewProj = layer.getMatShadowViewProj(); - -// near = layer.getSplitCameraNear(); -// far = layer.getSplitCameraFar(); -// levelCount = mainLight.getCSMLevel(); -// } -// setMat4Impl(data, *layoutGraph, "cc_matLightView", matShadowView); -// setVec4Impl(data, *layoutGraph, "cc_shadowProjDepthInfo", -// Vec4( -// matShadowProj.m[10], -// matShadowProj.m[14], -// matShadowProj.m[11], -// matShadowProj.m[15])); -// setVec4Impl(data, *layoutGraph, "cc_shadowProjInfo", -// Vec4( -// matShadowProj.m[00], -// matShadowProj.m[05], -// 1.0F / matShadowProj.m[00], -// 1.0F / matShadowProj.m[05])); -// setMat4Impl(data, *layoutGraph, "cc_matLightViewProj", matShadowViewProj); -// vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); -// setVec4Impl(data, *layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); -// vec4ShadowInfo.set( -// 0.0F, -// packing, -// mainLight.getShadowNormalBias(), -// static_cast(levelCount)); -// setVec4Impl(data, *layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); -// vec4ShadowInfo.set( -// shadowInfo.getSize().x, -// shadowInfo.getSize().y, -// static_cast(mainLight.getShadowPcf()), -// mainLight.getShadowBias()); -// setVec4Impl(data, *layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); -// } - -// void NativeSetter::setSpotLightProjectionConstants(const scene::SpotLight* light) { - -// } - -// void NativeSetter::setShadowMapConstants(const scene::Light* light, uint32_t numLevels) { - -// } - namespace { template @@ -466,105 +166,14 @@ void NativeRenderPassBuilder::addDepthStencil( stencil); } -namespace { - -void addComputeView(NativeRenderPassBuilder &builder, const ccstd::string &name, const ComputeView &view) { - CC_EXPECTS(!name.empty()); - CC_EXPECTS(!view.name.empty()); - auto &pass = get(RasterPassTag{}, builder.nodeID, *builder.renderGraph); - auto iter = pass.computeViews.find(name.c_str()); - if (iter == pass.computeViews.end()) { - bool added = false; - std::tie(iter, added) = pass.computeViews.emplace( - std::piecewise_construct, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple()); - CC_ENSURES(added); - } - iter->second.emplace_back(view); -} - -void addComputeView(NativeComputePassBuilder &builder, const ccstd::string &name, const ComputeView &view) { - CC_EXPECTS(!name.empty()); - CC_EXPECTS(!view.name.empty()); - auto &pass = get(ComputeTag{}, builder.nodeID, *builder.renderGraph); - auto iter = pass.computeViews.find(name.c_str()); - if (iter == pass.computeViews.end()) { - bool added = false; - std::tie(iter, added) = pass.computeViews.emplace( - std::piecewise_construct, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple()); - CC_ENSURES(added); - } - iter->second.emplace_back(view); -} - -template -void addComputeViewImpl( - const ccstd::string &name, const ComputeView &view, - RenderGraph::vertex_descriptor subpassID, - RenderGraph &renderGraph) { - CC_EXPECTS(!name.empty()); - CC_EXPECTS(!view.name.empty()); - auto &subpass = get(Tag{}, subpassID, renderGraph); - const auto passID = parent(subpassID, renderGraph); - CC_EXPECTS(passID != RenderGraph::null_vertex()); - CC_EXPECTS(holds(passID, renderGraph)); - auto &pass = get(RasterPassTag{}, passID, renderGraph); - CC_EXPECTS(subpass.subpassID < num_vertices(pass.subpassGraph)); - auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); - CC_EXPECTS(subpass.computeViews.size() == subpassData.computeViews.size()); - { - auto iter = subpassData.computeViews.find(name.c_str()); - if (iter == subpassData.computeViews.end()) { - bool added = false; - std::tie(iter, added) = subpassData.computeViews.emplace( - std::piecewise_construct, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple()); - CC_ENSURES(added); - } - iter->second.emplace_back(view); - } - { - auto iter = subpass.computeViews.find(name.c_str()); - if (iter == subpass.computeViews.end()) { - bool added = false; - std::tie(iter, added) = subpass.computeViews.emplace( - std::piecewise_construct, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple()); - CC_ENSURES(added); - } - iter->second.emplace_back(view); - } - CC_ENSURES(subpass.computeViews.size() == subpassData.computeViews.size()); - CC_ENSURES(subpass.computeViews.find(std::string_view{name}) != subpass.computeViews.end()); - CC_ENSURES(subpassData.computeViews.find(std::string_view{name}) != subpassData.computeViews.end()); - CC_ENSURES(subpass.computeViews.find(std::string_view{name})->second.size() == - subpassData.computeViews.find(std::string_view{name})->second.size()); -} - -void addComputeView( - NativeRenderSubpassBuilderImpl &builder, - const ccstd::string &name, const ComputeView &view) { - addComputeViewImpl(name, view, builder.nodeID, *builder.renderGraph); -} - -void addComputeView( - NativeComputeSubpassBuilder &builder, const ccstd::string &name, const ComputeView &view) { - addComputeViewImpl(name, view, builder.nodeID, *builder.renderGraph); -} - -} // namespace - // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) void NativeRenderPassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) { - addComputeView( - *this, + addPassComputeViewImpl( + RasterPassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -586,8 +195,10 @@ void NativeRenderPassBuilder::addTexture( void NativeRenderPassBuilder::addStorageBuffer( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addPassComputeViewImpl( + RasterPassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -601,8 +212,10 @@ void NativeRenderPassBuilder::addStorageBuffer( void NativeRenderPassBuilder::addStorageImage( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addPassComputeViewImpl( + RasterPassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -717,6 +330,8 @@ void addRasterViewImpl( gfx::ShaderStageFlagBit::NONE)); CC_ENSURES(res.second); res.first->second.slotID = slotID; + + pass.rasterViews.emplace(name, subpass.rasterViews.at(name.data())); } CC_ENSURES(subpass.rasterViews.size() == subpassData.rasterViews.size()); } @@ -768,8 +383,10 @@ void NativeRenderSubpassBuilderImpl::addDepthStencil( void NativeRenderSubpassBuilderImpl::addTexture( const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) { - addComputeView( - *this, + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -791,8 +408,10 @@ void NativeRenderSubpassBuilderImpl::addTexture( void NativeRenderSubpassBuilderImpl::addStorageBuffer( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -806,8 +425,10 @@ void NativeRenderSubpassBuilderImpl::addStorageBuffer( void NativeRenderSubpassBuilderImpl::addStorageImage( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -887,7 +508,7 @@ RenderQueueBuilder *NativeRenderSubpassBuilderImpl::addQueue( const auto phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); - auto queueID = addVertex( + auto queueID = addVertex2( QueueTag{}, std::forward_as_tuple(phaseName), std::forward_as_tuple(phaseName), @@ -912,12 +533,19 @@ void NativeRenderSubpassBuilderImpl::setShowStatistics(bool enable) { void NativeMultisampleRenderSubpassBuilder::resolveRenderTarget( const ccstd::string &source, const ccstd::string &target) { // NOLINT(bugprone-easily-swappable-parameters) auto &subpass = get(RasterSubpassTag{}, nodeID, *renderGraph); + + auto parentID = parent(nodeID, *renderGraph); + auto &pass = get(RasterPassTag{}, parentID, *renderGraph); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + subpass.resolvePairs.emplace_back( ccstd::pmr::string(source.data(), renderGraph->get_allocator()), ccstd::pmr::string(target.data(), renderGraph->get_allocator()), ResolveFlags::COLOR, gfx::ResolveMode::AVERAGE, gfx::ResolveMode::NONE); + + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } void NativeMultisampleRenderSubpassBuilder::resolveDepthStencil( @@ -931,12 +559,19 @@ void NativeMultisampleRenderSubpassBuilder::resolveDepthStencil( if (stencilMode != gfx::ResolveMode::NONE) { flags |= ResolveFlags::STENCIL; } + + auto parentID = parent(nodeID, *renderGraph); + auto &pass = get(RasterPassTag{}, parentID, *renderGraph); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + subpass.resolvePairs.emplace_back( ccstd::pmr::string(source.data(), renderGraph->get_allocator()), ccstd::pmr::string(target.data(), renderGraph->get_allocator()), flags, depthMode, stencilMode); + + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } void NativeComputeSubpassBuilder::addRenderTarget(const ccstd::string &name, const ccstd::string &slotName) { @@ -958,8 +593,10 @@ void NativeComputeSubpassBuilder::addRenderTarget(const ccstd::string &name, con void NativeComputeSubpassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) { - addComputeView( - *this, + addSubpassComputeViewImpl( + ComputeSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -981,8 +618,10 @@ void NativeComputeSubpassBuilder::addTexture( void NativeComputeSubpassBuilder::addStorageBuffer( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addSubpassComputeViewImpl( + ComputeSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -996,8 +635,10 @@ void NativeComputeSubpassBuilder::addStorageBuffer( void NativeComputeSubpassBuilder::addStorageImage( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addSubpassComputeViewImpl( + ComputeSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -1021,7 +662,7 @@ ComputeQueueBuilder *NativeComputeSubpassBuilder::addQueue(const ccstd::string & const auto phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); - auto queueID = addVertex( + auto queueID = addVertex2( QueueTag{}, std::forward_as_tuple(phaseName), std::forward_as_tuple(phaseName), @@ -1033,315 +674,11 @@ ComputeQueueBuilder *NativeComputeSubpassBuilder::addQueue(const ccstd::string & return new NativeComputeQueueBuilder(pipelineRuntime, renderGraph, queueID, layoutGraph, phaseLayoutID); } -namespace { - -void setShadowUBOLightView( - gfx::Device *device, - const LayoutGraphData &layoutGraph, - const pipeline::PipelineSceneData &sceneData, - const scene::Light &light, - uint32_t level, - RenderData &data) { - const auto &shadowInfo = *sceneData.getShadows(); - const auto &csmLayers = *sceneData.getCSMLayers(); - const auto &packing = pipeline::supportsR32FloatTexture(device) ? 0.0F : 1.0F; - const auto &cap = device->getCapabilities(); - Vec4 vec4ShadowInfo{}; - - // ShadowMap - switch (light.getType()) { - case scene::LightType::DIRECTIONAL: { - const auto &mainLight = dynamic_cast(light); - if (shadowInfo.isEnabled() && mainLight.isShadowEnabled()) { - if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { - float near = 0.1F; - float far = 0.0F; - Mat4 matShadowView; - Mat4 matShadowProj; - Mat4 matShadowViewProj; - scene::CSMLevel levelCount{}; - if (mainLight.isShadowFixedArea() || mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1) { - matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); - matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); - matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); - if (mainLight.isShadowFixedArea()) { - near = mainLight.getShadowNear(); - far = mainLight.getShadowFar(); - levelCount = static_cast(0); - } else { - near = 0.1F; - far = csmLayers.getSpecialLayer()->getShadowCameraFar(); - levelCount = scene::CSMLevel::LEVEL_1; - } - vec4ShadowInfo.set(static_cast(scene::LightType::DIRECTIONAL), packing, mainLight.getShadowNormalBias(), 0); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); - } else { - const auto &layer = *csmLayers.getLayers()[level]; - matShadowView = layer.getMatShadowView(); - matShadowProj = layer.getMatShadowProj(); - matShadowViewProj = layer.getMatShadowViewProj(); - - near = layer.getSplitCameraNear(); - far = layer.getSplitCameraFar(); - levelCount = mainLight.getCSMLevel(); - } - setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); - setVec4Impl(data, layoutGraph, "cc_shadowProjDepthInfo", - Vec4( - matShadowProj.m[10], - matShadowProj.m[14], - matShadowProj.m[11], - matShadowProj.m[15])); - setVec4Impl(data, layoutGraph, "cc_shadowProjInfo", - Vec4( - matShadowProj.m[00], - matShadowProj.m[05], - 1.0F / matShadowProj.m[00], - 1.0F / matShadowProj.m[05])); - setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); - vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); - setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); - vec4ShadowInfo.set( - static_cast(scene::LightType::DIRECTIONAL), - packing, - mainLight.getShadowNormalBias(), - static_cast(levelCount)); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); - vec4ShadowInfo.set( - shadowInfo.getSize().x, - shadowInfo.getSize().y, - static_cast(mainLight.getShadowPcf()), - mainLight.getShadowBias()); - setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); - } - } - break; - } - case scene::LightType::SPOT: { - const auto &spotLight = dynamic_cast(light); - if (shadowInfo.isEnabled() && spotLight.isShadowEnabled()) { - const auto &matShadowCamera = spotLight.getNode()->getWorldMatrix(); - const auto matShadowView = matShadowCamera.getInversed(); - setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); - - Mat4 matShadowViewProj{}; - Mat4::createPerspective(spotLight.getAngle(), 1.0F, 0.001F, - spotLight.getRange(), true, - cap.clipSpaceMinZ, cap.clipSpaceSignY, 0, &matShadowViewProj); - matShadowViewProj.multiply(matShadowView); - setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); - - const Vec4 shadowNFLSInfos(0.01F, spotLight.getRange(), 0.0F, 0.0F); - setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", shadowNFLSInfos); - - const Vec4 shadowWHPBInfos( - shadowInfo.getSize().x, - shadowInfo.getSize().y, - spotLight.getShadowPcf(), - spotLight.getShadowBias()); - setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", shadowWHPBInfos); - - const Vec4 shadowLPNNInfos(static_cast(scene::LightType::SPOT), packing, spotLight.getShadowNormalBias(), 0.0F); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", shadowLPNNInfos); - } - break; - } - default: - break; - } - - const auto &color = shadowInfo.getShadowColor4f(); - setColorImpl(data, layoutGraph, "cc_shadowColor", gfx::Color{color[0], color[1], color[2], color[3]}); -} - -float getPCFRadius( - const scene::Shadows &shadowInfo, - const scene::DirectionalLight &mainLight) { - const auto &shadowMapSize = shadowInfo.getSize().x; - switch (mainLight.getShadowPcf()) { - case scene::PCFType::HARD: - return 0.0F; - case scene::PCFType::SOFT: - return 1.0F / (shadowMapSize * 0.5F); - case scene::PCFType::SOFT_2X: - return 2.0F / (shadowMapSize * 0.5F); - case scene::PCFType::SOFT_4X: - return 3.0F / (shadowMapSize * 0.5F); - default: - break; - } - return 0.0F; -} - -void setShadowUBOView( - gfx::Device &device, - const LayoutGraphData &layoutGraph, - const pipeline::PipelineSceneData &sceneData, - const scene::DirectionalLight &mainLight, - RenderData &data) { - const auto &shadowInfo = *sceneData.getShadows(); - const auto &csmLayers = *sceneData.getCSMLayers(); - const auto &csmSupported = sceneData.getCSMSupported(); - const auto &packing = pipeline::supportsR32FloatTexture(&device) ? 0.0F : 1.0F; - Vec4 vec4ShadowInfo{}; - if (shadowInfo.isEnabled()) { - if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { - if (mainLight.isShadowEnabled()) { - if (mainLight.isShadowFixedArea() || - mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1 || !csmSupported) { - // Shadow - const auto &matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); - const auto &matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); - const auto &matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); - const auto &near = mainLight.getShadowNear(); - const auto &far = mainLight.getShadowFar(); - - setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); - setVec4Impl(data, layoutGraph, "cc_shadowProjDepthInfo", - Vec4(matShadowProj.m[10], matShadowProj.m[14], - matShadowProj.m[11], matShadowProj.m[15])); - - setVec4Impl(data, layoutGraph, "cc_shadowProjInfo", - Vec4(matShadowProj.m[00], matShadowProj.m[05], - 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05])); - setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); - vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); - setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); - vec4ShadowInfo.set(static_cast(scene::LightType::DIRECTIONAL), packing, mainLight.getShadowNormalBias(), 0); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); - } else { - { // CSM - const auto layerThreshold = getPCFRadius(shadowInfo, mainLight); - const auto numCascades = static_cast(mainLight.getCSMLevel()); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir0", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir1", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir2", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmAtlas", numCascades); - setMat4ArraySizeImpl(data, layoutGraph, "cc_matCSMViewProj", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmProjDepthInfo", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmProjInfo", numCascades); - - Vec4 csmSplitsInfo{}; - for (uint32_t i = 0; i < numCascades; ++i) { - const auto &layer = *csmLayers.getLayers()[i]; - - const auto &matShadowView = layer.getMatShadowView(); - vec4ShadowInfo.set(matShadowView.m[0], matShadowView.m[4], matShadowView.m[8], layerThreshold); - setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir0", vec4ShadowInfo, i); - vec4ShadowInfo.set(matShadowView.m[1], matShadowView.m[5], matShadowView.m[9], layer.getSplitCameraNear()); - setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir1", vec4ShadowInfo, i); - vec4ShadowInfo.set(matShadowView.m[2], matShadowView.m[6], matShadowView.m[10], layer.getSplitCameraFar()); - setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir2", vec4ShadowInfo, i); - - const auto &csmAtlas = layer.getCSMAtlas(); - setVec4ArrayElemImpl(data, layoutGraph, "cc_csmAtlas", csmAtlas, i); - - const auto &matShadowViewProj = layer.getMatShadowViewProj(); - setMat4ArrayElemImpl(data, layoutGraph, "cc_matCSMViewProj", matShadowViewProj, i); - - const auto &matShadowProj = layer.getMatShadowProj(); - setVec4ArrayElemImpl(data, layoutGraph, - "cc_csmProjDepthInfo", - Vec4(matShadowProj.m[10], matShadowProj.m[14], - matShadowProj.m[11], matShadowProj.m[15]), - i); - - setVec4ArrayElemImpl(data, layoutGraph, - "cc_csmProjInfo", - Vec4(matShadowProj.m[00], matShadowProj.m[05], - 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05]), - i); - - (&csmSplitsInfo.x)[i] = layer.getSplitCameraFar() / mainLight.getShadowDistance(); - } - setVec4Impl(data, layoutGraph, "cc_csmSplitsInfo", csmSplitsInfo); - } - { // Shadow - vec4ShadowInfo.set(0, 0, 0, 1.0F - mainLight.getShadowSaturation()); - setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); - vec4ShadowInfo.set( - static_cast(scene::LightType::DIRECTIONAL), - packing, - mainLight.getShadowNormalBias(), - static_cast(mainLight.getCSMLevel())); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); - } - } - { // Shadow - vec4ShadowInfo.set( - shadowInfo.getSize().x, shadowInfo.getSize().y, - static_cast(mainLight.getShadowPcf()), mainLight.getShadowBias()); - setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); - } - } - } else { - Vec3 tempVec3 = shadowInfo.getNormal().getNormalized(); - setVec4Impl(data, layoutGraph, - "cc_planarNDInfo", - Vec4(tempVec3.x, tempVec3.y, tempVec3.z, -shadowInfo.getDistance())); - } - { - const auto &color = shadowInfo.getShadowColor4f(); - setColorImpl(data, layoutGraph, "cc_shadowColor", - gfx::Color{color[0], color[1], color[2], color[3]}); - } - } -} - -void setTextureUBOView( - gfx::Device &device, - const LayoutGraphData &layoutGraph, - const pipeline::PipelineSceneData &sceneData, - RenderData &data) { - const auto &skybox = *sceneData.getSkybox(); - if (skybox.getReflectionMap()) { - auto &texture = *skybox.getReflectionMap()->getGFXTexture(); - auto *sampler = device.getSampler(skybox.getReflectionMap()->getSamplerInfo()); - setTextureImpl(data, layoutGraph, "cc_environment", &texture); - setSamplerImpl(data, layoutGraph, "cc_environment", sampler); - } else { - const auto *envmap = - skybox.getEnvmap() - ? skybox.getEnvmap() - : BuiltinResMgr::getInstance()->get("default-cube-texture"); - if (envmap) { - auto *texture = envmap->getGFXTexture(); - auto *sampler = device.getSampler(envmap->getSamplerInfo()); - setTextureImpl(data, layoutGraph, "cc_environment", texture); - setSamplerImpl(data, layoutGraph, "cc_environment", sampler); - } - } - const auto *diffuseMap = - skybox.getDiffuseMap() - ? skybox.getDiffuseMap() - : BuiltinResMgr::getInstance()->get("default-cube-texture"); - if (diffuseMap) { - auto *texture = diffuseMap->getGFXTexture(); - auto *sampler = device.getSampler(diffuseMap->getSamplerInfo()); - setTextureImpl(data, layoutGraph, "cc_diffuseMap", texture); - setSamplerImpl(data, layoutGraph, "cc_diffuseMap", sampler); - } - gfx::SamplerInfo samplerPointInfo{ - gfx::Filter::POINT, - gfx::Filter::POINT, - gfx::Filter::NONE, - gfx::Address::CLAMP, - gfx::Address::CLAMP, - gfx::Address::CLAMP}; - auto *pointSampler = device.getSampler(samplerPointInfo); - setSamplerImpl(data, layoutGraph, "cc_shadowMap", pointSampler); - // setTextureImpl(data, layoutGraph, "cc_shadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); - setSamplerImpl(data, layoutGraph, "cc_spotShadowMap", pointSampler); - // setTextureImpl(data, layoutGraph, "cc_spotShadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); -} - -} // namespace - void NativeRenderQueueBuilder::addSceneOfCamera( scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) { const auto *pLight = light.light.get(); SceneData scene(camera->getScene(), camera, sceneFlags, light); - auto sceneID = addVertex( + auto sceneID = addVertex2( SceneTag{}, std::forward_as_tuple("Camera"), std::forward_as_tuple(), @@ -1376,67 +713,103 @@ void NativeRenderQueueBuilder::addSceneOfCamera( *pDirLight, data); } } - setTextureUBOView( + setLegacyTextureUBOView( *pipelineRuntime->getDevice(), *layoutGraph, *pipelineRuntime->getPipelineSceneData(), data); } -// void NativeRenderQueueBuilder::addScene(const scene::Camera *camera, SceneFlags sceneFlags) { -// SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{}); +void NativeRenderQueueBuilder::addScene(const scene::Camera *camera, SceneFlags sceneFlags) { + SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{}); -// auto sceneID = addVertex( -// SceneTag{}, -// std::forward_as_tuple("Scene"), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(std::move(data)), -// *renderGraph, nodeID); -// CC_ENSURES(sceneID != RenderGraph::null_vertex()); -// } + auto sceneID = addVertex2( + SceneTag{}, + std::forward_as_tuple("Scene"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(data)), + *renderGraph, nodeID); + CC_ENSURES(sceneID != RenderGraph::null_vertex()); -// void NativeRenderQueueBuilder::addSceneCulledByDirectionalLight( -// const scene::Camera *camera, SceneFlags sceneFlags, -// scene::DirectionalLight *light, uint32_t level) { -// CC_EXPECTS(light); -// CC_EXPECTS(light->getType() != scene::LightType::UNKNOWN); -// SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{light, level}); + if (any(sceneFlags & SceneFlags::GPU_DRIVEN)) { + const auto passID = renderGraph->getPassID(nodeID); + const auto cullingID = dynamic_cast(pipelineRuntime)->nativeContext.sceneCulling.gpuCullingPassID; + CC_EXPECTS(cullingID != 0xFFFFFFFF); + if (holds(passID, *renderGraph)) { + ccstd::pmr::string drawIndirectBuffer("CCDrawIndirectBuffer"); + drawIndirectBuffer.append(std::to_string(cullingID)); + ccstd::pmr::string drawInstanceBuffer("CCDrawInstanceBuffer"); + drawInstanceBuffer.append(std::to_string(cullingID)); -// auto sceneID = addVertex( -// SceneTag{}, -// std::forward_as_tuple("Scene"), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(std::move(data)), -// *renderGraph, nodeID); -// CC_ENSURES(sceneID != RenderGraph::null_vertex()); -// } + auto& rasterPass = get(RasterPassTag{}, passID, *renderGraph); + if (rasterPass.computeViews.find(drawIndirectBuffer) != rasterPass.computeViews.end()) { + auto res = rasterPass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(drawIndirectBuffer), + std::forward_as_tuple()); + CC_ENSURES(res.second); + auto& view = res.first->second.emplace_back(); + view.name = "CCDrawIndirectBuffer"; + view.accessType = AccessType::READ; + view.shaderStageFlags = gfx::ShaderStageFlagBit::VERTEX | gfx::ShaderStageFlagBit::FRAGMENT; + } + if (rasterPass.computeViews.find(drawInstanceBuffer) != rasterPass.computeViews.end()) { + auto res = rasterPass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(drawInstanceBuffer), + std::forward_as_tuple()); + CC_ENSURES(res.second); + auto& view = res.first->second.emplace_back(); + view.name = "CCDrawInstanceBuffer"; + view.accessType = AccessType::READ; + view.shaderStageFlags = gfx::ShaderStageFlagBit::VERTEX | gfx::ShaderStageFlagBit::FRAGMENT; + } + } + } +} -// void NativeRenderQueueBuilder::addSceneCulledBySpotLight( -// const scene::Camera *camera, SceneFlags sceneFlags, -// scene::SpotLight *light) { -// CC_EXPECTS(light); -// CC_EXPECTS(light->getType() != scene::LightType::UNKNOWN); -// SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{light, 0}); +void NativeRenderQueueBuilder::addSceneCulledByDirectionalLight( + const scene::Camera *camera, SceneFlags sceneFlags, + scene::DirectionalLight *light, uint32_t level) { + CC_EXPECTS(light); + CC_EXPECTS(light->getType() != scene::LightType::UNKNOWN); + SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{light, level}); -// auto sceneID = addVertex( -// SceneTag{}, -// std::forward_as_tuple("Scene"), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(std::move(data)), -// *renderGraph, nodeID); -// CC_ENSURES(sceneID != RenderGraph::null_vertex()); -// } + auto sceneID = addVertex2( + SceneTag{}, + std::forward_as_tuple("Scene"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(data)), + *renderGraph, nodeID); + CC_ENSURES(sceneID != RenderGraph::null_vertex()); +} + +void NativeRenderQueueBuilder::addSceneCulledBySpotLight( + const scene::Camera *camera, SceneFlags sceneFlags, + scene::SpotLight *light) { + CC_EXPECTS(light); + CC_EXPECTS(light->getType() != scene::LightType::UNKNOWN); + SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{light, 0}); + + auto sceneID = addVertex2( + SceneTag{}, + std::forward_as_tuple("Scene"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(data)), + *renderGraph, nodeID); + CC_ENSURES(sceneID != RenderGraph::null_vertex()); +} void NativeRenderQueueBuilder::addFullscreenQuad( Material *material, uint32_t passID, SceneFlags sceneFlags) { std::string_view name = "FullscreenQuad"; - auto drawID = addVertex( + auto drawID = addVertex2( BlitTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -1451,7 +824,7 @@ void NativeRenderQueueBuilder::addCameraQuad( scene::Camera *camera, cc::Material *material, uint32_t passID, SceneFlags sceneFlags) { std::string_view name = "CameraQuad"; - auto drawID = addVertex( + auto drawID = addVertex2( BlitTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -1479,7 +852,7 @@ void NativeRenderQueueBuilder::addCameraQuad( *pDirLight, data); } } - setTextureUBOView( + setLegacyTextureUBOView( *pipelineRuntime->getDevice(), *layoutGraph, *pipelineRuntime->getPipelineSceneData(), @@ -1490,7 +863,7 @@ void NativeRenderQueueBuilder::clearRenderTarget(const ccstd::string &name, cons ccstd::pmr::vector clears(renderGraph->get_allocator()); clears.emplace_back(name.c_str(), gfx::ClearFlagBit::COLOR, color); - auto clearID = addVertex( + auto clearID = addVertex2( ClearTag{}, std::forward_as_tuple("ClearRenderTarget"), std::forward_as_tuple(), @@ -1508,7 +881,7 @@ void NativeRenderQueueBuilder::setViewport(const gfx::Viewport &viewport) { void NativeRenderQueueBuilder::addCustomCommand(std::string_view customBehavior) { std::string_view name = "FullscreenQuad"; - auto drawID = addVertex( + auto drawID = addVertex2( BlitTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -1533,7 +906,7 @@ RenderQueueBuilder *NativeRenderPassBuilder::addQueue( const auto phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); - auto queueID = addVertex( + auto queueID = addVertex2( QueueTag{}, std::forward_as_tuple(phaseName), std::forward_as_tuple(phaseName), @@ -1554,40 +927,10 @@ SubpassBuilder *addRenderSubpassImpl( const LayoutGraphData &layoutGraph, LayoutGraphData::vertex_descriptor passLayoutID, const ccstd::string &subpassName, uint32_t count, uint32_t quality) { // NOLINT(bugprone-easily-swappable-parameters) - CC_EXPECTS(!subpassName.empty()); 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(subpassName), - std::forward_as_tuple(), - subpassGraph); - CC_ENSURES(id == subpassIndex); - } - RasterSubpass subpass(subpassIndex, count, quality, renderGraph.get_allocator()); - subpass.viewport.width = pass.width; - subpass.viewport.height = pass.height; - - auto subpassID = addVertex( - RasterSubpassTag{}, - 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, passID); - - auto subpassLayoutID = LayoutGraphData::null_vertex(); - if constexpr (ENABLE_SUBPASS) { - subpassLayoutID = locate(passLayoutID, subpassName, layoutGraph); - } else { - subpassLayoutID = locate(LayoutGraphData::null_vertex(), subpassName, layoutGraph); - } - - CC_EXPECTS(subpassLayoutID != LayoutGraphData::null_vertex()); + auto [subpassID, subpassLayoutID] = addRenderSubpassVertex( + pass, renderGraph, passID, layoutGraph, passLayoutID, subpassName, count, quality); auto *builder = ccnew SubpassBuilder( pipelineRuntime, &renderGraph, subpassID, &layoutGraph, subpassLayoutID); @@ -1625,7 +968,7 @@ ComputeSubpassBuilder *NativeRenderPassBuilder::addComputeSubpass(const ccstd::s ComputeSubpass subpass(subpassIndex, renderGraph->get_allocator()); - auto subpassID = addVertex( + auto subpassID = addVertex2( ComputeSubpassTag{}, std::forward_as_tuple(subpassName), std::forward_as_tuple(subpassName), @@ -1658,12 +1001,187 @@ void NativeRenderPassBuilder::setVersion(const ccstd::string &name, uint64_t ver // noop } +void NativeMultisampleRenderPassBuilder::addRenderTarget( + const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) { + addRasterViewImpl( + name, + "", + "", + AccessType::WRITE, + AttachmentType::RENDER_TARGET, + loadOp, + storeOp, + gfx::ClearFlagBit::COLOR, + color, + subpassID, + *renderGraph); +} + +void NativeMultisampleRenderPassBuilder::addDepthStencil( + const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, + float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) { // NOLINT(bugprone-easily-swappable-parameters) + addRasterViewImpl( + name, + "", + "", + AccessType::WRITE, + AttachmentType::DEPTH_STENCIL, + loadOp, + storeOp, + clearFlags, + gfx::Color{depth, static_cast(stencil)}, + subpassID, + *renderGraph); +} + +void NativeMultisampleRenderPassBuilder::addTexture( + const ccstd::string &name, const ccstd::string &slotName, // NOLINT(bugprone-easily-swappable-parameters) + gfx::Sampler *sampler, uint32_t plane) { + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + subpassID, + name, + ComputeView{ + ccstd::pmr::string(slotName, renderGraph->get_allocator()), + AccessType::READ, + plane, + gfx::ClearFlagBit::NONE, + ClearValueType::NONE, + ClearValue{}, + gfx::ShaderStageFlagBit::NONE, + renderGraph->get_allocator()}); + if (sampler) { + auto iter = layoutGraph->attributeIndex.find(std::string_view{slotName}); + if (iter != layoutGraph->attributeIndex.end()) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, subpassID); + data.samplers[iter->second.value] = sampler; + } + } +} + +void NativeMultisampleRenderPassBuilder::addStorageBuffer( + const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + subpassID, + name, + ComputeView{ + ccstd::pmr::string(slotName, renderGraph->get_allocator()), + accessType, + gfx::ClearFlagBit::NONE, + ClearValueType::NONE, + ClearValue{}, + gfx::ShaderStageFlagBit::NONE, + renderGraph->get_allocator()}); +} + +void NativeMultisampleRenderPassBuilder::addStorageImage( + const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + subpassID, + name, + ComputeView{ + ccstd::pmr::string(slotName, renderGraph->get_allocator()), + accessType, + gfx::ClearFlagBit::NONE, + ClearValueType::NONE, + ClearValue{}, + gfx::ShaderStageFlagBit::NONE, + renderGraph->get_allocator()}); +} + +RenderQueueBuilder *NativeMultisampleRenderPassBuilder::addQueue( + QueueHint hint, const ccstd::string &phaseName) { + CC_EXPECTS(!phaseName.empty()); + CC_EXPECTS(subpassLayoutID == layoutID); + CC_EXPECTS(subpassLayoutID != LayoutGraphData::null_vertex()); + + const auto phaseLayoutID = locate(subpassLayoutID, phaseName, *layoutGraph); + CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); + + auto queueID = addVertex2( + QueueTag{}, + std::forward_as_tuple(phaseName), + std::forward_as_tuple(phaseName), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(hint, phaseLayoutID), + *renderGraph, subpassID); + + return new NativeRenderQueueBuilder(pipelineRuntime, renderGraph, queueID, layoutGraph, phaseLayoutID); +} + +void NativeMultisampleRenderPassBuilder::setViewport(const gfx::Viewport &viewport) { + auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + subpass.viewport = viewport; +} + +void NativeMultisampleRenderPassBuilder::setVersion(const ccstd::string &name, uint64_t version) { + // noop +} + +bool NativeMultisampleRenderPassBuilder::getShowStatistics() const { + const auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + return subpass.showStatistics; +} + +void NativeMultisampleRenderPassBuilder::setShowStatistics(bool enable) { + auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + subpass.showStatistics = enable; +} + +void NativeMultisampleRenderPassBuilder::resolveRenderTarget( + const ccstd::string &source, const ccstd::string &target) { // NOLINT(bugprone-easily-swappable-parameters) + auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + + auto &pass = get(RasterPassTag{}, nodeID, *renderGraph); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + + subpass.resolvePairs.emplace_back( + ccstd::pmr::string(source.data(), renderGraph->get_allocator()), + ccstd::pmr::string(target.data(), renderGraph->get_allocator()), + ResolveFlags::COLOR, + gfx::ResolveMode::AVERAGE, + gfx::ResolveMode::NONE); + + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); +} + +void NativeMultisampleRenderPassBuilder::resolveDepthStencil( + const ccstd::string &source, const ccstd::string &target, // NOLINT(bugprone-easily-swappable-parameters) + gfx::ResolveMode depthMode, gfx::ResolveMode stencilMode) { // NOLINT(bugprone-easily-swappable-parameters) + auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + ResolveFlags flags = ResolveFlags::NONE; + if (depthMode != gfx::ResolveMode::NONE) { + flags |= ResolveFlags::DEPTH; + } + if (stencilMode != gfx::ResolveMode::NONE) { + flags |= ResolveFlags::STENCIL; + } + + auto &pass = get(RasterPassTag{}, nodeID, *renderGraph); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + + subpass.resolvePairs.emplace_back( + ccstd::pmr::string(source.data(), renderGraph->get_allocator()), + ccstd::pmr::string(target.data(), renderGraph->get_allocator()), + flags, + depthMode, + stencilMode); + + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); +} + // NativeComputeQueue void NativeComputeQueueBuilder::addDispatch( uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, Material *material, uint32_t passID) { std::string_view name("Dispatch"); - addVertex( + addVertex2( DispatchTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -1682,8 +1200,10 @@ void NativeComputeQueueBuilder::addDispatch( void NativeComputePassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) { - addComputeView( - *this, + addPassComputeViewImpl( + ComputeTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -1705,8 +1225,10 @@ void NativeComputePassBuilder::addTexture( void NativeComputePassBuilder::addStorageBuffer( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addPassComputeViewImpl( + ComputeTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -1720,8 +1242,10 @@ void NativeComputePassBuilder::addStorageBuffer( void NativeComputePassBuilder::addStorageImage( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addPassComputeViewImpl( + ComputeTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -1759,7 +1283,7 @@ ComputeQueueBuilder *NativeComputePassBuilder::addQueue(const ccstd::string &pha const auto phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); - auto queueID = addVertex( + auto queueID = addVertex2( QueueTag{}, std::forward_as_tuple(phaseName), std::forward_as_tuple(phaseName), @@ -1771,318 +1295,6 @@ ComputeQueueBuilder *NativeComputePassBuilder::addQueue(const ccstd::string &pha return new NativeComputeQueueBuilder(pipelineRuntime, renderGraph, queueID, layoutGraph, phaseLayoutID); } -namespace { - -const char *getName(const gfx::LoadOp &op) { - switch (op) { - case gfx::LoadOp::LOAD: - return "LOAD"; - case gfx::LoadOp::CLEAR: - return "CLEAR"; - case gfx::LoadOp::DISCARD: - return "DISCARD"; - default: - return "UNKNOWN"; - } - return "UNKNOWN"; -} - -const char *getName(const gfx::StoreOp &op) { - switch (op) { - case gfx::StoreOp::STORE: - return "STORE"; - case gfx::StoreOp::DISCARD: - return "DISCARD"; - default: - return "UNKNOWN"; - } - return "UNKNOWN"; -} - -std::string getName(const gfx::ClearFlagBit &flags) { - std::ostringstream oss; - int count = 0; - if (hasAnyFlags(flags, gfx::ClearFlagBit::COLOR)) { - if (count++) { - oss << "|"; - } - oss << "COLOR"; - } - if (hasAnyFlags(flags, gfx::ClearFlagBit::DEPTH)) { - if (count++) { - oss << "|"; - } - oss << "DEPTH"; - } - if (hasAnyFlags(flags, gfx::ClearFlagBit::STENCIL)) { - if (count++) { - oss << "|"; - } - oss << "STENCIL"; - } - if (flags == gfx::ClearFlagBit::NONE) { - oss << "NONE"; - } - return oss.str(); -} - -struct RenderGraphPrintVisitor : boost::dfs_visitor<> { - void discover_vertex( - RenderGraph::vertex_descriptor vertID, - const AddressableView &gv) const { - const auto &g = gv.mGraph; - const auto &name = get(RenderGraph::NameTag{}, g, vertID); - visitObject( - vertID, gv.mGraph, - [&](const RasterPass &pass) { - OSS << "RasterPass \"" << name << "\" {\n"; - indent(space); - for (const auto &[name, rasterView] : pass.rasterViews) { - OSS << "RasterView \"" << name << "\" {\n"; - { - INDENT(); - OSS << "slotName: \"" << rasterView.slotName << "\";\n"; - OSS << "accessType: " << getName(rasterView.accessType) << ";\n"; - OSS << "attachmentType: " << getName(rasterView.attachmentType) << ";\n"; - OSS << "loadOp: " << getName(rasterView.loadOp) << ";\n"; - OSS << "storeOp: " << getName(rasterView.storeOp) << ";\n"; - OSS << "clearFlags: " << getName(rasterView.clearFlags) << ";\n"; - const auto &c = rasterView.clearColor; - if (hasAnyFlags(rasterView.clearFlags, gfx::ClearFlagBit::COLOR)) { - OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; - } else if (hasAnyFlags(rasterView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { - OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; - } - } - OSS << "}\n"; - } - for (const auto &[name, computeViews] : pass.computeViews) { - OSS << "ComputeViews \"" << name << "\" {\n"; - { - INDENT(); - for (const auto &computeView : computeViews) { - OSS << "ComputeView \"" << computeView.name << "\" {\n"; - { - INDENT(); - OSS << "accessType: " << getName(computeView.accessType) << ";\n"; - OSS << "clearFlags: " << getName(computeView.clearFlags) << ";\n"; - const auto &c = computeView.clearValue; - if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::COLOR)) { - OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; - } else if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { - OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; - } - } - OSS << "}\n"; - } - } - OSS << "}\n"; - } - }, - [&](const RasterSubpass &subpass) { - std::ignore = subpass; - }, - [&](const ComputeSubpass &subpass) { - std::ignore = subpass; - }, - [&](const ComputePass &pass) { - OSS << "ComputePass \"" << name << "\" {\n"; - indent(space); - for (const auto &[name, computeViews] : pass.computeViews) { - OSS << "ComputeViews \"" << name << "\" {\n"; - { - INDENT(); - for (const auto &computeView : computeViews) { - OSS << "ComputeView \"" << computeView.name << "\" {\n"; - { - INDENT(); - OSS << "accessType: " << getName(computeView.accessType) << ";\n"; - OSS << "clearFlags: " << getName(computeView.clearFlags) << ";\n"; - const auto &c = computeView.clearValue; - if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::COLOR)) { - OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; - } else if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { - OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; - } - } - OSS << "}\n"; - } - } - OSS << "}\n"; - } - }, - [&](const ResolvePass &pass) { - OSS << "ResolvePass \"" << name << "\" {\n"; - for (const auto &pair : pass.resolvePairs) { - INDENT(); - OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; - } - indent(space); - }, - [&](const CopyPass &pass) { - OSS << "CopyPass \"" << name << "\" {\n"; - for (const auto &pair : pass.copyPairs) { - INDENT(); - OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; - } - indent(space); - }, - [&](const MovePass &pass) { - OSS << "MovePass \"" << name << "\" {\n"; - for (const auto &pair : pass.movePairs) { - INDENT(); - OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; - } - indent(space); - }, - [&](const RaytracePass &pass) { - std::ignore = pass; - OSS << "RaytracePass \"" << name << "\" {\n"; - indent(space); - }, - [&](const RenderQueue &queue) { - OSS << "Queue \"" << name << "\" {\n"; - { - INDENT(); - OSS << "hint: " << getName(queue.hint) << ";\n"; - } - indent(space); - }, - [&](const SceneData &scene) { - std::ignore = scene; - OSS << "Scene \"" << name << "\" {\n"; - indent(space); - }, - [&](const Blit &blit) { - std::ignore = blit; - OSS << "Blit \"" << name << "\";\n"; - }, - [&](const Dispatch &dispatch) { - OSS << "Dispatch \"" << name << "\", [" - << dispatch.threadGroupCountX << ", " - << dispatch.threadGroupCountY << ", " - << dispatch.threadGroupCountZ << "];\n"; - }, - [&](const ccstd::pmr::vector &clearViews) { - OSS << "Clear \"" << name << "\" {\n"; - indent(space); - for (const auto &view : clearViews) { - INDENT(); - OSS << "\"" << view.slotName << "\" {\n"; - { - INDENT(); - OSS << "clearFlags: " << getName(view.clearFlags) << ";\n"; - const auto &c = view.clearColor; - if (hasAnyFlags(view.clearFlags, gfx::ClearFlagBit::COLOR)) { - OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; - } else if (hasAnyFlags(view.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { - OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; - } - } - OSS << "}\n"; - } - }, - [&](const gfx::Viewport &vp) { - OSS << "Viewport \"" << name << "\" [" - << "left: " << vp.left << ", " - << "top: " << vp.top << ", " - << "width: " << vp.width << ", " - << "height: " << vp.height << ", " - << "minDepth: " << vp.minDepth << ", " - << "maxDepth: " << vp.maxDepth << "]\n"; - }); - } - - void finish_vertex( - RenderGraph::vertex_descriptor vertID, - const AddressableView &gv) const { - std::ignore = gv; - visitObject( - vertID, gv.mGraph, - [&](const RasterPass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const RasterSubpass &subpass) { - std::ignore = subpass; - }, - [&](const ComputeSubpass &subpass) { - std::ignore = subpass; - }, - [&](const ComputePass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const ResolvePass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const CopyPass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const MovePass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const RaytracePass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const RenderQueue &queue) { - std::ignore = queue; - unindent(space); - OSS << "}\n"; - }, - [&](const SceneData &scene) { - std::ignore = scene; - unindent(space); - OSS << "}\n"; - }, - [&](const Blit &blit) { - }, - [&](const Dispatch &dispatch) { - }, - [&](const ccstd::pmr::vector &clear) { - std::ignore = clear; - unindent(space); - OSS << "}\n"; - }, - [&](const gfx::Viewport &clear) { - }); - } - - std::ostringstream &oss; - ccstd::pmr::string &space; -}; - -} // namespace - -ccstd::string RenderGraph::print( - boost::container::pmr::memory_resource *scratch) const { - const auto &rg = *this; - std::ostringstream oss; - ccstd::pmr::string space(scratch); - oss << "\n"; - OSS << "RenderGraph {\n"; - { - INDENT(); - RenderGraphPrintVisitor visitor{ - {}, oss, space}; - AddressableView graphView(rg); - auto colors = rg.colors(scratch); - boost::depth_first_search(graphView, visitor, get(colors, rg)); - } - OSS << "}\n"; - return oss.str(); -} - } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.cpp new file mode 100644 index 0000000000..dce7e2773f --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.cpp @@ -0,0 +1,327 @@ +#include +#include +#include "cocos/renderer/pipeline/custom/RenderCommonNames.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/details/DebugUtils.h" +#include "cocos/renderer/pipeline/custom/details/GraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/GraphView.h" + +namespace cc { + +namespace render { + +namespace { + +const char *getName(const gfx::LoadOp &op) { + switch (op) { + case gfx::LoadOp::LOAD: + return "LOAD"; + case gfx::LoadOp::CLEAR: + return "CLEAR"; + case gfx::LoadOp::DISCARD: + return "DISCARD"; + default: + return "UNKNOWN"; + } + return "UNKNOWN"; +} + +const char *getName(const gfx::StoreOp &op) { + switch (op) { + case gfx::StoreOp::STORE: + return "STORE"; + case gfx::StoreOp::DISCARD: + return "DISCARD"; + default: + return "UNKNOWN"; + } + return "UNKNOWN"; +} + +std::string getName(const gfx::ClearFlagBit &flags) { + std::ostringstream oss; + int count = 0; + if (hasAnyFlags(flags, gfx::ClearFlagBit::COLOR)) { + if (count++) { + oss << "|"; + } + oss << "COLOR"; + } + if (hasAnyFlags(flags, gfx::ClearFlagBit::DEPTH)) { + if (count++) { + oss << "|"; + } + oss << "DEPTH"; + } + if (hasAnyFlags(flags, gfx::ClearFlagBit::STENCIL)) { + if (count++) { + oss << "|"; + } + oss << "STENCIL"; + } + if (flags == gfx::ClearFlagBit::NONE) { + oss << "NONE"; + } + return oss.str(); +} + +struct RenderGraphPrintVisitor : boost::dfs_visitor<> { + void discover_vertex( + RenderGraph::vertex_descriptor vertID, + const AddressableView &gv) const { + const auto &g = gv.mGraph; + const auto &name = get(RenderGraph::NameTag{}, g, vertID); + visitObject( + vertID, gv.mGraph, + [&](const RasterPass &pass) { + OSS << "RasterPass \"" << name << "\" {\n"; + indent(space); + for (const auto &[name, rasterView] : pass.rasterViews) { + OSS << "RasterView \"" << name << "\" {\n"; + { + INDENT(); + OSS << "slotName: \"" << rasterView.slotName << "\";\n"; + OSS << "accessType: " << getName(rasterView.accessType) << ";\n"; + OSS << "attachmentType: " << getName(rasterView.attachmentType) << ";\n"; + OSS << "loadOp: " << getName(rasterView.loadOp) << ";\n"; + OSS << "storeOp: " << getName(rasterView.storeOp) << ";\n"; + OSS << "clearFlags: " << getName(rasterView.clearFlags) << ";\n"; + const auto &c = rasterView.clearColor; + if (hasAnyFlags(rasterView.clearFlags, gfx::ClearFlagBit::COLOR)) { + OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; + } else if (hasAnyFlags(rasterView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { + OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; + } + } + OSS << "}\n"; + } + for (const auto &[name, computeViews] : pass.computeViews) { + OSS << "ComputeViews \"" << name << "\" {\n"; + { + INDENT(); + for (const auto &computeView : computeViews) { + OSS << "ComputeView \"" << computeView.name << "\" {\n"; + { + INDENT(); + OSS << "accessType: " << getName(computeView.accessType) << ";\n"; + OSS << "clearFlags: " << getName(computeView.clearFlags) << ";\n"; + const auto &c = computeView.clearValue; + if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::COLOR)) { + OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; + } else if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { + OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; + } + } + OSS << "}\n"; + } + } + OSS << "}\n"; + } + }, + [&](const RasterSubpass &subpass) { + std::ignore = subpass; + }, + [&](const ComputeSubpass &subpass) { + std::ignore = subpass; + }, + [&](const ComputePass &pass) { + OSS << "ComputePass \"" << name << "\" {\n"; + indent(space); + for (const auto &[name, computeViews] : pass.computeViews) { + OSS << "ComputeViews \"" << name << "\" {\n"; + { + INDENT(); + for (const auto &computeView : computeViews) { + OSS << "ComputeView \"" << computeView.name << "\" {\n"; + { + INDENT(); + OSS << "accessType: " << getName(computeView.accessType) << ";\n"; + OSS << "clearFlags: " << getName(computeView.clearFlags) << ";\n"; + const auto &c = computeView.clearValue; + if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::COLOR)) { + OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; + } else if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { + OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; + } + } + OSS << "}\n"; + } + } + OSS << "}\n"; + } + }, + [&](const ResolvePass &pass) { + OSS << "ResolvePass \"" << name << "\" {\n"; + for (const auto &pair : pass.resolvePairs) { + INDENT(); + OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; + } + indent(space); + }, + [&](const CopyPass &pass) { + OSS << "CopyPass \"" << name << "\" {\n"; + for (const auto &pair : pass.copyPairs) { + INDENT(); + OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; + } + indent(space); + }, + [&](const MovePass &pass) { + OSS << "MovePass \"" << name << "\" {\n"; + for (const auto &pair : pass.movePairs) { + INDENT(); + OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; + } + indent(space); + }, + [&](const RaytracePass &pass) { + std::ignore = pass; + OSS << "RaytracePass \"" << name << "\" {\n"; + indent(space); + }, + [&](const RenderQueue &queue) { + OSS << "Queue \"" << name << "\" {\n"; + { + INDENT(); + OSS << "hint: " << getName(queue.hint) << ";\n"; + } + indent(space); + }, + [&](const SceneData &scene) { + std::ignore = scene; + OSS << "Scene \"" << name << "\" {\n"; + indent(space); + }, + [&](const Blit &blit) { + std::ignore = blit; + OSS << "Blit \"" << name << "\";\n"; + }, + [&](const Dispatch &dispatch) { + OSS << "Dispatch \"" << name << "\", [" + << dispatch.threadGroupCountX << ", " + << dispatch.threadGroupCountY << ", " + << dispatch.threadGroupCountZ << "];\n"; + }, + [&](const ccstd::pmr::vector &clearViews) { + OSS << "Clear \"" << name << "\" {\n"; + indent(space); + for (const auto &view : clearViews) { + INDENT(); + OSS << "\"" << view.slotName << "\" {\n"; + { + INDENT(); + OSS << "clearFlags: " << getName(view.clearFlags) << ";\n"; + const auto &c = view.clearColor; + if (hasAnyFlags(view.clearFlags, gfx::ClearFlagBit::COLOR)) { + OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; + } else if (hasAnyFlags(view.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { + OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; + } + } + OSS << "}\n"; + } + }, + [&](const gfx::Viewport &vp) { + OSS << "Viewport \"" << name << "\" [" + << "left: " << vp.left << ", " + << "top: " << vp.top << ", " + << "width: " << vp.width << ", " + << "height: " << vp.height << ", " + << "minDepth: " << vp.minDepth << ", " + << "maxDepth: " << vp.maxDepth << "]\n"; + }); + } + + void finish_vertex( + RenderGraph::vertex_descriptor vertID, + const AddressableView &gv) const { + std::ignore = gv; + visitObject( + vertID, gv.mGraph, + [&](const RasterPass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const RasterSubpass &subpass) { + std::ignore = subpass; + }, + [&](const ComputeSubpass &subpass) { + std::ignore = subpass; + }, + [&](const ComputePass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const ResolvePass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const CopyPass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const MovePass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const RaytracePass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const RenderQueue &queue) { + std::ignore = queue; + unindent(space); + OSS << "}\n"; + }, + [&](const SceneData &scene) { + std::ignore = scene; + unindent(space); + OSS << "}\n"; + }, + [&](const Blit &blit) { + }, + [&](const Dispatch &dispatch) { + }, + [&](const ccstd::pmr::vector &clear) { + std::ignore = clear; + unindent(space); + OSS << "}\n"; + }, + [&](const gfx::Viewport &clear) { + }); + } + + std::ostringstream &oss; + ccstd::pmr::string &space; +}; + +} // namespace + +ccstd::string RenderGraph::print( + boost::container::pmr::memory_resource *scratch) const { + const auto &rg = *this; + std::ostringstream oss; + ccstd::pmr::string space(scratch); + oss << "\n"; + OSS << "RenderGraph {\n"; + { + INDENT(); + RenderGraphPrintVisitor visitor{ + {}, oss, space}; + AddressableView graphView(rg); + auto colors = rg.colors(scratch); + boost::depth_first_search(graphView, visitor, get(colors, rg)); + } + OSS << "}\n"; + return oss.str(); +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h new file mode 100644 index 0000000000..1885886921 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h @@ -0,0 +1,216 @@ +#pragma once +#include "cocos/renderer/pipeline/custom/LayoutGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/NativeTypes.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" +#include "pipeline/custom/RenderGraphTypes.h" + +namespace cc { + +namespace render { + +template +RenderGraph::vertex_descriptor +addVertex2(Tag tag, Component0 &&c0, Component1 &&c1, Component2 &&c2, Component3 &&c3, ValueT &&val, + RenderGraph &g, RenderGraph::vertex_descriptor u = RenderGraph::null_vertex()) { + auto v = addVertex( + tag, + std::forward(c0), + std::forward(c1), + std::forward(c2), + std::forward(c3), + std::forward(val), + g, + u); + g.sortedVertices.emplace_back(v); + CC_EXPECTS(g.sortedVertices.size() == num_vertices(g)); + return v; +} + +inline LayoutGraphData::vertex_descriptor getSubpassOrPassID( + RenderGraph::vertex_descriptor vertID, + const RenderGraph &rg, const LayoutGraphData &lg) { + const auto queueID = parent(vertID, rg); + CC_ENSURES(queueID != RenderGraph::null_vertex()); + const auto subpassOrPassID = parent(queueID, rg); + CC_ENSURES(subpassOrPassID != RenderGraph::null_vertex()); + const auto passID = parent(subpassOrPassID, rg); + + auto layoutID = LayoutGraphData::null_vertex(); + if (passID == RenderGraph::null_vertex()) { // single render pass + const auto &layoutName = get(RenderGraph::LayoutTag{}, rg, subpassOrPassID); + CC_ENSURES(!layoutName.empty()); + layoutID = locate(LayoutGraphData::null_vertex(), layoutName, lg); + } else { // render pass + const auto &passLayoutName = get(RenderGraph::LayoutTag{}, rg, passID); + CC_ENSURES(!passLayoutName.empty()); + const auto passLayoutID = locate(LayoutGraphData::null_vertex(), passLayoutName, lg); + CC_ENSURES(passLayoutID != LayoutGraphData::null_vertex()); + + const auto &subpassLayoutName = get(RenderGraph::LayoutTag{}, rg, subpassOrPassID); + if (subpassLayoutName.empty()) { + layoutID = passLayoutID; // expect to be multisample pass + } else { + const auto subpassLayoutID = locate(passLayoutID, subpassLayoutName, lg); + CC_ENSURES(subpassLayoutID != LayoutGraphData::null_vertex()); + layoutID = subpassLayoutID; + } + + } + CC_ENSURES(layoutID != LayoutGraphData::null_vertex()); + return layoutID; +} + +inline std::tuple +addRenderPassVertex( + RenderGraph &renderGraph, const LayoutGraphData &layoutGraph, + 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 &passName) { + RasterPass pass(renderGraph.get_allocator()); + pass.width = width; + pass.height = height; + pass.viewport.width = width; + pass.viewport.height = height; + pass.count = count; + pass.quality = quality; + + auto passID = addVertex2( + RasterPassTag{}, + 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(), passName, layoutGraph); + CC_EXPECTS(passLayoutID != LayoutGraphData::null_vertex()); + + return {passID, passLayoutID}; +} + +inline std::tuple +addRenderSubpassVertex( + RasterPass &pass, + 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) + + // if subpassName is empty, it must be basic multisample render pass + CC_EXPECTS(!subpassName.empty() || count > 1); + + auto &subpassGraph = pass.subpassGraph; + const auto subpassIndex = num_vertices(pass.subpassGraph); + { + auto id = addVertex( + std::piecewise_construct, + std::forward_as_tuple(subpassName), + std::forward_as_tuple(), + subpassGraph); + CC_ENSURES(id == subpassIndex); + } + + RasterSubpass subpass(subpassIndex, count, quality, renderGraph.get_allocator()); + subpass.viewport.width = pass.width; + subpass.viewport.height = pass.height; + + auto subpassID = addVertex2( + RasterSubpassTag{}, + 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, passID); + + auto subpassLayoutID = LayoutGraphData::null_vertex(); + if (subpassName.empty()) { // Basic multisample render pass (single subpass) + CC_EXPECTS(count > 1); + subpassLayoutID = passLayoutID; + } else { + if constexpr (ENABLE_SUBPASS) { + subpassLayoutID = locate(passLayoutID, subpassName, layoutGraph); + } else { + subpassLayoutID = locate(LayoutGraphData::null_vertex(), subpassName, layoutGraph); + } + } + CC_ENSURES(subpassLayoutID != LayoutGraphData::null_vertex()); + + return {subpassID, subpassLayoutID}; +} + +template +void addPassComputeViewImpl( + Tag tag, + RenderGraph &renderGraph, + RenderGraph::vertex_descriptor passID, + const ccstd::string &name, const ComputeView &view) { + std::ignore = tag; + CC_EXPECTS(!name.empty()); + CC_EXPECTS(!view.name.empty()); + auto &pass = get(Tag{}, passID, renderGraph); + auto iter = pass.computeViews.find(name.c_str()); + if (iter == pass.computeViews.end()) { + bool added = false; + std::tie(iter, added) = pass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple()); + CC_ENSURES(added); + } + iter->second.emplace_back(view); +} + +template +void addSubpassComputeViewImpl( + Tag tag, + RenderGraph &renderGraph, + RenderGraph::vertex_descriptor subpassID, + const ccstd::string &name, const ComputeView &view) { + std::ignore = tag; + CC_EXPECTS(!name.empty()); + CC_EXPECTS(!view.name.empty()); + auto &subpass = get(Tag{}, subpassID, renderGraph); + const auto passID = parent(subpassID, renderGraph); + CC_EXPECTS(passID != RenderGraph::null_vertex()); + CC_EXPECTS(holds(passID, renderGraph)); + auto &pass = get(RasterPassTag{}, passID, renderGraph); + CC_EXPECTS(subpass.subpassID < num_vertices(pass.subpassGraph)); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + CC_EXPECTS(subpass.computeViews.size() == subpassData.computeViews.size()); + { + auto iter = subpassData.computeViews.find(name.c_str()); + if (iter == subpassData.computeViews.end()) { + bool added = false; + std::tie(iter, added) = subpassData.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple()); + CC_ENSURES(added); + } + iter->second.emplace_back(view); + } + { + auto iter = subpass.computeViews.find(name.c_str()); + if (iter == subpass.computeViews.end()) { + bool added = false; + std::tie(iter, added) = subpass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple()); + CC_ENSURES(added); + } + iter->second.emplace_back(view); + } + CC_ENSURES(subpass.computeViews.size() == subpassData.computeViews.size()); + CC_ENSURES(subpass.computeViews.find(std::string_view{name}) != subpass.computeViews.end()); + CC_ENSURES(subpassData.computeViews.find(std::string_view{name}) != subpassData.computeViews.end()); + CC_ENSURES(subpass.computeViews.find(std::string_view{name})->second.size() == + subpassData.computeViews.find(std::string_view{name})->second.size()); +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index 20709a6f97..984e215a9a 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -126,7 +126,7 @@ gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { } // usage - TextureUsage usage = TextureUsage::SAMPLED | TextureUsage::TRANSFER_SRC | TextureUsage::TRANSFER_DST; + TextureUsage usage = TextureUsage::NONE; if (any(desc.flags & ResourceFlags::COLOR_ATTACHMENT)) { usage |= TextureUsage::COLOR_ATTACHMENT; } @@ -143,6 +143,15 @@ gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { if (any(desc.flags & ResourceFlags::SHADING_RATE)) { usage |= TextureUsage::SHADING_RATE; } + if (any(desc.flags & ResourceFlags::SAMPLED)) { + usage |= TextureUsage::SAMPLED; + } + if (any(desc.flags & ResourceFlags::TRANSFER_SRC)) { + usage |= TextureUsage::TRANSFER_SRC; + } + if (any(desc.flags & ResourceFlags::TRANSFER_DST)) { + usage |= TextureUsage::TRANSFER_DST; + } return { type, diff --git a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp index 28f590b1b5..f2cfd0111b 100644 --- a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp @@ -1,16 +1,11 @@ -#include "LayoutGraphGraphs.h" -#include "NativePipelineTypes.h" -#include "NativeUtils.h" -#include "RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" +#include "cocos/renderer/pipeline/custom/details/Range.h" #include "cocos/scene/Octree.h" #include "cocos/scene/RenderScene.h" #include "cocos/scene/Skybox.h" #include "cocos/scene/SpotLight.h" -#include "details/GslUtils.h" -#include "details/Range.h" -#include "pipeline/custom/LayoutGraphTypes.h" -#include "pipeline/custom/NativeUtils.h" -#include "pipeline/custom/RenderCommonTypes.h" namespace cc { diff --git a/native/cocos/renderer/pipeline/custom/NativeSetter.cpp b/native/cocos/renderer/pipeline/custom/NativeSetter.cpp new file mode 100644 index 0000000000..6f4e2ca6fd --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeSetter.cpp @@ -0,0 +1,153 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "cocos/renderer/pipeline/custom/NativeBuiltinUtils.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/NativeUtils.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/scene/RenderScene.h" +#include "cocos/scene/SpotLight.h" + +namespace cc { + +namespace render { + +void NativeSetter::setMat4(const ccstd::string &name, const Mat4 &mat) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setMat4Impl(data, *layoutGraph, name, mat); +} + +void NativeSetter::setQuaternion(const ccstd::string &name, const Quaternion &quat) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setQuaternionImpl(data, *layoutGraph, name, quat); +} + +void NativeSetter::setColor(const ccstd::string &name, const gfx::Color &color) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setColorImpl(data, *layoutGraph, name, color); +} + +void NativeSetter::setVec4(const ccstd::string &name, const Vec4 &vec) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setVec4Impl(data, *layoutGraph, name, vec); +} + +void NativeSetter::setVec2(const ccstd::string &name, const Vec2 &vec) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setVec2Impl(data, *layoutGraph, name, vec); +} + +void NativeSetter::setFloat(const ccstd::string &name, float v) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setFloatImpl(data, *layoutGraph, name, v); +} + +void NativeSetter::setArrayBuffer(const ccstd::string &name, const ArrayBuffer *buffer) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setArrayBufferImpl(data, *layoutGraph, name, *buffer); +} + +void NativeSetter::setBuffer(const ccstd::string &name, gfx::Buffer *buffer) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setBufferImpl(data, *layoutGraph, name, buffer); +} + +void NativeSetter::setTexture(const ccstd::string &name, gfx::Texture *texture) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setTextureImpl(data, *layoutGraph, name, texture); +} + +void NativeSetter::setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setReadWriteBufferImpl(data, *layoutGraph, name, buffer); +} + +void NativeSetter::setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setReadWriteTextureImpl(data, *layoutGraph, name, texture); +} + +void NativeSetter::setSampler(const ccstd::string &name, gfx::Sampler *sampler) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setSamplerImpl(data, *layoutGraph, name, sampler); +} + +void NativeSetter::setVec4ArraySize(const ccstd::string &name, uint32_t sz) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setVec4ArraySizeImpl(data, *layoutGraph, name, sz); +} + +void NativeSetter::setVec4ArrayElem(const ccstd::string &name, const cc::Vec4 &vec, uint32_t id) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setVec4ArrayElemImpl(data, *layoutGraph, name, vec, id); +} + +void NativeSetter::setMat4ArraySize(const ccstd::string &name, uint32_t sz) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setMat4ArraySizeImpl(data, *layoutGraph, name, sz); +} + +void NativeSetter::setMat4ArrayElem(const ccstd::string &name, const cc::Mat4 &mat, uint32_t id) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setMat4ArrayElemImpl(data, *layoutGraph, name, mat, id); +} + +void NativeSetter::setBuiltinCameraConstants(const scene::Camera *camera) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setCameraUBOValues( + *camera, + *layoutGraph, + *pipelineRuntime->getPipelineSceneData(), + camera->getScene()->getMainLight(), data); +} + +void NativeSetter::setBuiltinDirectionalLightViewConstants( + const scene::DirectionalLight *light, uint32_t level) { + CC_EXPECTS(light); + auto *device = pipelineRuntime->getDevice(); + const auto &sceneData = *pipelineRuntime->getPipelineSceneData(); + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setShadowUBOLightView(device, *layoutGraph, sceneData, *light, level, data); +} + +void NativeSetter::setBuiltinSpotLightViewConstants(const scene::SpotLight *light) { + CC_EXPECTS(light); + auto *device = pipelineRuntime->getDevice(); + const auto &sceneData = *pipelineRuntime->getPipelineSceneData(); + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setShadowUBOLightView(device, *layoutGraph, sceneData, *light, 0, data); +} + +void NativeSetter::setBuiltinShadowMapConstants( + const scene::DirectionalLight *light) { + CC_EXPECTS(light); + auto *device = pipelineRuntime->getDevice(); + const auto &sceneData = *pipelineRuntime->getPipelineSceneData(); + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setShadowUBOView(*device, *layoutGraph, sceneData, *light, data); +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeUtils.cpp b/native/cocos/renderer/pipeline/custom/NativeUtils.cpp index 75af2336a1..4edad50235 100644 --- a/native/cocos/renderer/pipeline/custom/NativeUtils.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeUtils.cpp @@ -1,99 +1,37 @@ -#include "NativeUtils.h" -#include "LayoutGraphGraphs.h" -#include "NativePipelineTypes.h" -#include "RenderGraphGraphs.h" -#include "cocos/application/ApplicationManager.h" -#include "cocos/core/Root.h" -#include "details/GslUtils.h" +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "cocos/renderer/pipeline/custom/NativeUtils.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" namespace cc { + namespace render { -void setupQuadVertexBuffer(gfx::Device &device, const Vec4 &viewport, float vbData[16]) { - auto minX = static_cast(viewport.x); - auto maxX = static_cast(viewport.x + viewport.z); - auto minY = static_cast(viewport.y); - auto maxY = static_cast(viewport.y + viewport.w); - if (device.getCapabilities().screenSpaceSignY > 0) { - std::swap(minY, maxY); - } - int n = 0; - vbData[n++] = -1.0F; - vbData[n++] = -1.0F; - vbData[n++] = minX; // uv - vbData[n++] = maxY; - vbData[n++] = 1.0F; - vbData[n++] = -1.0F; - vbData[n++] = maxX; - vbData[n++] = maxY; - vbData[n++] = -1.0F; - vbData[n++] = 1.0F; - vbData[n++] = minX; - vbData[n++] = minY; - vbData[n++] = 1.0F; - vbData[n++] = 1.0F; - vbData[n++] = maxX; - vbData[n++] = minY; -} - -// NOLINTNEXTLINE(bugprone-easily-swappable-parameters) -void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter) { - const auto &root = *Root::getInstance(); - const auto shadingWidth = static_cast(width); - const auto shadingHeight = static_cast(height); - setter.setVec4( - "cc_time", - Vec4( - root.getCumulativeTime(), - root.getFrameTime(), - static_cast(CC_CURRENT_ENGINE()->getTotalFrames()), - 0.0F)); - - setter.setVec4( - "cc_screenSize", - Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); - setter.setVec4( - "cc_nativeSize", - Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); -#if 0 - const auto *debugView = root.getDebugView(); - if (debugView) { - setter.setVec4( - "cc_debug_view_mode", - Vec4(static_cast(debugView->getSingleMode()), - debugView->isLightingWithAlbedo() ? 1.0F : 0.0F, - debugView->isCsmLayerColoration() ? 1.0F : 0.0F, - 0.0F)); - Vec4 debugPackVec{}; - for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); - i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { - const auto idx = i % 4; - (&debugPackVec.x)[idx] = debugView->isCompositeModeEnabled(i) ? 1.0F : 0.0F; - const auto packIdx = static_cast(floor(static_cast(i) / 4.0F)); - if (idx == 3) { - std::string name("cc_debug_view_composite_pack_"); - name.append(std::to_string(packIdx + 1)); - setter.setVec4(name, debugPackVec); - } - } - } else { - setter.setVec4("cc_debug_view_mode", Vec4(0.0F, 1.0F, 0.0F, 0.0F)); - Vec4 debugPackVec{}; - for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); - i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { - const auto idx = i % 4; - (&debugPackVec.x)[idx] = 1.0F; - const auto packIdx = static_cast(floor(i / 4.0)); - if (idx == 3) { - std::string name("cc_debug_view_composite_pack_"); - name.append(std::to_string(packIdx + 1)); - setter.setVec4(name, debugPackVec); - } - } - } -#endif -} - namespace { render::NameLocalID getNameID( @@ -225,35 +163,6 @@ void setSamplerImpl(RenderData &data, const LayoutGraphData &lg, const ccstd::st data.samplers[nameID.value] = sampler; } -LayoutGraphData::vertex_descriptor getSubpassOrPassID( - RenderGraph::vertex_descriptor vertID, - const RenderGraph &rg, const LayoutGraphData &lg) { - const auto queueID = parent(vertID, rg); - CC_ENSURES(queueID != RenderGraph::null_vertex()); - const auto subpassOrPassID = parent(queueID, rg); - CC_ENSURES(subpassOrPassID != RenderGraph::null_vertex()); - const auto passID = parent(subpassOrPassID, rg); - - auto layoutID = LayoutGraphData::null_vertex(); - if (passID == RenderGraph::null_vertex()) { // single render pass - const auto &layoutName = get(RenderGraph::LayoutTag{}, rg, subpassOrPassID); - CC_ENSURES(!layoutName.empty()); - layoutID = locate(LayoutGraphData::null_vertex(), layoutName, lg); - } else { // render pass - const auto &passLayoutName = get(RenderGraph::LayoutTag{}, rg, passID); - CC_ENSURES(!passLayoutName.empty()); - const auto passLayoutID = locate(LayoutGraphData::null_vertex(), passLayoutName, lg); - CC_ENSURES(passLayoutID != LayoutGraphData::null_vertex()); - - const auto &subpassLayoutName = get(RenderGraph::LayoutTag{}, rg, subpassOrPassID); - CC_ENSURES(!subpassLayoutName.empty()); - const auto subpassLayoutID = locate(passLayoutID, subpassLayoutName, lg); - CC_ENSURES(subpassLayoutID != LayoutGraphData::null_vertex()); - layoutID = subpassLayoutID; - } - CC_ENSURES(layoutID != LayoutGraphData::null_vertex()); - return layoutID; -} - } // namespace render + } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeUtils.h b/native/cocos/renderer/pipeline/custom/NativeUtils.h index 620aa64b3e..82595dc3c9 100644 --- a/native/cocos/renderer/pipeline/custom/NativeUtils.h +++ b/native/cocos/renderer/pipeline/custom/NativeUtils.h @@ -1,18 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + #pragma once #include "cocos/core/ArrayBuffer.h" #include "cocos/math/Vec4.h" -#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" -#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphFwd.h" +#include "cocos/renderer/pipeline/custom/RenderGraphFwd.h" #include "cocos/renderer/pipeline/custom/RenderInterfaceFwd.h" namespace cc { -namespace gfx { -class Device; -} -namespace render { -void setupQuadVertexBuffer(gfx::Device &device, const Vec4 &viewport, float vbData[16]); -void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter); +namespace render { void setMat4Impl( RenderData &data, const LayoutGraphData &lg, std::string_view name, @@ -56,11 +75,6 @@ void setReadWriteTextureImpl(RenderData &data, const LayoutGraphData &lg, const void setSamplerImpl(RenderData &data, const LayoutGraphData &lg, const ccstd::string &name, gfx::Sampler *sampler); -// Implementation -LayoutGraphData::vertex_descriptor getSubpassOrPassID( - RenderGraph::vertex_descriptor vertID, - const RenderGraph &rg, const LayoutGraphData &lg); - } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h b/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h index 8f54ad52ca..1628d725ef 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h @@ -29,6 +29,7 @@ */ // clang-format off #pragma once +#include "cocos/base/std/hash/hash.h" #include "cocos/base/std/variant.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" @@ -84,4 +85,13 @@ struct PipelineStatistics; } // namespace cc +namespace ccstd { + +template <> +struct hash { + hash_t operator()(const cc::render::ResolvePair& val) const noexcept; +}; + +} // namespace ccstd + // clang-format on diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h index fea8e265f8..eb6dfe6a9b 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h @@ -32,6 +32,7 @@ #include "cocos/base/Ptr.h" #include "cocos/base/std/container/map.h" #include "cocos/base/std/container/string.h" +#include "cocos/base/std/hash/hash.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/pipeline/custom/RenderCommonFwd.h" #include "cocos/scene/Light.h" @@ -101,6 +102,8 @@ enum class ResourceFlags : uint32_t { DEPTH_STENCIL_ATTACHMENT = 0x20, INPUT_ATTACHMENT = 0x40, SHADING_RATE = 0x80, + TRANSFER_SRC = 0x100, + TRANSFER_DST = 0x200, }; constexpr ResourceFlags operator|(const ResourceFlags lhs, const ResourceFlags rhs) noexcept { @@ -154,6 +157,7 @@ enum class SceneFlags : uint32_t { DRAW_INSTANCING = 0x800, DRAW_NON_INSTANCING = 0x1000, REFLECTION_PROBE = 0x2000, + GPU_DRIVEN = 0x4000, ALL = 0xFFFFFFFF, }; @@ -325,6 +329,15 @@ struct ResolvePair { gfx::ResolveMode mode1{gfx::ResolveMode::SAMPLE_ZERO}; }; +inline bool operator==(const ResolvePair& lhs, const ResolvePair& rhs) noexcept { + return std::forward_as_tuple(lhs.source, lhs.target, lhs.resolveFlags, lhs.mode, lhs.mode1) == + std::forward_as_tuple(rhs.source, rhs.target, rhs.resolveFlags, rhs.mode, rhs.mode1); +} + +inline bool operator!=(const ResolvePair& lhs, const ResolvePair& rhs) noexcept { + return !(lhs == rhs); +} + struct CopyPair { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -420,4 +433,18 @@ struct PipelineStatistics { } // namespace cc +namespace ccstd { + +inline hash_t hash::operator()(const cc::render::ResolvePair& val) const noexcept { + hash_t seed = 0; + hash_combine(seed, val.source); + hash_combine(seed, val.target); + hash_combine(seed, val.resolveFlags); + hash_combine(seed, val.mode); + hash_combine(seed, val.mode1); + return seed; +} + +} // namespace ccstd + // clang-format on diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp index 0d6236eb38..bcb977b9e3 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp @@ -124,15 +124,18 @@ ComputeView::ComputeView(ComputeView const& rhs, const allocator_type& alloc) Subpass::Subpass(const allocator_type& alloc) noexcept : rasterViews(alloc), - computeViews(alloc) {} + computeViews(alloc), + resolvePairs(alloc) {} Subpass::Subpass(Subpass&& rhs, const allocator_type& alloc) : rasterViews(std::move(rhs.rasterViews), alloc), - computeViews(std::move(rhs.computeViews), alloc) {} + computeViews(std::move(rhs.computeViews), alloc), + resolvePairs(std::move(rhs.resolvePairs), alloc) {} Subpass::Subpass(Subpass const& rhs, const allocator_type& alloc) : rasterViews(rhs.rasterViews, alloc), - computeViews(rhs.computeViews, alloc) {} + computeViews(rhs.computeViews, alloc), + resolvePairs(rhs.resolvePairs, alloc) {} SubpassGraph::SubpassGraph(const allocator_type& alloc) noexcept : _vertices(alloc), @@ -416,7 +419,8 @@ RenderGraph::RenderGraph(const allocator_type& alloc) noexcept dispatches(alloc), clearViews(alloc), viewports(alloc), - index(alloc) {} + index(alloc), + sortedVertices(alloc) {} RenderGraph::RenderGraph(RenderGraph&& rhs, const allocator_type& alloc) : objects(std::move(rhs.objects), alloc), @@ -439,7 +443,8 @@ RenderGraph::RenderGraph(RenderGraph&& rhs, const allocator_type& alloc) dispatches(std::move(rhs.dispatches), alloc), clearViews(std::move(rhs.clearViews), alloc), viewports(std::move(rhs.viewports), alloc), - index(std::move(rhs.index), alloc) {} + index(std::move(rhs.index), alloc), + sortedVertices(std::move(rhs.sortedVertices), alloc) {} // ContinuousContainer void RenderGraph::reserve(vertices_size_type sz) { diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h index d0f7e0aa9f..acf43826fd 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h @@ -166,7 +166,7 @@ struct ResourceDesc { uint16_t depthOrArraySize{0}; uint16_t mipLevels{0}; gfx::Format format{gfx::Format::UNKNOWN}; - gfx::SampleCount sampleCount{gfx::SampleCount::ONE}; + gfx::SampleCount sampleCount{gfx::SampleCount::X1}; gfx::TextureFlagBit textureFlags{gfx::TextureFlagBit::NONE}; ResourceFlags flags{ResourceFlags::NONE}; }; @@ -242,11 +242,12 @@ struct Subpass { PmrTransparentMap rasterViews; PmrTransparentMap> computeViews; + ccstd::pmr::vector resolvePairs; }; inline bool operator==(const Subpass& lhs, const Subpass& rhs) noexcept { - return std::forward_as_tuple(lhs.rasterViews, lhs.computeViews) == - std::forward_as_tuple(rhs.rasterViews, rhs.computeViews); + return std::forward_as_tuple(lhs.rasterViews, lhs.computeViews, lhs.resolvePairs) == + std::forward_as_tuple(rhs.rasterViews, rhs.computeViews, rhs.resolvePairs); } inline bool operator!=(const Subpass& lhs, const Subpass& rhs) noexcept { @@ -1047,6 +1048,7 @@ struct RenderGraph { impl::ValueHandle, impl::ValueHandle>; + vertex_descriptor getPassID(vertex_descriptor nodeID) const; ccstd::string print(boost::container::pmr::memory_resource* scratch) const; // ContinuousContainer @@ -1123,6 +1125,7 @@ struct RenderGraph { ccstd::pmr::vector viewports; // Members PmrUnorderedStringMap index; + ccstd::pmr::vector sortedVertices; }; } // namespace render @@ -1168,6 +1171,7 @@ inline hash_t hash::operator()(const cc::render::Subpass& v hash_t seed = 0; hash_combine(seed, val.rasterViews); hash_combine(seed, val.computeViews); + hash_combine(seed, val.resolvePairs); return seed; } diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h index c88d1732b0..7a72a5f60e 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h @@ -49,16 +49,15 @@ class RenderNode; class Setter; class RenderQueueBuilder; class BasicRenderPassBuilder; +class BasicMultisampleRenderPassBuilder; class BasicPipeline; class RenderSubpassBuilder; class MultisampleRenderSubpassBuilder; class ComputeQueueBuilder; class ComputeSubpassBuilder; class RenderPassBuilder; +class MultisampleRenderPassBuilder; class ComputePassBuilder; -class SceneVisitor; -class SceneTask; -class SceneTransversal; class Pipeline; class PipelineBuilder; class RenderingModule; diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h index 3a2d25b3a3..4c5e015b56 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h @@ -290,6 +290,11 @@ enum class SubpassCapabilities : uint32_t { * @zh 支持读取当前像素任意颜色值 */ INPUT_COLOR_MRT = 1 << 2, + /** + * @en Each subpass has its own sample count. + * @zh 每个Subpass拥有不同的采样数 + */ + HETEROGENEOUS_SAMPLE_COUNT = 1 << 3, }; constexpr SubpassCapabilities operator|(const SubpassCapabilities lhs, const SubpassCapabilities rhs) noexcept { @@ -445,6 +450,13 @@ public: * @param name @en descriptor name in shader. @zh 填写着色器中的描述符(descriptor)名字 */ virtual void setSampler(const ccstd::string &name, gfx::Sampler *sampler) = 0; + virtual void setBuiltinCameraConstants(const scene::Camera *camera) = 0; + virtual void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) = 0; + virtual void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) = 0; + virtual void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) = 0; + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light) { + setBuiltinDirectionalLightViewConstants(light, 0); + } }; /** @@ -468,6 +480,9 @@ public: * @param sceneFlags @en Rendering flags of the scene @zh 场景渲染标志位 */ virtual void addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) = 0; + virtual void addScene(const scene::Camera *camera, SceneFlags sceneFlags) = 0; + virtual void addSceneCulledByDirectionalLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::DirectionalLight *light, uint32_t level) = 0; + virtual void addSceneCulledBySpotLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::SpotLight *light) = 0; /** * @en Render a full-screen quad. * @zh 渲染全屏四边形 @@ -636,6 +651,20 @@ public: } }; +class BasicMultisampleRenderPassBuilder : public BasicRenderPassBuilder { +public: + BasicMultisampleRenderPassBuilder() noexcept = default; + + virtual void resolveRenderTarget(const ccstd::string &source, const ccstd::string &target) = 0; + virtual void resolveDepthStencil(const ccstd::string &source, const ccstd::string &target, gfx::ResolveMode depthMode, gfx::ResolveMode stencilMode) = 0; + void resolveDepthStencil(const ccstd::string &source, const ccstd::string &target) { + resolveDepthStencil(source, target, gfx::ResolveMode::SAMPLE_ZERO, gfx::ResolveMode::SAMPLE_ZERO); + } + void resolveDepthStencil(const ccstd::string &source, const ccstd::string &target, gfx::ResolveMode depthMode) { + resolveDepthStencil(source, target, depthMode, gfx::ResolveMode::SAMPLE_ZERO); + } +}; + /** * @en BasicPipeline * Basic pipeline provides basic rendering features which are supported on all platforms. @@ -731,6 +760,8 @@ public: * @param format @en Format of the resource @zh 资源的格式 */ virtual void updateDepthStencil(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) = 0; + virtual uint32_t addResource(const ccstd::string &name, ResourceDimension dimension, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) = 0; + virtual void updateResource(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount) = 0; /** * @engineInternal * @en Begin rendering one frame @@ -770,7 +801,7 @@ public: * @param passName @en Pass name declared in the effect. Default value is 'default' @zh effect中的pass name,缺省为'default' * @returns Multisample basic render pass builder */ - virtual BasicRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) = 0; + virtual BasicMultisampleRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) = 0; /** * @deprecated Method will be removed in 3.9.0 */ @@ -815,7 +846,7 @@ public: BasicRenderPassBuilder *addRenderPass(uint32_t width, uint32_t height) { return addRenderPass(width, height, "default"); } - BasicRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality) { + BasicMultisampleRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality) { return addMultisampleRenderPass(width, height, count, quality, "default"); } }; @@ -1187,6 +1218,14 @@ public: } }; +class MultisampleRenderPassBuilder : public BasicMultisampleRenderPassBuilder { +public: + MultisampleRenderPassBuilder() noexcept = default; + + 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; +}; + /** * @en Compute pass * @zh 计算通道 @@ -1271,61 +1310,6 @@ public: } }; -/** - * @deprecated @en Not used @zh 未使用 - */ -class SceneVisitor { -public: - SceneVisitor() noexcept = default; - SceneVisitor(SceneVisitor&& rhs) = delete; - SceneVisitor(SceneVisitor const& rhs) = delete; - SceneVisitor& operator=(SceneVisitor&& rhs) = delete; - SceneVisitor& operator=(SceneVisitor const& rhs) = delete; - virtual ~SceneVisitor() noexcept = default; - - virtual const pipeline::PipelineSceneData *getPipelineSceneData() const = 0; - virtual void setViewport(const gfx::Viewport &vp) = 0; - virtual void setScissor(const gfx::Rect &rect) = 0; - virtual void bindPipelineState(gfx::PipelineState *pso) = 0; - virtual void bindDescriptorSet(uint32_t set, gfx::DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) = 0; - virtual void bindInputAssembler(gfx::InputAssembler *ia) = 0; - virtual void updateBuffer(gfx::Buffer *buff, const void *data, uint32_t size) = 0; - virtual void draw(const gfx::DrawInfo &info) = 0; -}; - -/** - * @deprecated @en Not used @zh 未使用 - */ -class SceneTask { -public: - SceneTask() noexcept = default; - SceneTask(SceneTask&& rhs) = delete; - SceneTask(SceneTask const& rhs) = delete; - SceneTask& operator=(SceneTask&& rhs) = delete; - SceneTask& operator=(SceneTask const& rhs) = delete; - virtual ~SceneTask() noexcept = default; - - virtual TaskType getTaskType() const noexcept = 0; - virtual void start() = 0; - virtual void join() = 0; - virtual void submit() = 0; -}; - -/** - * @deprecated @en Not used @zh 未使用 - */ -class SceneTransversal { -public: - SceneTransversal() noexcept = default; - SceneTransversal(SceneTransversal&& rhs) = delete; - SceneTransversal(SceneTransversal const& rhs) = delete; - SceneTransversal& operator=(SceneTransversal&& rhs) = delete; - SceneTransversal& operator=(SceneTransversal const& rhs) = delete; - virtual ~SceneTransversal() noexcept = default; - - virtual SceneTask *transverse(SceneVisitor *visitor) const = 0; -}; - /** * @en Render pipeline. * @zh 渲染管线 @@ -1389,6 +1373,7 @@ public: */ 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 &passName) override = 0 /* covariant */; + MultisampleRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) override = 0 /* covariant */; /** * @en Add compute pass * @zh 添加计算通道 @@ -1438,6 +1423,8 @@ public: * @param movePairs @en Array of move source and target @zh 移动来源与目标的数组 */ virtual void addMovePass(const ccstd::vector &movePairs) = 0; + virtual void addBuiltinGpuCullingPass(const scene::Camera *camera, const std::string &hzbName, const scene::Light *light) = 0; + virtual void addBuiltinHzbGenerationPass(const std::string &sourceDepthStencilName, const std::string &targetHzbName) = 0; /** * @experimental */ @@ -1461,6 +1448,12 @@ public: void updateStorageTexture(const ccstd::string &name, uint32_t width, uint32_t height) { updateStorageTexture(name, width, height, gfx::Format::UNKNOWN); } + void addBuiltinGpuCullingPass(const scene::Camera *camera) { + addBuiltinGpuCullingPass(camera, "", nullptr); + } + void addBuiltinGpuCullingPass(const scene::Camera *camera, const std::string &hzbName) { + addBuiltinGpuCullingPass(camera, hzbName, nullptr); + } }; /** diff --git a/native/cocos/renderer/pipeline/custom/test/test.h b/native/cocos/renderer/pipeline/custom/test/test.h index cb28556b1d..ed8f44f5ee 100644 --- a/native/cocos/renderer/pipeline/custom/test/test.h +++ b/native/cocos/renderer/pipeline/custom/test/test.h @@ -149,7 +149,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn nameSet.emplace(viewName); } - auto &rasterViews = hasSubpass ? (*subpass).rasterViews : raster.rasterViews; + auto &views = hasSubpass ? (*subpass).rasterViews : raster.rasterViews; auto view = RasterView{ viewName.c_str(), isOutput ? AccessType::WRITE : AccessType::READ, @@ -161,7 +161,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn gfx::ShaderStageFlagBit::NONE, }; view.slotID = slot; - rasterViews.emplace(viewName.c_str(), view); + views.emplace(viewName.c_str(), view); if (subpassViews) { subpassViews->emplace(viewName.c_str(), view); @@ -170,6 +170,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn if (iter == raster.attachmentIndexMap.end()) { raster.attachmentIndexMap.emplace(viewName, newID); } + rasterViews.emplace(viewName, view); } ++slot; } @@ -566,117 +567,117 @@ static void runTestGraph(const RenderGraph &renderGraph, const ResourceGraph &re using cc::gfx::TextureFlagBit; \ ResourceInfo resources = { \ {"0", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"1", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"2", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"3", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"4", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"5", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"6", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"7", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"8", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"9", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"10", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"11", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"12", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"13", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"14", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"15", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"16", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"17", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"18", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"19", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::EXTERNAL}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"20", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::EXTERNAL}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"21", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::EXTERNAL}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"22", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::BACKBUFFER}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index adc4639b49..115e2fe5ca 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -283,7 +283,7 @@ void ShadowFlow::initShadowFrameBuffer(const RenderPipeline *pipeline, const sce const gfx::ColorAttachment colorAttachment{ format, - gfx::SampleCount::ONE, + gfx::SampleCount::X1, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, device->getGeneralBarrier({ @@ -294,7 +294,7 @@ void ShadowFlow::initShadowFrameBuffer(const RenderPipeline *pipeline, const sce const gfx::DepthStencilAttachment depthStencilAttachment{ gfx::Format::DEPTH, - gfx::SampleCount::ONE, + gfx::SampleCount::X1, gfx::LoadOp::CLEAR, gfx::StoreOp::DISCARD, gfx::LoadOp::CLEAR, diff --git a/native/tests/unit-test/src/complicated_barrier_case.cpp b/native/tests/unit-test/src/complicated_barrier_case.cpp index ec1f32703e..3fdb5ae8a4 100644 --- a/native/tests/unit-test/src/complicated_barrier_case.cpp +++ b/native/tests/unit-test/src/complicated_barrier_case.cpp @@ -136,7 +136,11 @@ TEST(complicatedBarrierTest, test12) { const auto& node3 = barrierMap.at(3); ExpectEq(node3.blockBarrier.frontBarriers.empty(), true); ExpectEq(node3.blockBarrier.rearBarriers.empty(), true); - ExpectEq(node3.subpassBarriers.empty(), true); + + // subpass barrier size is the same as renderpass subpassinfo, though maybe empty. + ExpectEq(node3.subpassBarriers.size() == 1, true); + ExpectEq(node3.subpassBarriers.front().frontBarriers.empty(), true); + ExpectEq(node3.subpassBarriers.front().rearBarriers.empty(), true); //node4 const auto& node4 = barrierMap.at(4); @@ -181,6 +185,7 @@ TEST(complicatedBarrierTest, test12) { const auto& node5 = barrierMap.at(5); ExpectEq(node5.blockBarrier.frontBarriers.size() == 1, true); ExpectEq(node5.blockBarrier.rearBarriers.size() == 1, true); + // not raster pass ExpectEq(node5.subpassBarriers.empty(), true); auto iter7in5 = findBarrierByResID(node5.blockBarrier.rearBarriers, 7); @@ -198,6 +203,7 @@ TEST(complicatedBarrierTest, test12) { ExpectEq(node6.blockBarrier.frontBarriers.size() == 1, true); // resource later used by raster pass, so that layout can be transferred automatically. ExpectEq(node6.blockBarrier.rearBarriers.empty(), true); + // not a raster pass ExpectEq(node6.subpassBarriers.empty(), true); // node7 @@ -205,7 +211,7 @@ TEST(complicatedBarrierTest, test12) { // undefined layout already in initial layout ExpectEq(node7.blockBarrier.frontBarriers.empty(), true); ExpectEq(node7.blockBarrier.rearBarriers.empty(), true); - ExpectEq(node7.subpassBarriers.empty(), true); + ExpectEq(node7.subpassBarriers.empty(), false); ExpectEq(node7.blockBarrier.rearBarriers.size(), 0); @@ -219,7 +225,7 @@ TEST(complicatedBarrierTest, test12) { const auto& node13 = barrierMap.at(13); ExpectEq(node13.blockBarrier.frontBarriers.size(), 0); ExpectEq(node13.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node13.subpassBarriers.empty(), true); + ExpectEq(node13.subpassBarriers.empty(), false); //node14: almost the same as 13 @@ -234,6 +240,7 @@ TEST(complicatedBarrierTest, test12) { const auto& node16 = barrierMap.at(16); ExpectEq(node16.blockBarrier.frontBarriers.empty(), true); ExpectEq(node16.blockBarrier.rearBarriers.empty(), true); + // not raster pass ExpectEq(node16.subpassBarriers.empty(), true); //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); diff --git a/native/tests/unit-test/src/simple_closed_barrier_test.cpp b/native/tests/unit-test/src/simple_closed_barrier_test.cpp index 6cfbcc275e..644132e90f 100644 --- a/native/tests/unit-test/src/simple_closed_barrier_test.cpp +++ b/native/tests/unit-test/src/simple_closed_barrier_test.cpp @@ -54,7 +54,9 @@ TEST(simpleClosedBarrierTest, test11) { const auto& node1 = barrierMap.at(1); ExpectEq(node1.blockBarrier.frontBarriers.size(), 0); ExpectEq(node1.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node1.subpassBarriers.empty(), true); + ExpectEq(node1.subpassBarriers.size() == 1, true); + ExpectEq(node1.subpassBarriers.front().frontBarriers.empty(), true); + ExpectEq(node1.subpassBarriers.front().rearBarriers.empty(), true); // transitioned by renderpass info //ExpectEq(node1.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); @@ -65,7 +67,9 @@ TEST(simpleClosedBarrierTest, test11) { const auto& node2 = barrierMap.at(2); ExpectEq(node2.blockBarrier.frontBarriers.size(), 0); ExpectEq(node2.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node2.subpassBarriers.empty(), true); + ExpectEq(node2.subpassBarriers.size() == 1, true); + ExpectEq(node2.subpassBarriers.front().frontBarriers.empty(), true); + ExpectEq(node2.subpassBarriers.front().rearBarriers.empty(), true); // ditto //// res3 diff --git a/native/tools/swig-config/gfx.i b/native/tools/swig-config/gfx.i index 452f7b47ae..a0944e0ffd 100644 --- a/native/tools/swig-config/gfx.i +++ b/native/tools/swig-config/gfx.i @@ -65,6 +65,7 @@ namespace cc { namespace gfx { %ignore CommandBuffer::execute; %ignore CommandBuffer::updateBuffer; +%ignore CommandBuffer::resolveTexture; %ignore CommandBuffer::copyBuffersToTexture; %rename(drawWithInfo) CommandBuffer::draw(const DrawInfo&); diff --git a/native/tools/swig-config/render.i b/native/tools/swig-config/render.i index 4db861b41f..dbaf304bec 100644 --- a/native/tools/swig-config/render.i +++ b/native/tools/swig-config/render.i @@ -47,8 +47,6 @@ using namespace cc::render; %ignore cc::render::PipelineRuntime::isOcclusionQueryEnabled; %ignore cc::render::PipelineRuntime::resetRenderQueue; %ignore cc::render::PipelineRuntime::isRenderQueueReset; -%ignore cc::render::SceneVisitor::bindDescriptorSet; -%ignore cc::render::SceneVisitor::updateBuffer; // ----- Rename Section ------ // Brief: Classes, methods or attributes needs to be renamed @@ -118,8 +116,6 @@ using namespace cc::render; %attribute(cc::render::BasicPipeline, cc::render::PipelineType, type, getType); %attribute(cc::render::BasicPipeline, cc::render::PipelineCapabilities, capabilities, getCapabilities); %attribute(cc::render::RenderSubpassBuilder, bool, showStatistics, getShowStatistics, setShowStatistics); -%attribute(cc::render::SceneVisitor, cc::pipeline::PipelineSceneData*, pipelineSceneData, getPipelineSceneData); -%attribute(cc::render::SceneTask, cc::render::TaskType, taskType, getTaskType); // ----- Import Section ------ // Brief: Import header files which are depended by 'Include Section'