diff --git a/.eslintignore b/.eslintignore index fa24a7e144..1abee526a9 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,4 +1,3 @@ *.jsb.ts **/*.ems.ts -cocos/gfx/webgpu/**/* cocos/webgpu/**/* \ No newline at end of file diff --git a/@types/pal/wasm.d.ts b/@types/pal/wasm.d.ts index d6783b940a..efaf599ed5 100644 --- a/@types/pal/wasm.d.ts +++ b/@types/pal/wasm.d.ts @@ -19,6 +19,8 @@ declare module 'pal/wasm' { */ export function fetchBuffer (binaryUrl: string): Promise; + export function fetchUrl(binaryUrl: string): Promise; + /** * Sometimes we need to put wasm modules in subpackage to reduce code size. * In this case we need to ensure that the wasm modules is ready before we import them. diff --git a/@types/webGPU.d.ts b/@types/webGPU.d.ts new file mode 100644 index 0000000000..8b2bebe872 --- /dev/null +++ b/@types/webGPU.d.ts @@ -0,0 +1,3233 @@ +// ********************************************************************************************* +// This file is manually-edited by diffing against an autogenerated file. See README.md. +// ********************************************************************************************* + +// ********************************************************************************************* +// Manually-written +// ********************************************************************************************* + +interface HTMLCanvasElement { + getContext( + contextId: + | 'webgpu' + ): GPUCanvasContext | null; +} + +interface OffscreenCanvas { + getContext( + contextId: + | 'webgpu' + ): GPUCanvasContext | null; +} + +// Defined as an empty interface here to prevent errors when using these types in a worker. +interface HTMLVideoElement {} + +type GPUOrigin2DStrict = + + | Iterable + | GPUOrigin2DDictStrict; + +interface GPUOrigin2DDictStrict + extends GPUOrigin2DDict { + /** @deprecated Does not exist for GPUOrigin2D. */ + z?: undefined; +} + +type GPUExtent3DStrict = + + | Iterable + | GPUExtent3DDictStrict; + +// GPUExtent3DDictStrict is defined to help developers catch a common class of errors. +// This interface defines depth as an undefined, which will cause a type check failure if someone +// attempts to set depth rather than depthOrArrayLayers on a GPUExtent3D (an easy mistake to make.) +interface GPUExtent3DDictStrict + extends GPUExtent3DDict { + /** @deprecated The correct name is `depthOrArrayLayers`. */ + depth?: undefined; +} + +// ********************************************************************************************* +// Semi-auto-generated (by manual diff with autogenerated types) +// ********************************************************************************************* + +type GPUBindingResource = + + | GPUSampler + | GPUTextureView + | GPUBufferBinding + | GPUExternalTexture; +type GPUBufferDynamicOffset = + number; +type GPUBufferUsageFlags = + number; +type GPUColor = + + | Iterable + | GPUColorDict; +type GPUColorWriteFlags = + number; +type GPUDepthBias = + number; +type GPUExtent3D = + + | Iterable + | GPUExtent3DDict; +type GPUFlagsConstant = + number; +type GPUImageCopyExternalImageSource = + + | ImageBitmap + | ImageData + | HTMLImageElement + | HTMLVideoElement + | VideoFrame + | HTMLCanvasElement + | OffscreenCanvas; +type GPUIndex32 = + number; +type GPUIntegerCoordinate = + number; +type GPUIntegerCoordinateOut = + number; +type GPUMapModeFlags = + number; +type GPUOrigin2D = + + | Iterable + | GPUOrigin2DDict; +type GPUOrigin3D = + + | Iterable + | GPUOrigin3DDict; +type GPUPipelineConstantValue = + number; +type GPUSampleMask = + number; +type GPUShaderStageFlags = + number; +type GPUSignedOffset32 = + number; +type GPUSize32 = + number; +type GPUSize32Out = + number; +type GPUSize64 = + number; +type GPUSize64Out = + number; +type GPUStencilValue = + number; +type GPUTextureUsageFlags = + number; +type GPUAddressMode = + + | 'clamp-to-edge' + | 'repeat' + | 'mirror-repeat'; +type GPUAutoLayoutMode = + 'auto'; +type GPUBlendFactor = + + | 'zero' + | 'one' + | 'src' + | 'one-minus-src' + | 'src-alpha' + | 'one-minus-src-alpha' + | 'dst' + | 'one-minus-dst' + | 'dst-alpha' + | 'one-minus-dst-alpha' + | 'src-alpha-saturated' + | 'constant' + | 'one-minus-constant'; +type GPUBlendOperation = + + | 'add' + | 'subtract' + | 'reverse-subtract' + | 'min' + | 'max'; +type GPUBufferBindingType = + + | 'uniform' + | 'storage' + | 'read-only-storage'; +type GPUBufferMapState = + + | 'unmapped' + | 'pending' + | 'mapped'; +type GPUCanvasAlphaMode = + + | 'opaque' + | 'premultiplied'; +type GPUCompareFunction = + + | 'never' + | 'less' + | 'equal' + | 'less-equal' + | 'greater' + | 'not-equal' + | 'greater-equal' + | 'always'; +type GPUCompilationMessageType = + + | 'error' + | 'warning' + | 'info'; +type GPUCullMode = + + | 'none' + | 'front' + | 'back'; +type GPUDeviceLostReason = + + | 'unknown' + | 'destroyed'; +type GPUErrorFilter = + + | 'validation' + | 'out-of-memory' + | 'internal'; +type GPUFeatureName = + + | 'depth-clip-control' + | 'depth32float-stencil8' + | 'texture-compression-bc' + | 'texture-compression-etc2' + | 'texture-compression-astc' + | 'timestamp-query' + | 'indirect-first-instance' + | 'shader-f16' + | 'rg11b10ufloat-renderable' + | 'bgra8unorm-storage' + | 'float32-filterable'; +type GPUFilterMode = + + | 'nearest' + | 'linear'; +type GPUFrontFace = + + | 'ccw' + | 'cw'; +type GPUIndexFormat = + + | 'uint16' + | 'uint32'; +type GPULoadOp = + + | 'load' + | 'clear'; +type GPUMipmapFilterMode = + + | 'nearest' + | 'linear'; +type GPUPipelineErrorReason = + + | 'validation' + | 'internal'; +type GPUPowerPreference = + + | 'low-power' + | 'high-performance'; +type GPUPrimitiveTopology = + + | 'point-list' + | 'line-list' + | 'line-strip' + | 'triangle-list' + | 'triangle-strip'; +type GPUQueryType = + + | 'occlusion' + | 'timestamp'; +type GPUSamplerBindingType = + + | 'filtering' + | 'non-filtering' + | 'comparison'; +type GPUStencilOperation = + + | 'keep' + | 'zero' + | 'replace' + | 'invert' + | 'increment-clamp' + | 'decrement-clamp' + | 'increment-wrap' + | 'decrement-wrap'; +type GPUStorageTextureAccess = + + | 'write-only' + | 'read-only' + | 'read-write'; +type GPUStoreOp = + + | 'store' + | 'discard'; +type GPUTextureAspect = + + | 'all' + | 'stencil-only' + | 'depth-only'; +type GPUTextureDimension = + + | '1d' + | '2d' + | '3d'; +type GPUTextureFormat = + + | 'r8unorm' + | 'r8snorm' + | 'r8uint' + | 'r8sint' + | 'r16uint' + | 'r16sint' + | 'r16float' + | 'rg8unorm' + | 'rg8snorm' + | 'rg8uint' + | 'rg8sint' + | 'r32uint' + | 'r32sint' + | 'r32float' + | 'rg16uint' + | 'rg16sint' + | 'rg16float' + | 'rgba8unorm' + | 'rgba8unorm-srgb' + | 'rgba8snorm' + | 'rgba8uint' + | 'rgba8sint' + | 'bgra8unorm' + | 'bgra8unorm-srgb' + | 'rgb9e5ufloat' + | 'rgb10a2uint' + | 'rgb10a2unorm' + | 'rg11b10ufloat' + | 'rg32uint' + | 'rg32sint' + | 'rg32float' + | 'rgba16uint' + | 'rgba16sint' + | 'rgba16float' + | 'rgba32uint' + | 'rgba32sint' + | 'rgba32float' + | 'stencil8' + | 'depth16unorm' + | 'depth24plus' + | 'depth24plus-stencil8' + | 'depth32float' + | 'depth32float-stencil8' + | 'bc1-rgba-unorm' + | 'bc1-rgba-unorm-srgb' + | 'bc2-rgba-unorm' + | 'bc2-rgba-unorm-srgb' + | 'bc3-rgba-unorm' + | 'bc3-rgba-unorm-srgb' + | 'bc4-r-unorm' + | 'bc4-r-snorm' + | 'bc5-rg-unorm' + | 'bc5-rg-snorm' + | 'bc6h-rgb-ufloat' + | 'bc6h-rgb-float' + | 'bc7-rgba-unorm' + | 'bc7-rgba-unorm-srgb' + | 'etc2-rgb8unorm' + | 'etc2-rgb8unorm-srgb' + | 'etc2-rgb8a1unorm' + | 'etc2-rgb8a1unorm-srgb' + | 'etc2-rgba8unorm' + | 'etc2-rgba8unorm-srgb' + | 'eac-r11unorm' + | 'eac-r11snorm' + | 'eac-rg11unorm' + | 'eac-rg11snorm' + | 'astc-4x4-unorm' + | 'astc-4x4-unorm-srgb' + | 'astc-5x4-unorm' + | 'astc-5x4-unorm-srgb' + | 'astc-5x5-unorm' + | 'astc-5x5-unorm-srgb' + | 'astc-6x5-unorm' + | 'astc-6x5-unorm-srgb' + | 'astc-6x6-unorm' + | 'astc-6x6-unorm-srgb' + | 'astc-8x5-unorm' + | 'astc-8x5-unorm-srgb' + | 'astc-8x6-unorm' + | 'astc-8x6-unorm-srgb' + | 'astc-8x8-unorm' + | 'astc-8x8-unorm-srgb' + | 'astc-10x5-unorm' + | 'astc-10x5-unorm-srgb' + | 'astc-10x6-unorm' + | 'astc-10x6-unorm-srgb' + | 'astc-10x8-unorm' + | 'astc-10x8-unorm-srgb' + | 'astc-10x10-unorm' + | 'astc-10x10-unorm-srgb' + | 'astc-12x10-unorm' + | 'astc-12x10-unorm-srgb' + | 'astc-12x12-unorm' + | 'astc-12x12-unorm-srgb'; +type GPUTextureSampleType = + + | 'float' + | 'unfilterable-float' + | 'depth' + | 'sint' + | 'uint'; +type GPUTextureViewDimension = + + | '1d' + | '2d' + | '2d-array' + | 'cube' + | 'cube-array' + | '3d'; +type GPUVertexFormat = + + | 'uint8x2' + | 'uint8x4' + | 'sint8x2' + | 'sint8x4' + | 'unorm8x2' + | 'unorm8x4' + | 'snorm8x2' + | 'snorm8x4' + | 'uint16x2' + | 'uint16x4' + | 'sint16x2' + | 'sint16x4' + | 'unorm16x2' + | 'unorm16x4' + | 'snorm16x2' + | 'snorm16x4' + | 'float16x2' + | 'float16x4' + | 'float32' + | 'float32x2' + | 'float32x3' + | 'float32x4' + | 'uint32' + | 'uint32x2' + | 'uint32x3' + | 'uint32x4' + | 'sint32' + | 'sint32x2' + | 'sint32x3' + | 'sint32x4' + | 'unorm10-10-10-2'; +type GPUVertexStepMode = + + | 'vertex' + | 'instance'; + +interface GPUBindGroupDescriptor + extends GPUObjectDescriptorBase { + /** + * The {@link GPUBindGroupLayout} the entries of this bind group will conform to. + */ + layout: GPUBindGroupLayout; + /** + * A list of entries describing the resources to expose to the shader for each binding + * described by the {@link GPUBindGroupDescriptor#layout}. + */ + entries: Iterable; +} + +interface GPUBindGroupEntry { + /** + * A unique identifier for a resource binding within the {@link GPUBindGroup}, corresponding to a + * {@link GPUBindGroupLayoutEntry#binding|GPUBindGroupLayoutEntry.binding} and a @binding + * attribute in the {@link GPUShaderModule}. + */ + binding: GPUIndex32; + /** + * The resource to bind, which may be a {@link GPUSampler}, {@link GPUTextureView}, + * {@link GPUExternalTexture}, or {@link GPUBufferBinding}. + */ + resource: GPUBindingResource; +} + +interface GPUBindGroupLayoutDescriptor + extends GPUObjectDescriptorBase { + entries: Iterable; +} + +interface GPUBindGroupLayoutEntry { + /** + * A unique identifier for a resource binding within the {@link GPUBindGroupLayout}, corresponding + * to a {@link GPUBindGroupEntry#binding|GPUBindGroupEntry.binding} and a @binding + * attribute in the {@link GPUShaderModule}. + */ + binding: GPUIndex32; + /** + * A bitset of the members of {@link GPUShaderStage}. + * Each set bit indicates that a {@link GPUBindGroupLayoutEntry}'s resource + * will be accessible from the associated shader stage. + */ + visibility: GPUShaderStageFlags; + /** + * When map/exist|provided, indicates the binding resource type for this {@link GPUBindGroupLayoutEntry} + * is {@link GPUBufferBinding}. + */ + buffer?: GPUBufferBindingLayout; + /** + * When map/exist|provided, indicates the binding resource type for this {@link GPUBindGroupLayoutEntry} + * is {@link GPUSampler}. + */ + sampler?: GPUSamplerBindingLayout; + /** + * When map/exist|provided, indicates the binding resource type for this {@link GPUBindGroupLayoutEntry} + * is {@link GPUTextureView}. + */ + texture?: GPUTextureBindingLayout; + /** + * When map/exist|provided, indicates the binding resource type for this {@link GPUBindGroupLayoutEntry} + * is {@link GPUTextureView}. + */ + storageTexture?: GPUStorageTextureBindingLayout; + /** + * When map/exist|provided, indicates the binding resource type for this {@link GPUBindGroupLayoutEntry} + * is {@link GPUExternalTexture}. + */ + externalTexture?: GPUExternalTextureBindingLayout; +} + +interface GPUBlendComponent { + /** + * Defines the {@link GPUBlendOperation} used to calculate the values written to the target + * attachment components. + */ + operation?: GPUBlendOperation; + /** + * Defines the {@link GPUBlendFactor} operation to be performed on values from the fragment shader. + */ + srcFactor?: GPUBlendFactor; + /** + * Defines the {@link GPUBlendFactor} operation to be performed on values from the target attachment. + */ + dstFactor?: GPUBlendFactor; +} + +interface GPUBlendState { + /** + * Defines the blending behavior of the corresponding render target for color channels. + */ + color: GPUBlendComponent; + /** + * Defines the blending behavior of the corresponding render target for the alpha channel. + */ + alpha: GPUBlendComponent; +} + +interface GPUBufferBinding { + /** + * The {@link GPUBuffer} to bind. + */ + buffer: GPUBuffer; + /** + * The offset, in bytes, from the beginning of {@link GPUBufferBinding#buffer} to the + * beginning of the range exposed to the shader by the buffer binding. + */ + offset?: GPUSize64; + /** + * The size, in bytes, of the buffer binding. + * If not map/exist|provided, specifies the range starting at + * {@link GPUBufferBinding#offset} and ending at the end of {@link GPUBufferBinding#buffer}. + */ + size?: GPUSize64; +} + +interface GPUBufferBindingLayout { + /** + * Indicates the type required for buffers bound to this bindings. + */ + type?: GPUBufferBindingType; + /** + * Indicates whether this binding requires a dynamic offset. + */ + hasDynamicOffset?: boolean; + /** + * Indicates the minimum {@link GPUBufferBinding#size} of a buffer binding used with this bind point. + * Bindings are always validated against this size in {@link GPUDevice#createBindGroup}. + * If this *is not* `0`, pipeline creation additionally [$validating shader binding|validates$] + * that this value ≥ the minimum buffer binding size of the variable. + * If this *is* `0`, it is ignored by pipeline creation, and instead draw/dispatch commands + * [$Validate encoder bind groups|validate$] that each binding in the {@link GPUBindGroup} + * satisfies the minimum buffer binding size of the variable. + * Note: + * Similar execution-time validation is theoretically possible for other + * binding-related fields specified for early validation, like + * {@link GPUTextureBindingLayout#sampleType} and {@link GPUStorageTextureBindingLayout#format}, + * which currently can only be validated in pipeline creation. + * However, such execution-time validation could be costly or unnecessarily complex, so it is + * available only for {@link GPUBufferBindingLayout#minBindingSize} which is expected to have the + * most ergonomic impact. + */ + minBindingSize?: GPUSize64; +} +type PredefinedGPUColorSpace = 'display-p3' | 'srgb'; +interface GPUBufferDescriptor + extends GPUObjectDescriptorBase { + /** + * The size of the buffer in bytes. + */ + size: GPUSize64; + /** + * The allowed usages for the buffer. + */ + usage: GPUBufferUsageFlags; + /** + * If `true` creates the buffer in an already mapped state, allowing + * {@link GPUBuffer#getMappedRange} to be called immediately. It is valid to set + * {@link GPUBufferDescriptor#mappedAtCreation} to `true` even if {@link GPUBufferDescriptor#usage} + * does not contain {@link GPUBufferUsage#MAP_READ} or {@link GPUBufferUsage#MAP_WRITE}. This can be + * used to set the buffer's initial data. + * Guarantees that even if the buffer creation eventually fails, it will still appear as if the + * mapped range can be written/read to until it is unmapped. + */ + mappedAtCreation?: boolean; +} + +interface GPUCanvasConfiguration { + /** + * The {@link GPUDevice} that textures returned by {@link GPUCanvasContext#getCurrentTexture} will be + * compatible with. + */ + device: GPUDevice; + /** + * The format that textures returned by {@link GPUCanvasContext#getCurrentTexture} will have. + * Must be one of the Supported context formats. + */ + format: GPUTextureFormat; + /** + * The usage that textures returned by {@link GPUCanvasContext#getCurrentTexture} will have. + * {@link GPUTextureUsage#RENDER_ATTACHMENT} is the default, but is not automatically included + * if the usage is explicitly set. Be sure to include {@link GPUTextureUsage#RENDER_ATTACHMENT} + * when setting a custom usage if you wish to use textures returned by + * {@link GPUCanvasContext#getCurrentTexture} as color targets for a render pass. + */ + usage?: GPUTextureUsageFlags; + /** + * The formats that views created from textures returned by + * {@link GPUCanvasContext#getCurrentTexture} may use. + */ + viewFormats?: Iterable; + /** + * The color space that values written into textures returned by + * {@link GPUCanvasContext#getCurrentTexture} should be displayed with. + */ + colorSpace?: PredefinedGPUColorSpace; + /** + * Determines the effect that alpha values will have on the content of textures returned by + * {@link GPUCanvasContext#getCurrentTexture} when read, displayed, or used as an image source. + */ + alphaMode?: GPUCanvasAlphaMode; +} + +interface GPUColorDict { + /** + * The red channel value. + */ + r: number; + /** + * The green channel value. + */ + g: number; + /** + * The blue channel value. + */ + b: number; + /** + * The alpha channel value. + */ + a: number; +} + +interface GPUColorTargetState { + /** + * The {@link GPUTextureFormat} of this color target. The pipeline will only be compatible with + * {@link GPURenderPassEncoder}s which use a {@link GPUTextureView} of this format in the + * corresponding color attachment. + */ + format: GPUTextureFormat; + /** + * The blending behavior for this color target. If left undefined, disables blending for this + * color target. + */ + blend?: GPUBlendState; + /** + * Bitmask controlling which channels are are written to when drawing to this color target. + */ + writeMask?: GPUColorWriteFlags; +} + +type GPUCommandBufferDescriptor = + GPUObjectDescriptorBase; +type GPUCommandEncoderDescriptor = + GPUObjectDescriptorBase; + +interface GPUComputePassDescriptor + extends GPUObjectDescriptorBase { + /** + * Defines which timestamp values will be written for this pass, and where to write them to. + */ + timestampWrites?: GPUComputePassTimestampWrites; +} + +interface GPUComputePassTimestampWrites { + /** + * The {@link GPUQuerySet}, of type {@link GPUQueryType#"timestamp"}, that the query results will be + * written to. + */ + querySet: GPUQuerySet; + /** + * If defined, indicates the query index in {@link GPURenderPassTimestampWrites#querySet} into + * which the timestamp at the beginning of the compute pass will be written. + */ + beginningOfPassWriteIndex?: GPUSize32; + /** + * If defined, indicates the query index in {@link GPURenderPassTimestampWrites#querySet} into + * which the timestamp at the end of the compute pass will be written. + */ + endOfPassWriteIndex?: GPUSize32; +} + +interface GPUComputePipelineDescriptor + extends GPUPipelineDescriptorBase { + /** + * Describes the compute shader entry point of the pipeline. + */ + compute: GPUProgrammableStage; +} + +interface GPUDepthStencilState { + /** + * The {@link GPUTextureViewDescriptor#format} of {@link GPURenderPassDescriptor#depthStencilAttachment} + * this {@link GPURenderPipeline} will be compatible with. + */ + format: GPUTextureFormat; + /** + * Indicates if this {@link GPURenderPipeline} can modify + * {@link GPURenderPassDescriptor#depthStencilAttachment} depth values. + */ + depthWriteEnabled?: boolean; + /** + * The comparison operation used to test fragment depths against + * {@link GPURenderPassDescriptor#depthStencilAttachment} depth values. + */ + depthCompare?: GPUCompareFunction; + /** + * Defines how stencil comparisons and operations are performed for front-facing primitives. + */ + stencilFront?: GPUStencilFaceState; + /** + * Defines how stencil comparisons and operations are performed for back-facing primitives. + */ + stencilBack?: GPUStencilFaceState; + /** + * Bitmask controlling which {@link GPURenderPassDescriptor#depthStencilAttachment} stencil value + * bits are read when performing stencil comparison tests. + */ + stencilReadMask?: GPUStencilValue; + /** + * Bitmask controlling which {@link GPURenderPassDescriptor#depthStencilAttachment} stencil value + * bits are written to when performing stencil operations. + */ + stencilWriteMask?: GPUStencilValue; + /** + * Constant depth bias added to each fragment. See [$biased fragment depth$] for details. + */ + depthBias?: GPUDepthBias; + /** + * Depth bias that scales with the fragment’s slope. See [$biased fragment depth$] for details. + */ + depthBiasSlopeScale?: number; + /** + * The maximum depth bias of a fragment. See [$biased fragment depth$] for details. + */ + depthBiasClamp?: number; +} + +interface GPUDeviceDescriptor + extends GPUObjectDescriptorBase { + /** + * Specifies the features that are required by the device request. + * The request will fail if the adapter cannot provide these features. + * Exactly the specified set of features, and no more or less, will be allowed in validation + * of API calls on the resulting device. + */ + requiredFeatures?: Iterable; + /** + * Specifies the limits that are required by the device request. + * The request will fail if the adapter cannot provide these limits. + * Each key must be the name of a member of supported limits. + * Exactly the specified limits, and no limit/better or worse, + * will be allowed in validation of API calls on the resulting device. + * + */ + requiredLimits?: Record< + string, + GPUSize64 + >; + /** + * The descriptor for the default {@link GPUQueue}. + */ + defaultQueue?: GPUQueueDescriptor; +} + +interface GPUExtent3DDict { + /** + * The width of the extent. + */ + width: GPUIntegerCoordinate; + /** + * The height of the extent. + */ + height?: GPUIntegerCoordinate; + /** + * The depth of the extent or the number of array layers it contains. + * If used with a {@link GPUTexture} with a {@link GPUTextureDimension} of {@link GPUTextureDimension#"3d"} + * defines the depth of the texture. If used with a {@link GPUTexture} with a {@link GPUTextureDimension} + * of {@link GPUTextureDimension#"2d"} defines the number of array layers in the texture. + */ + depthOrArrayLayers?: GPUIntegerCoordinate; +} + +interface GPUExternalTextureBindingLayout {} + +interface GPUExternalTextureDescriptor + extends GPUObjectDescriptorBase { + source: + | HTMLVideoElement + | VideoFrame; + colorSpace?: PredefinedGPUColorSpace; +} + +interface GPUFragmentState + extends GPUProgrammableStage { + /** + * A list of {@link GPUColorTargetState} defining the formats and behaviors of the color targets + * this pipeline writes to. + */ + targets: Iterable; +} + +interface GPUImageCopyBuffer + extends GPUImageDataLayout { + /** + * A buffer which either contains image data to be copied or will store the image data being + * copied, depending on the method it is being passed to. + */ + buffer: GPUBuffer; +} + +interface GPUImageCopyExternalImage { + /** + * The source of the image copy. The copy source data is captured at the moment that + * {@link GPUQueue#copyExternalImageToTexture} is issued. Source size is defined by source + * type, given by this table: + * + * + * + * + * + * + * + * + * + * + * + * + *
Source type + * Width + * Height + *
{@link ImageBitmap} + * {@link ImageBitmap#width|ImageBitmap.width} + * {@link ImageBitmap#height|ImageBitmap.height} + *
{@link HTMLVideoElement} + * video/intrinsic width|intrinsic width of the frame + * video/intrinsic height|intrinsic height of the frame + *
{@link VideoFrame} + * {@link VideoFrame#codedWidth|VideoFrame.codedWidth} + * {@link VideoFrame#codedHeight|VideoFrame.codedHeight} + *
{@link HTMLCanvasElement} + * {@link HTMLCanvasElement#width|HTMLCanvasElement.width} + * {@link HTMLCanvasElement#height|HTMLCanvasElement.height} + *
{@link OffscreenCanvas} + * {@link OffscreenCanvas#width|OffscreenCanvas.width} + * {@link OffscreenCanvas#height|OffscreenCanvas.height} + *
+ */ + source: GPUImageCopyExternalImageSource; + /** + * Defines the origin of the copy - the minimum (top-left) corner of the source sub-region to copy from. + * Together with `copySize`, defines the full copy sub-region. + */ + origin?: GPUOrigin2DStrict; + /** + * Describes whether the source image is vertically flipped, or not. + * If this option is set to `true`, the copy is flipped vertically: the bottom row of the source + * region is copied into the first row of the destination region, and so on. + * The {@link GPUImageCopyExternalImage#origin} option is still relative to the top-left corner + * of the source image, increasing downward. + */ + flipY?: boolean; +} + +interface GPUImageCopyTexture { + /** + * Texture to copy to/from. + */ + texture: GPUTexture; + /** + * Mip-map level of the {@link GPUImageCopyTexture#texture} to copy to/from. + */ + mipLevel?: GPUIntegerCoordinate; + /** + * Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from. + * Together with `copySize`, defines the full copy sub-region. + */ + origin?: GPUOrigin3D; + /** + * Defines which aspects of the {@link GPUImageCopyTexture#texture} to copy to/from. + */ + aspect?: GPUTextureAspect; +} + +interface GPUImageCopyTextureTagged + extends GPUImageCopyTexture { + /** + * Describes the color space and encoding used to encode data into the destination texture. + * This [[#color-space-conversions|may result]] in values outside of the range [0, 1] + * being written to the target texture, if its format can represent them. + * Otherwise, the results are clamped to the target texture format's range. + * Note: + * If {@link GPUImageCopyTextureTagged#colorSpace} matches the source image, + * conversion may not be necessary. See [[#color-space-conversion-elision]]. + */ + colorSpace?: PredefinedGPUColorSpace; + /** + * Describes whether the data written into the texture should have its RGB channels + * premultiplied by the alpha channel, or not. + * If this option is set to `true` and the {@link GPUImageCopyExternalImage#source} is also + * premultiplied, the source RGB values must be preserved even if they exceed their + * corresponding alpha values. + * Note: + * If {@link GPUImageCopyTextureTagged#premultipliedAlpha} matches the source image, + * conversion may not be necessary. See [[#color-space-conversion-elision]]. + */ + premultipliedAlpha?: boolean; +} + +interface GPUImageDataLayout { + /** + * The offset, in bytes, from the beginning of the image data source (such as a + * {@link GPUImageCopyBuffer#buffer|GPUImageCopyBuffer.buffer}) to the start of the image data + * within that source. + */ + offset?: GPUSize64; + /** + * The stride, in bytes, between the beginning of each block row and the subsequent block row. + * Required if there are multiple block rows (i.e. the copy height or depth is more than one block). + */ + bytesPerRow?: GPUSize32; + /** + * Number of block rows per single image of the texture. + * {@link GPUImageDataLayout#rowsPerImage} × + * {@link GPUImageDataLayout#bytesPerRow} is the stride, in bytes, between the beginning of each image of data and the subsequent image. + * Required if there are multiple images (i.e. the copy depth is more than one). + */ + rowsPerImage?: GPUSize32; +} + +interface GPUMultisampleState { + /** + * Number of samples per pixel. This {@link GPURenderPipeline} will be compatible only + * with attachment textures ({@link GPURenderPassDescriptor#colorAttachments} + * and {@link GPURenderPassDescriptor#depthStencilAttachment}) + * with matching {@link GPUTextureDescriptor#sampleCount}s. + */ + count?: GPUSize32; + /** + * Mask determining which samples are written to. + */ + mask?: GPUSampleMask; + /** + * When `true` indicates that a fragment's alpha channel should be used to generate a sample + * coverage mask. + */ + alphaToCoverageEnabled?: boolean; +} + +interface GPUObjectDescriptorBase { + /** + * The initial value of {@link GPUObjectBase#label|GPUObjectBase.label}. + */ + label?: string; +} + +interface GPUOrigin2DDict { + x?: GPUIntegerCoordinate; + y?: GPUIntegerCoordinate; +} + +interface GPUOrigin3DDict { + x?: GPUIntegerCoordinate; + y?: GPUIntegerCoordinate; + z?: GPUIntegerCoordinate; +} + +interface GPUPipelineDescriptorBase + extends GPUObjectDescriptorBase { + /** + * The {@link GPUPipelineLayout} for this pipeline, or {@link GPUAutoLayoutMode#"auto"} to generate + * the pipeline layout automatically. + * Note: If {@link GPUAutoLayoutMode#"auto"} is used the pipeline cannot share {@link GPUBindGroup}s + * with any other pipelines. + */ + layout: + | GPUPipelineLayout + | GPUAutoLayoutMode; +} + +interface GPUPipelineErrorInit { + reason: GPUPipelineErrorReason; +} + +interface GPUPipelineLayoutDescriptor + extends GPUObjectDescriptorBase { + /** + * A list of {@link GPUBindGroupLayout}s the pipeline will use. Each element corresponds to a + * @group attribute in the {@link GPUShaderModule}, with the `N`th element corresponding with + * `@group(N)`. + */ + bindGroupLayouts: Iterable; +} + +interface GPUPrimitiveState { + /** + * The type of primitive to be constructed from the vertex inputs. + */ + topology?: GPUPrimitiveTopology; + /** + * For pipelines with strip topologies + * ({@link GPUPrimitiveTopology#"line-strip"} or {@link GPUPrimitiveTopology#"triangle-strip"}), + * this determines the index buffer format and primitive restart value + * ({@link GPUIndexFormat#"uint16"}/`0xFFFF` or {@link GPUIndexFormat#"uint32"}/`0xFFFFFFFF`). + * It is not allowed on pipelines with non-strip topologies. + * Note: Some implementations require knowledge of the primitive restart value to compile + * pipeline state objects. + * To use a strip-topology pipeline with an indexed draw call + * ({@link GPURenderCommandsMixin#drawIndexed()} or {@link GPURenderCommandsMixin#drawIndexedIndirect}), + * this must be set, and it must match the index buffer format used with the draw call + * (set in {@link GPURenderCommandsMixin#setIndexBuffer}). + * See [[#primitive-assembly]] for additional details. + */ + stripIndexFormat?: GPUIndexFormat; + /** + * Defines which polygons are considered front-facing. + */ + frontFace?: GPUFrontFace; + /** + * Defines which polygon orientation will be culled, if any. + */ + cullMode?: GPUCullMode; + /** + * If true, indicates that depth clipping is disabled. + * Requires the {@link GPUFeatureName#"depth-clip-control"} feature to be enabled. + */ + unclippedDepth?: boolean; +} + +interface GPUProgrammableStage { + /** + * The {@link GPUShaderModule} containing the code that this programmable stage will execute. + */ + module: GPUShaderModule; + /** + * The name of the function in {@link GPUProgrammableStage#module} that this stage will use to + * perform its work. + */ + entryPoint?: string; + /** + * Specifies the values of pipeline-overridable constants in the shader module + * {@link GPUProgrammableStage#module}. + * Each such pipeline-overridable constant is uniquely identified by a single + * pipeline-overridable constant identifier string (representing the numeric ID of the + * constant, if one is specified, and otherwise the constant's identifier name). + * WGSL names (identifiers) in source maps follow the rules defined in WGSL identifier comparison. + * The key of each key-value pair must equal the identifier string of one such constant. + * When the pipeline is executed, that constant will have the specified value. + * Values are specified as GPUPipelineConstantValue, which is a {@link double}. + * They are converted [$to WGSL type$] of the pipeline-overridable constant (`bool`/`i32`/`u32`/`f32`/`f16`). + * If conversion fails, a validation error is generated. + */ + constants?: Record< + string, + GPUPipelineConstantValue + >; +} + +interface GPUQuerySetDescriptor + extends GPUObjectDescriptorBase { + /** + * The type of queries managed by {@link GPUQuerySet}. + */ + type: GPUQueryType; + /** + * The number of queries managed by {@link GPUQuerySet}. + */ + count: GPUSize32; +} + +type GPUQueueDescriptor = + GPUObjectDescriptorBase; +type GPURenderBundleDescriptor = + GPUObjectDescriptorBase; + +interface GPURenderBundleEncoderDescriptor + extends GPURenderPassLayout { + /** + * If `true`, indicates that the render bundle does not modify the depth component of the + * {@link GPURenderPassDepthStencilAttachment} of any render pass the render bundle is executed + * in. + */ + depthReadOnly?: boolean; + /** + * If `true`, indicates that the render bundle does not modify the stencil component of the + * {@link GPURenderPassDepthStencilAttachment} of any render pass the render bundle is executed + * in. + */ + stencilReadOnly?: boolean; +} + +interface GPURenderPassColorAttachment { + /** + * A {@link GPUTextureView} describing the texture subresource that will be output to for this + * color attachment. + */ + view: GPUTextureView; + /** + * Indicates the depth slice index of {@link GPUTextureViewDimension#"3d"} {@link GPURenderPassColorAttachment#view} + * that will be output to for this color attachment. + */ + depthSlice?: GPUIntegerCoordinate; + /** + * A {@link GPUTextureView} describing the texture subresource that will receive the resolved + * output for this color attachment if {@link GPURenderPassColorAttachment#view} is + * multisampled. + */ + resolveTarget?: GPUTextureView; + /** + * Indicates the value to clear {@link GPURenderPassColorAttachment#view} to prior to executing the + * render pass. If not map/exist|provided, defaults to `{r: 0, g: 0, b: 0, a: 0}`. Ignored + * if {@link GPURenderPassColorAttachment#loadOp} is not {@link GPULoadOp#"clear"}. + * The components of {@link GPURenderPassColorAttachment#clearValue} are all double values. + * They are converted [$to a texel value of texture format$] matching the render attachment. + * If conversion fails, a validation error is generated. + */ + clearValue?: GPUColor; + /** + * Indicates the load operation to perform on {@link GPURenderPassColorAttachment#view} prior to + * executing the render pass. + * Note: It is recommended to prefer clearing; see {@link GPULoadOp#"clear"} for details. + */ + loadOp: GPULoadOp; + /** + * The store operation to perform on {@link GPURenderPassColorAttachment#view} + * after executing the render pass. + */ + storeOp: GPUStoreOp; +} + +interface GPURenderPassDepthStencilAttachment { + /** + * A {@link GPUTextureView} describing the texture subresource that will be output to + * and read from for this depth/stencil attachment. + */ + view: GPUTextureView; + /** + * Indicates the value to clear {@link GPURenderPassDepthStencilAttachment#view}'s depth component + * to prior to executing the render pass. Ignored if {@link GPURenderPassDepthStencilAttachment#depthLoadOp} + * is not {@link GPULoadOp#"clear"}. Must be between 0.0 and 1.0, inclusive. + * + */ + depthClearValue?: number; + /** + * Indicates the load operation to perform on {@link GPURenderPassDepthStencilAttachment#view}'s + * depth component prior to executing the render pass. + * Note: It is recommended to prefer clearing; see {@link GPULoadOp#"clear"} for details. + */ + depthLoadOp?: GPULoadOp; + /** + * The store operation to perform on {@link GPURenderPassDepthStencilAttachment#view}'s + * depth component after executing the render pass. + */ + depthStoreOp?: GPUStoreOp; + /** + * Indicates that the depth component of {@link GPURenderPassDepthStencilAttachment#view} + * is read only. + */ + depthReadOnly?: boolean; + /** + * Indicates the value to clear {@link GPURenderPassDepthStencilAttachment#view}'s stencil component + * to prior to executing the render pass. Ignored if {@link GPURenderPassDepthStencilAttachment#stencilLoadOp} + * is not {@link GPULoadOp#"clear"}. + * The value will be converted to the type of the stencil aspect of `view` by taking the same + * number of LSBs as the number of bits in the stencil aspect of one texel block of `view`. + */ + stencilClearValue?: GPUStencilValue; + /** + * Indicates the load operation to perform on {@link GPURenderPassDepthStencilAttachment#view}'s + * stencil component prior to executing the render pass. + * Note: It is recommended to prefer clearing; see {@link GPULoadOp#"clear"} for details. + */ + stencilLoadOp?: GPULoadOp; + /** + * The store operation to perform on {@link GPURenderPassDepthStencilAttachment#view}'s + * stencil component after executing the render pass. + */ + stencilStoreOp?: GPUStoreOp; + /** + * Indicates that the stencil component of {@link GPURenderPassDepthStencilAttachment#view} + * is read only. + */ + stencilReadOnly?: boolean; +} + +interface GPURenderPassDescriptor + extends GPUObjectDescriptorBase { + /** + * The set of {@link GPURenderPassColorAttachment} values in this sequence defines which + * color attachments will be output to when executing this render pass. + * Due to compatible usage list|usage compatibility, no color attachment + * may alias another attachment or any resource used inside the render pass. + */ + colorAttachments: Iterable; + /** + * The {@link GPURenderPassDepthStencilAttachment} value that defines the depth/stencil + * attachment that will be output to and tested against when executing this render pass. + * Due to compatible usage list|usage compatibility, no writable depth/stencil attachment + * may alias another attachment or any resource used inside the render pass. + */ + depthStencilAttachment?: GPURenderPassDepthStencilAttachment; + /** + * The {@link GPUQuerySet} value defines where the occlusion query results will be stored for this pass. + */ + occlusionQuerySet?: GPUQuerySet; + /** + * Defines which timestamp values will be written for this pass, and where to write them to. + */ + timestampWrites?: GPURenderPassTimestampWrites; + /** + * The maximum number of draw calls that will be done in the render pass. Used by some + * implementations to size work injected before the render pass. Keeping the default value + * is a good default, unless it is known that more draw calls will be done. + */ + maxDrawCount?: GPUSize64; +} + +interface GPURenderPassLayout + extends GPUObjectDescriptorBase { + /** + * A list of the {@link GPUTextureFormat}s of the color attachments for this pass or bundle. + */ + colorFormats: Iterable; + /** + * The {@link GPUTextureFormat} of the depth/stencil attachment for this pass or bundle. + */ + depthStencilFormat?: GPUTextureFormat; + /** + * Number of samples per pixel in the attachments for this pass or bundle. + */ + sampleCount?: GPUSize32; +} + +interface GPURenderPassTimestampWrites { + /** + * The {@link GPUQuerySet}, of type {@link GPUQueryType#"timestamp"}, that the query results will be + * written to. + */ + querySet: GPUQuerySet; + /** + * If defined, indicates the query index in {@link GPURenderPassTimestampWrites#querySet} into + * which the timestamp at the beginning of the render pass will be written. + */ + beginningOfPassWriteIndex?: GPUSize32; + /** + * If defined, indicates the query index in {@link GPURenderPassTimestampWrites#querySet} into + * which the timestamp at the end of the render pass will be written. + */ + endOfPassWriteIndex?: GPUSize32; +} + +interface GPURenderPipelineDescriptor + extends GPUPipelineDescriptorBase { + /** + * Describes the vertex shader entry point of the pipeline and its input buffer layouts. + */ + vertex: GPUVertexState; + /** + * Describes the primitive-related properties of the pipeline. + */ + primitive?: GPUPrimitiveState; + /** + * Describes the optional depth-stencil properties, including the testing, operations, and bias. + */ + depthStencil?: GPUDepthStencilState; + /** + * Describes the multi-sampling properties of the pipeline. + */ + multisample?: GPUMultisampleState; + /** + * Describes the fragment shader entry point of the pipeline and its output colors. If + * not map/exist|provided, the [[#no-color-output]] mode is enabled. + */ + fragment?: GPUFragmentState; +} + +interface GPURequestAdapterOptions { + /** + * Optionally provides a hint indicating what class of adapter should be selected from + * the system's available adapters. + * The value of this hint may influence which adapter is chosen, but it must not + * influence whether an adapter is returned or not. + * Note: + * The primary utility of this hint is to influence which GPU is used in a multi-GPU system. + * For instance, some laptops have a low-power integrated GPU and a high-performance + * discrete GPU. This hint may also affect the power configuration of the selected GPU to + * match the requested power preference. + * Note: + * Depending on the exact hardware configuration, such as battery status and attached displays + * or removable GPUs, the user agent may select different adapters given the same power + * preference. + * Typically, given the same hardware configuration and state and + * `powerPreference`, the user agent is likely to select the same adapter. + */ + powerPreference?: GPUPowerPreference; + /** + * When set to `true` indicates that only a fallback adapter may be returned. If the user + * agent does not support a fallback adapter, will cause {@link GPU#requestAdapter} to + * resolve to `null`. + * Note: + * {@link GPU#requestAdapter} may still return a fallback adapter if + * {@link GPURequestAdapterOptions#forceFallbackAdapter} is set to `false` and either no + * other appropriate adapter is available or the user agent chooses to return a + * fallback adapter. Developers that wish to prevent their applications from running on + * fallback adapters should check the {@link GPUAdapter}.{@link GPUAdapter#isFallbackAdapter} + * attribute prior to requesting a {@link GPUDevice}. + */ + forceFallbackAdapter?: boolean; +} + +interface GPUSamplerBindingLayout { + /** + * Indicates the required type of a sampler bound to this bindings. + */ + type?: GPUSamplerBindingType; +} + +interface GPUSamplerDescriptor + extends GPUObjectDescriptorBase { + /** + */ + addressModeU?: GPUAddressMode; + /** + */ + addressModeV?: GPUAddressMode; + /** + * Specifies the {{GPUAddressMode|address modes}} for the texture width, height, and depth + * coordinates, respectively. + */ + addressModeW?: GPUAddressMode; + /** + * Specifies the sampling behavior when the sample footprint is smaller than or equal to one + * texel. + */ + magFilter?: GPUFilterMode; + /** + * Specifies the sampling behavior when the sample footprint is larger than one texel. + */ + minFilter?: GPUFilterMode; + /** + * Specifies behavior for sampling between mipmap levels. + */ + mipmapFilter?: GPUMipmapFilterMode; + /** + */ + lodMinClamp?: number; + /** + * Specifies the minimum and maximum levels of detail, respectively, used internally when + * sampling a texture. + */ + lodMaxClamp?: number; + /** + * When provided the sampler will be a comparison sampler with the specified + * {@link GPUCompareFunction}. + * Note: Comparison samplers may use filtering, but the sampling results will be + * implementation-dependent and may differ from the normal filtering rules. + */ + compare?: GPUCompareFunction; + /** + * Specifies the maximum anisotropy value clamp used by the sampler. + * Note: Most implementations support {@link GPUSamplerDescriptor#maxAnisotropy} values in range + * between 1 and 16, inclusive. The used value of {@link GPUSamplerDescriptor#maxAnisotropy} will + * be clamped to the maximum value that the platform supports. + */ + maxAnisotropy?: number; +} + +interface GPUShaderModuleCompilationHint { + entryPoint: string; + /** + * A {@link GPUPipelineLayout} that the {@link GPUShaderModule} may be used with in a future + * {@link GPUDevice#createComputePipeline()} or {@link GPUDevice#createRenderPipeline} call. + * If set to {@link GPUAutoLayoutMode#"auto"} the layout will be the [$default pipeline layout$] + * for the entry point associated with this hint will be used. + */ + layout?: + | GPUPipelineLayout + | GPUAutoLayoutMode; +} + +interface GPUShaderModuleDescriptor + extends GPUObjectDescriptorBase { + /** + * The WGSL source code for the shader + * module. + */ + code: string; + /** + * If defined MAY be interpreted as a source-map-v3 format. + * Source maps are optional, but serve as a standardized way to support dev-tool + * integration such as source-language debugging [[SourceMap]]. + * WGSL names (identifiers) in source maps follow the rules defined in WGSL identifier + * comparison. + */ + sourceMap?: any; + /** + * A list of {@link GPUShaderModuleCompilationHint}s. + * Any hint provided by an application **should** contain information about one entry point of + * a pipeline that will eventually be created from the entry point. + * Implementations **should** use any information present in the {@link GPUShaderModuleCompilationHint} + * to perform as much compilation as is possible within {@link GPUDevice#createShaderModule}. + * Aside from type-checking, these hints are not validated in any way. + *
+ * Supplying information in {@link GPUShaderModuleDescriptor#compilationHints} does not have any + * observable effect, other than performance. It may be detrimental to performance to + * provide hints for pipelines that never end up being created. + * Because a single shader module can hold + * multiple entry points, and multiple pipelines can be created from a single shader + * module, it can be more performant for an implementation to do as much compilation as + * possible once in {@link GPUDevice#createShaderModule} rather than multiple times in + * the multiple calls to {@link GPUDevice#createComputePipeline} or + * {@link GPUDevice#createRenderPipeline}. + *
+ * Note: + * Hints are not validated in an observable way, but user agents **may** surface identifiable + * errors (like unknown entry point names or incompatible pipeline layouts) to developers, + * for example in the browser developer console. + */ + compilationHints?: Array; +} + +interface GPUStencilFaceState { + /** + * The {@link GPUCompareFunction} used when testing fragments against + * {@link GPURenderPassDescriptor#depthStencilAttachment} stencil values. + */ + compare?: GPUCompareFunction; + /** + * The {@link GPUStencilOperation} performed if the fragment stencil comparison test described by + * {@link GPUStencilFaceState#compare} fails. + */ + failOp?: GPUStencilOperation; + /** + * The {@link GPUStencilOperation} performed if the fragment depth comparison described by + * {@link GPUDepthStencilState#depthCompare} fails. + */ + depthFailOp?: GPUStencilOperation; + /** + * The {@link GPUStencilOperation} performed if the fragment stencil comparison test described by + * {@link GPUStencilFaceState#compare} passes. + */ + passOp?: GPUStencilOperation; +} + +interface GPUStorageTextureBindingLayout { + /** + * The access mode for this binding, indicating readability and writability. + */ + access?: GPUStorageTextureAccess; + /** + * The required {@link GPUTextureViewDescriptor#format} of texture views bound to this binding. + */ + format: GPUTextureFormat; + /** + * Indicates the required {@link GPUTextureViewDescriptor#dimension} for texture views bound to + * this binding. + */ + viewDimension?: GPUTextureViewDimension; +} + +interface GPUTextureBindingLayout { + /** + * Indicates the type required for texture views bound to this binding. + */ + sampleType?: GPUTextureSampleType; + /** + * Indicates the required {@link GPUTextureViewDescriptor#dimension} for texture views bound to + * this binding. + */ + viewDimension?: GPUTextureViewDimension; + /** + * Indicates whether or not texture views bound to this binding must be multisampled. + */ + multisampled?: boolean; +} + +interface GPUTextureDescriptor + extends GPUObjectDescriptorBase { + /** + * The width, height, and depth or layer count of the texture. + */ + size: GPUExtent3DStrict; + /** + * The number of mip levels the texture will contain. + */ + mipLevelCount?: GPUIntegerCoordinate; + /** + * The sample count of the texture. A {@link GPUTextureDescriptor#sampleCount} > `1` indicates + * a multisampled texture. + */ + sampleCount?: GPUSize32; + /** + * Whether the texture is one-dimensional, an array of two-dimensional layers, or three-dimensional. + */ + dimension?: GPUTextureDimension; + /** + * The format of the texture. + */ + format: GPUTextureFormat; + /** + * The allowed usages for the texture. + */ + usage: GPUTextureUsageFlags; + /** + * Specifies what view {@link GPUTextureViewDescriptor#format} values will be allowed when calling + * {@link GPUTexture#createView} on this texture (in addition to the texture's actual + * {@link GPUTextureDescriptor#format}). + *
+ * Adding a format to this list may have a significant performance impact, so it is best + * to avoid adding formats unnecessarily. + * The actual performance impact is highly dependent on the target system; developers must + * test various systems to find out the impact on their particular application. + * For example, on some systems any texture with a {@link GPUTextureDescriptor#format} or + * {@link GPUTextureDescriptor#viewFormats} entry including + * {@link GPUTextureFormat#"rgba8unorm-srgb"} will perform less optimally than a + * {@link GPUTextureFormat#"rgba8unorm"} texture which does not. + * Similar caveats exist for other formats and pairs of formats on other systems. + *
+ * Formats in this list must be texture view format compatible with the texture format. + *
+ * Two {@link GPUTextureFormat}s `format` and `viewFormat` are texture view format compatible if: + * - `format` equals `viewFormat`, or + * - `format` and `viewFormat` differ only in whether they are `srgb` formats (have the `-srgb` suffix). + *
+ */ + viewFormats?: Iterable; +} + +interface GPUTextureViewDescriptor + extends GPUObjectDescriptorBase { + /** + * The format of the texture view. Must be either the {@link GPUTextureDescriptor#format} of the + * texture or one of the {@link GPUTextureDescriptor#viewFormats} specified during its creation. + */ + format?: GPUTextureFormat; + /** + * The dimension to view the texture as. + */ + dimension?: GPUTextureViewDimension; + /** + * Which {@link GPUTextureAspect|aspect(s)} of the texture are accessible to the texture view. + */ + aspect?: GPUTextureAspect; + /** + * The first (most detailed) mipmap level accessible to the texture view. + */ + baseMipLevel?: GPUIntegerCoordinate; + /** + * How many mipmap levels, starting with {@link GPUTextureViewDescriptor#baseMipLevel}, are accessible to + * the texture view. + */ + mipLevelCount?: GPUIntegerCoordinate; + /** + * The index of the first array layer accessible to the texture view. + */ + baseArrayLayer?: GPUIntegerCoordinate; + /** + * How many array layers, starting with {@link GPUTextureViewDescriptor#baseArrayLayer}, are accessible + * to the texture view. + */ + arrayLayerCount?: GPUIntegerCoordinate; +} + +interface GPUUncapturedErrorEventInit + extends EventInit { + error: GPUError; +} + +interface GPUVertexAttribute { + /** + * The {@link GPUVertexFormat} of the attribute. + */ + format: GPUVertexFormat; + /** + * The offset, in bytes, from the beginning of the element to the data for the attribute. + */ + offset: GPUSize64; + /** + * The numeric location associated with this attribute, which will correspond with a + * "@location" attribute + * declared in the {@link GPURenderPipelineDescriptor#vertex}.{@link GPUProgrammableStage#module|module}. + */ + shaderLocation: GPUIndex32; +} + +interface GPUVertexBufferLayout { + /** + * The stride, in bytes, between elements of this array. + */ + arrayStride: GPUSize64; + /** + * Whether each element of this array represents per-vertex data or per-instance data + */ + stepMode?: GPUVertexStepMode; + /** + * An array defining the layout of the vertex attributes within each element. + */ + attributes: Iterable; +} + +interface GPUVertexState + extends GPUProgrammableStage { + /** + * A list of {@link GPUVertexBufferLayout}s defining the layout of the vertex attribute data in the + * vertex buffers used by this pipeline. + */ + buffers?: Iterable; +} + +interface GPUBindingCommandsMixin { + /** + * Sets the current {@link GPUBindGroup} for the given index. + * @param index - The index to set the bind group at. + * @param bindGroup - Bind group to use for subsequent render or compute commands. + * + * @param dynamicOffsets - Array containing buffer offsets in bytes for each entry in + * `bindGroup` marked as {@link GPUBindGroupLayoutEntry#buffer}.{@link GPUBufferBindingLayout#hasDynamicOffset}.--> + */ + setBindGroup( + index: GPUIndex32, + bindGroup: GPUBindGroup | null, + dynamicOffsets?: Iterable + ): undefined; + /** + * Sets the current {@link GPUBindGroup} for the given index, specifying dynamic offsets as a subset + * of a {@link Uint32Array}. + * @param index - The index to set the bind group at. + * @param bindGroup - Bind group to use for subsequent render or compute commands. + * @param dynamicOffsetsData - Array containing buffer offsets in bytes for each entry in + * `bindGroup` marked as {@link GPUBindGroupLayoutEntry#buffer}.{@link GPUBufferBindingLayout#hasDynamicOffset}. + * @param dynamicOffsetsDataStart - Offset in elements into `dynamicOffsetsData` where the + * buffer offset data begins. + * @param dynamicOffsetsDataLength - Number of buffer offsets to read from `dynamicOffsetsData`. + */ + setBindGroup( + index: GPUIndex32, + bindGroup: GPUBindGroup | null, + dynamicOffsetsData: Uint32Array, + dynamicOffsetsDataStart: GPUSize64, + dynamicOffsetsDataLength: GPUSize32 + ): undefined; +} + +interface GPUCommandsMixin {} + +interface GPUDebugCommandsMixin { + /** + * Begins a labeled debug group containing subsequent commands. + * @param groupLabel - The label for the command group. + */ + pushDebugGroup( + groupLabel: string + ): undefined; + /** + * Ends the labeled debug group most recently started by {@link GPUDebugCommandsMixin#pushDebugGroup}. + */ + popDebugGroup(): undefined; + /** + * Marks a point in a stream of commands with a label. + * @param markerLabel - The label to insert. + */ + insertDebugMarker( + markerLabel: string + ): undefined; +} + +interface GPUObjectBase { + label: string; +} + +interface GPUPipelineBase { + /** + * Gets a {@link GPUBindGroupLayout} that is compatible with the {@link GPUPipelineBase}'s + * {@link GPUBindGroupLayout} at `index`. + * @param index - Index into the pipeline layout's {@link GPUPipelineLayout#[[bindGroupLayouts]]} + * sequence. + */ + getBindGroupLayout( + index: number + ): GPUBindGroupLayout; +} + +interface GPURenderCommandsMixin { + /** + * Sets the current {@link GPURenderPipeline}. + * @param pipeline - The render pipeline to use for subsequent drawing commands. + */ + setPipeline( + pipeline: GPURenderPipeline + ): undefined; + /** + * Sets the current index buffer. + * @param buffer - Buffer containing index data to use for subsequent drawing commands. + * @param indexFormat - Format of the index data contained in `buffer`. + * @param offset - Offset in bytes into `buffer` where the index data begins. Defaults to `0`. + * @param size - Size in bytes of the index data in `buffer`. + * Defaults to the size of the buffer minus the offset. + */ + setIndexBuffer( + buffer: GPUBuffer, + indexFormat: GPUIndexFormat, + offset?: GPUSize64, + size?: GPUSize64 + ): undefined; + /** + * Sets the current vertex buffer for the given slot. + * @param slot - The vertex buffer slot to set the vertex buffer for. + * @param buffer - Buffer containing vertex data to use for subsequent drawing commands. + * @param offset - Offset in bytes into `buffer` where the vertex data begins. Defaults to `0`. + * @param size - Size in bytes of the vertex data in `buffer`. + * Defaults to the size of the buffer minus the offset. + */ + setVertexBuffer( + slot: GPUIndex32, + buffer: GPUBuffer | null, + offset?: GPUSize64, + size?: GPUSize64 + ): undefined; + /** + * Draws primitives. + * See [[#rendering-operations]] for the detailed specification. + * @param vertexCount - The number of vertices to draw. + * @param instanceCount - The number of instances to draw. + * @param firstVertex - Offset into the vertex buffers, in vertices, to begin drawing from. + * @param firstInstance - First instance to draw. + */ + draw( + vertexCount: GPUSize32, + instanceCount?: GPUSize32, + firstVertex?: GPUSize32, + firstInstance?: GPUSize32 + ): undefined; + /** + * Draws indexed primitives. + * See [[#rendering-operations]] for the detailed specification. + * @param indexCount - The number of indices to draw. + * @param instanceCount - The number of instances to draw. + * @param firstIndex - Offset into the index buffer, in indices, begin drawing from. + * @param baseVertex - Added to each index value before indexing into the vertex buffers. + * @param firstInstance - First instance to draw. + */ + drawIndexed( + indexCount: GPUSize32, + instanceCount?: GPUSize32, + firstIndex?: GPUSize32, + baseVertex?: GPUSignedOffset32, + firstInstance?: GPUSize32 + ): undefined; + /** + * Draws primitives using parameters read from a {@link GPUBuffer}. + * See [[#rendering-operations]] for the detailed specification. + * packed block of **four 32-bit unsigned integer values (16 bytes total)**, given in the same + * order as the arguments for {@link GPURenderEncoderBase#draw}. For example: + * @param indirectBuffer - Buffer containing the indirect draw parameters. + * @param indirectOffset - Offset in bytes into `indirectBuffer` where the drawing data begins. + */ + drawIndirect( + indirectBuffer: GPUBuffer, + indirectOffset: GPUSize64 + ): undefined; + /** + * Draws indexed primitives using parameters read from a {@link GPUBuffer}. + * See [[#rendering-operations]] for the detailed specification. + * tightly packed block of **five 32-bit unsigned integer values (20 bytes total)**, given in + * the same order as the arguments for {@link GPURenderEncoderBase#drawIndexed}. For example: + * @param indirectBuffer - Buffer containing the indirect drawIndexed parameters. + * @param indirectOffset - Offset in bytes into `indirectBuffer` where the drawing data begins. + */ + drawIndexedIndirect( + indirectBuffer: GPUBuffer, + indirectOffset: GPUSize64 + ): undefined; +} + +interface NavigatorGPU { + /** + * A global singleton providing top-level entry points like {@link GPU#requestAdapter}. + */ + readonly gpu: GPU; +} + +interface GPU { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPU'; + /** + * Requests an adapter from the user agent. + * The user agent chooses whether to return an adapter, and, if so, + * chooses according to the provided options. + * @param options - Criteria used to select the adapter. + */ + requestAdapter( + options?: GPURequestAdapterOptions + ): Promise; + /** + * Returns an optimal {@link GPUTextureFormat} for displaying 8-bit depth, standard dynamic range + * content on this system. Must only return {@link GPUTextureFormat#"rgba8unorm"} or + * {@link GPUTextureFormat#"bgra8unorm"}. + * The returned value can be passed as the {@link GPUCanvasConfiguration#format} to + * {@link GPUCanvasContext#configure} calls on a {@link GPUCanvasContext} to ensure the associated + * canvas is able to display its contents efficiently. + * Note: Canvases which are not displayed to the screen may or may not benefit from using this + * format. + */ + getPreferredCanvasFormat(): GPUTextureFormat; + readonly wgslLanguageFeatures: WGSLLanguageFeatures; +} + +declare var GPU: { + prototype: GPU; + new (): never; +}; + +interface GPUAdapter { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUAdapter'; + /** + * The set of values in `this`.{@link GPUAdapter#[[adapter]]}.{@link adapter#[[features]]}. + */ + readonly features: GPUSupportedFeatures; + /** + * The limits in `this`.{@link GPUAdapter#[[adapter]]}.{@link adapter#[[limits]]}. + */ + readonly limits: GPUSupportedLimits; + /** + * Returns the value of {@link GPUAdapter#[[adapter]]}.{@link adapter#[[fallback]]}. + */ + readonly isFallbackAdapter: boolean; + /** + * Requests a device from the adapter. + * This is a one-time action: if a device is returned successfully, + * the adapter becomes invalid. + * @param descriptor - Description of the {@link GPUDevice} to request. + */ + requestDevice( + descriptor?: GPUDeviceDescriptor + ): Promise; + /** + * Requests the {@link GPUAdapterInfo} for this {@link GPUAdapter}. + * Note: Adapter info values are returned with a Promise to give user agents an + * opportunity to perform potentially long-running checks in the future. + */ + requestAdapterInfo(): Promise; +} + +declare var GPUAdapter: { + prototype: GPUAdapter; + new (): never; +}; + +interface GPUAdapterInfo { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUAdapterInfo'; + /** + * The name of the vendor of the adapter, if available. Empty string otherwise. + */ + readonly vendor: string; + /** + * The name of the family or class of GPUs the adapter belongs to, if available. Empty + * string otherwise. + */ + readonly architecture: string; + /** + * A vendor-specific identifier for the adapter, if available. Empty string otherwise. + * Note: This is a value that represents the type of adapter. For example, it may be a + * [PCI device ID](https://pcisig.com/). It does not uniquely identify a given piece of + * hardware like a serial number. + */ + readonly device: string; + /** + * A human readable string describing the adapter as reported by the driver, if available. + * Empty string otherwise. + * Note: Because no formatting is applied to {@link GPUAdapterInfo#description} attempting to parse + * this value is not recommended. Applications which change their behavior based on the + * {@link GPUAdapterInfo}, such as applying workarounds for known driver issues, should rely on the + * other fields when possible. + */ + readonly description: string; +} + +declare var GPUAdapterInfo: { + prototype: GPUAdapterInfo; +}; + +interface GPUBindGroup + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUBindGroup'; +} + +declare var GPUBindGroup: { + prototype: GPUBindGroup; + new (): never; +}; + +interface GPUBindGroupLayout + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUBindGroupLayout'; +} + +declare var GPUBindGroupLayout: { + prototype: GPUBindGroupLayout; + new (): never; +}; + +interface GPUBuffer + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUBuffer'; + readonly size: GPUSize64Out; + readonly usage: GPUFlagsConstant; + readonly mapState: GPUBufferMapState; + /** + * Maps the given range of the {@link GPUBuffer} and resolves the returned {@link Promise} when the + * {@link GPUBuffer}'s content is ready to be accessed with {@link GPUBuffer#getMappedRange}. + * The resolution of the returned {@link Promise} **only** indicates that the buffer has been mapped. + * It does not guarantee the completion of any other operations visible to the content timeline, + * and in particular does not imply that any other {@link Promise} returned from + * {@link GPUQueue#onSubmittedWorkDone()} or {@link GPUBuffer#mapAsync} on other {@link GPUBuffer}s + * have resolved. + * The resolution of the {@link Promise} returned from {@link GPUQueue#onSubmittedWorkDone} + * **does** imply the completion of + * {@link GPUBuffer#mapAsync} calls made prior to that call, + * on {@link GPUBuffer}s last used exclusively on that queue. + * @param mode - Whether the buffer should be mapped for reading or writing. + * @param offset - Offset in bytes into the buffer to the start of the range to map. + * @param size - Size in bytes of the range to map. + */ + mapAsync( + mode: GPUMapModeFlags, + offset?: GPUSize64, + size?: GPUSize64 + ): Promise; + /** + * Returns an {@link ArrayBuffer} with the contents of the {@link GPUBuffer} in the given mapped range. + * @param offset - Offset in bytes into the buffer to return buffer contents from. + * @param size - Size in bytes of the {@link ArrayBuffer} to return. + */ + getMappedRange( + offset?: GPUSize64, + size?: GPUSize64 + ): ArrayBuffer; + /** + * Unmaps the mapped range of the {@link GPUBuffer} and makes it's contents available for use by the + * GPU again. + */ + unmap(): undefined; + /** + * Destroys the {@link GPUBuffer}. + * Note: It is valid to destroy a buffer multiple times. + * Note: Since no further operations can be enqueued using this buffer, implementations can + * free resource allocations, including mapped memory that was just unmapped. + */ + destroy(): undefined; +} + +declare var GPUBuffer: { + prototype: GPUBuffer; + new (): never; +}; + +interface GPUCanvasContext { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUCanvasContext'; + /** + * The canvas this context was created from. + */ + readonly canvas: + | HTMLCanvasElement + | OffscreenCanvas; + /** + * Configures the context for this canvas. + * This clears the drawing buffer to transparent black (in [$Replace the drawing buffer$]). + * @param configuration - Desired configuration for the context. + */ + configure( + configuration: GPUCanvasConfiguration + ): undefined; + /** + * Removes the context configuration. Destroys any textures produced while configured. + */ + unconfigure(): undefined; + /** + * Get the {@link GPUTexture} that will be composited to the document by the {@link GPUCanvasContext} + * next. + * Note: The same {@link GPUTexture} object will be returned by every + * call to {@link GPUCanvasContext#getCurrentTexture} until "[$Expire the current texture$]" + * runs, even if that {@link GPUTexture} is destroyed, failed validation, or failed to allocate. + */ + getCurrentTexture(): GPUTexture; +} + +declare var GPUCanvasContext: { + prototype: GPUCanvasContext; + new (): never; +}; + +interface GPUCommandBuffer + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUCommandBuffer'; +} + +declare var GPUCommandBuffer: { + prototype: GPUCommandBuffer; + new (): never; +}; + +interface GPUCommandEncoder + extends GPUObjectBase, + GPUCommandsMixin, + GPUDebugCommandsMixin { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUCommandEncoder'; + /** + * Begins encoding a render pass described by `descriptor`. + * @param descriptor - Description of the {@link GPURenderPassEncoder} to create. + */ + beginRenderPass( + descriptor: GPURenderPassDescriptor + ): GPURenderPassEncoder; + /** + * Begins encoding a compute pass described by `descriptor`. + * descriptor: + */ + beginComputePass( + descriptor?: GPUComputePassDescriptor + ): GPUComputePassEncoder; + /** + * Encode a command into the {@link GPUCommandEncoder} that copies data from a sub-region of a + * {@link GPUBuffer} to a sub-region of another {@link GPUBuffer}. + * @param source - The {@link GPUBuffer} to copy from. + * @param sourceOffset - Offset in bytes into `source` to begin copying from. + * @param destination - The {@link GPUBuffer} to copy to. + * @param destinationOffset - Offset in bytes into `destination` to place the copied data. + * @param size - Bytes to copy. + */ + copyBufferToBuffer( + source: GPUBuffer, + sourceOffset: GPUSize64, + destination: GPUBuffer, + destinationOffset: GPUSize64, + size: GPUSize64 + ): undefined; + /** + * Encode a command into the {@link GPUCommandEncoder} that copies data from a sub-region of a + * {@link GPUBuffer} to a sub-region of one or multiple continuous texture subresources. + * @param source - Combined with `copySize`, defines the region of the source buffer. + * @param destination - Combined with `copySize`, defines the region of the destination texture subresource. + * `copySize`: + */ + copyBufferToTexture( + source: GPUImageCopyBuffer, + destination: GPUImageCopyTexture, + copySize: GPUExtent3DStrict + ): undefined; + /** + * Encode a command into the {@link GPUCommandEncoder} that copies data from a sub-region of one or + * multiple continuous texture subresources to a sub-region of a {@link GPUBuffer}. + * @param source - Combined with `copySize`, defines the region of the source texture subresources. + * @param destination - Combined with `copySize`, defines the region of the destination buffer. + * `copySize`: + */ + copyTextureToBuffer( + source: GPUImageCopyTexture, + destination: GPUImageCopyBuffer, + copySize: GPUExtent3DStrict + ): undefined; + /** + * Encode a command into the {@link GPUCommandEncoder} that copies data from a sub-region of one + * or multiple contiguous texture subresources to another sub-region of one or + * multiple continuous texture subresources. + * @param source - Combined with `copySize`, defines the region of the source texture subresources. + * @param destination - Combined with `copySize`, defines the region of the destination texture subresources. + * `copySize`: + */ + copyTextureToTexture( + source: GPUImageCopyTexture, + destination: GPUImageCopyTexture, + copySize: GPUExtent3DStrict + ): undefined; + /** + * Encode a command into the {@link GPUCommandEncoder} that fills a sub-region of a + * {@link GPUBuffer} with zeros. + * @param buffer - The {@link GPUBuffer} to clear. + * @param offset - Offset in bytes into `buffer` where the sub-region to clear begins. + * @param size - Size in bytes of the sub-region to clear. Defaults to the size of the buffer minus `offset`. + */ + clearBuffer( + buffer: GPUBuffer, + offset?: GPUSize64, + size?: GPUSize64 + ): undefined; + /** + * Resolves query results from a {@link GPUQuerySet} out into a range of a {@link GPUBuffer}. + * querySet: + * firstQuery: + * queryCount: + * destination: + * destinationOffset: + */ + resolveQuerySet( + querySet: GPUQuerySet, + firstQuery: GPUSize32, + queryCount: GPUSize32, + destination: GPUBuffer, + destinationOffset: GPUSize64 + ): undefined; + /** + * Completes recording of the commands sequence and returns a corresponding {@link GPUCommandBuffer}. + * descriptor: + */ + finish( + descriptor?: GPUCommandBufferDescriptor + ): GPUCommandBuffer; +} + +declare var GPUCommandEncoder: { + prototype: GPUCommandEncoder; + new (): never; +}; + +interface GPUCompilationInfo { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUCompilationInfo'; + readonly messages: ReadonlyArray; +} + +declare var GPUCompilationInfo: { + prototype: GPUCompilationInfo; + new (): never; +}; + +interface GPUCompilationMessage { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUCompilationMessage'; + /** + * The human-readable, localizable text for this compilation message. + * Note: The {@link GPUCompilationMessage#message} should follow the best practices for language + * and direction information. This includes making use of any future standards which may + * emerge regarding the reporting of string language and direction metadata. + *

Editorial note: + * At the time of this writing, no language/direction recommendation is available that provides + * compatibility and consistency with legacy APIs, but when there is, adopt it formally. + */ + readonly message: string; + /** + * The severity level of the message. + * If the {@link GPUCompilationMessage#type} is {@link GPUCompilationMessageType#"error"}, it + * corresponds to a shader-creation error. + */ + readonly type: GPUCompilationMessageType; + /** + * The line number in the shader {@link GPUShaderModuleDescriptor#code} the + * {@link GPUCompilationMessage#message} corresponds to. Value is one-based, such that a lineNum of + * `1` indicates the first line of the shader {@link GPUShaderModuleDescriptor#code}. Lines are + * delimited by line breaks. + * If the {@link GPUCompilationMessage#message} corresponds to a substring this points to + * the line on which the substring begins. Must be `0` if the {@link GPUCompilationMessage#message} + * does not correspond to any specific point in the shader {@link GPUShaderModuleDescriptor#code}. + */ + readonly lineNum: number; + /** + * The offset, in UTF-16 code units, from the beginning of line {@link GPUCompilationMessage#lineNum} + * of the shader {@link GPUShaderModuleDescriptor#code} to the point or beginning of the substring + * that the {@link GPUCompilationMessage#message} corresponds to. Value is one-based, such that a + * {@link GPUCompilationMessage#linePos} of `1` indicates the first code unit of the line. + * If {@link GPUCompilationMessage#message} corresponds to a substring this points to the + * first UTF-16 code unit of the substring. Must be `0` if the {@link GPUCompilationMessage#message} + * does not correspond to any specific point in the shader {@link GPUShaderModuleDescriptor#code}. + */ + readonly linePos: number; + /** + * The offset from the beginning of the shader {@link GPUShaderModuleDescriptor#code} in UTF-16 + * code units to the point or beginning of the substring that {@link GPUCompilationMessage#message} + * corresponds to. Must reference the same position as {@link GPUCompilationMessage#lineNum} and + * {@link GPUCompilationMessage#linePos}. Must be `0` if the {@link GPUCompilationMessage#message} + * does not correspond to any specific point in the shader {@link GPUShaderModuleDescriptor#code}. + */ + readonly offset: number; + /** + * The number of UTF-16 code units in the substring that {@link GPUCompilationMessage#message} + * corresponds to. If the message does not correspond with a substring then + * {@link GPUCompilationMessage#length} must be 0. + */ + readonly length: number; +} + +declare var GPUCompilationMessage: { + prototype: GPUCompilationMessage; + new (): never; +}; + +interface GPUComputePassEncoder + extends GPUObjectBase, + GPUCommandsMixin, + GPUDebugCommandsMixin, + GPUBindingCommandsMixin { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUComputePassEncoder'; + /** + * Sets the current {@link GPUComputePipeline}. + * @param pipeline - The compute pipeline to use for subsequent dispatch commands. + */ + setPipeline( + pipeline: GPUComputePipeline + ): undefined; + /** + * Dispatch work to be performed with the current {@link GPUComputePipeline}. + * See [[#computing-operations]] for the detailed specification. + * @param workgroupCountX - X dimension of the grid of workgroups to dispatch. + * @param workgroupCountY - Y dimension of the grid of workgroups to dispatch. + * @param workgroupCountZ - Z dimension of the grid of workgroups to dispatch. + */ + dispatchWorkgroups( + workgroupCountX: GPUSize32, + workgroupCountY?: GPUSize32, + workgroupCountZ?: GPUSize32 + ): undefined; + /** + * Dispatch work to be performed with the current {@link GPUComputePipeline} using parameters read + * from a {@link GPUBuffer}. + * See [[#computing-operations]] for the detailed specification. + * packed block of **three 32-bit unsigned integer values (12 bytes total)**, + * given in the same order as the arguments for {@link GPUComputePassEncoder#dispatchWorkgroups}. + * For example: + * @param indirectBuffer - Buffer containing the indirect dispatch parameters. + * @param indirectOffset - Offset in bytes into `indirectBuffer` where the dispatch data begins. + */ + dispatchWorkgroupsIndirect( + indirectBuffer: GPUBuffer, + indirectOffset: GPUSize64 + ): undefined; + /** + * Completes recording of the compute pass commands sequence. + */ + end(): undefined; +} + +declare var GPUComputePassEncoder: { + prototype: GPUComputePassEncoder; + new (): never; +}; + +interface GPUComputePipeline + extends GPUObjectBase, + GPUPipelineBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUComputePipeline'; +} + +declare var GPUComputePipeline: { + prototype: GPUComputePipeline; + new (): never; +}; + +declare interface VideoFrame {} +interface GPUDevice + extends EventTarget, + GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUDevice'; + /** + * A set containing the {@link GPUFeatureName} values of the features + * supported by the device (i.e. the ones with which it was created). + */ + readonly features: GPUSupportedFeatures; + /** + * Exposes the limits supported by the device + * (which are exactly the ones with which it was created). + */ + readonly limits: GPUSupportedLimits; + /** + * The primary {@link GPUQueue} for this device. + */ + readonly queue: GPUQueue; + /** + * Destroys the device, preventing further operations on it. + * Outstanding asynchronous operations will fail. + * Note: It is valid to destroy a device multiple times. + */ + destroy(): undefined; + /** + * Creates a {@link GPUBuffer}. + * @param descriptor - Description of the {@link GPUBuffer} to create. + */ + createBuffer( + descriptor: GPUBufferDescriptor + ): GPUBuffer; + /** + * Creates a {@link GPUTexture}. + * @param descriptor - Description of the {@link GPUTexture} to create. + */ + createTexture( + descriptor: GPUTextureDescriptor + ): GPUTexture; + /** + * Creates a {@link GPUSampler}. + * @param descriptor - Description of the {@link GPUSampler} to create. + */ + createSampler( + descriptor?: GPUSamplerDescriptor + ): GPUSampler; + /** + * Creates a {@link GPUExternalTexture} wrapping the provided image source. + * @param descriptor - Provides the external image source object (and any creation options). + */ + importExternalTexture( + descriptor: GPUExternalTextureDescriptor + ): GPUExternalTexture; + /** + * Creates a {@link GPUBindGroupLayout}. + * @param descriptor - Description of the {@link GPUBindGroupLayout} to create. + */ + createBindGroupLayout( + descriptor: GPUBindGroupLayoutDescriptor + ): GPUBindGroupLayout; + /** + * Creates a {@link GPUPipelineLayout}. + * @param descriptor - Description of the {@link GPUPipelineLayout} to create. + */ + createPipelineLayout( + descriptor: GPUPipelineLayoutDescriptor + ): GPUPipelineLayout; + /** + * Creates a {@link GPUBindGroup}. + * @param descriptor - Description of the {@link GPUBindGroup} to create. + */ + createBindGroup( + descriptor: GPUBindGroupDescriptor + ): GPUBindGroup; + /** + * Creates a {@link GPUShaderModule}. + * @param descriptor - Description of the {@link GPUShaderModule} to create. + */ + createShaderModule( + descriptor: GPUShaderModuleDescriptor + ): GPUShaderModule; + /** + * Creates a {@link GPUComputePipeline} using immediate pipeline creation. + * @param descriptor - Description of the {@link GPUComputePipeline} to create. + */ + createComputePipeline( + descriptor: GPUComputePipelineDescriptor + ): GPUComputePipeline; + /** + * Creates a {@link GPURenderPipeline} using immediate pipeline creation. + * @param descriptor - Description of the {@link GPURenderPipeline} to create. + */ + createRenderPipeline( + descriptor: GPURenderPipelineDescriptor + ): GPURenderPipeline; + /** + * Creates a {@link GPUComputePipeline} using async pipeline creation. + * The returned {@link Promise} resolves when the created pipeline + * is ready to be used without additional delay. + * If pipeline creation fails, the returned {@link Promise} rejects with an {@link GPUPipelineError}. + * Note: Use of this method is preferred whenever possible, as it prevents blocking the + * queue timeline work on pipeline compilation. + * @param descriptor - Description of the {@link GPUComputePipeline} to create. + */ + createComputePipelineAsync( + descriptor: GPUComputePipelineDescriptor + ): Promise; + /** + * Creates a {@link GPURenderPipeline} using async pipeline creation. + * The returned {@link Promise} resolves when the created pipeline + * is ready to be used without additional delay. + * If pipeline creation fails, the returned {@link Promise} rejects with an {@link GPUPipelineError}. + * Note: Use of this method is preferred whenever possible, as it prevents blocking the + * queue timeline work on pipeline compilation. + * @param descriptor - Description of the {@link GPURenderPipeline} to create. + */ + createRenderPipelineAsync( + descriptor: GPURenderPipelineDescriptor + ): Promise; + /** + * Creates a {@link GPUCommandEncoder}. + * @param descriptor - Description of the {@link GPUCommandEncoder} to create. + */ + createCommandEncoder( + descriptor?: GPUCommandEncoderDescriptor + ): GPUCommandEncoder; + /** + * Creates a {@link GPURenderBundleEncoder}. + * @param descriptor - Description of the {@link GPURenderBundleEncoder} to create. + */ + createRenderBundleEncoder( + descriptor: GPURenderBundleEncoderDescriptor + ): GPURenderBundleEncoder; + /** + * Creates a {@link GPUQuerySet}. + * @param descriptor - Description of the {@link GPUQuerySet} to create. + */ + createQuerySet( + descriptor: GPUQuerySetDescriptor + ): GPUQuerySet; + /** + * A slot-backed attribute holding a promise which is created with the device, remains + * pending for the lifetime of the device, then resolves when the device is lost. + * Upon initialization, it is set to a new promise. + */ + readonly lost: Promise; + /** + * Pushes a new GPU error scope onto the {@link GPUDevice#[[errorScopeStack]]} for `this`. + * @param filter - Which class of errors this error scope observes. + */ + pushErrorScope( + filter: GPUErrorFilter + ): undefined; + /** + * Pops a GPU error scope off the {@link GPUDevice#[[errorScopeStack]]} for `this` + * and resolves to **any** {@link GPUError} observed by the error scope, or `null` if none. + * There is no guarantee of the ordering of promise resolution. + */ + popErrorScope(): Promise; + /** + * An event handler IDL attribute for the {@link GPUDevice#uncapturederror} event type. + */ + onuncapturederror: + | (( + this: GPUDevice, + ev: GPUUncapturedErrorEvent + ) => any) + | null; +} + +declare var GPUDevice: { + prototype: GPUDevice; + new (): never; +}; + +interface GPUDeviceLostInfo { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUDeviceLostInfo'; + readonly reason: GPUDeviceLostReason; + readonly message: string; +} + +declare var GPUDeviceLostInfo: { + prototype: GPUDeviceLostInfo; + new (): never; +}; + +interface GPUError { + /** + * A human-readable, localizable text message providing information about the error that + * occurred. + * Note: This message is generally intended for application developers to debug their + * applications and capture information for debug reports, not to be surfaced to end-users. + * Note: User agents should not include potentially machine-parsable details in this message, + * such as free system memory on {@link GPUErrorFilter#"out-of-memory"} or other details about the + * conditions under which memory was exhausted. + * Note: The {@link GPUError#message} should follow the best practices for language and + * direction information. This includes making use of any future standards which may emerge + * regarding the reporting of string language and direction metadata. + *

Editorial note: + * At the time of this writing, no language/direction recommendation is available that provides + * compatibility and consistency with legacy APIs, but when there is, adopt it formally. + */ + readonly message: string; +} + +declare var GPUError: { + prototype: GPUError; + new (): never; +}; + +interface GPUExternalTexture + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUExternalTexture'; +} + +declare var GPUExternalTexture: { + prototype: GPUExternalTexture; + new (): never; +}; + +interface GPUInternalError + extends GPUError { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUInternalError'; +} + +declare var GPUInternalError: { + prototype: GPUInternalError; + new ( + message: string + ): GPUInternalError; +}; + +interface GPUOutOfMemoryError + extends GPUError { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUOutOfMemoryError'; +} + +declare var GPUOutOfMemoryError: { + prototype: GPUOutOfMemoryError; + new ( + message: string + ): GPUOutOfMemoryError; +}; + +interface GPUPipelineError + extends DOMException { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUPipelineError'; + /** + * A read-only slot-backed attribute exposing the type of error encountered in pipeline creation + * as a GPUPipelineErrorReason: + *

    + * - "validation": A [$validation error$]. + * - "internal": An [$internal error$]. + *
+ */ + readonly reason: GPUPipelineErrorReason; +} + +declare var GPUPipelineError: { + prototype: GPUPipelineError; + new ( + message: + | string + | undefined, + options: GPUPipelineErrorInit + ): GPUPipelineError; +}; + +interface GPUPipelineLayout + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUPipelineLayout'; +} + +declare var GPUPipelineLayout: { + prototype: GPUPipelineLayout; + new (): never; +}; + +interface GPUQuerySet + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUQuerySet'; + /** + * Destroys the {@link GPUQuerySet}. + */ + destroy(): undefined; + /** + * The type of the queries managed by this {@link GPUQuerySet}. + */ + readonly type: GPUQueryType; + /** + * The number of queries managed by this {@link GPUQuerySet}. + */ + readonly count: GPUSize32Out; +} + +declare var GPUQuerySet: { + prototype: GPUQuerySet; + new (): never; +}; + +interface GPUQueue + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUQueue'; + /** + * Schedules the execution of the command buffers by the GPU on this queue. + * Submitted command buffers cannot be used again. + * `commandBuffers`: + */ + submit( + commandBuffers: Iterable + ): undefined; + /** + * Returns a {@link Promise} that resolves once this queue finishes processing all the work submitted + * up to this moment. + * Resolution of this {@link Promise} implies the completion of + * {@link GPUBuffer#mapAsync} calls made prior to that call, + * on {@link GPUBuffer}s last used exclusively on that queue. + */ + onSubmittedWorkDone(): Promise; + /** + * Issues a write operation of the provided data into a {@link GPUBuffer}. + * @param buffer - The buffer to write to. + * @param bufferOffset - Offset in bytes into `buffer` to begin writing at. + * @param data - Data to write into `buffer`. + * @param dataOffset - Offset in into `data` to begin writing from. Given in elements if + * `data` is a `TypedArray` and bytes otherwise. + * @param size - Size of content to write from `data` to `buffer`. Given in elements if + * `data` is a `TypedArray` and bytes otherwise. + */ + writeBuffer( + buffer: GPUBuffer, + bufferOffset: GPUSize64, + data: + | BufferSource + | SharedArrayBuffer, + dataOffset?: GPUSize64, + size?: GPUSize64 + ): undefined; + /** + * Issues a write operation of the provided data into a {@link GPUTexture}. + * @param destination - The texture subresource and origin to write to. + * @param data - Data to write into `destination`. + * @param dataLayout - Layout of the content in `data`. + * @param size - Extents of the content to write from `data` to `destination`. + */ + writeTexture( + destination: GPUImageCopyTexture, + data: + | BufferSource + | SharedArrayBuffer, + dataLayout: GPUImageDataLayout, + size: GPUExtent3DStrict + ): undefined; + /** + * Issues a copy operation of the contents of a platform image/canvas + * into the destination texture. + * This operation performs [[#color-space-conversions|color encoding]] into the destination + * encoding according to the parameters of {@link GPUImageCopyTextureTagged}. + * Copying into a `-srgb` texture results in the same texture bytes, not the same decoded + * values, as copying into the corresponding non-`-srgb` format. + * Thus, after a copy operation, sampling the destination texture has + * different results depending on whether its format is `-srgb`, all else unchanged. + * + * @param source - source image and origin to copy to `destination`. + * @param destination - The texture subresource and origin to write to, and its encoding metadata. + * @param copySize - Extents of the content to write from `source` to `destination`. + */ + copyExternalImageToTexture( + source: GPUImageCopyExternalImage, + destination: GPUImageCopyTextureTagged, + copySize: GPUExtent3DStrict + ): undefined; +} + +declare var GPUQueue: { + prototype: GPUQueue; + new (): never; +}; + +interface GPURenderBundle + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPURenderBundle'; +} + +declare var GPURenderBundle: { + prototype: GPURenderBundle; + new (): never; +}; + +interface GPURenderBundleEncoder + extends GPUObjectBase, + GPUCommandsMixin, + GPUDebugCommandsMixin, + GPUBindingCommandsMixin, + GPURenderCommandsMixin { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPURenderBundleEncoder'; + /** + * Completes recording of the render bundle commands sequence. + * descriptor: + */ + finish( + descriptor?: GPURenderBundleDescriptor + ): GPURenderBundle; +} + +declare var GPURenderBundleEncoder: { + prototype: GPURenderBundleEncoder; + new (): never; +}; + +interface GPURenderPassEncoder + extends GPUObjectBase, + GPUCommandsMixin, + GPUDebugCommandsMixin, + GPUBindingCommandsMixin, + GPURenderCommandsMixin { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPURenderPassEncoder'; + /** + * Sets the viewport used during the rasterization stage to linearly map from + * NDC|normalized device coordinates to viewport coordinates. + * @param x - Minimum X value of the viewport in pixels. + * @param y - Minimum Y value of the viewport in pixels. + * @param width - Width of the viewport in pixels. + * @param height - Height of the viewport in pixels. + * @param minDepth - Minimum depth value of the viewport. + * @param maxDepth - Maximum depth value of the viewport. + */ + setViewport( + x: number, + y: number, + width: number, + height: number, + minDepth: number, + maxDepth: number + ): undefined; + /** + * Sets the scissor rectangle used during the rasterization stage. + * After transformation into viewport coordinates any fragments which fall outside the scissor + * rectangle will be discarded. + * @param x - Minimum X value of the scissor rectangle in pixels. + * @param y - Minimum Y value of the scissor rectangle in pixels. + * @param width - Width of the scissor rectangle in pixels. + * @param height - Height of the scissor rectangle in pixels. + */ + setScissorRect( + x: GPUIntegerCoordinate, + y: GPUIntegerCoordinate, + width: GPUIntegerCoordinate, + height: GPUIntegerCoordinate + ): undefined; + /** + * Sets the constant blend color and alpha values used with {@link GPUBlendFactor#"constant"} + * and {@link GPUBlendFactor#"one-minus-constant"} {@link GPUBlendFactor}s. + * @param color - The color to use when blending. + */ + setBlendConstant( + color: GPUColor + ): undefined; + /** + * Sets the {@link RenderState#[[stencilReference]]} value used during stencil tests with + * the {@link GPUStencilOperation#"replace"} {@link GPUStencilOperation}. + * @param reference - The new stencil reference value. + */ + setStencilReference( + reference: GPUStencilValue + ): undefined; + /** + * @param queryIndex - The index of the query in the query set. + */ + beginOcclusionQuery( + queryIndex: GPUSize32 + ): undefined; + /** + */ + endOcclusionQuery(): undefined; + /** + * Executes the commands previously recorded into the given {@link GPURenderBundle}s as part of + * this render pass. + * When a {@link GPURenderBundle} is executed, it does not inherit the render pass's pipeline, bind + * groups, or vertex and index buffers. After a {@link GPURenderBundle} has executed, the render + * pass's pipeline, bind group, and vertex/index buffer state is cleared + * (to the initial, empty values). + * Note: The state is cleared, not restored to the previous state. + * This occurs even if zero {@link GPURenderBundle|GPURenderBundles} are executed. + * @param bundles - List of render bundles to execute. + */ + executeBundles( + bundles: Iterable + ): undefined; + /** + * Completes recording of the render pass commands sequence. + */ + end(): undefined; +} + +declare var GPURenderPassEncoder: { + prototype: GPURenderPassEncoder; + new (): never; +}; + +interface GPURenderPipeline + extends GPUObjectBase, + GPUPipelineBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPURenderPipeline'; +} + +declare var GPURenderPipeline: { + prototype: GPURenderPipeline; + new (): never; +}; + +interface GPUSampler + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUSampler'; +} + +declare var GPUSampler: { + prototype: GPUSampler; + new (): never; +}; + +interface GPUShaderModule + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUShaderModule'; + /** + * Returns any messages generated during the {@link GPUShaderModule}'s compilation. + * The locations, order, and contents of messages are implementation-defined. + * In particular, messages may not be ordered by {@link GPUCompilationMessage#lineNum}. + */ + getCompilationInfo(): Promise; +} + +declare var GPUShaderModule: { + prototype: GPUShaderModule; + new (): never; +}; + +type GPUSupportedFeatures = + ReadonlySet; + +interface GPUSupportedLimits { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUSupportedLimits'; + readonly maxTextureDimension1D: number; + readonly maxTextureDimension2D: number; + readonly maxTextureDimension3D: number; + readonly maxTextureArrayLayers: number; + readonly maxBindGroups: number; + readonly maxBindGroupsPlusVertexBuffers: number; + readonly maxBindingsPerBindGroup: number; + readonly maxDynamicUniformBuffersPerPipelineLayout: number; + readonly maxDynamicStorageBuffersPerPipelineLayout: number; + readonly maxSampledTexturesPerShaderStage: number; + readonly maxSamplersPerShaderStage: number; + readonly maxStorageBuffersPerShaderStage: number; + readonly maxStorageTexturesPerShaderStage: number; + readonly maxUniformBuffersPerShaderStage: number; + readonly maxUniformBufferBindingSize: number; + readonly maxStorageBufferBindingSize: number; + readonly minUniformBufferOffsetAlignment: number; + readonly minStorageBufferOffsetAlignment: number; + readonly maxVertexBuffers: number; + readonly maxBufferSize: number; + readonly maxVertexAttributes: number; + readonly maxVertexBufferArrayStride: number; + readonly maxInterStageShaderComponents: number; + readonly maxInterStageShaderVariables: number; + readonly maxColorAttachments: number; + readonly maxColorAttachmentBytesPerSample: number; + readonly maxComputeWorkgroupStorageSize: number; + readonly maxComputeInvocationsPerWorkgroup: number; + readonly maxComputeWorkgroupSizeX: number; + readonly maxComputeWorkgroupSizeY: number; + readonly maxComputeWorkgroupSizeZ: number; + readonly maxComputeWorkgroupsPerDimension: number; +} + +declare var GPUSupportedLimits: { + prototype: GPUSupportedLimits; +}; + +interface GPUTexture + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUTexture'; + /** + * Creates a {@link GPUTextureView}. + * @param descriptor - Description of the {@link GPUTextureView} to create. + */ + createView( + descriptor?: GPUTextureViewDescriptor + ): GPUTextureView; + /** + * Destroys the {@link GPUTexture}. + */ + destroy(): undefined; + /** + * The width of this {@link GPUTexture}. + */ + readonly width: GPUIntegerCoordinateOut; + /** + * The height of this {@link GPUTexture}. + */ + readonly height: GPUIntegerCoordinateOut; + /** + * The depth or layer count of this {@link GPUTexture}. + */ + readonly depthOrArrayLayers: GPUIntegerCoordinateOut; + /** + * The number of mip levels of this {@link GPUTexture}. + */ + readonly mipLevelCount: GPUIntegerCoordinateOut; + /** + * The number of sample count of this {@link GPUTexture}. + */ + readonly sampleCount: GPUSize32Out; + /** + * The dimension of the set of texel for each of this {@link GPUTexture}'s subresources. + */ + readonly dimension: GPUTextureDimension; + /** + * The format of this {@link GPUTexture}. + */ + readonly format: GPUTextureFormat; + /** + * The allowed usages for this {@link GPUTexture}. + */ + readonly usage: GPUFlagsConstant; +} + +declare var GPUTexture: { + prototype: GPUTexture; + new (): never; +}; + +interface GPUTextureView + extends GPUObjectBase { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUTextureView'; +} + +declare var GPUTextureView: { + prototype: GPUTextureView; + new (): never; +}; + +interface GPUUncapturedErrorEvent + extends Event { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUUncapturedErrorEvent'; + /** + * A slot-backed attribute holding an object representing the error that was uncaptured. + * This has the same type as errors returned by {@link GPUDevice#popErrorScope}. + */ + readonly error: GPUError; +} + +declare var GPUUncapturedErrorEvent: { + prototype: GPUUncapturedErrorEvent; + new ( + type: string, + gpuUncapturedErrorEventInitDict: GPUUncapturedErrorEventInit + ): GPUUncapturedErrorEvent; +}; + +interface GPUValidationError + extends GPUError { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUValidationError'; +} + +declare var GPUValidationError: { + prototype: GPUValidationError; + new ( + message: string + ): GPUValidationError; +}; + +type WGSLLanguageFeatures = + ReadonlySet; + +interface Navigator + extends NavigatorGPU {} + +interface WorkerNavigator + extends NavigatorGPU {} + +interface GPUBufferUsage { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUBufferUsage'; + readonly MAP_READ: GPUFlagsConstant; + readonly MAP_WRITE: GPUFlagsConstant; + readonly COPY_SRC: GPUFlagsConstant; + readonly COPY_DST: GPUFlagsConstant; + readonly INDEX: GPUFlagsConstant; + readonly VERTEX: GPUFlagsConstant; + readonly UNIFORM: GPUFlagsConstant; + readonly STORAGE: GPUFlagsConstant; + readonly INDIRECT: GPUFlagsConstant; + readonly QUERY_RESOLVE: GPUFlagsConstant; +} + +declare var GPUBufferUsage: { + prototype: GPUBufferUsage; + readonly MAP_READ: GPUFlagsConstant; + readonly MAP_WRITE: GPUFlagsConstant; + readonly COPY_SRC: GPUFlagsConstant; + readonly COPY_DST: GPUFlagsConstant; + readonly INDEX: GPUFlagsConstant; + readonly VERTEX: GPUFlagsConstant; + readonly UNIFORM: GPUFlagsConstant; + readonly STORAGE: GPUFlagsConstant; + readonly INDIRECT: GPUFlagsConstant; + readonly QUERY_RESOLVE: GPUFlagsConstant; +}; + +interface GPUColorWrite { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUColorWrite'; + readonly RED: GPUFlagsConstant; + readonly GREEN: GPUFlagsConstant; + readonly BLUE: GPUFlagsConstant; + readonly ALPHA: GPUFlagsConstant; + readonly ALL: GPUFlagsConstant; +} + +declare var GPUColorWrite: { + prototype: GPUColorWrite; + readonly RED: GPUFlagsConstant; + readonly GREEN: GPUFlagsConstant; + readonly BLUE: GPUFlagsConstant; + readonly ALPHA: GPUFlagsConstant; + readonly ALL: GPUFlagsConstant; +}; + +interface GPUMapMode { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUMapMode'; + readonly READ: GPUFlagsConstant; + readonly WRITE: GPUFlagsConstant; +} + +declare var GPUMapMode: { + prototype: GPUMapMode; + new (): never; + readonly READ: GPUFlagsConstant; + readonly WRITE: GPUFlagsConstant; +}; + +interface GPUShaderStage { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUShaderStage'; + readonly VERTEX: GPUFlagsConstant; + readonly FRAGMENT: GPUFlagsConstant; + readonly COMPUTE: GPUFlagsConstant; +} + +declare var GPUShaderStage: { + prototype: GPUShaderStage; + readonly VERTEX: GPUFlagsConstant; + readonly FRAGMENT: GPUFlagsConstant; + readonly COMPUTE: GPUFlagsConstant; +}; + +interface GPUTextureUsage { + /** + * Nominal type branding. + * https://github.com/microsoft/TypeScript/pull/33038 + * @internal + */ + readonly __brand: 'GPUTextureUsage'; + readonly COPY_SRC: GPUFlagsConstant; + readonly COPY_DST: GPUFlagsConstant; + readonly TEXTURE_BINDING: GPUFlagsConstant; + readonly STORAGE_BINDING: GPUFlagsConstant; + readonly RENDER_ATTACHMENT: GPUFlagsConstant; +} + +declare var GPUTextureUsage: { + prototype: GPUTextureUsage; + readonly COPY_SRC: GPUFlagsConstant; + readonly COPY_DST: GPUFlagsConstant; + readonly TEXTURE_BINDING: GPUFlagsConstant; + readonly STORAGE_BINDING: GPUFlagsConstant; + readonly RENDER_ATTACHMENT: GPUFlagsConstant; +}; diff --git a/cc.config.json b/cc.config.json index 2580c47189..161e73f748 100644 --- a/cc.config.json +++ b/cc.config.json @@ -19,6 +19,11 @@ "gfx-empty": { "modules": ["gfx-empty"] }, + "gfx-webgpu": { + "modules": [ + "gfx-webgpu" + ] + }, "3d": { "modules": ["3d"], "dependentAssets": [ diff --git a/cocos/game/game.ts b/cocos/game/game.ts index 1c5b94da94..4bc45c4dff 100644 --- a/cocos/game/game.ts +++ b/cocos/game/game.ts @@ -109,15 +109,17 @@ export interface IGameConfig { * - 1 - 强制使用 canvas 渲染。 * - 2 - 强制使用 WebGL 渲染,但是在部分 Android 浏览器中这个选项会被忽略。 * - 3 - 使用空渲染器,可以用于测试和服务器端环境,目前暂时用于 Cocos 内部测试使用 + * - 4 - 强制使用 WebGPU 渲染,但是在部分浏览器中这个选项会被忽略 * @en * Sets the renderer type, only useful on web: * - 0 - Automatically chosen by engine. * - 1 - Forced to use canvas renderer. * - 2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers. * - 3 - Use Headless Renderer, which is useful in test or server env, only for internal use by cocos team for now + * - 4 - Force WebGPU rendering, but this option will be ignored in some browsers. * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.RENDERING: { "renderMode": 0 }}``` to set this. */ - renderMode?: 0 | 1 | 2 | 3; + renderMode?: 0 | 1 | 2 | 3 | 4; /** * @en @@ -748,7 +750,8 @@ export class Game extends EventTarget { this.emit(Game.EVENT_PRE_INFRASTRUCTURE_INIT); return this.onPreInfrastructureInitDelegate.dispatch(); }) - .then((): void => { + // gfx init + .then((): boolean | Promise => { if (DEBUG) { // eslint-disable-next-line no-console console.time('Init Infrastructure'); @@ -763,8 +766,9 @@ export class Game extends EventTarget { } screen.init(); garbageCollectionManager.init(); - deviceManager.init(this.canvas, bindingMappingInfo); - + return deviceManager.init(this.canvas, bindingMappingInfo); + }) + .then(() => { const renderPipelineUuid = settings.querySettings(Settings.Category.RENDERING, 'renderPipeline') as string; if (renderPipelineUuid === 'ca127c79-69d6-4afd-8183-d712d7b80e14') { if (!macro.CUSTOM_PIPELINE_NAME) { diff --git a/cocos/game/splash-screen.ts b/cocos/game/splash-screen.ts index 480f1c3895..b7a6ab56bc 100644 --- a/cocos/game/splash-screen.ts +++ b/cocos/game/splash-screen.ts @@ -29,11 +29,14 @@ import { Sampler, SamplerInfo, Shader, Texture, TextureInfo, Device, InputAssembler, InputAssemblerInfo, Attribute, Buffer, BufferInfo, Rect, Color, BufferTextureCopy, CommandBuffer, BufferUsageBit, Format, MemoryUsageBit, TextureType, TextureUsageBit, Address, Swapchain, Framebuffer, + DescriptorSetInfo, + DescriptorSet, } from '../gfx'; import { PipelineStateManager } from '../rendering'; import { SetIndex } from '../rendering/define'; import { ccwindow, legacyCC } from '../core/global-exports'; import { XREye } from '../xr/xr-enums'; +import { PipelineRuntime } from '../rendering/custom'; const v2_0 = new Vec2(); type SplashLogoType = 'default' | 'none' | 'custom'; @@ -61,7 +64,7 @@ interface SplashLogo { image?: string; base64?: string; } - +const _dsInfo = new DescriptorSetInfo(null!); export class SplashScreen { private settings!: ISplashSetting; private _curTime = 0; @@ -377,7 +380,6 @@ export class SplashScreen { const descriptorSet = pass.descriptorSet; descriptorSet.bindSampler(binding, this.sampler); descriptorSet.update(); - const region = new BufferTextureCopy(); region.texExtent.width = this.bgImage.width; region.texExtent.height = this.bgImage.height; @@ -412,7 +414,6 @@ export class SplashScreen { const descriptorSet = pass.descriptorSet; descriptorSet.bindSampler(binding, this.sampler); descriptorSet.update(); - const region = new BufferTextureCopy(); region.texExtent.width = this.logoImage.width; region.texExtent.height = this.logoImage.height; @@ -524,7 +525,7 @@ export class SplashScreen { cmdBuff.begin(); cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors, 1.0, 0); - + const pipeline = cclegacy.director.root.pipeline as PipelineRuntime; if (this.settings.background!.type === 'custom') { const bgPass = this.bgMat.passes[0]; const bgPso = PipelineStateManager.getOrCreatePipelineState( @@ -536,6 +537,7 @@ export class SplashScreen { ); cmdBuff.bindPipelineState(bgPso); + cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, bgPass.descriptorSet); cmdBuff.bindInputAssembler(this.quadAssmebler); cmdBuff.draw(this.quadAssmebler); @@ -552,6 +554,7 @@ export class SplashScreen { ); cmdBuff.bindPipelineState(logoPso); + cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, logoPass.descriptorSet); cmdBuff.bindInputAssembler(this.quadAssmebler); cmdBuff.draw(this.quadAssmebler); @@ -568,6 +571,7 @@ export class SplashScreen { ); cmdBuff.bindPipelineState(watermarkPso); + cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, wartermarkPass.descriptorSet); cmdBuff.bindInputAssembler(this.quadAssmebler); cmdBuff.draw(this.quadAssmebler); diff --git a/cocos/gfx/base/define.ts b/cocos/gfx/base/define.ts index 176b91f85e..1e6f584380 100644 --- a/cocos/gfx/base/define.ts +++ b/cocos/gfx/base/define.ts @@ -2471,3 +2471,7 @@ export function formatAlignment (format: Format): FormatAlignment { export function alignTo (size: number, alignment: number): number { return Math.ceil(size / alignment) * alignment; } + +declare interface GPUTexture {} + +export type TextureHandle = GPUTexture | number; diff --git a/cocos/gfx/base/device.ts b/cocos/gfx/base/device.ts index ff4f113b59..c9da24b0f8 100644 --- a/cocos/gfx/base/device.ts +++ b/cocos/gfx/base/device.ts @@ -161,7 +161,7 @@ export abstract class Device { public static canvas: HTMLCanvasElement; // Hack for WebGL device initialization process - public abstract initialize (info: Readonly): boolean; + public abstract initialize (info: Readonly): boolean | Promise; public abstract destroy (): void; @@ -358,7 +358,9 @@ export abstract class Device { * @zh 是否开启自动GFX内部barrier推导,web无影响。 * @param format The GFX format to be queried. */ - public enableAutoBarrier (en: boolean): void {} + public enableAutoBarrier (en: boolean): void { + // noop + } /** * @en Get maximum supported sample count. diff --git a/cocos/gfx/base/texture.ts b/cocos/gfx/base/texture.ts index 0e3efe8239..81d4e10a79 100644 --- a/cocos/gfx/base/texture.ts +++ b/cocos/gfx/base/texture.ts @@ -33,6 +33,7 @@ import { TextureInfo, TextureViewInfo, ISwapchainTextureInfo, + TextureHandle, } from './define'; /** @@ -167,7 +168,7 @@ export abstract class Texture extends GFXObject { public abstract destroy (): void; - public abstract getGLTextureHandle (): number; + public abstract getTextureHandle (): TextureHandle; /** * @en Resize texture. diff --git a/cocos/gfx/device-manager.ts b/cocos/gfx/device-manager.ts index 2db9c1c60a..69e78f9151 100644 --- a/cocos/gfx/device-manager.ts +++ b/cocos/gfx/device-manager.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ -import { JSB, WEBGPU } from 'internal:constants'; +import { EDITOR, JSB, WEBGPU } from 'internal:constants'; import { cclegacy, error, getError, sys, screen, Settings, settings } from '../core'; import { BindingMappingInfo, DeviceInfo, SwapchainInfo } from './base/define'; import { Device } from './base/device'; @@ -67,7 +67,14 @@ export enum LegacyRenderMode { * @zh * 使用空渲染器,可以用于测试和服务器端环境,目前暂时用于 Cocos 内部测试使用。 */ - HEADLESS = 3 + HEADLESS = 3, + /** + * @en + * Force WebGPU rendering, but this option will be ignored in some browsers. + * @zh + * 强制使用 WebGPU 渲染,但是在部分浏览器中这个选项会被忽略。 + */ + WEBGPU = 4, } /** @@ -77,8 +84,9 @@ export enum RenderType { UNKNOWN = -1, CANVAS = 0, WEBGL = 1, - OPENGL = 2, - HEADLESS = 3, + WEBGPU = 2, + OPENGL = 3, + HEADLESS = 4, } /** @@ -91,7 +99,7 @@ export class DeviceManager { private _canvas: HTMLCanvasElement | null = null; private _swapchain!: Swapchain; private _renderType: RenderType = RenderType.UNKNOWN; - + private _deviceInitialized = false; public get gfxDevice (): Device { return this._gfxDevice; } @@ -100,18 +108,46 @@ export class DeviceManager { return this._swapchain; } - public init (canvas: HTMLCanvasElement | null, bindingMappingInfo: BindingMappingInfo): void { + private _tryInitializeWebGPUDevice (DeviceConstructor, info: DeviceInfo): Promise { + if (this._deviceInitialized) { + return Promise.resolve(true); + } + if (DeviceConstructor) { + this._gfxDevice = new DeviceConstructor(); + return new Promise((resolve, reject) => { + (this._gfxDevice.initialize(info) as Promise).then((val) => { + this._deviceInitialized = val; + resolve(val); + }).catch((err) => { + reject(err); + }); + }); + } + return Promise.resolve(false); + } + + private _tryInitializeDeviceSync (DeviceConstructor, info: DeviceInfo): boolean { + if (this._deviceInitialized) { + return true; + } + if (DeviceConstructor) { + this._gfxDevice = new DeviceConstructor(); + this._deviceInitialized = this._gfxDevice.initialize(info) as boolean; + } + return this._deviceInitialized; + } + + public init (canvas: HTMLCanvasElement | null, bindingMappingInfo: BindingMappingInfo): boolean | Promise { // Avoid setup to be called twice. - if (this.initialized) { return; } - const renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode'); + if (this.initialized) { return true; } + const renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode') as LegacyRenderMode; this._canvas = canvas; - + if (this._canvas) { this._canvas.oncontextmenu = (): boolean => false; } this._renderType = this._determineRenderType(renderMode); - - // WebGL context created successfully - if (this._renderType === RenderType.WEBGL) { - const deviceInfo = new DeviceInfo(bindingMappingInfo); - + this._deviceInitialized = false; + const deviceInfo = new DeviceInfo(bindingMappingInfo); + // WebGL or WebGPU context created successfully + if (this._renderType === RenderType.WEBGL || this._renderType === RenderType.WEBGPU) { if (JSB && (globalThis as any).gfx) { this._gfxDevice = gfx.DeviceManager.create(deviceInfo); } else { @@ -121,31 +157,30 @@ export class DeviceManager { if (sys.browserType === BrowserType.UC) { useWebGL2 = false; } - - const deviceCtors: Constructor[] = []; - if (WEBGPU) { - deviceCtors.push(cclegacy.WebGPUDevice); + Device.canvas = canvas!; + if (this._renderType === RenderType.WEBGPU) { + return new Promise((resolve, reject) => { + this._tryInitializeWebGPUDevice(cclegacy.WebGPUDevice, deviceInfo).then((val) => { + this._initSwapchain(); + resolve(val); + }).catch((err) => { + reject(err); + }); + }); } if (useWebGL2 && cclegacy.WebGL2Device) { - deviceCtors.push(cclegacy.WebGL2Device); + this._tryInitializeDeviceSync(cclegacy.WebGL2Device, deviceInfo); } if (cclegacy.WebGLDevice) { - deviceCtors.push(cclegacy.WebGLDevice); + this._tryInitializeDeviceSync(cclegacy.WebGLDevice, deviceInfo); } if (cclegacy.EmptyDevice) { - deviceCtors.push(cclegacy.EmptyDevice); - } - - Device.canvas = canvas!; - for (let i = 0; i < deviceCtors.length; i++) { - this._gfxDevice = new deviceCtors[i](); - if (this._gfxDevice.initialize(deviceInfo)) { break; } + this._tryInitializeDeviceSync(cclegacy.EmptyDevice, deviceInfo); } this._initSwapchain(); } } else if (this._renderType === RenderType.HEADLESS && cclegacy.EmptyDevice) { - this._gfxDevice = new cclegacy.EmptyDevice(); - this._gfxDevice.initialize(new DeviceInfo(bindingMappingInfo)); + this._tryInitializeDeviceSync(cclegacy.EmptyDevice, deviceInfo); this._initSwapchain(); } @@ -153,10 +188,9 @@ export class DeviceManager { // todo fix here for wechat game error('can not support canvas rendering in 3D'); this._renderType = RenderType.UNKNOWN; - return; + return false; } - - if (this._canvas) { this._canvas.oncontextmenu = (): boolean => false; } + return true; } private _initSwapchain (): void { @@ -167,8 +201,12 @@ export class DeviceManager { this._swapchain = this._gfxDevice.createSwapchain(swapchainInfo); } + private _supportWebGPU (): boolean { + return 'gpu' in navigator; + } + private _determineRenderType (renderMode: LegacyRenderMode): RenderType { - if (typeof renderMode !== 'number' || renderMode > RenderType.HEADLESS || renderMode < LegacyRenderMode.AUTO) { + if (typeof renderMode !== 'number' || renderMode > LegacyRenderMode.WEBGPU || renderMode < LegacyRenderMode.AUTO) { renderMode = LegacyRenderMode.AUTO; } // Determine RenderType @@ -178,7 +216,10 @@ export class DeviceManager { if (renderMode === LegacyRenderMode.CANVAS) { renderType = RenderType.CANVAS; supportRender = true; - } else if (renderMode === LegacyRenderMode.AUTO || renderMode === LegacyRenderMode.WEBGL) { + } else if (renderMode === LegacyRenderMode.AUTO || renderMode === LegacyRenderMode.WEBGPU) { + renderType = (this._supportWebGPU() && !EDITOR) ? RenderType.WEBGPU : RenderType.WEBGL; + supportRender = true; + } else if (renderMode === LegacyRenderMode.WEBGL) { renderType = RenderType.WEBGL; supportRender = true; } else if (renderMode === LegacyRenderMode.HEADLESS) { diff --git a/cocos/gfx/empty/empty-device.ts b/cocos/gfx/empty/empty-device.ts index b0465f8de6..7da46c3210 100644 --- a/cocos/gfx/empty/empty-device.ts +++ b/cocos/gfx/empty/empty-device.ts @@ -91,9 +91,15 @@ export class EmptyDevice extends Device { this._swapchain = null; } - public flushCommands (cmdBuffs: Readonly): void {} - public acquire (swapchains: Readonly): void {} - public present (): void {} + public flushCommands (cmdBuffs: Readonly): void { + // noop + } + public acquire (swapchains: Readonly): void { + // noop + } + public present (): void { + // noop + } public createCommandBuffer (info: Readonly): CommandBuffer { const cmdBuff = new EmptyCommandBuffer(); @@ -210,9 +216,15 @@ export class EmptyDevice extends Device { return this._bufferBarriers.get(hash)!; } - public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void {} - public copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: Readonly): void {} - public copyTexImagesToTexture (texImages: Readonly, texture: Texture, regions: Readonly): void {} + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void { + // noop + } + public copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: Readonly): void { + // noop + } + public copyTexImagesToTexture (texImages: Readonly, texture: Texture, regions: Readonly): void { + // noop + } } cclegacy.EmptyDevice = EmptyDevice; diff --git a/cocos/gfx/empty/empty-texture.ts b/cocos/gfx/empty/empty-texture.ts index 6b1eb316c6..fc802637c5 100644 --- a/cocos/gfx/empty/empty-texture.ts +++ b/cocos/gfx/empty/empty-texture.ts @@ -51,7 +51,7 @@ export class EmptyTexture extends Texture { } public destroy (): void {} - public getGLTextureHandle (): number { + public getTextureHandle (): number { return 0; } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 6367e870c8..531974d410 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -61,7 +61,7 @@ import { WebGLCmdFuncCopyBuffersToTexture, WebGLCmdFuncCopyTextureToBuffers, Web import { GeneralBarrier } from '../base/states/general-barrier'; import { TextureBarrier } from '../base/states/texture-barrier'; import { BufferBarrier } from '../base/states/buffer-barrier'; -import { debug } from '../../core'; +import { debug, error } from '../../core'; import { Swapchain } from '../base/swapchain'; import { IWebGLExtensions, WebGLDeviceManager } from './webgl-define'; import { IWebGLBindingMapping, IWebGLBlitManager } from './webgl-gpu-objects'; @@ -137,7 +137,7 @@ export class WebGLDevice extends Device { const gl = this._context = getContext(Device.canvas); if (!gl) { - console.error('This device does not support WebGL.'); + error('This device does not support WebGL.'); return false; } @@ -244,9 +244,13 @@ export class WebGLDevice extends Device { this._swapchain = null; } - public flushCommands (cmdBuffs: CommandBuffer[]): void {} + public flushCommands (cmdBuffs: CommandBuffer[]): void { + // noop + } - public acquire (swapchains: Swapchain[]): void {} + public acquire (swapchains: Swapchain[]): void { + // noop + } public present (): void { const queue = (this._queue as WebGLQueue); diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/gfx/webgl/webgl-texture.ts index ef16fbd24e..86d18a2442 100644 --- a/cocos/gfx/webgl/webgl-texture.ts +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -52,8 +52,13 @@ export class WebGLTexture extends Texture { this._info.copy(texInfo); this._isPowerOf2 = IsPowerOf2(this._info.width) && IsPowerOf2(this._info.height); - this._size = FormatSurfaceSize(this._info.format, this.width, this.height, - this.depth, this._info.levelCount) * this._info.layerCount; + this._size = FormatSurfaceSize( + this._info.format, + this.width, + this.height, + this.depth, + this._info.levelCount, + ) * this._info.layerCount; if (!this._isTextureView) { this._gpuTexture = { @@ -112,7 +117,7 @@ export class WebGLTexture extends Texture { } } - public getGLTextureHandle () : number { + public getTextureHandle (): number { const gpuTexture = this._gpuTexture; if (!gpuTexture) { return 0; @@ -142,8 +147,13 @@ export class WebGLTexture extends Texture { this._info.width = width; this._info.height = height; - this._size = FormatSurfaceSize(this._info.format, this.width, this.height, - this.depth, this._info.levelCount) * this._info.layerCount; + this._size = FormatSurfaceSize( + this._info.format, + this.width, + this.height, + this.depth, + this._info.levelCount, + ) * this._info.layerCount; if (!this._isTextureView && this._gpuTexture) { this._gpuTexture.width = width; diff --git a/cocos/gfx/webgl2/webgl2-command-buffer.ts b/cocos/gfx/webgl2/webgl2-command-buffer.ts index c4810681b6..84a3f6bdd0 100644 --- a/cocos/gfx/webgl2/webgl2-command-buffer.ts +++ b/cocos/gfx/webgl2/webgl2-command-buffer.ts @@ -414,10 +414,13 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public pipelineBarrier (GeneralBarrier: Readonly, bufferBarriers?: Readonly, + public pipelineBarrier ( + GeneralBarrier: Readonly, + bufferBarriers?: Readonly, buffers?: Readonly, textureBarriers?: Readonly, - textures?: Readonly): void {} + textures?: Readonly, + ): void {} protected bindStates (): void { const bindStatesCmd = this._cmdAllocator.bindStatesCmdPool.alloc(WebGL2CmdBindStates); diff --git a/cocos/gfx/webgl2/webgl2-device.ts b/cocos/gfx/webgl2/webgl2-device.ts index c46c3e6539..f67d996a60 100644 --- a/cocos/gfx/webgl2/webgl2-device.ts +++ b/cocos/gfx/webgl2/webgl2-device.ts @@ -62,7 +62,7 @@ import { WebGL2CmdFuncCopyTextureToBuffers, WebGL2CmdFuncCopyBuffersToTexture, W import { GeneralBarrier } from '../base/states/general-barrier'; import { TextureBarrier } from '../base/states/texture-barrier'; import { BufferBarrier } from '../base/states/buffer-barrier'; -import { debug, sys } from '../../core'; +import { debug, error, sys } from '../../core'; import { Swapchain } from '../base/swapchain'; import { IWebGL2Extensions, WebGL2DeviceManager } from './webgl2-define'; import { IWebGL2BindingMapping, IWebGL2BlitManager } from './webgl2-gpu-objects'; @@ -139,7 +139,7 @@ export class WebGL2Device extends Device { const gl = this._context = getContext(Device.canvas); if (!gl) { - console.error('This device does not support WebGL2.'); + error('This device does not support WebGL2.'); return false; } @@ -254,9 +254,13 @@ export class WebGL2Device extends Device { this._swapchain = null; } - public flushCommands (cmdBuffs: Readonly): void {} + public flushCommands (cmdBuffs: Readonly): void { + // noop + } - public acquire (swapchains: Readonly): void {} + public acquire (swapchains: Readonly): void { + // noop + } public present (): void { const queue = (this._queue as WebGL2Queue); diff --git a/cocos/gfx/webgl2/webgl2-swapchain.ts b/cocos/gfx/webgl2/webgl2-swapchain.ts index 6b499933e5..3bef1a4116 100644 --- a/cocos/gfx/webgl2/webgl2-swapchain.ts +++ b/cocos/gfx/webgl2/webgl2-swapchain.ts @@ -248,7 +248,8 @@ export class WebGL2Swapchain extends Swapchain { nullTexRegion.texSubres.layerCount = 6; WebGL2DeviceManager.instance.copyBuffersToTexture( [nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff], - this.nullTexCube, [nullTexRegion], + this.nullTexCube, + [nullTexRegion], ); this._blitManager = new IWebGL2BlitManager(); diff --git a/cocos/gfx/webgl2/webgl2-texture.ts b/cocos/gfx/webgl2/webgl2-texture.ts index 824e3c2af7..3e37f77862 100644 --- a/cocos/gfx/webgl2/webgl2-texture.ts +++ b/cocos/gfx/webgl2/webgl2-texture.ts @@ -55,8 +55,13 @@ export class WebGL2Texture extends Texture { this._info.copy(texInfo); this._isPowerOf2 = IsPowerOf2(this._info.width) && IsPowerOf2(this._info.height); - this._size = FormatSurfaceSize(this._info.format, this.width, this.height, - this.depth, this._info.levelCount) * this._info.layerCount; + this._size = FormatSurfaceSize( + this._info.format, + this.width, + this.height, + this.depth, + this._info.levelCount, + ) * this._info.layerCount; if (!this._isTextureView) { this._gpuTexture = { @@ -135,7 +140,7 @@ export class WebGL2Texture extends Texture { } } - public getGLTextureHandle () : number { + public getTextureHandle (): number { const gpuTexture = this._gpuTexture; if (!gpuTexture) { return 0; @@ -164,8 +169,13 @@ export class WebGL2Texture extends Texture { const oldSize = this._size; this._info.width = width; this._info.height = height; - this._size = FormatSurfaceSize(this._info.format, this.width, this.height, - this.depth, this._info.levelCount) * this._info.layerCount; + this._size = FormatSurfaceSize( + this._info.format, + this.width, + this.height, + this.depth, + this._info.levelCount, + ) * this._info.layerCount; if (!this._isTextureView && this._gpuTexture) { this._gpuTexture.width = width; diff --git a/cocos/gfx/webgpu/define.ts b/cocos/gfx/webgpu/define.ts new file mode 100644 index 0000000000..34725ed8c3 --- /dev/null +++ b/cocos/gfx/webgpu/define.ts @@ -0,0 +1,93 @@ +/* + Copyright (c) 2024 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. +*/ + +import { DescriptorSet } from '../base/descriptor-set'; +import { DescriptorSetLayout } from '../base/descriptor-set-layout'; +import { WebGPUBuffer } from './webgpu-buffer'; +import { WebGPUDevice } from './webgpu-device'; +import { WebGPUSampler } from './webgpu-sampler'; +import { WebGPUTexture } from './webgpu-texture'; + +export class WebGPUDeviceManager { + static get instance (): WebGPUDevice { + return WebGPUDeviceManager._instance!; + } + static setInstance (instance: WebGPUDevice): void { + WebGPUDeviceManager._instance = instance; + } + private static _instance: WebGPUDevice | null = null; +} + +function hashCombine (hash, currHash: number): number { + return currHash ^= (hash >>> 0) + 0x9e3779b9 + (currHash << 6) + (currHash >> 2); +} + +export function hashCombineNum (val: number, currHash: number): number { + const hash = 5381; + return hashCombine((hash * 33) ^ val, currHash); +} + +export function hashCombineStr (str: string, currHash: number): number { + // DJB2 HASH + let hash = 5381; + const strLength = str.length; + for (let i = 0; i < strLength; i++) { + hash = (hash * 33) ^ str.charCodeAt(i); + } + return hashCombine(hash, currHash); +} + +export class DefaultResources { + // hash, targetResource + buffersDescLayout: Map = new Map(); + texturesDescLayout: Map = new Map(); + samplersDescLayout: Map = new Map(); + buffer!: WebGPUBuffer; + texture!: WebGPUTexture; + sampler!: WebGPUSampler; + setLayout!: DescriptorSetLayout; + descSet!: DescriptorSet; +} + +export function isBound (binds: number[], compares: number[]): boolean { + return binds.length === compares.length && binds.every((bind) => compares.includes(bind)); +} + +export function copyNumbersToTarget (source: number[], target: number[], start: number, count: number): void { + // Check that the source array is out of range + if (start + count > source.length) { + throw new Error('Source array is out of bounds'); + } + // Check whether the target array is out of range + if (start + count > target.length) { + target.length = start + count; + } + const sliceToCopy = source.slice(start, start + count); + target.splice(start, count, ...sliceToCopy); +} + +export enum DescUpdateFrequency { + LOW, + NORMAL, +} diff --git a/cocos/gfx/webgpu/webgpu-buffer.ts b/cocos/gfx/webgpu/webgpu-buffer.ts new file mode 100644 index 0000000000..85581d7771 --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-buffer.ts @@ -0,0 +1,186 @@ +/* + Copyright (c) 2024 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. +*/ + +import { warn } from '../../core'; +import { Buffer } from '../base/buffer'; + +import { + BufferUsageBit, + IndirectBuffer, + BufferSource, + BufferInfo, + BufferViewInfo, +} from '../base/define'; +import { WebGPUDeviceManager } from './define'; +import { + WebGPUCmdFuncCreateBuffer, + WebGPUCmdFuncDestroyBuffer, + WebGPUCmdFuncResizeBuffer, + WebGPUCmdFuncUpdateBuffer, +} from './webgpu-commands'; +import { IWebGPUGPUBuffer as IWebGPUBuffer } from './webgpu-gpu-objects'; + +export class WebGPUBuffer extends Buffer { + get gpuBuffer (): IWebGPUBuffer { + return this._gpuBuffer!; + } + + private _gpuBuffer: IWebGPUBuffer | null = null; + private _indirectBuffer: IndirectBuffer | null = null; + private _hasChange: boolean = false; + get hasChange (): boolean { + return this._hasChange; + } + public resetChange (): void { + this._hasChange = false; + } + public initialize (info: Readonly | Readonly): void { + if ('buffer' in info) { // buffer view + // validate: webGPU buffer offset must be 256 bytes aligned + // which can be guaranteed by WebGPUDevice::uboOffsetAligned + this._isBufferView = true; + + const buffer = info.buffer as WebGPUBuffer; + + this._usage = buffer.usage; + this._memUsage = buffer.memUsage; + this._size = this._stride = Math.ceil(info.range / 4.0) * 4; + this._count = 1; + this._flags = buffer.flags; + + this._gpuBuffer = { + usage: this._usage, + memUsage: this._memUsage, + size: this._size, + stride: this._stride, + buffer: null, + indirects: buffer.gpuBuffer.indirects, + gpuTarget: buffer.gpuBuffer.gpuTarget, + gpuBuffer: buffer.gpuBuffer.gpuBuffer, + gpuOffset: info.offset, + flags: this._flags, + drawIndirectByIndex: false, + }; + } else { // native buffer + this._usage = info.usage; + this._memUsage = info.memUsage; + this._size = Math.ceil(info.size / 4.0) * 4; + this._stride = Math.max(info.stride || this._size, 1); + this._count = this._size / this._stride; + this._flags = info.flags; + + if (this._usage & BufferUsageBit.INDIRECT) { + this._indirectBuffer = new IndirectBuffer(); + } + + this._gpuBuffer = { + usage: this._usage, + memUsage: this._memUsage, + size: this._size, + stride: this._stride, + buffer: null, + indirects: [], + gpuTarget: 0, + flags: this._flags, + gpuBuffer: null, + gpuOffset: 0, + drawIndirectByIndex: false, + }; + + if (info.usage & BufferUsageBit.INDIRECT) { + this._gpuBuffer.indirects = this._indirectBuffer!.drawInfos; + } + const device = WebGPUDeviceManager.instance; + WebGPUCmdFuncCreateBuffer(device, this._gpuBuffer); + + device.memoryStatus.bufferSize += this._size; + } + } + + public destroy (): void { + if (this._gpuBuffer) { + if (!this._isBufferView) { + const device = WebGPUDeviceManager.instance; + WebGPUCmdFuncDestroyBuffer(device, this._gpuBuffer); + device.memoryStatus.bufferSize -= this._size; + } + this._hasChange = true; + this._gpuBuffer = null; + } + } + + public resize (size: number): void { + if (this._isBufferView) { + warn('cannot resize buffer views!'); + return; + } + + const oldSize = this._size; + if (oldSize === size) { return; } + + this._size = size; + this._count = this._size / this._stride; + this._hasChange = true; + if (this._gpuBuffer) { + this._gpuBuffer.size = this._size; + if (this._size > 0) { + const device = WebGPUDeviceManager.instance; + WebGPUCmdFuncResizeBuffer(device, this._gpuBuffer); + device.memoryStatus.bufferSize -= oldSize; + device.memoryStatus.bufferSize += this._size; + } + } + } + + public update (buffer: BufferSource, size?: number): void { + if (this._isBufferView) { + warn('cannot update through buffer views!'); + return; + } + + let buffSize: number; + if (size !== undefined) { + buffSize = size; + } else if (this._usage & BufferUsageBit.INDIRECT) { + buffSize = 0; + } else { + buffSize = (buffer as ArrayBuffer).byteLength; + } + // Make sure buffSize is a multiple of 4 + buffSize = Math.ceil(buffSize / 4.0) * 4; + if (this.size < buffSize) { + this.resize(buffSize); + } + this._hasChange = true; + const device = WebGPUDeviceManager.instance; + + WebGPUCmdFuncUpdateBuffer( + device, + this._gpuBuffer!, + buffer, + 0, + buffSize, + ); + } +} diff --git a/cocos/gfx/webgpu/webgpu-command-allocator.ts b/cocos/gfx/webgpu/webgpu-command-allocator.ts new file mode 100644 index 0000000000..169c9f7560 --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-command-allocator.ts @@ -0,0 +1,151 @@ +/* + Copyright (c) 2024 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. +*/ + +import { CachedArray } from '../../core/memop/cached-array'; +import { + WebGPUCmdBeginRenderPass, + WebGPUCmdBindStates, + WebGPUCmdCopyBufferToTexture, + WebGPUCmdDraw, + WebGPUCmdObject, + WebGPUCmdPackage, + WebGPUCmdUpdateBuffer, +} from './webgpu-commands'; + +export class WebGPUCommandPool { + private _frees: (T | null)[]; + private _freeIdx: number = 0; + private _freeCmds: CachedArray; + + constructor (Clazz: new() => T, count: number) { + this._frees = new Array(count); + this._freeCmds = new CachedArray(count); + for (let i = 0; i < count; ++i) { + this._frees[i] = new Clazz(); + } + this._freeIdx = count - 1; + } + + public alloc (Clazz: new() => T): T { + if (this._freeIdx < 0) { + const size = this._frees.length * 2; + const temp = this._frees; + this._frees = new Array(size); + + const increase = size - temp.length; + for (let i = 0; i < increase; ++i) { + this._frees[i] = new Clazz(); + } + + for (let i = increase, j = 0; i < size; ++i, ++j) { + this._frees[i] = temp[j]; + } + + this._freeIdx += increase; + } + + const cmd = this._frees[this._freeIdx]!; + this._frees[this._freeIdx--] = null; + ++cmd.refCount; + return cmd; + } + + public free (cmd: T): void { + if (--cmd.refCount === 0) { + this._freeCmds.push(cmd); + } + } + + public freeCmds (cmds: CachedArray): void { + const cmdLength = cmds.length; + for (let i = 0; i < cmdLength; ++i) { + if (--cmds.array[i].refCount === 0) { + this._freeCmds.push(cmds.array[i]); + } + } + } + + public release (): void { + const freeCmdLength = this._freeCmds.length; + for (let i = 0; i < freeCmdLength; ++i) { + const cmd = this._freeCmds.array[i]; + cmd.clear(); + this._frees[++this._freeIdx] = cmd; + } + this._freeCmds.clear(); + } +} + +export class WebGPUCommandAllocator { + public beginRenderPassCmdPool: WebGPUCommandPool; + public bindStatesCmdPool: WebGPUCommandPool; + public drawCmdPool: WebGPUCommandPool; + public updateBufferCmdPool: WebGPUCommandPool; + public copyBufferToTextureCmdPool: WebGPUCommandPool; + + constructor () { + this.beginRenderPassCmdPool = new WebGPUCommandPool(WebGPUCmdBeginRenderPass, 1); + this.bindStatesCmdPool = new WebGPUCommandPool(WebGPUCmdBindStates, 1); + this.drawCmdPool = new WebGPUCommandPool(WebGPUCmdDraw, 1); + this.updateBufferCmdPool = new WebGPUCommandPool(WebGPUCmdUpdateBuffer, 1); + this.copyBufferToTextureCmdPool = new WebGPUCommandPool(WebGPUCmdCopyBufferToTexture, 1); + } + + public clearCmds (cmdPackage: WebGPUCmdPackage): void { + if (cmdPackage.beginRenderPassCmds.length) { + this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds); + cmdPackage.beginRenderPassCmds.clear(); + } + + if (cmdPackage.bindStatesCmds.length) { + this.bindStatesCmdPool.freeCmds(cmdPackage.bindStatesCmds); + cmdPackage.bindStatesCmds.clear(); + } + + if (cmdPackage.drawCmds.length) { + this.drawCmdPool.freeCmds(cmdPackage.drawCmds); + cmdPackage.drawCmds.clear(); + } + + if (cmdPackage.updateBufferCmds.length) { + this.updateBufferCmdPool.freeCmds(cmdPackage.updateBufferCmds); + cmdPackage.updateBufferCmds.clear(); + } + + if (cmdPackage.copyBufferToTextureCmds.length) { + this.copyBufferToTextureCmdPool.freeCmds(cmdPackage.copyBufferToTextureCmds); + cmdPackage.copyBufferToTextureCmds.clear(); + } + + cmdPackage.cmds.clear(); + } + + public releaseCmds (): void { + this.beginRenderPassCmdPool.release(); + this.bindStatesCmdPool.release(); + this.drawCmdPool.release(); + this.updateBufferCmdPool.release(); + this.copyBufferToTextureCmdPool.release(); + } +} diff --git a/cocos/gfx/webgpu/webgpu-command-buffer.ts b/cocos/gfx/webgpu/webgpu-command-buffer.ts new file mode 100644 index 0000000000..571b41bc0c --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-command-buffer.ts @@ -0,0 +1,745 @@ +/* + Copyright (c) 2024 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. +*/ + +import { DescriptorSet } from '../base/descriptor-set'; +import { Buffer } from '../base/buffer'; +import { CommandBuffer } from '../base/command-buffer'; +import { + BufferUsageBit, + CommandBufferType, + LoadOp, + StencilFace, + StoreOp, + BufferSource, + DrawInfo, + CommandBufferInfo, + BufferTextureCopy, + Color, + Rect, + Viewport, + Filter, + TextureBlit, + ShaderStageFlagBit, +} from '../base/define'; +import { Framebuffer } from '../base/framebuffer'; +import { InputAssembler } from '../base/input-assembler'; +import { PipelineState } from '../base/pipeline-state'; +import { Texture } from '../base/texture'; +import { WebGPUDescriptorSet } from './webgpu-descriptor-set'; +import { WebGPUBuffer } from './webgpu-buffer'; +import { WebGPUCommandAllocator } from './webgpu-command-allocator'; +import { + clearRect, + WebGPUCmd, + WebGPUCmdCopyBufferToTexture, + WebGPUCmdPackage, + WebGPUCmdUpdateBuffer, +} from './webgpu-commands'; +import { WebGPUDevice } from './webgpu-device'; +import { WebGPUFramebuffer } from './webgpu-framebuffer'; +import { + IWebGPUGPUInputAssembler, + IWebGPUGPUDescriptorSet, + IWebGPUGPUPipelineState, + IWebGPUGPUPipelineLayout, + IWebGPUGPURenderPass, +} from './webgpu-gpu-objects'; +import { WebGPUInputAssembler } from './webgpu-input-assembler'; +import { WebGPUPipelineState } from './webgpu-pipeline-state'; +import { WebGPUTexture } from './webgpu-texture'; +import { RenderPass } from '../base/render-pass'; +import { WebGPURenderPass } from './webgpu-render-pass'; +import { INT_MAX } from '../../core/math/bits'; +import { GeneralBarrier } from '../base/states/general-barrier'; +import { TextureBarrier } from '../base/states/texture-barrier'; +import { BufferBarrier } from '../base/states/buffer-barrier'; +import { DescUpdateFrequency, WebGPUDeviceManager } from './define'; +import { WebGPUSwapchain } from './webgpu-swapchain'; +import { WebGPUPipelineLayout } from './webgpu-pipeline-layout'; +import { WebGPUDescriptorSetLayout } from './webgpu-descriptor-set-layout'; +import { error } from '../../core'; + +export interface IWebGPUDepthBias { + constantFactor: number; + clamp: number; + slopeFactor: number; +} + +export interface IWebGPUDepthBounds { + minBounds: number; + maxBounds: number; +} + +export interface IWebGPUStencilWriteMask { + face: StencilFace; + writeMask: number; +} + +export interface IWebGPUStencilCompareMask { + face: StencilFace; + reference: number; + compareMask: number; +} + +interface CommandEncoder { commandEncoder: GPUCommandEncoder, renderPassEncoder: GPURenderPassEncoder } +let currPipelineState: WebGPUPipelineState | null = null; +const descriptorSets: WebGPUDescriptorSet[] = []; +const renderAreas: Rect[] = []; +export class WebGPUCommandBuffer extends CommandBuffer { + public pipelineBarrier ( + barrier: Readonly | null, + bufferBarriers?: readonly BufferBarrier[] | undefined, + buffers?: readonly Buffer[] | undefined, + textureBarriers?: readonly TextureBarrier[] | undefined, + textures?: readonly Texture[] | undefined, + ): void { + throw new Error('Method not implemented.'); + } + public blitTexture (srcTexture: Readonly, dstTexture: Texture, regions: readonly TextureBlit[], filter: Filter): void { + throw new Error('Method not implemented.'); + } + + public cmdPackage: WebGPUCmdPackage = new WebGPUCmdPackage(); + protected _webGPUAllocator: WebGPUCommandAllocator | null = null; + protected _isInRenderPass = false; + protected _curGPUPipelineState: IWebGPUGPUPipelineState | null = null; + protected _curWebGPUPipelineState: WebGPUPipelineState | null = null; + protected _curGPUDescriptorSets: IWebGPUGPUDescriptorSet[] = []; + protected _curGPUInputAssembler: IWebGPUGPUInputAssembler | null = null; + protected _curDynamicOffsets: number[][] = []; + protected _curViewport: Viewport | null = null; + protected _curScissor: Rect | null = null; + protected _curLineWidth: number | null = null; + protected _curDepthBias: IWebGPUDepthBias | null = null; + protected _curBlendConstants: number[] = []; + protected _curDepthBounds: IWebGPUDepthBounds | null = null; + protected _curStencilWriteMask: IWebGPUStencilWriteMask | null = null; + protected _curStencilCompareMask: IWebGPUStencilCompareMask | null = null; + protected _isStateValid = false; + protected _globalDescriptors: WebGPUDescriptorSet[] = []; + + private _nativeCommandBuffer: GPUCommandBuffer | null = null; + private _encoder: CommandEncoder | undefined = undefined; + private _descSetDirtyIndex: number = INT_MAX; + private _nativePassDesc: GPURenderPassDescriptor | null = null; + private _wgpuRenderPass!: WebGPURenderPass; + + private _renderPassFuncQueue: ((renPassEncoder: GPURenderPassEncoder) => void)[] = []; + + public initialize (info: CommandBufferInfo): boolean { + this._type = info.type; + this._queue = info.queue; + const device = WebGPUDeviceManager.instance; + this._webGPUAllocator = device.cmdAllocator; + this._encoder = {} as CommandEncoder; + + const setCount = device.bindingMappings.blockOffsets.length; + for (let i = 0; i < setCount; i++) { + this._curGPUDescriptorSets.push(null!); + this._curDynamicOffsets.push([]); + } + + return true; + } + + public destroy (): void { + if (this._webGPUAllocator) { + this._webGPUAllocator.clearCmds(this.cmdPackage); + this._webGPUAllocator = null; + } + } + + public begin (renderPass?: RenderPass, subpass?: number, frameBuffer?: Framebuffer): void { + this._webGPUAllocator!.clearCmds(this.cmdPackage); + renderAreas.length = 0; + this._curGPUPipelineState = null; + this._curGPUInputAssembler = null; + this._curGPUDescriptorSets.length = 0; + const dynamicOffsetSize = this._curDynamicOffsets.length; + for (let i = 0; i < dynamicOffsetSize; i++) { + this._curDynamicOffsets[i].length = 0; + } + this._curViewport = null; + this._curScissor = null; + this._curLineWidth = null; + this._curDepthBias = null; + this._curBlendConstants.length = 0; + this._curDepthBounds = null; + this._curStencilWriteMask = null; + this._curStencilCompareMask = null; + this._numDrawCalls = 0; + this._numInstances = 0; + this._numTris = 0; + } + + public end (): void { + this._isStateValid = false; + this._isInRenderPass = false; + } + + public beginRenderPass ( + renderPass: RenderPass, + framebuffer: Framebuffer, + renderArea: Rect, + clearColors: Color[], + clearDepth: number, + clearStencil: number, + ): void { + const device = WebGPUDeviceManager.instance; + const gpuDevice = device; + this._wgpuRenderPass = renderPass as WebGPURenderPass; + this._nativePassDesc = this._wgpuRenderPass.gpuRenderPass.nativeRenderPass!; + const originalRP = this._wgpuRenderPass.gpuRenderPass.originalRP!; + const gpuFramebuffer = (framebuffer as WebGPUFramebuffer).gpuFramebuffer; + renderAreas.push(renderArea); + let needPartialClear = false; + const renderingFullScreen = gpuFramebuffer.gpuColorTextures.every((val) => { + if (renderArea.x !== 0 || renderArea.y !== 0 || renderArea.width !== val.width || renderArea.height !== val.height) { + return false; + } + return true; + }); + const swapchain = gpuDevice.getSwapchains()[0] as WebGPUSwapchain; + const clearColorSize = clearColors.length; + for (let i = 0; i < clearColorSize; i++) { + const colorTex = gpuFramebuffer.isOffscreen ? gpuFramebuffer.gpuColorTextures[i].getTextureView() + : swapchain.colorGPUTextureView; + colorTex!.label = gpuFramebuffer.isOffscreen ? 'offscreen' : 'swapchain'; + if (!renderingFullScreen) { + needPartialClear = originalRP.colorAttachments[i].loadOp === 'clear'; + if (renderAreas.length > 1) { + this._nativePassDesc.colorAttachments[i].loadOp = 'load'; + } + } + this._nativePassDesc.colorAttachments[i].view = colorTex; + this._nativePassDesc.colorAttachments[i].clearValue = [clearColors[i].x, clearColors[i].y, clearColors[i].z, clearColors[i].w]; + } + + if (this._wgpuRenderPass.depthStencilAttachment) { + const tex = gpuFramebuffer.gpuDepthStencilTexture?.gpuTexture; + const depthTex = tex ? tex.createView() : swapchain.gpuDepthStencilTextureView; + const depthStencilAttachment = this._nativePassDesc.depthStencilAttachment!; + depthStencilAttachment.view = depthTex; + depthStencilAttachment.depthClearValue = clearDepth; + depthStencilAttachment.stencilClearValue = clearStencil; + } + + renderArea.x = Math.floor(renderArea.x); + renderArea.y = Math.floor(renderArea.y); + renderArea.width = Math.floor(renderArea.width); + renderArea.height = Math.floor(renderArea.height); + const vpfunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setViewport(renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.0, 1.0); + }; + const srfunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setScissorRect(renderArea.x, renderArea.y, renderArea.width, renderArea.height); + }; + + this._renderPassFuncQueue.push(vpfunc); + this._renderPassFuncQueue.push(srfunc); + + if (!renderingFullScreen && needPartialClear) { + let idx = 0; + gpuFramebuffer.gpuColorTextures.forEach((tex) => { + clearRect(device, tex, renderArea, clearColors[idx]); + idx++; + }); + } + + this._isInRenderPass = true; + } + + public endRenderPass (): void { + const device = WebGPUDeviceManager.instance; + const nativeDevice = (device).nativeDevice!; + const cmdEncoder = nativeDevice.createCommandEncoder(); + const passEncoder = cmdEncoder.beginRenderPass(this._nativePassDesc!); + this._renderPassFuncQueue.forEach((cb) => { + cb(passEncoder); + }); + + passEncoder.end(); + nativeDevice?.queue.submit([cmdEncoder.finish()]); + let idx = 0; + for (const attachment of this._nativePassDesc!.colorAttachments) { + attachment!.loadOp = this._wgpuRenderPass.gpuRenderPass.originalRP!.colorAttachments[idx].loadOp; + idx++; + } + this._isInRenderPass = false; + this._isStateValid = false; + this._renderPassFuncQueue.length = 0; + } + + public bindPipelineState (pipelineState: PipelineState): void { + const webgpuPipelineState = (pipelineState as WebGPUPipelineState); + const gpuPipelineState = webgpuPipelineState.gpuPipelineState; + if (gpuPipelineState !== this._curGPUPipelineState) { + this._curWebGPUPipelineState = webgpuPipelineState; + this._curGPUPipelineState = gpuPipelineState; + currPipelineState = webgpuPipelineState; + this._isStateValid = true; + } + } + + public bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: number[]): void { + const gpuDescriptorSets = (descriptorSet as unknown as WebGPUDescriptorSet).gpuDescriptorSet; + if (gpuDescriptorSets !== this._curGPUDescriptorSets[set]) { + this._curGPUDescriptorSets[set] = gpuDescriptorSets; + descriptorSets[set] = descriptorSet as WebGPUDescriptorSet; + this._isStateValid = true; + } + if (dynamicOffsets) { + const offsets = this._curDynamicOffsets[set]; + const dynamicOffsetSize = dynamicOffsets.length; + for (let i = 0; i < dynamicOffsetSize; i++) offsets[i] = dynamicOffsets[i]; + offsets.length = dynamicOffsetSize; + this._isStateValid = true; + } + } + + public bindInputAssembler (inputAssembler: InputAssembler): void { + const gpuInputAssembler = (inputAssembler as unknown as WebGPUInputAssembler).gpuInputAssembler; + this._curGPUInputAssembler = gpuInputAssembler; + this._isStateValid = true; + } + + public setViewport (viewport: Viewport): void { + viewport.left = Math.floor(viewport.left); + viewport.top = Math.floor(viewport.top); + viewport.width = Math.floor(viewport.width); + viewport.height = Math.floor(viewport.height); + viewport.minDepth = Math.floor(viewport.minDepth); + viewport.maxDepth = Math.floor(viewport.maxDepth); + this._curViewport = new Viewport(viewport.left, viewport.top, viewport.width, viewport.height, viewport.minDepth, viewport.maxDepth); + const vpfunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setViewport( + viewport.left, + viewport.top, + viewport.width, + viewport.height, + viewport.minDepth, + viewport.maxDepth, + ); + }; + this._renderPassFuncQueue.push(vpfunc); + this._isStateValid = true; + } + + public setScissor (scissor: Rect): void { + scissor.x = Math.floor(scissor.x); + scissor.y = Math.floor(scissor.y); + scissor.width = Math.floor(scissor.width); + scissor.height = Math.floor(scissor.height); + const srfunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setScissorRect(scissor.x, scissor.y, scissor.width, scissor.height); + }; + this._renderPassFuncQueue.push(srfunc); + this._isStateValid = true; + } + + public setLineWidth (lineWidth: number): void { + error('line width not supproted by webGPU'); + } + + public setDepthBias (depthBiasConstantFactor: number, depthBiasClamp: number, depthBiasSlopeFactor: number): void { + if (!this._curDepthBias) { + this._curDepthBias = { + constantFactor: depthBiasConstantFactor, + clamp: depthBiasClamp, + slopeFactor: depthBiasSlopeFactor, + }; + this._isStateValid = true; + } else if (this._curDepthBias.constantFactor !== depthBiasConstantFactor + || this._curDepthBias.clamp !== depthBiasClamp + || this._curDepthBias.slopeFactor !== depthBiasSlopeFactor) { + this._curDepthBias.constantFactor = depthBiasConstantFactor; + this._curDepthBias.clamp = depthBiasClamp; + this._curDepthBias.slopeFactor = depthBiasSlopeFactor; + this._isStateValid = true; + } + } + + public setBlendConstants (blendConstants: Color): void { + if ( + this._curBlendConstants[0] !== blendConstants.x + || this._curBlendConstants[1] !== blendConstants.y + || this._curBlendConstants[2] !== blendConstants.z + || this._curBlendConstants[3] !== blendConstants.w) { + this._curBlendConstants.length = 0; + Array.prototype.push.apply(this._curBlendConstants, [blendConstants.x, blendConstants.y, blendConstants.z, blendConstants.w]); + this._isStateValid = true; + } + } + + public setDepthBound (minDepthBounds: number, maxDepthBounds: number): void { + if (!this._curDepthBounds) { + this._curDepthBounds = { + minBounds: minDepthBounds, + maxBounds: maxDepthBounds, + }; + this._isStateValid = true; + } else if (this._curDepthBounds.minBounds !== minDepthBounds + || this._curDepthBounds.maxBounds !== maxDepthBounds) { + this._curDepthBounds = { + minBounds: minDepthBounds, + maxBounds: maxDepthBounds, + }; + this._isStateValid = true; + } + } + + public setStencilWriteMask (face: StencilFace, writeMask: number): void { + if (!this._curStencilWriteMask) { + this._curStencilWriteMask = { + face, + writeMask, + }; + this._isStateValid = true; + } else if (this._curStencilWriteMask.face !== face + || this._curStencilWriteMask.writeMask !== writeMask) { + this._curStencilWriteMask.face = face; + this._curStencilWriteMask.writeMask = writeMask; + this._isStateValid = true; + } + } + + public setStencilCompareMask (face: StencilFace, reference: number, compareMask: number): void { + if (!this._curStencilCompareMask) { + this._curStencilCompareMask = { + face, + reference, + compareMask, + }; + this._isStateValid = true; + } else if (this._curStencilCompareMask.face !== face + || this._curStencilCompareMask.reference !== reference + || this._curStencilCompareMask.compareMask !== compareMask) { + this._curStencilCompareMask.face = face; + this._curStencilCompareMask.reference = reference; + this._curStencilCompareMask.compareMask = compareMask; + this._isStateValid = true; + } + } + + public draw (inputAssembler: InputAssembler): void { + const device = WebGPUDeviceManager.instance; + if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass) { + error('Command \'draw\' must be recorded inside a render pass.'); + return; + } + if (this._isStateValid) { + this.bindStates(); + } + + const ia = inputAssembler as unknown as WebGPUInputAssembler; + const iaData = ia.gpuInputAssembler; + + const nativeDevice = device; + + if (ia.indirectBuffer) { + const indirectBuffer = iaData.gpuIndirectBuffer!; + if (nativeDevice.multiDrawIndirectSupport) { + // not support yet + } else { + const drawInfoCount = iaData.gpuIndirectBuffer?.indirects.length as number; + if (indirectBuffer.drawIndirectByIndex) { + const drawFunc = (passEncoder: GPURenderPassEncoder): void => { + const drawInfoSize = Object.keys(DrawInfo).length; + for (let i = 0; i < drawInfoCount; i++) { + passEncoder?.drawIndexedIndirect(indirectBuffer.gpuBuffer!, indirectBuffer.gpuOffset + i * drawInfoSize); + } + }; + this._renderPassFuncQueue.push(drawFunc); + } else { + // FIXME: draw IndexedIndirect and Indirect by different buffer + const drawFunc = (passEncoder: GPURenderPassEncoder): void => { + const drawInfoSize = Object.keys(DrawInfo).length; + for (let i = 0; i < drawInfoCount; i++) { + passEncoder?.drawIndirect(indirectBuffer.gpuBuffer!, indirectBuffer.gpuOffset + i * drawInfoSize); + } + }; + this._renderPassFuncQueue.push(drawFunc); + } + } + } else { + const instanceCount = inputAssembler.instanceCount > 0 ? inputAssembler.instanceCount : 1; + const drawByIndex = inputAssembler.indexBuffer && (ia.indexCount > 0); + + if (drawByIndex) { + const drawFunc = (passEncoder: GPURenderPassEncoder): void => { + const instanceCount = Math.max(ia.instanceCount, 1); + passEncoder?.drawIndexed(ia.indexCount, instanceCount, ia.firstIndex, ia.firstVertex, ia.firstInstance); + }; + this._renderPassFuncQueue.push(drawFunc); + } else { + const drawFunc = (passEncoder: GPURenderPassEncoder): void => { + const instanceCount = Math.max(ia.instanceCount, 1); + passEncoder?.draw(ia.vertexCount, instanceCount, ia.firstVertex, ia.firstInstance); + }; + this._renderPassFuncQueue.push(drawFunc); + } + } + + ++this._numDrawCalls; + this._numInstances += inputAssembler.instanceCount; + const indexCount = inputAssembler.indexCount || inputAssembler.vertexCount; + if (this._curGPUPipelineState) { + const gpuPrimitive = this._curGPUPipelineState.gpuPrimitive; + switch (gpuPrimitive) { + case 'triangle-strip': + this._numTris += (indexCount - 2) * Math.max(inputAssembler.instanceCount, 1); + break; + case 'triangle-list': { + this._numTris += indexCount / 3 * Math.max(inputAssembler.instanceCount, 1); + break; + } + default: + break; + } + } + } + + public updateBuffer (buffer: Buffer, data: BufferSource, offset?: number, size?: number): void { + if (this._type === CommandBufferType.PRIMARY && this._isInRenderPass) { + error('Command \'updateBuffer\' must be recorded outside a render pass.'); + return; + } + const gpuBuffer = (buffer as unknown as WebGPUBuffer).gpuBuffer; + if (!gpuBuffer) { + return; + } + const cmd = this._webGPUAllocator!.updateBufferCmdPool.alloc(WebGPUCmdUpdateBuffer); + let buffSize = 0; + let buff: BufferSource | null = null; + + // TODO: Have to copy to staging buffer first to make this work for the execution is deferred. + // But since we are using specialized primary command buffers in WebGL backends, we leave it as is for now + if (buffer.usage & BufferUsageBit.INDIRECT) { + buff = data; + } else { + if (size !== undefined) { + buffSize = size; + } else { + buffSize = (data as ArrayBuffer).byteLength; + } + buff = data; + } + const device = WebGPUDeviceManager.instance; + const nativeDevice = (device).nativeDevice; + nativeDevice?.queue.writeBuffer(gpuBuffer.gpuBuffer!, gpuBuffer.gpuOffset, buff as ArrayBuffer); + } + + public copyBuffersToTexture (buffers: ArrayBufferView[], texture: Texture, regions: BufferTextureCopy[]): void { + if (this._type === CommandBufferType.PRIMARY && this._isInRenderPass) { + error('Command \'copyBufferToTexture\' must be recorded outside a render pass.'); + return; + } + const gpuTexture = (texture as WebGPUTexture).gpuTexture; + if (!gpuTexture) { + return; + } + const cmd = this._webGPUAllocator!.copyBufferToTextureCmdPool.alloc(WebGPUCmdCopyBufferToTexture); + cmd.gpuTexture = gpuTexture; + cmd.regions = regions; + cmd.buffers = buffers; + + this.cmdPackage.copyBufferToTextureCmds.push(cmd); + this.cmdPackage.cmds.push(WebGPUCmd.COPY_BUFFER_TO_TEXTURE); + } + + public execute (cmdBuffs: CommandBuffer[], count: number): void { + for (let i = 0; i < count; ++i) { + const WebGPUCmdBuff = cmdBuffs[i] as WebGPUCommandBuffer; + const cmdPackage = WebGPUCmdBuff.cmdPackage; + const rpLength = cmdPackage.beginRenderPassCmds.length; + for (let c = 0; c < rpLength; ++c) { + const cmd = cmdPackage.beginRenderPassCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.beginRenderPassCmds.push(cmd); + } + const bindStatesCmds = cmdPackage.bindStatesCmds; + const stateCmdCount = bindStatesCmds.length; + for (let c = 0; c < stateCmdCount; ++c) { + const cmd = bindStatesCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.bindStatesCmds.push(cmd); + } + const drawCmds = cmdPackage.drawCmds; + const drawCmdCount = drawCmds.length; + for (let c = 0; c < drawCmdCount; ++c) { + const cmd = drawCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.drawCmds.push(cmd); + } + const updateBufferCmdCount = cmdPackage.updateBufferCmds.length; + for (let c = 0; c < updateBufferCmdCount; ++c) { + const cmd = cmdPackage.updateBufferCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.updateBufferCmds.push(cmd); + } + const copyBufferTexCmdCount = cmdPackage.copyBufferToTextureCmds.length; + for (let c = 0; c < copyBufferTexCmdCount; ++c) { + const cmd = cmdPackage.copyBufferToTextureCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.copyBufferToTextureCmds.push(cmd); + } + + this.cmdPackage.cmds.concat(cmdPackage.cmds.array); + + this._numDrawCalls += WebGPUCmdBuff._numDrawCalls; + this._numInstances += WebGPUCmdBuff._numInstances; + this._numTris += WebGPUCmdBuff._numTris; + } + } + + protected bindStates (): void { + if (!this._curGPUPipelineState) { + return; + } + const gpuShader = this._curGPUPipelineState.gpuShader!; + const bindingMaps = gpuShader.bindings; + let vertBinds: number[][] = []; let fragBinds: number[][] = []; let vertAttrs; + for (const stage of gpuShader.gpuStages) { + if (stage.type === ShaderStageFlagBit.VERTEX) { + vertBinds = stage.bindings; + vertAttrs = stage.attrs; + } else if (stage.type === ShaderStageFlagBit.FRAGMENT) { + fragBinds = stage.bindings; + } + } + const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout; + const wgpuPipLayout = (currPipelineState?.pipelineLayout as WebGPUPipelineLayout); + let needFetchPipLayout = false; + const descSize = descriptorSets.length; + for (let i = 0; i < descSize; i++) { + descriptorSets[i].prepare( + i ? DescUpdateFrequency.NORMAL : DescUpdateFrequency.LOW, + bindingMaps.get(i)!, + vertBinds[i] || [], + fragBinds[i] || [], + ); + const layout = descriptorSets[i].layout as WebGPUDescriptorSetLayout; + const currGrpLayout = layout.gpuDescriptorSetLayout!.bindGroupLayout; + const notEqualLayout = gpuPipelineLayout.gpuBindGroupLayouts[i] !== currGrpLayout; + if (layout.hasChanged || notEqualLayout) { + if (notEqualLayout) { + wgpuPipLayout.changeSetLayout(i, layout); + } + layout.resetChanged(); + needFetchPipLayout = true; + } + } + + if (needFetchPipLayout || !wgpuPipLayout.gpuPipelineLayout!.nativePipelineLayout + || this._curGPUPipelineState.pipelineState!.layout !== gpuPipelineLayout.nativePipelineLayout) { + wgpuPipLayout.fetchPipelineLayout(false); + this._curWebGPUPipelineState?.updatePipelineLayout(); + needFetchPipLayout = true; + } + this._curWebGPUPipelineState!.prepare(this._curGPUInputAssembler!, needFetchPipLayout); + const { dynamicOffsetIndices } = gpuPipelineLayout; + // ----------------------------wgpu pipline state----------------------------- + const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline; + const pplFunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setPipeline(wgpuPipeline); + }; + this._renderPassFuncQueue.push(pplFunc); + if (this._curGPUPipelineState.pipelineState?.depthStencil) { + const stencilRef = this._curGPUPipelineState.stencilRef; + const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setStencilReference(stencilRef); + }; + this._renderPassFuncQueue.push(stencilRefFunc); + } + const currGPUDescSize = this._curGPUDescriptorSets.length; + const wgpuBindGroups = new Array(currGPUDescSize); + const wgpuDynOffsets = new Array(currGPUDescSize); + for (let i = 0; i < currGPUDescSize; i++) { + const curGpuDesc = this._curGPUDescriptorSets[i]; + wgpuBindGroups[i] = curGpuDesc.bindGroup; + wgpuDynOffsets[i] = [...this._curDynamicOffsets[i]]; + if (!descriptorSets[i].dynamicOffsetCount) { + wgpuDynOffsets[i] = []; + } else if (descriptorSets[i] && descriptorSets[i].dynamicOffsetCount !== wgpuDynOffsets[i].length) { + wgpuDynOffsets[i].length = descriptorSets[i].dynamicOffsetCount; + for (let j = 0; j < descriptorSets[i].dynamicOffsetCount; j++) { + if (!wgpuDynOffsets[i][j]) { + wgpuDynOffsets[i][j] = 0; + } + } + } + } + + const bgfunc = (passEncoder: GPURenderPassEncoder): void => { + const gpuBindGroupSize = wgpuBindGroups.length; + for (let i = 0; i < gpuBindGroupSize; i++) { + // FIXME: this is a special sentence that 2 in 3 parameters I'm not certain. + passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]); + } + }; + this._renderPassFuncQueue.push(bgfunc); + + // ---------------------------- wgpu input assembly ----------------------------- + const ia = this._curGPUInputAssembler!; + const wgpuVertexBuffers = new Array<{ slot: number, buffer: GPUBuffer, offset: number }>(ia.gpuVertexBuffers.length); + const gpuVertBuffSize = ia.gpuVertexBuffers.length; + for (let i = 0; i < gpuVertBuffSize; i++) { + wgpuVertexBuffers[i] = { slot: i, buffer: ia.gpuVertexBuffers[i].gpuBuffer!, offset: ia.gpuVertexBuffers[i].gpuOffset }; + } + const vbFunc = (passEncoder: GPURenderPassEncoder): void => { + const vertBuffSize = wgpuVertexBuffers.length; + for (let i = 0; i < vertBuffSize; i++) { + passEncoder.setVertexBuffer(wgpuVertexBuffers[i].slot, wgpuVertexBuffers[i].buffer, wgpuVertexBuffers[i].offset); + } + }; + this._renderPassFuncQueue.push(vbFunc); + if (ia.gpuIndexBuffer) { + const wgpuIndexBuffer: { indexType: GPUIndexFormat, buffer: GPUBuffer, offset: number, size: number } = { + indexType: ia.gpuIndexType, + buffer: ia.gpuIndexBuffer.gpuBuffer as GPUBuffer, + offset: ia.gpuIndexBuffer.gpuOffset, + size: ia.gpuIndexBuffer.size, + }; + const ibFunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setIndexBuffer( + wgpuIndexBuffer.buffer, + wgpuIndexBuffer.indexType, + wgpuIndexBuffer.offset, + wgpuIndexBuffer.size, + ); + }; + this._renderPassFuncQueue.push(ibFunc); + } + const bcFunc = (passEncoder: GPURenderPassEncoder): void => { + passEncoder.setBlendConstant([this._curBlendConstants[0], + this._curBlendConstants[1], + this._curBlendConstants[2], + this._curBlendConstants[3]]); + }; + + if (this._curBlendConstants.length) this._renderPassFuncQueue.push(bcFunc); + + this._isStateValid = false; + } +} diff --git a/cocos/gfx/webgpu/webgpu-commands.ts b/cocos/gfx/webgpu/webgpu-commands.ts new file mode 100644 index 0000000000..45e9ef13ab --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-commands.ts @@ -0,0 +1,1712 @@ +/* + Copyright (c) 2024 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. +*/ + +import { CachedArray } from '../../core/memop/cached-array'; +import { BufferSource, DrawInfo, IndirectBuffer, Texture } from '..'; +import { + BufferUsageBit, + ColorMask, + Filter, + Format, + FormatInfos, + ShaderStageFlagBit, + TextureType, + TextureUsageBit, + ShaderStageFlags, + DescriptorType, + Color, Rect, Viewport, BufferTextureCopy, + SamplerInfo, + BufferInfo, + FormatSize, + formatAlignment, + alignTo, + TextureFlagBit, +} from '../base/define'; + +import { WebGPUCommandAllocator } from './webgpu-command-allocator'; +import { + IWebGPUDepthBias, + IWebGPUDepthBounds, + IWebGPUStencilCompareMask, + IWebGPUStencilWriteMask, +} from './webgpu-command-buffer'; +import { WebGPUDevice } from './webgpu-device'; +import { + IWebGPUGPUInputAssembler, + IWebGPUAttrib, + IWebGPUGPUDescriptorSet, + IWebGPUGPUBuffer, + IWebGPUGPUFramebuffer, + IWebGPUGPUPipelineState, + IWebGPUGPUSampler, + IWebGPUGPUShader, + IWebGPUTexture, + IWebGPUGPURenderPass, + IWebGPUGPUShaderStage, +} from './webgpu-gpu-objects'; +import { copy } from '../../core/utils/array'; +import { clear } from '../../asset/asset-manager/utilities'; +import { error, log, warn } from '../../core'; + +const WebGPUAdressMode: GPUAddressMode[] = [ + 'repeat', // WRAP, + 'mirror-repeat', // MIRROR, + 'clamp-to-edge', // CLAMP, + 'clamp-to-edge', // BORDER, +]; + +const WebGPUCompareFunc: GPUCompareFunction[] = [ + 'never', + 'less', + 'equal', + 'less-equal', + 'greater', + 'not-equal', + 'greater-equal', + 'always', +]; + +const SAMPLES: number[] = [ + 1, + 2, + 4, + 8, + 16, + 32, + 64, +]; + +const _f32v4 = new Float32Array(4); + +// tslint:disable: max-line-length + +function CmpF32NotEuqal (a: number, b: number): boolean { + const c = a - b; + return (c > 0.000001 || c < -0.000001); +} + +export function GFXStageToWebGPUStage (stage: ShaderStageFlags): number { + let flag = 0x0; + if (stage & ShaderStageFlagBit.VERTEX) { flag |= GPUShaderStage.VERTEX; } + if (stage & ShaderStageFlagBit.FRAGMENT) { flag |= GPUShaderStage.FRAGMENT; } + if (stage & ShaderStageFlagBit.COMPUTE) { flag |= GPUShaderStage.COMPUTE; } + if (stage === ShaderStageFlagBit.ALL) { flag |= (GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE); } + if (flag === 0x0) { throw new Error('shader stage not supported by webGPU!'); } + return flag; +} + +type WebGPUResourceTypeName = + | 'buffer' + | 'texture' + | 'sampler' + | 'externalTexture' + | 'storageTexture'; + +export function GFXSamplerToGPUSamplerDescType (info: Readonly): GPUSamplerBindingType { + if (info.magFilter !== Filter.LINEAR && info.minFilter !== Filter.LINEAR) { + return 'non-filtering'; + } else { + return 'filtering'; + } +} + +export function GFXDescTypeToGPUBufferDescType (descType: DescriptorType): GPUBufferBindingType { + switch (descType) { + case DescriptorType.UNIFORM_BUFFER: + case DescriptorType.DYNAMIC_UNIFORM_BUFFER: + return 'uniform'; + case DescriptorType.STORAGE_BUFFER: + case DescriptorType.DYNAMIC_STORAGE_BUFFER: + default: + return 'storage'; + } +} + +export function GFXDescTypeToWebGPUDescType (descType: DescriptorType): WebGPUResourceTypeName { + switch (descType) { + case DescriptorType.UNIFORM_BUFFER: + case DescriptorType.DYNAMIC_UNIFORM_BUFFER: + case DescriptorType.STORAGE_BUFFER: + return 'buffer'; + case DescriptorType.SAMPLER: + return 'sampler'; + case DescriptorType.SAMPLER_TEXTURE: + return 'texture'; + case DescriptorType.STORAGE_IMAGE: + return 'storageTexture'; + default: + return 'externalTexture'; + } +} + +export function GFXFormatToWGPUVertexFormat (format: Format): GPUVertexFormat { + switch (format) { + case Format.R32F: return 'float32'; + case Format.R32UI: return 'uint32'; + case Format.R32I: return 'sint32'; + case Format.RG8: return 'unorm8x2'; + case Format.RG8SN: return 'snorm8x2'; + case Format.RG8UI: return 'uint8x2'; + case Format.RG8I: return 'sint8x2'; + case Format.RG16F: return 'float16x2'; + case Format.RG16UI: return 'uint16x2'; + case Format.RG16I: return 'sint16x2'; + case Format.RG32F: return 'float32x2'; + case Format.RG32UI: return 'uint32x2'; + case Format.RG32I: return 'sint32x2'; + case Format.RGB32F: return 'float32x3'; + case Format.RGB32UI: return 'uint32x3'; + case Format.RGB32I: return 'sint32x3'; + case Format.BGRA8: return 'unorm8x4'; + case Format.RGBA8: return 'unorm8x4'; + case Format.SRGB8_A8: return 'uint8x4'; + case Format.RGBA8SN: return 'snorm8x4'; + case Format.RGBA8UI: return 'uint8x4'; + case Format.RGBA8I: return 'sint8x4'; + case Format.RGBA16F: return 'float16x4'; + case Format.RGBA16UI: return 'uint16x4'; + case Format.RGBA16I: return 'sint16x4'; + case Format.RGBA32F: return 'float32x4'; + case Format.RGBA32UI: return 'uint32x4'; + case Format.RGBA32I: return 'sint32x4'; + + default: { + warn('Unsupported Format, return sint8x4 in default.'); + return 'sint8x4'; + } + } +} + +function GFXFormatToWGPUTextureFormat (format: Format): GPUTextureFormat { + switch (format) { + case Format.R8: return 'r8unorm'; + case Format.R8SN: return 'r8snorm'; + case Format.R8UI: return 'r8uint'; + case Format.R8I: return 'r8sint'; + case Format.RG8: return 'rg8unorm'; + case Format.RG8SN: return 'rg8snorm'; + case Format.RG8UI: return 'rg8uint'; + case Format.RG8I: return 'rg8sint'; + case Format.BGRA8: return 'bgra8unorm'; + case Format.RGBA8: return 'rgba8unorm'; + case Format.SRGB8_A8: return 'rgba8unorm-srgb'; + case Format.RGBA8SN: return 'rgba8snorm'; + case Format.RGBA8UI: return 'rgba8uint'; + case Format.RGBA8I: return 'rgba8sint'; + case Format.R16I: return 'r16sint'; + case Format.R16UI: return 'r16uint'; + case Format.R16F: return 'r16sint'; + case Format.RG16I: return 'rg16sint'; + case Format.RG16UI: return 'rg16uint'; + case Format.RG16F: return 'rg16float'; + case Format.RGBA16I: return 'rgba16sint'; + case Format.RGBA16UI: return 'rgba16uint'; + case Format.RGBA16F: return 'rgba16float'; + case Format.R32I: return 'r32sint'; + case Format.R32UI: return 'r32uint'; + case Format.R32F: return 'r32float'; + case Format.RG32I: return 'rg32sint'; + case Format.RG32UI: return 'rg32uint'; + case Format.RG32F: return 'rg32float'; + case Format.RGBA32I: return 'rgba32sint'; + case Format.RGBA32UI: return 'rgba32uint'; + case Format.RGBA32F: return 'rgba32float'; + case Format.RGB10A2: return 'rgb10a2unorm'; + + case Format.DEPTH: return 'depth24plus'; + case Format.DEPTH_STENCIL: return 'depth24plus-stencil8'; + + case Format.BC1_ALPHA: return 'bc1-rgba-unorm'; + case Format.BC1_SRGB_ALPHA: return 'bc1-rgba-unorm-srgb'; + case Format.BC2: return 'bc2-rgba-unorm'; + case Format.BC2_SRGB: return 'bc2-rgba-unorm-srgb'; + case Format.BC3: return 'bc3-rgba-unorm'; + case Format.BC3_SRGB: return 'bc3-rgba-unorm-srgb'; + case Format.BC4_SNORM: return 'bc4-r-snorm'; + case Format.BC6H_SF16: return 'bc6h-rgb-float'; + case Format.BC6H_UF16: return 'bc6h-rgb-ufloat'; + case Format.BC7: return 'bc7-rgba-unorm'; + case Format.BC7_SRGB: return 'bc7-rgba-unorm-srgb'; + + default: { + warn('Unsupported Format, return bgra8unorm indefault.'); + return 'bgra8unorm'; + } + } +} + +export function GFXFormatToWGPUFormat (format: Format): GPUTextureFormat { + return GFXFormatToWGPUTextureFormat(format); +} + +function wGPUTextureFormatToGFXFormat (format: GPUTextureFormat): Format { + switch (format) { + case 'r8unorm': return Format.R8; + case 'r8snorm': return Format.R8SN; + case 'r8uint': return Format.R8UI; + case 'r8sint': return Format.R8I; + case 'rg8unorm': return Format.RG8; + case 'rg8snorm': return Format.RG8SN; + case 'rg8uint': return Format.RG8UI; + case 'rg8sint': return Format.RG8I; + case 'bgra8unorm': return Format.BGRA8; + case 'rgba8unorm': return Format.RGBA8; + case 'rgba8unorm-srgb': return Format.SRGB8_A8; + case 'rgba8snorm': return Format.RGBA8SN; + case 'rgba8uint': return Format.RGBA8UI; + case 'rgba8sint': return Format.RGBA8I; + case 'r16sint': return Format.R16I; + case 'r16uint': return Format.R16UI; + case 'r16float': return Format.R16F; + case 'rg16sint': return Format.RG16I; + case 'rg16uint': return Format.RG16UI; + case 'rg16float': return Format.RG16F; + case 'rgba16sint': return Format.RGBA16I; + case 'rgba16uint': return Format.RGBA16UI; + case 'rgba16float': return Format.RGBA16F; + case 'r32sint': return Format.R32I; + case 'r32uint': return Format.R32UI; + case 'r32float': return Format.R32F; + case 'rg32sint': return Format.RG32I; + case 'rg32uint': return Format.RG32UI; + case 'rg32float': return Format.RG32F; + case 'rgba32sint': return Format.RGBA32I; + case 'rgba32uint': return Format.RGBA32UI; + case 'rgba32float': return Format.RGBA32F; + case 'rgb10a2unorm': return Format.RGB10A2; + case 'depth24plus': return Format.DEPTH; + case 'depth24plus-stencil8': return Format.DEPTH_STENCIL; + case 'bc1-rgba-unorm': return Format.BC1_ALPHA; + case 'bc1-rgba-unorm-srgb': return Format.BC1_SRGB_ALPHA; + case 'bc2-rgba-unorm': return Format.BC2; + case 'bc2-rgba-unorm-srgb': return Format.BC2_SRGB; + case 'bc3-rgba-unorm': return Format.BC3; + case 'bc3-rgba-unorm-srgb': return Format.BC3_SRGB; + case 'bc4-r-snorm': return Format.BC4_SNORM; + case 'bc6h-rgb-float': return Format.BC6H_SF16; + case 'bc6h-rgb-ufloat': return Format.BC6H_UF16; + case 'bc7-rgba-unorm': return Format.BC7; + case 'bc7-rgba-unorm-srgb': return Format.BC7_SRGB; + default: + return Format.BGRA8; + } +} + +export function WGPUFormatToGFXFormat (format: GPUTextureFormat): Format { + return wGPUTextureFormatToGFXFormat(format); +} + +export function GFXTextureToWebGPUTexture (textureType: TextureType): GPUTextureViewDimension { + switch (textureType) { + case TextureType.TEX1D: return '1d'; + case TextureType.TEX2D: return '2d'; + case TextureType.TEX2D_ARRAY: return '2d-array'; + case TextureType.TEX3D: return '3d'; + case TextureType.CUBE: return 'cube'; + default: { + error('Unsupported textureType, convert to WebGPUTexture failed.'); + return '2d'; + } + } +} + +export function GFXTextureUsageToNative (usage: TextureUsageBit): GPUTextureUsageFlags { + let nativeUsage: GPUTextureUsageFlags = 0; + if (usage & TextureUsageBit.TRANSFER_SRC) { + nativeUsage |= GPUTextureUsage.COPY_SRC; + } + + if (usage & TextureUsageBit.TRANSFER_DST) { + nativeUsage |= GPUTextureUsage.COPY_DST; + } + + if (usage & TextureUsageBit.SAMPLED) { + nativeUsage |= GPUTextureUsage.TEXTURE_BINDING; + } + + if (usage & TextureUsageBit.STORAGE) { + nativeUsage |= GPUTextureUsage.STORAGE_BINDING; + } + + if (usage & TextureUsageBit.COLOR_ATTACHMENT || usage & TextureUsageBit.DEPTH_STENCIL_ATTACHMENT) { + nativeUsage |= GPUTextureUsage.RENDER_ATTACHMENT; + } + + if (!nativeUsage) { + // The default value is TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT + // An error will be thrown saying "Destination texture needs to have CopyDst and RenderAttachment usage." + // if you use GPUTextureUsage.COPY_DST without GPUTextureUsage.RENDER_ATTACHMENT. + nativeUsage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT; + } + + if (!(nativeUsage & GPUTextureUsage.COPY_DST)) { + nativeUsage |= GPUTextureUsage.COPY_DST; + } + + if ((nativeUsage & (GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST)) + && !(nativeUsage & (GPUTextureUsage.RENDER_ATTACHMENT))) { + nativeUsage |= GPUTextureUsage.RENDER_ATTACHMENT; + } + + return nativeUsage; +} + +export const WebGPUStencilOp: GPUStencilOperation[] = [ + 'zero', + 'keep', + 'replace', + 'increment-clamp', + 'decrement-clamp', + 'invert', + 'increment-wrap', + 'decrement-wrap', +]; + +export const WebGPUCompereFunc: GPUCompareFunction[] = [ + 'never', + 'less', + 'equal', + 'less-equal', + 'greater', + 'not-equal', + 'greater-equal', + 'always', +]; + +export const WebGPUBlendOps: GPUBlendOperation[] = [ + 'add', + 'subtract', + 'reverse-subtract', + 'min', + 'max', +]; + +export function WebGPUBlendMask (mask: ColorMask): GPUColorWriteFlags { + switch (mask) { + case ColorMask.R: + return GPUColorWrite.RED; + case ColorMask.G: + return GPUColorWrite.GREEN; + case ColorMask.B: + return GPUColorWrite.BLUE; + case ColorMask.A: + return GPUColorWrite.ALPHA; + default: + return GPUColorWrite.ALL; + } +} + +export const WebGPUBlendFactors: GPUBlendFactor[] = [ + 'zero', + 'one', + 'src-alpha', + 'dst-alpha', + 'one-minus-src-alpha', + 'one-minus-dst-alpha', + 'src', + 'dst', + 'one-minus-src', + 'one-minus-dst', + 'src-alpha-saturated', + 'constant', // CONSTANT_COLOR + 'one-minus-constant', // ONE_MINUS_CONSTANT_COLOR + 'src-alpha', // CONSTANT_ALPHA: not supported + 'one-minus-src-alpha', // ONE_MINUS_CONSTANT_ALPHA: not supported +]; + +export enum WebGPUCmd { + BEGIN_RENDER_PASS, + END_RENDER_PASS, + BIND_STATES, + DRAW, + UPDATE_BUFFER, + COPY_BUFFER_TO_TEXTURE, + COUNT, +} + +export abstract class WebGPUCmdObject { + public cmdType: WebGPUCmd; + public refCount = 0; + + constructor (type: WebGPUCmd) { + this.cmdType = type; + } + + public abstract clear (); +} + +export class WebGPUCmdBeginRenderPass extends WebGPUCmdObject { + public gpuRenderPass: IWebGPUGPURenderPass | null = null; + public gpuFramebuffer: IWebGPUGPUFramebuffer | null = null; + public renderArea = new Rect(); + public clearColors: Color[] = []; + public clearDepth = 1.0; + public clearStencil = 0; + + constructor () { + super(WebGPUCmd.BEGIN_RENDER_PASS); + } + + public clear (): void { + this.gpuFramebuffer = null; + this.clearColors.length = 0; + } +} + +export class WebGPUCmdBindStates extends WebGPUCmdObject { + public gpuPipelineState: IWebGPUGPUPipelineState | null = null; + public gpuInputAssembler: IWebGPUGPUInputAssembler | null = null; + public gpuDescriptorSets: IWebGPUGPUDescriptorSet[] = []; + public dynamicOffsets: number[] = []; + public viewport: Viewport | null = null; + public scissor: Rect | null = null; + public lineWidth: number | null = null; + public depthBias: IWebGPUDepthBias | null = null; + public blendConstants: number[] = []; + public depthBounds: IWebGPUDepthBounds | null = null; + public stencilWriteMask: IWebGPUStencilWriteMask | null = null; + public stencilCompareMask: IWebGPUStencilCompareMask | null = null; + + constructor () { + super(WebGPUCmd.BIND_STATES); + } + + public clear (): void { + this.gpuPipelineState = null; + this.gpuInputAssembler = null; + this.gpuDescriptorSets.length = 0; + this.dynamicOffsets.length = 0; + this.viewport = null; + this.scissor = null; + this.lineWidth = null; + this.depthBias = null; + this.blendConstants.length = 0; + this.depthBounds = null; + this.stencilWriteMask = null; + this.stencilCompareMask = null; + } +} + +export class WebGPUCmdDraw extends WebGPUCmdObject { + public drawInfo = new DrawInfo(); + + constructor () { + super(WebGPUCmd.DRAW); + } + + public clear (): void { + // nothing + } +} + +export class WebGPUCmdUpdateBuffer extends WebGPUCmdObject { + public gpuBuffer: IWebGPUGPUBuffer | null = null; + public buffer: BufferSource | null = null; + public offset = 0; + public size = 0; + + constructor () { + super(WebGPUCmd.UPDATE_BUFFER); + } + + public clear (): void { + this.gpuBuffer = null; + this.buffer = null; + } +} + +export class WebGPUCmdCopyBufferToTexture extends WebGPUCmdObject { + public gpuTexture: IWebGPUTexture | null = null; + public buffers: ArrayBufferView[] = []; + public regions: BufferTextureCopy[] = []; + + constructor () { + super(WebGPUCmd.COPY_BUFFER_TO_TEXTURE); + } + + public clear (): void { + this.gpuTexture = null; + this.buffers.length = 0; + this.regions.length = 0; + } +} + +export class WebGPUCmdPackage { + public cmds: CachedArray = new CachedArray(1); + public beginRenderPassCmds: CachedArray = new CachedArray(1); + public bindStatesCmds: CachedArray = new CachedArray(1); + public drawCmds: CachedArray = new CachedArray(1); + public updateBufferCmds: CachedArray = new CachedArray(1); + public copyBufferToTextureCmds: CachedArray = new CachedArray(1); + + public clearCmds (allocator: WebGPUCommandAllocator): void { + if (this.beginRenderPassCmds.length) { + allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds); + this.beginRenderPassCmds.clear(); + } + + if (this.bindStatesCmds.length) { + allocator.bindStatesCmdPool.freeCmds(this.bindStatesCmds); + this.bindStatesCmds.clear(); + } + + if (this.drawCmds.length) { + allocator.drawCmdPool.freeCmds(this.drawCmds); + this.drawCmds.clear(); + } + + if (this.updateBufferCmds.length) { + allocator.updateBufferCmdPool.freeCmds(this.updateBufferCmds); + this.updateBufferCmds.clear(); + } + + if (this.copyBufferToTextureCmds.length) { + allocator.copyBufferToTextureCmdPool.freeCmds(this.copyBufferToTextureCmds); + this.copyBufferToTextureCmds.clear(); + } + + this.cmds.clear(); + } +} + +export function WebGPUCmdFuncCreateBuffer (device: WebGPUDevice, gpuBuffer: IWebGPUGPUBuffer): void { + const nativeDevice: GPUDevice = device.nativeDevice!; + + const bufferDesc = {} as GPUBufferDescriptor; + bufferDesc.size = gpuBuffer.size; + + let bufferUsage = 0x0; + if ((gpuBuffer.usage & BufferUsageBit.INDEX || gpuBuffer.usage & BufferUsageBit.VERTEX) && !(gpuBuffer.usage & BufferUsageBit.TRANSFER_DST)) { + gpuBuffer.usage |= BufferUsageBit.TRANSFER_DST; + } + if (gpuBuffer.usage & BufferUsageBit.VERTEX) bufferUsage |= GPUBufferUsage.VERTEX; + if (gpuBuffer.usage & BufferUsageBit.INDEX) bufferUsage |= GPUBufferUsage.INDEX; + if (gpuBuffer.usage & BufferUsageBit.UNIFORM) bufferUsage |= GPUBufferUsage.UNIFORM; + if (gpuBuffer.usage & BufferUsageBit.INDIRECT) bufferUsage |= GPUBufferUsage.INDIRECT; + if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) bufferUsage |= GPUBufferUsage.COPY_SRC; + if (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) bufferUsage |= GPUBufferUsage.COPY_DST; + if (gpuBuffer.usage & BufferUsageBit.STORAGE) bufferUsage |= GPUBufferUsage.STORAGE; + + if (bufferUsage === 0x0) { + warn('Unsupported GFXBufferType yet, create UNIFORM buffer in default.'); + bufferUsage |= GPUBufferUsage.UNIFORM; + } + + if (!(bufferUsage & GPUBufferUsage.COPY_DST)) { + bufferUsage |= GPUBufferUsage.COPY_DST; + } + bufferDesc.usage = bufferUsage; + gpuBuffer.gpuTarget = bufferUsage; + gpuBuffer.gpuBuffer = nativeDevice.createBuffer(bufferDesc); +} + +export function WebGPUCmdFuncDestroyBuffer (device: WebGPUDevice, gpuBuffer: IWebGPUGPUBuffer): void { + if (gpuBuffer.gpuBuffer) { + gpuBuffer.gpuBuffer.destroy(); + } +} + +export function WebGPUCmdFuncResizeBuffer (device: WebGPUDevice, gpuBuffer: IWebGPUGPUBuffer): void { + WebGPUCmdFuncDestroyBuffer(device, gpuBuffer); + WebGPUCmdFuncCreateBuffer(device, gpuBuffer); +} + +export function WebGPUCmdFuncUpdateBuffer ( + device: WebGPUDevice, + gpuBuffer: IWebGPUGPUBuffer, + buffer: BufferSource, + offset: number, + size: number, +): void { + if (gpuBuffer.usage & BufferUsageBit.INDIRECT) { + gpuBuffer.indirects.length = offset; + Array.prototype.push.apply(gpuBuffer.indirects, (buffer as IndirectBuffer).drawInfos); + } else { + const nativeDevice: GPUDevice = device.nativeDevice!; + let buff = buffer as ArrayBuffer; + let rawBuffer: ArrayBuffer; + + // arraybuffer size not equal to buff.bytelength, so new another array + buff = buff.slice(0, size); + + if ('buffer' in buff) { + // es-lint as any + rawBuffer = (buff as any).buffer; + } else { + rawBuffer = buff; + } + + if (rawBuffer.byteLength !== size) { + rawBuffer = rawBuffer.slice(0, size); + } + // Buffer.gpubuffer may not able to be mapped directly, so staging buffer here. + const stagingBuffer = nativeDevice.createBuffer({ + label: `staging buffer ${size}`, + size, + usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC, + mappedAtCreation: true, + }); + const mappedRange = stagingBuffer.getMappedRange(); + new Uint8Array(mappedRange).set(new Uint8Array(rawBuffer)); + stagingBuffer.unmap(); + const commandEncoder = nativeDevice.createCommandEncoder(); + commandEncoder.copyBufferToBuffer(stagingBuffer, 0, gpuBuffer.gpuBuffer as GPUBuffer, offset, size); + const commandBuffer = commandEncoder.finish(); + nativeDevice.queue.submit([commandBuffer]); + stagingBuffer.destroy(); + } +} + +export function WebGPUCmdFuncCreateTexture (device: WebGPUDevice, gpuTexture: IWebGPUTexture): void { + // dimension optional + gpuTexture.gpuTarget = GFXTextureToWebGPUTexture(gpuTexture.type); + gpuTexture.gpuInternalFmt = GFXFormatToWGPUTextureFormat(gpuTexture.format); + gpuTexture.gpuFormat = GFXFormatToWGPUFormat(gpuTexture.format); + gpuTexture.gpuUsage = GFXTextureUsageToNative(gpuTexture.usage); + gpuTexture.gpuWrapS = gpuTexture.isPowerOf2 ? 'repeat' : 'clamp-to-edge'; + gpuTexture.gpuWrapT = gpuTexture.isPowerOf2 ? 'repeat' : 'clamp-to-edge'; + gpuTexture.gpuMinFilter = 'linear'; + gpuTexture.gpuMagFilter = 'linear'; + // only 1 and 4 supported. + gpuTexture.samples = Number(gpuTexture.samples) > 1 ? 4 : 1; + const texDescriptor: GPUTextureDescriptor = { + size: [gpuTexture.width, gpuTexture.height, gpuTexture.arrayLayer], + mipLevelCount: gpuTexture.mipLevel, + sampleCount: gpuTexture.samples, + format: gpuTexture.gpuFormat, + usage: gpuTexture.gpuUsage, + }; + + gpuTexture.gpuTexture = device.nativeDevice!.createTexture(texDescriptor); +} + +export function WebGPUCmdFuncDestroyTexture (gpuTexture: IWebGPUTexture): void { + if (gpuTexture.gpuTexture) { + gpuTexture.gpuTexture.destroy(); + } +} + +export function WebGPUCmdFuncResizeTexture (device: WebGPUDevice, gpuTexture: IWebGPUTexture): void { + if (gpuTexture.gpuTexture) { + WebGPUCmdFuncDestroyTexture(gpuTexture); + } + WebGPUCmdFuncCreateTexture(device, gpuTexture); +} + +export function WebGPUCmdFuncCreateSampler (device: WebGPUDevice, gpuSampler: IWebGPUGPUSampler): void { + const nativeDevice: GPUDevice = device.nativeDevice!; + + gpuSampler.gpuMinFilter = (gpuSampler.minFilter === Filter.LINEAR || gpuSampler.minFilter === Filter.ANISOTROPIC) ? 'linear' : 'nearest'; + gpuSampler.gpuMagFilter = (gpuSampler.magFilter === Filter.LINEAR || gpuSampler.magFilter === Filter.ANISOTROPIC) ? 'linear' : 'nearest'; + gpuSampler.gpuMipFilter = (gpuSampler.mipFilter === Filter.LINEAR || gpuSampler.mipFilter === Filter.ANISOTROPIC) ? 'linear' : 'nearest'; + gpuSampler.gpuWrapS = WebGPUAdressMode[gpuSampler.addressU]; + gpuSampler.gpuWrapT = WebGPUAdressMode[gpuSampler.addressV]; + gpuSampler.gpuWrapR = WebGPUAdressMode[gpuSampler.addressW]; + + const samplerDesc = {} as GPUSamplerDescriptor; + samplerDesc.addressModeU = gpuSampler.gpuWrapS; + samplerDesc.addressModeV = gpuSampler.gpuWrapT; + samplerDesc.addressModeW = gpuSampler.gpuWrapR; + samplerDesc.minFilter = gpuSampler.gpuMinFilter; + samplerDesc.magFilter = gpuSampler.gpuMagFilter; + samplerDesc.mipmapFilter = gpuSampler.gpuMipFilter; + samplerDesc.lodMinClamp = 0;// gpuSampler.minLOD; + samplerDesc.lodMaxClamp = gpuSampler.mipLevel;// gpuSampler.maxLOD; + if (WebGPUCompareFunc[gpuSampler.compare] !== 'always') { + samplerDesc.compare = WebGPUCompareFunc[gpuSampler.compare]; + } + samplerDesc.maxAnisotropy = gpuSampler.maxAnisotropy || 1; + const sampler: GPUSampler = nativeDevice.createSampler(samplerDesc); + gpuSampler.gpuSampler = sampler; +} + +export function WebGPUCmdFuncDestroySampler (device: WebGPUDevice, gpuSampler: IWebGPUGPUSampler): void { + if (gpuSampler.gpuSampler) { + gpuSampler.gpuSampler = null; + } +} + +export function WebGPUCmdFuncDestroyFramebuffer (device: WebGPUDevice, gpuFramebuffer: IWebGPUGPUFramebuffer): void { + if (gpuFramebuffer.gpuFramebuffer) { + gpuFramebuffer.gpuFramebuffer.destroy(); + gpuFramebuffer.gpuFramebuffer = null; + } +} + +const copyTexToBufferDesc: GPUBufferDescriptor = {} as GPUBufferDescriptor; +const destArrayBuffer: ArrayBuffer[] = []; +export async function WebGPUCmdFuncCopyTextureToBuffer ( + device: WebGPUDevice, + texture: IWebGPUTexture, + buffers: ArrayBufferView[], + regions: readonly BufferTextureCopy[], +): Promise { + let x = 0; + let y = 0; + let w = 1; + let h = 1; + const nativeDevice: GPUDevice = device.nativeDevice!; + const commandEncoder = nativeDevice.createCommandEncoder({}); + const regionSize = regions.length; + for (let k = 0; k < regionSize; k++) { + if (destArrayBuffer[k]) { + (buffers[k] as Uint8Array).set(new Uint8Array(destArrayBuffer[k]), 0); + } + copyTexToBufferDesc.size = buffers[k].byteLength; + copyTexToBufferDesc.usage = GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST; + + const copyDestBuffer = nativeDevice.createBuffer(copyTexToBufferDesc); + const region = regions[k]; + x = region.texOffset.x; + y = region.texOffset.y; + w = region.texExtent.width; + h = region.texExtent.height; + + commandEncoder.copyTextureToBuffer({ + texture: texture.gpuTexture!, + mipLevel: 0, + origin: { + x, + y, + }, + }, { + buffer: copyDestBuffer, + offset: 0, + bytesPerRow: w * 4, + rowsPerImage: h, + }, { + width: w, + height: h, + }); + + nativeDevice.queue.submit([commandEncoder.finish()]); + // eslint-disable-next-line no-await-in-loop + await copyDestBuffer.mapAsync(GPUMapMode.READ); + destArrayBuffer[k] = copyDestBuffer.getMappedRange(); + (buffers[k] as Uint8Array).set(new Uint8Array(destArrayBuffer[k]), 0); + } +} + +export const SEPARATE_SAMPLER_BINDING_OFFSET = 16; +function seperateCombinedSamplerTexture (shaderSource: string): string { + // gather + const samplerReg = /.*?(\(set = \d+, binding = )(\d+)\) uniform[^;]+sampler(\w*) (\w+);/g; + let iter = samplerReg.exec(shaderSource); + // samplerName, samplerType + const referredMap = new Map(); + while (iter) { + const samplerName = iter[4]; + const samplerType = iter[3]; + referredMap.set(samplerName, samplerType); + iter = samplerReg.exec(shaderSource); + } + + let code = shaderSource; + const sampReg = /.*?(\(set = \d+, binding = )(\d+)\) uniform[^;]+sampler(\w*) (\w+);/g; + let it = sampReg.exec(code); + while (it) { + code = code.replace(sampReg, `layout$1 $2) uniform texture$3 $4;\n + layout$1 $2 + ${SEPARATE_SAMPLER_BINDING_OFFSET}) uniform sampler $4_sampler;\n`); + it = sampReg.exec(code); + } + + const builtinSample = ['texture', 'textureSize', 'texelFetch', 'textureLod']; + const replaceBultin = (samplerName: string, samplerType: string, target: string): string => { + builtinSample.forEach((sampleFunc) => { + const builtinSampleReg = new RegExp(`${sampleFunc}\\s*\\(\\s*${samplerName}\\s*,`); + let builtinFuncIter = builtinSampleReg.exec(target); + while (builtinFuncIter) { + target = target.replace(builtinFuncIter[0], `${sampleFunc}(sampler${samplerType}(${samplerName}, ${samplerName}_sampler),`); + builtinFuncIter = builtinSampleReg.exec(target); + } + }); + return target; + }; + + const funcReg = /\s([\S]+)\s*\(([\w\s,]+)\)[\s|\\|n]*{/g; + let funcIter = funcReg.exec(code); + const funcSet = new Set(); + const paramTypeMap = new Map(); + while (funcIter) { + paramTypeMap.clear(); + + const params = funcIter[2]; + let paramsRes = params.slice(); + if (params.includes('sampler')) { + const paramIndexSet = new Set(); + const paramArr = params.split(','); + const paramSize = paramArr.length; + for (let i = 0; i < paramSize; ++i) { + const paramDecl = paramArr[i].split(' '); + const typeDecl = paramDecl[paramDecl.length - 2]; + if (typeDecl.includes('sampler') && typeDecl !== 'sampler') { + const samplerType = typeDecl.replace('sampler', ''); + const paramName = paramDecl[paramDecl.length - 1]; + paramsRes = paramsRes.replace(paramArr[i], ` texture${samplerType} ${paramName}, sampler ${paramName}_sampler`); + paramIndexSet.add(i); + paramTypeMap.set(paramName, samplerType); + } + } + + code = code.replace(params, paramsRes); + + const funcName = funcIter[1]; + // function may overload + if (!funcSet.has(funcName)) { + const funcSamplerReg = new RegExp(`${funcName}\\s*?\\((\\s*[^;\\{]+)`, 'g'); + let matched; + // eslint-disable-next-line no-cond-assign + while ((matched = funcSamplerReg.exec(code)) !== null) { + if (!matched[1].match(/\b\w+\b\s*\b\w+\b/g)) { + const stripStr = matched[1][matched[1].length - 1] === ')' ? matched[1].slice(0, -1) : matched[1]; + const params = stripStr.split(','); + let queued = 0; // '(' + let paramIndex = 0; + const paramSize = params.length; + for (let i = 0; i < paramSize; ++i) { + if (params[i].includes('(')) { + ++queued; + } + if (params[i].includes(')')) { + --queued; + } + + if (!queued || i === paramSize - 1) { + if (paramIndexSet.has(paramIndex)) { + params[i] += `, ${params[i]}_sampler`; + } + ++paramIndex; + } + } + const newParams = params.join(','); + const newInvokeStr = matched[0].replace(stripStr, newParams); + code = code.replace(matched[0] as string, newInvokeStr as string); + } + } + } + + let count = 1; + let startIndex = code.indexOf(funcIter[1], funcIter.index); + startIndex = code.indexOf('{', startIndex) + 1; + let endIndex = 0; + while (count) { + if (code.charAt(startIndex) === '{') { + ++count; + } else if (code.charAt(startIndex) === '}') { + --count; + } + + if (count === 0) { + endIndex = startIndex; + break; + } + + const nextLeft = code.indexOf('{', startIndex + 1); + const nextRight = code.indexOf('}', startIndex + 1); + startIndex = nextLeft === -1 ? nextRight : Math.min(nextLeft, nextRight); + } + const funcBody = code.slice(funcIter.index, endIndex); + let newFunc = funcBody; + paramTypeMap.forEach((type, name) => { + newFunc = replaceBultin(name, type, newFunc); + }); + + code = code.replace(funcBody, newFunc); + funcSet.add(funcIter[1]); + } + funcIter = funcReg.exec(code); + } + + referredMap.forEach((type, name) => { + code = replaceBultin(name, type, code); + }); + + /////////////////////////////////////////////////////////// + // isNan, isInf has been removed in dawn:tint + + let functionDefs = ''; + const precisionKeyWord = 'highp'; + const isNanIndex = code.indexOf('isnan'); + if (isNanIndex !== -1) { + // getPrecision(isNanIndex); + functionDefs += `\n + bool isNan(${precisionKeyWord} float val) { + return (val < 0.0 || 0.0 < val || val == 0.0) ? false : true; + } + \n`; + code = code.replace(/isnan\(/gi, 'isNan('); + } + + const isInfIndex = code.indexOf('isinf'); + if (isInfIndex !== -1) { + // getPrecision(isInfIndex); + functionDefs += `\n + bool isInf(${precisionKeyWord} float x) { + return x == x * 2.0 && x != 0.0; + } + \n`; + code = code.replace(/isinf\(/gi, 'isInf('); + } + + /////////////////////////////////////////////////////////// + + let firstPrecisionIdx = code.indexOf('precision'); + firstPrecisionIdx = code.indexOf(';', firstPrecisionIdx); + firstPrecisionIdx += 1; + code = `${code.slice(0, firstPrecisionIdx)}\n${functionDefs}\n${code.slice(firstPrecisionIdx)}`; + + return code; +} + +function reflect (wgsl: string[]): number[][] { + const bindingList: number[][] = []; + for (const wgslStr of wgsl) { + // @group(1) @binding(0) var x_78 : Constants; + // @group(1) @binding(1) var albedoMap : texture_2d; + const reg = /@group\((\d)\)\s+@binding\((\d+)\)/g; + let iter = reg.exec(wgslStr); + while (iter) { + const set = +iter[1]; + const binding = +iter[2]; + while (bindingList.length <= set) { + bindingList.push([]); + } + bindingList[set][bindingList[set].length] = binding; + iter = reg.exec(wgslStr); + } + } + return bindingList; +} + +interface ClearPassData { + vertShader: GPUShaderModule | null; + fragShader: GPUShaderModule | null; + bindGroupLayout: GPUBindGroupLayout | null; + pipelineLayout: GPUPipelineLayout | null; + pipeline: GPURenderPipeline | null; +} +const clearPassData: ClearPassData = { + vertShader: null, + fragShader: null, + bindGroupLayout: null, + pipelineLayout: null, + pipeline: null, +}; +export function clearRect (device: WebGPUDevice, texture: IWebGPUTexture, renderArea: Rect, color: Color): void { + const format = texture.gpuTexture!.format; + const dimension = texture.gpuTarget; + const nativeDevice = device.nativeDevice!; + if (!clearPassData.vertShader) { + const clearQuadVert = ` + struct VertexOutput { + @builtin(position) Position: vec4, + } + + @vertex + fn main(@builtin(vertex_index) VertexIndex: u32) -> VertexOutput { + var pos = array, 6>( + vec2(1.0, 1.0), + vec2(1.0, -1.0), + vec2(-1.0, -1.0), + vec2(1.0, 1.0), + vec2(-1.0, -1.0), + vec2(-1.0, 1.0) + ); + + var output: VertexOutput; + output.Position = vec4(pos[VertexIndex], 0.0, 1.0); + return output; + } + `; + + const clearQuadFrag = ` + struct ClearColor { + color: vec4, + } + + @group(0) @binding(0) var uClearColor: ClearColor; + + @fragment + fn main() -> @location(0) vec4 { + return uClearColor.color; + } + `; + const vertShaderModule = nativeDevice.createShaderModule({ code: clearQuadVert }); + const fragShaderModule = nativeDevice.createShaderModule({ code: clearQuadFrag }); + clearPassData.vertShader = vertShaderModule; + clearPassData.fragShader = fragShaderModule; + + const bufferEntry: GPUBindGroupLayoutEntry = { + binding: 0, + visibility: GPUShaderStage.FRAGMENT, + buffer: { + type: 'uniform', + hasDynamicOffset: false, + minBindingSize: 16, + }, + }; + const bgLayoutDesc: GPUBindGroupLayoutDescriptor = { + label: 'clearPassBGLayout', + entries: [bufferEntry], + }; + + const bindGroupLayout = nativeDevice.createBindGroupLayout(bgLayoutDesc); + clearPassData.bindGroupLayout = bindGroupLayout; + + const pipelineLayoutDesc: GPUPipelineLayoutDescriptor = { + label: 'clearPassPipelineLayout', + bindGroupLayouts: [clearPassData.bindGroupLayout], + }; + + const pipelineLayout = nativeDevice.createPipelineLayout(pipelineLayoutDesc); + clearPassData.pipelineLayout = pipelineLayout; + + const vertexState: GPUVertexState = { + module: clearPassData.vertShader, + entryPoint: 'main', + }; + + const primitiveState: GPUPrimitiveState = { + topology: 'triangle-list', + frontFace: 'ccw', + cullMode: 'none', + }; + const colorState: GPUColorTargetState = { + format, + writeMask: 0xF, + }; + + const fragState: GPUFragmentState = { + module: clearPassData.fragShader, + entryPoint: 'main', + targets: [colorState], + }; + const multisample: GPUMultisampleState = { + count: 1, + alphaToCoverageEnabled: false, + mask: 0xFFFFFFFF, + }; + + const pipelineDesc: GPURenderPipelineDescriptor = { + label: 'clearPassPipeline', + layout: clearPassData.pipelineLayout, + vertex: vertexState, + primitive: primitiveState, + fragment: fragState, + multisample, + }; + const pipeline = nativeDevice.createRenderPipeline(pipelineDesc); + clearPassData.pipeline = pipeline; + } + const commandEncoder: GPUCommandEncoder = nativeDevice.createCommandEncoder(); + const desc: GPUTextureViewDescriptor = { + format, + dimension: '2d', + baseMipLevel: 0, + mipLevelCount: 1, + baseArrayLayer: 0, + arrayLayerCount: 1, + aspect: 'all', + }; + const dstView = texture.gpuTexture?.createView(desc); + const bufferDesc: GPUBufferDescriptor = { + usage: GPUBufferUsage.UNIFORM, + size: 16, + mappedAtCreation: true, + }; + + const uniformBuffer = nativeDevice.createBuffer(bufferDesc); + const colorArr: number[] = [color.x, color.y, color.z, color.w]; + + const mappedBuffer = uniformBuffer.getMappedRange(0, 16); + const f32 = new Float32Array(mappedBuffer); + f32.set(colorArr); + uniformBuffer.unmap(); + + const entry: GPUBindGroupEntry = { + binding: 0, + resource: { + buffer: uniformBuffer, + offset: 0, + size: 16, + }, + }; + + const bindgroupDesc: GPUBindGroupDescriptor = { + layout: clearPassData.bindGroupLayout!, + entries: [entry], + }; + const bindGroup = nativeDevice.createBindGroup(bindgroupDesc); + const colorAttachment: GPURenderPassColorAttachment = { + view: dstView!, + loadOp: 'load', + storeOp: 'store', + clearValue: [0.88, 0.88, 0.88, 1.0], + }; + + const rpDesc: GPURenderPassDescriptor = { + colorAttachments: [colorAttachment], + }; + + const renderPassEncoder = commandEncoder.beginRenderPass(rpDesc); + renderPassEncoder.setPipeline(clearPassData.pipeline!); + + renderPassEncoder.setBindGroup(0, bindGroup); + renderPassEncoder.setViewport(renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.0, 1.0); + renderPassEncoder.setScissorRect(renderArea.x, renderArea.y, renderArea.width, renderArea.height); + renderPassEncoder.draw(6, 1, 0, 0); + + renderPassEncoder.end(); + const commandBuffer = commandEncoder.finish(); + nativeDevice.queue.submit([commandBuffer]); + uniformBuffer.destroy(); +} + +function findEmployAttr (stage: IWebGPUGPUShaderStage): void { + if (stage.type !== ShaderStageFlagBit.VERTEX) { + return; + } + const locationRegex = /@location\(\d+\)[ ]+\w+/g; + const matches = stage.source.match(locationRegex); + if (!matches) { + return; + } + let idx = 0; + matches.forEach((match) => { + const locRegex = /@location\((\d+)\)/g; + const matchLoc = match.match(locRegex)!; + const location = matchLoc[0].slice(matchLoc[0].indexOf('(') + 1, matchLoc[0].indexOf(')')).trim(); + const locNameRegex = /@location\(\d+\)/; + const locName = match.replace(locNameRegex, '').trim(); + const rmvLocRegex = new RegExp(`,*[ ]*@location\\(\\d+\\)[ ]+${locName}+\\b\\s*:\\s*\\w+\\<\\w+\\>\\s*`); + const equalAttr = new RegExp(`\\b(\\w+)\\s*=[ ]*${locName}\\b\\s*;`, 'g'); + const targetVar = stage.source.match(equalAttr)!; + const targetVarName = targetVar[0]; + const searchTarVarName = targetVarName.slice(0, targetVarName.indexOf('=')).trim(); + const matchCountRegex = new RegExp(`\\.*\\b${searchTarVarName}\\b\\.*`, 'g'); + const matchesCount = stage.source.match(matchCountRegex); + const usageCount = matchesCount ? matchesCount.length : 0; + if (usageCount <= 2) { + stage.source = stage.source.replace(rmvLocRegex, ''); + stage.source = stage.source.replace(equalAttr, ''); + const varNameReg = new RegExp(`var\\<\\w+\\>\\s+${searchTarVarName}+\\s*:\\s*\\w+\\<\\w+\\>\\s*;`); + stage.source = stage.source.replace(varNameReg, ''); + } else { + stage.attrs.set(parseInt(location), locName); + } + idx++; + }); +} + +export function WebGPUCmdFuncCreateGPUShader (device: WebGPUDevice, gpuShader: IWebGPUGPUShader): void { + const nativeDevice = device.nativeDevice!; + const glslang = device.glslang; + const twgsl = device.twgsl; + const wgslCodes: string[] = []; + const stageSize = gpuShader.gpuStages.length; + for (let i = 0; i < stageSize; ++i) { + wgslCodes.length = 0; + const gpuStage = gpuShader.gpuStages[i]; + const glslSource = seperateCombinedSamplerTexture(gpuStage.source); + const stageStr = gpuStage.type === ShaderStageFlagBit.VERTEX ? 'vertex' + : gpuStage.type === ShaderStageFlagBit.FRAGMENT ? 'fragment' : 'compute'; + const sourceCode = `#version 450\n#define CC_USE_WGPU 1\n${glslSource}`; + const spv = glslang.compileGLSL(sourceCode, stageStr, false, '1.3'); + + let wgsl: string = twgsl.convertSpirV2WGSL(spv); + if (wgsl === '') { + error('empty wgsl'); + } + gpuStage.source = wgsl; + findEmployAttr(gpuStage); + wgsl = gpuStage.source; + const shader: GPUShaderModule = nativeDevice?.createShaderModule({ code: wgsl }); + // eslint-disable-next-line no-loop-func + shader.getCompilationInfo().then((compileInfo: GPUCompilationInfo) => { + compileInfo.messages.forEach((info) => { + log(sourceCode, wgsl, info.lineNum, info.linePos, info.type, info.message); + }); + // eslint-disable-next-line no-loop-func + }).catch((compileInfo: GPUCompilationInfo) => { + compileInfo.messages.forEach((info) => { + log(sourceCode, wgsl, info.lineNum, info.linePos, info.type, info.message); + }); + }); + const shaderStage: GPUProgrammableStage = { + module: shader, + entryPoint: 'main', + }; + gpuStage.gpuShader = shaderStage; + wgslCodes.push(wgsl); + const bindingList = reflect(wgslCodes); + gpuStage.bindings = bindingList; + const bindingListSize = bindingList.length; + for (let s = 0; s < bindingListSize; s++) { + const currBindingSize = bindingList[s].length; + if (currBindingSize) { + if (!gpuShader.bindings.has(s)) { + gpuShader.bindings.set(s, []); + } + const bindings = gpuShader.bindings.get(s)!; + for (let b = 0; b < currBindingSize; b++) { + if (!bindings.includes(bindingList[s][b])) { + bindings.push(bindingList[s][b]); + } + } + } + } + } +} + +export function WebGPUCmdFuncDestroyShader (device: WebGPUDevice, gpuShader: IWebGPUGPUShader): void { + if (gpuShader.gpuProgram) { + gpuShader.gpuProgram = null; + } +} + +export function WebGPUCmdFuncCreateInputAssember (device: WebGPUDevice, gpuInputAssembler: IWebGPUGPUInputAssembler): void { + const attrSize = gpuInputAssembler.attributes.length; + gpuInputAssembler.gpuAttribs = new Array(attrSize); + + const offsets = [0, 0, 0, 0, 0, 0, 0, 0]; + + for (let i = 0; i < attrSize; ++i) { + const attrib = gpuInputAssembler.attributes[i]; + + const stream = attrib.stream !== undefined ? attrib.stream : 0; + + const gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; + + const gpuType = 0; + const size = FormatInfos[attrib.format].size; + + gpuInputAssembler.gpuAttribs[i] = { + name: attrib.name, + gpuBuffer: gpuBuffer.gpuBuffer, + gpuType, + size, + count: FormatInfos[attrib.format].count, + stride: gpuBuffer.stride, + componentCount: 4, + isNormalized: (attrib.isNormalized !== undefined ? attrib.isNormalized : false), + isInstanced: (attrib.isInstanced !== undefined ? attrib.isInstanced : false), + offset: offsets[stream], + }; + + offsets[stream] += size; + } +} + +export function WebGPUCmdFuncDestroyInputAssembler (device: WebGPUDevice, gpuInputAssembler: IWebGPUGPUInputAssembler): void { + // noop +} + +interface IWebGPUStateCache { + gpuPipelineState: IWebGPUGPUPipelineState | null; + gpuInputAssembler: IWebGPUGPUInputAssembler | null; + reverseCW: boolean; + gpuPrimitive: GPUPrimitiveTopology; + invalidateAttachments: number[]; +} + +function maxElementOfImageArray (bufInfoArr: BufferTextureCopy[]): number { + let maxSize = 0; + const bufInfoSize = bufInfoArr.length; + for (let i = 0; i < bufInfoSize; i++) { + const curSize = bufInfoArr[i].texExtent.width * bufInfoArr[i].texExtent.height * bufInfoArr[i].texExtent.depth; + maxSize = maxSize < curSize ? curSize : maxSize; + } + return maxSize; +} + +export function WebGPUCmdFuncCopyTexImagesToTexture ( + device: WebGPUDevice, + texImages: TexImageSource[], + gpuTexture: IWebGPUTexture, + regions: BufferTextureCopy[], +): void { + // name all native webgpu resource nativeXXX distinguished from gpuTexture passed in. + const nativeDevice = device.nativeDevice!; + const regionSize = regions.length; + for (let i = 0; i < regionSize; i++) { + const region = regions[i]; + const texImg = texImages[i]; + nativeDevice.queue.copyExternalImageToTexture( + { source: texImg }, + { + texture: gpuTexture.gpuTexture!, + mipLevel: region.texSubres.mipLevel, + origin: { + x: region.texOffset.x, + y: region.texOffset.y, + z: region.texSubres.baseArrayLayer, + }, + }, + [regions[i].texExtent.width, regions[i].texExtent.height, regions[i].texExtent.depth], + ); + } + if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) { + genMipMap(device, gpuTexture, 1, gpuTexture.mipLevel - 1, 0); + } +} + +export function TextureSampleTypeTrait (format: Format): GPUTextureSampleType { + switch (format) { + case Format.R8: + case Format.R8SN: + case Format.RG8: + case Format.RGBA8: + case Format.BGRA8: + case Format.RG8SN: + case Format.SRGB8_A8: + case Format.RGB10A2: + case Format.RGBA16F: + return 'float'; + case Format.R8UI: + case Format.R16UI: + case Format.RG8UI: + case Format.R32UI: + case Format.RG16UI: + case Format.RGBA8UI: + case Format.RG32UI: + case Format.RGBA32UI: + case Format.RGBA16UI: + case Format.DEPTH_STENCIL: + return 'uint'; + case Format.R8I: + case Format.R16I: + case Format.RG8I: + case Format.RG16I: + case Format.RGBA8I: + case Format.RG32I: + case Format.RGBA16I: + case Format.RGBA32I: + case Format.R32I: + return 'sint'; + case Format.R16F: + case Format.R32F: + case Format.RG16F: + case Format.R11G11B10F: + case Format.RG32F: + case Format.RGBA32F: + return 'unfilterable-float'; + case Format.DEPTH: + return 'depth'; + default: + warn('Unsupported texture sample type yet. Please refer to the documentation for supported formats.'); + return 'float'; + } +} + +interface MipmapPassData { + vertShader: GPUShaderModule; + fragShader: GPUShaderModule; + sampler: GPUSampler; + bindGroupLayout: GPUBindGroupLayout; + pipelineLayout: GPUPipelineLayout; + pipeline: GPURenderPipeline; +} + +let mipmapData: MipmapPassData; + +function genMipMap (device: WebGPUDevice, texture: IWebGPUTexture, fromLevel: number, levelCount: number, baseLayer: number): void { + const format = texture.gpuFormat; + const dimension = texture.gpuTarget; + const nativeDevice = device.nativeDevice!; + if (!mipmapData) { + mipmapData = {} as any; + const texQuadVert = ` + struct VertexOutput { + @builtin(position) Position : vec4, + @location(0) fragUV : vec2, + } + + @vertex + fn vert_main(@builtin(vertex_index) VertexIndex : u32) -> VertexOutput { + var pos = array, 6>( + vec2( 1.0, 1.0), + vec2( 1.0, -1.0), + vec2(-1.0, -1.0), + vec2( 1.0, 1.0), + vec2(-1.0, -1.0), + vec2(-1.0, 1.0) + ); + + var uv = array, 6>( + vec2(1.0, 0.0), + vec2(1.0, 1.0), + vec2(0.0, 1.0), + vec2(1.0, 0.0), + vec2(0.0, 1.0), + vec2(0.0, 0.0) + ); + + var output : VertexOutput; + output.Position = vec4(pos[VertexIndex], 0.0, 1.0); + output.fragUV = uv[VertexIndex]; + return output; + } + `; + const texQuadFrag = ` + @group(0) @binding(0) var mySampler : sampler; + @group(0) @binding(1) var myTexture : texture_2d; + + @fragment + fn frag_main(@location(0) fragUV : vec2) -> @location(0) vec4 { + return textureSample(myTexture, mySampler, fragUV); + } + `; + + const samplerDesc: GPUSamplerDescriptor = {}; + samplerDesc.label = 'filterSampler'; + samplerDesc.addressModeU = 'mirror-repeat'; + samplerDesc.addressModeV = 'mirror-repeat'; + samplerDesc.addressModeW = 'mirror-repeat'; + samplerDesc.magFilter = 'linear'; + samplerDesc.minFilter = 'linear'; + samplerDesc.mipmapFilter = 'linear'; + samplerDesc.lodMinClamp = 0.0; + samplerDesc.lodMaxClamp = 32.0; + samplerDesc.maxAnisotropy = 1; + mipmapData.sampler = nativeDevice.createSampler(samplerDesc); + + const shaderDescVert: GPUShaderModule = nativeDevice.createShaderModule({ + code: texQuadVert, + }); + mipmapData.vertShader = shaderDescVert; + const shaderDescFrag: GPUShaderModule = nativeDevice.createShaderModule({ + code: texQuadFrag, + }); + mipmapData.fragShader = shaderDescFrag; + + const samplerEntry: GPUBindGroupLayoutEntry = { + binding: 0, + visibility: GPUShaderStage.FRAGMENT, + sampler: { + type: 'filtering', + }, + }; + + const textureEntry: GPUBindGroupLayoutEntry = { + binding: 1, + visibility: GPUShaderStage.FRAGMENT, + texture: { + sampleType: TextureSampleTypeTrait(texture.format), + viewDimension: '2d', + multisampled: false, + }, + }; + + const bgLayoutDesc: GPUBindGroupLayoutDescriptor = { + label: 'fullscreenTexturedQuadBGLayout', + entries: [samplerEntry, textureEntry], + }; + + const bindGroupLayout = nativeDevice.createBindGroupLayout(bgLayoutDesc); + mipmapData.bindGroupLayout = bindGroupLayout; + + const pipelineLayoutDesc: GPUPipelineLayoutDescriptor = { + label: 'fullscreenTexturedQuadPipelineLayout', + bindGroupLayouts: [bindGroupLayout], + }; + + const pipelineLayout = nativeDevice.createPipelineLayout(pipelineLayoutDesc); + mipmapData.pipelineLayout = pipelineLayout; + + const vertexState: GPUVertexState = { + module: mipmapData.vertShader, + entryPoint: 'vert_main', + buffers: [], + }; + + const primitiveState: GPUPrimitiveState = { + topology: 'triangle-list', + frontFace: 'ccw', + cullMode: 'none', + }; + + const colorState: GPUColorTargetState = { + format, + writeMask: 0xF, + }; + + const fragState: GPUFragmentState = { + module: mipmapData.fragShader, + entryPoint: 'frag_main', + targets: [colorState], + }; + + const multisample: GPUMultisampleState = { + count: 1, + alphaToCoverageEnabled: false, + mask: 0xFFFFFFFF, + }; + + const pipelineDesc: GPURenderPipelineDescriptor = { + label: 'fullscreenTexturedQuadPipeline', + layout: pipelineLayout, + vertex: vertexState, + primitive: primitiveState, + fragment: fragState, + multisample, + }; + const pipeline = nativeDevice.createRenderPipeline(pipelineDesc); + mipmapData.pipeline = pipeline; + } + + const desc: GPUTextureViewDescriptor = { + format, + dimension: '2d', + baseMipLevel: fromLevel, + mipLevelCount: 1, + baseArrayLayer: baseLayer, + arrayLayerCount: 1, + aspect: 'all', + }; + + const commandEncoder: GPUCommandEncoder = nativeDevice.createCommandEncoder(); + + for (let i = fromLevel; i < fromLevel + levelCount; ++i) { + desc.baseMipLevel = i - 1; + const srcView: GPUTextureView = texture.gpuTexture!.createView(desc); + desc.baseMipLevel = i; + desc.baseArrayLayer = baseLayer; + desc.arrayLayerCount = 1; + const dstView: GPUTextureView = texture.gpuTexture!.createView(desc); + + const entries: GPUBindGroupEntry[] = [ + { + binding: 0, + resource: mipmapData.sampler, + }, + { + binding: 1, + resource: srcView, + }, + ]; + + const bindgroupDesc: GPUBindGroupDescriptor = { + layout: mipmapData.bindGroupLayout, + entries, + }; + + const bindGroup: GPUBindGroup = nativeDevice.createBindGroup(bindgroupDesc); + + const colorAttachment: GPURenderPassColorAttachment = { + view: dstView, + loadOp: 'clear', + storeOp: 'store', + clearValue: [0.88, 0.88, 0.88, 1.0], + }; + + const rpDesc: GPURenderPassDescriptor = { + colorAttachments: [colorAttachment], + }; + + const renderPassEncoder: GPURenderPassEncoder = commandEncoder.beginRenderPass(rpDesc); + renderPassEncoder.setPipeline(mipmapData.pipeline); + renderPassEncoder.setBindGroup(0, bindGroup); + renderPassEncoder.draw(6, 1, 0, 0); + renderPassEncoder.end(); + } + + const commandBuffer = commandEncoder.finish(); + nativeDevice.queue.submit([commandBuffer]); +} + +export function WebGPUCmdFuncCopyBuffersToTexture ( + device: WebGPUDevice, + buffers: ArrayBufferView[], + gpuTexture: IWebGPUTexture, + regions: BufferTextureCopy[], +): void { + const nativeDevice = device.nativeDevice!; + const dstFormat = gpuTexture.format; + const blockSize = formatAlignment(dstFormat); + const regionSize = regions.length; + for (let i = 0; i < regionSize; ++i) { + const region = regions[i]; + const bufferPixelWidth = region.buffStride > 0 ? region.buffStride : region.texExtent.width; + const bufferPixelHeight = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; + const bytesPerRow = FormatSize(dstFormat, region.texExtent.width, 1, 1); + const bufferBytesPerRow = FormatSize(dstFormat, bufferPixelWidth, 1, 1); + const bufferBytesPerImageSlice = FormatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, 1); + const bufferBytesPerImageLayer = FormatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, region.texExtent.depth); + const targetWidth = region.texExtent.width === 0 ? 0 : alignTo(region.texExtent.width, blockSize.width); + const targetHeight = region.texExtent.height === 0 ? 0 : alignTo(region.texExtent.height, blockSize.height); + const imgDataLayout: GPUImageDataLayout = { + offset: 0, + bytesPerRow: bufferBytesPerRow, + rowsPerImage: bufferPixelHeight, + }; + const compactInWidth = bufferPixelWidth === region.texExtent.width; + for (let l = region.texSubres.baseArrayLayer; l < region.texSubres.layerCount + region.texSubres.baseArrayLayer; l++) { + for (let d = region.texOffset.z; d < region.texExtent.depth + region.texOffset.z; d++) { + if (compactInWidth) { + const arrayBuffer: ArrayBufferView | ArrayBufferLike = buffers[i]; + let buffer: Uint8Array; // buffers and regions are a one-to-one mapping + if ('buffer' in arrayBuffer) { + buffer = new Uint8Array(arrayBuffer.buffer, arrayBuffer.byteOffset, arrayBuffer.byteLength); + } else { + buffer = new Uint8Array(arrayBuffer); + } + const srcData = new Uint8Array(buffer, buffer.byteOffset + + region.buffOffset + + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + + (d - region.texOffset.z) * bufferBytesPerImageSlice); + const copyTarget = { + texture: gpuTexture.gpuTexture!, + mipLevel: region.texSubres.mipLevel, + origin: { + x: region.texOffset.x, + y: region.texOffset.y, + z: l, + }, + }; + nativeDevice.queue.writeTexture(copyTarget, srcData, imgDataLayout, [targetWidth, targetHeight, region.texExtent.depth]); + } else { + for (let h = region.texOffset.y; h < region.texExtent.height + region.texOffset.y; h += blockSize.height) { + const srcData = new Uint8Array(buffers[i].buffer, buffers[i].byteOffset + + region.buffOffset + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + + ((d - region.texOffset.z) * bufferBytesPerImageSlice + + (h - region.texOffset.y) / blockSize.height * bufferBytesPerRow)); + const copyTarget = { + texture: gpuTexture.gpuTexture!, + mipLevel: region.texSubres.mipLevel, + origin: { + x: region.texOffset.x, + y: h, + z: l, + }, + }; + nativeDevice.queue.writeTexture(copyTarget, srcData, imgDataLayout, [targetWidth, blockSize.height, region.texExtent.depth]); + } + } + } + if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) { + genMipMap(device, gpuTexture, 1, gpuTexture.mipLevel - 1, 0); + } + } + } +} diff --git a/cocos/gfx/webgpu/webgpu-define.ts b/cocos/gfx/webgpu/webgpu-define.ts index 155206bef1..8d6d0da97b 100644 --- a/cocos/gfx/webgpu/webgpu-define.ts +++ b/cocos/gfx/webgpu/webgpu-define.ts @@ -128,7 +128,8 @@ WEBGPU && promiseForWebGPUInstantiation.then(() => { const oldCmdCopyBuffersToTexture = CommandBuffer.prototype.copyBuffersToTexture; CommandBuffer.prototype.copyBuffersToTexture = function (buffers: Readonly, texture: typeof Texture, regions: Readonly) { const ucharBuffers: Uint8Array[] = []; - for (let i = 0; i < buffers.length; ++i) { + const buffSize = buffers.length + for (let i = 0; i < buffSize; ++i) { const buffer = buffers[i]; if ('buffer' in buffer) { ucharBuffers.push(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)); @@ -142,7 +143,8 @@ WEBGPU && promiseForWebGPUInstantiation.then(() => { const oldDeviceCopyBuffersToTexture = Device.prototype.copyBuffersToTexture; Device.prototype.copyBuffersToTexture = function (buffers: Readonly, texture: typeof Texture, regions: Readonly) { const ucharBuffers: Uint8Array[] = []; - for (let i = 0; i < buffers.length; ++i) { + const buffSize = buffers.length; + for (let i = 0; i < buffSize; ++i) { const buffer = buffers[i]; if ('buffer' in buffer) { ucharBuffers.push(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)); @@ -155,7 +157,8 @@ WEBGPU && promiseForWebGPUInstantiation.then(() => { Device.prototype.copyTexImagesToTexture = function (texImages: TexImageSource[], texture: typeof Texture, regions: BufferTextureCopy[]) { const buffers: Uint8Array[] = []; - for (let i = 0; i < regions.length; i++) { + const regionSize = regions.length; + for (let i = 0; i < regionSize; i++) { if ('getContext' in texImages[i]) { const canvasElem = texImages[i] as HTMLCanvasElement; const imageData = canvasElem.getContext('2d')?.getImageData(0, 0, texImages[i].width, texImages[i].height); @@ -255,10 +258,9 @@ WEBGPU && promiseForWebGPUInstantiation.then(() => { if (params.includes('sampler')) { const paramIndexSet = new Set(); const paramArr = params.split(','); - - for (let i = 0; i < paramArr.length; ++i) { + const paramSize = paramArr.length; + for (let i = 0; i < paramSize; ++i) { const paramDecl = paramArr[i].split(' '); - // assert(paramDecl.length >= 2) const typeDecl = paramDecl[paramDecl.length - 2]; if (typeDecl.includes('sampler') && typeDecl !== 'sampler') { const samplerType = typeDecl.replace('sampler', ''); @@ -284,7 +286,8 @@ WEBGPU && promiseForWebGPUInstantiation.then(() => { let params = stripStr.split(','); let queued = 0; // '(' let paramIndex = 0; - for (let i = 0; i < params.length; ++i) { + const currParamsSize = params.length; + for (let i = 0; i < currParamsSize; ++i) { if (params[i].includes('(')) { ++queued; } @@ -292,7 +295,7 @@ WEBGPU && promiseForWebGPUInstantiation.then(() => { --queued; } - if (!queued || i === params.length - 1) { + if (!queued || i === currParamsSize - 1) { if (paramIndexSet.has(paramIndex)) { params[i] += `, ${params[i]}_sampler`; } @@ -418,7 +421,8 @@ WEBGPU && promiseForWebGPUInstantiation.then(() => { const createShader = Device.prototype.createShader; Device.prototype.createShader = function (shaderInfo: ShaderInfo) { const wgslStages: string[] = []; - for (let i = 0; i < shaderInfo.stages.length; ++i) { + const stageSize = shaderInfo.stages.length; + for (let i = 0; i < stageSize; ++i) { let glslSource = seperateCombinedSamplerTexture(shaderInfo.stages[i].source); const stageStr = shaderInfo.stages[i].stage === ShaderStageFlagBit.VERTEX ? 'vertex' : shaderInfo.stages[i].stage === ShaderStageFlagBit.FRAGMENT ? 'fragment' : 'compute'; diff --git a/cocos/gfx/webgpu/webgpu-descriptor-set-layout.ts b/cocos/gfx/webgpu/webgpu-descriptor-set-layout.ts new file mode 100644 index 0000000000..6a584ecde9 --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-descriptor-set-layout.ts @@ -0,0 +1,227 @@ +/* + Copyright (c) 2024 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. +*/ + +import { DescriptorSetLayout } from '../base/descriptor-set-layout'; +import { IWebGPUGPUDescriptorSetLayout } from './webgpu-gpu-objects'; +import { GFXStageToWebGPUStage, GFXDescTypeToGPUBufferDescType, GFXSamplerToGPUSamplerDescType, + SEPARATE_SAMPLER_BINDING_OFFSET, TextureSampleTypeTrait } from './webgpu-commands'; +import { + DescriptorSetLayoutInfo, + DESCRIPTOR_DYNAMIC_TYPE, + DescriptorSetLayoutBinding, + Format, + DescriptorType, +} from '../base/define'; +import { DescUpdateFrequency, WebGPUDeviceManager, isBound } from './define'; +import { WebGPUTexture } from './webgpu-texture'; +import { DescriptorSet } from '../base/descriptor-set'; +import { WebGPUBuffer } from './webgpu-buffer'; +import { WebGPUSampler } from './webgpu-sampler'; + +export function FormatToWGPUFormatType (format: Format): GPUTextureSampleType { + if (format === Format.DEPTH_STENCIL) { + return 'unfilterable-float'; + } + return TextureSampleTypeTrait(format); +} +export class WebGPUDescriptorSetLayout extends DescriptorSetLayout { + get gpuDescriptorSetLayout (): IWebGPUGPUDescriptorSetLayout | null { return this._gpuDescriptorSetLayout!; } + + private _gpuDescriptorSetLayout: IWebGPUGPUDescriptorSetLayout | null = null; + private _bindGrpLayoutEntries: Map = new Map(); + + private _hasChange = false; + private _currBinds: number[] = []; + private _prepareEntries: GPUBindGroupLayoutEntry[] = []; + + public buffers: Map = new Map(); + public textures: Map = new Map(); + public samplers: Map = new Map(); + + public references: DescriptorSet[] = []; + public get currBinds (): number[] { + return this._currBinds; + } + public get prepareEntries (): GPUBindGroupLayoutEntry[] { + return this._prepareEntries; + } + public get bindGrpLayoutEntries (): Map { + return this._bindGrpLayoutEntries; + } + + public get hasChanged (): boolean { + return this._hasChange; + } + public resetChanged (): void { + this._hasChange = false; + } + public initialize (info: Readonly): void { + Array.prototype.push.apply(this._bindings, info.bindings); + + let descriptorCount = 0; let maxBinding = -1; + const flattenedIndices: number[] = []; + const bindingSize = this._bindings.length; + for (let i = 0; i < bindingSize; i++) { + const binding = this._bindings[i]; + flattenedIndices.push(descriptorCount); + descriptorCount += binding.count; + if (binding.binding > maxBinding) maxBinding = binding.binding; + } + + this._bindingIndices = Array(maxBinding + 1).fill(-1); + const descriptorIndices = this._descriptorIndices = Array(maxBinding + 1).fill(-1); + for (let i = 0; i < bindingSize; i++) { + const binding = this._bindings[i]; + this._bindingIndices[binding.binding] = i; + descriptorIndices[binding.binding] = flattenedIndices[i]; + } + const dynamicBindings: number[] = []; + for (let i = 0; i < bindingSize; i++) { + const binding = this._bindings[i]; + if (binding.descriptorType & DESCRIPTOR_DYNAMIC_TYPE) { + for (let j = 0; j < binding.count; j++) { + dynamicBindings.push(binding.binding); + } + } + } + this._gpuDescriptorSetLayout = { + bindings: this._bindings, + dynamicBindings, + descriptorIndices, + descriptorCount, + bindGroupLayout: null, + }; + } + + // In order to avoid binding exceeding the number specified by webgpu, + // gpulayout changes dynamically instead of binding everything at once. + public updateBindGroupLayout ( + binding: DescriptorSetLayoutBinding, + buffer: WebGPUBuffer | null, + texture: WebGPUTexture | null, + sampler: WebGPUSampler | null, + ): void { + let bindIdx = binding.binding; + const visibility = GFXStageToWebGPUStage(binding.stageFlags); + const entries = this._bindGrpLayoutEntries; + const wgpuDeviceInst = WebGPUDeviceManager.instance; + if (sampler) { + bindIdx += SEPARATE_SAMPLER_BINDING_OFFSET; + } + const currEntry: GPUBindGroupLayoutEntry = {} as GPUBindGroupLayoutEntry; + currEntry.binding = bindIdx; + currEntry.visibility = visibility; + if (buffer) { + currEntry.buffer = { type: GFXDescTypeToGPUBufferDescType(binding.descriptorType)! }; + currEntry.buffer.hasDynamicOffset = !!(binding.descriptorType & (DescriptorType.DYNAMIC_STORAGE_BUFFER + | DescriptorType.DYNAMIC_UNIFORM_BUFFER)); + entries.set(bindIdx, currEntry); + } + if (texture) { + const targetTex = texture; + currEntry.texture = { + sampleType: FormatToWGPUFormatType(texture.format), + viewDimension: targetTex.gpuTexture.gpuTarget, + multisampled: Number(targetTex.gpuTexture.samples) > 1, + }; + // const defaultTexture = wgpuDeviceInst.getDefaultDescResources(currEntry, targetTex.gpuTexture) as WebGPUTexture; + // this.textures.set(bindIdx, defaultTexture); + entries.set(bindIdx, currEntry); + } + if (sampler) { + currEntry.sampler = { type: GFXSamplerToGPUSamplerDescType(sampler.info) }; + // const defaultSampler = wgpuDeviceInst.getDefaultDescResources(currEntry, sampler.gpuSampler) as WebGPUSampler; + // this.samplers.set(bindIdx, defaultSampler); + entries.set(bindIdx, currEntry); + } + } + + public removeRef (ref: DescriptorSet): void { + const index = this.references.indexOf(ref); + if (index !== -1) { + this.references.splice(index, 1); + } + if (this.references.length === 0) { + this.clear(); + } + } + + public addRef (ref: DescriptorSet): void { + if (!this.references.includes(ref)) { + this.references.push(ref); + } + } + + public resetGroupLayout (): void { + if (this._gpuDescriptorSetLayout?.bindGroupLayout) { + this._gpuDescriptorSetLayout.bindGroupLayout = null; + this._hasChange = true; + } + } + + public prepare (frequency: DescUpdateFrequency, binds: number[], vertBinds: number[] = [], fragBinds: number[] = []): void { + if (isBound(binds, this._currBinds) && frequency !== DescUpdateFrequency.LOW + && binds.length === this._prepareEntries.length) return; + this._currBinds = binds; + if (frequency !== DescUpdateFrequency.LOW) { + this._prepareEntries.length = 0; + binds.forEach((bind: number) => { + let currGrpEntryLayout = this._bindGrpLayoutEntries.get(bind < 0 ? 0 : bind)!; + if (!currGrpEntryLayout && bind < 0) { + currGrpEntryLayout = Array.from(this._bindGrpLayoutEntries.values())[0]; + } + if (vertBinds.includes(currGrpEntryLayout.binding) && !(currGrpEntryLayout.visibility & GPUShaderStage.VERTEX)) { + currGrpEntryLayout.visibility |= GPUShaderStage.VERTEX; + } else if (!vertBinds.includes(currGrpEntryLayout.binding) && (currGrpEntryLayout.visibility & GPUShaderStage.VERTEX)) { + currGrpEntryLayout.visibility ^= GPUShaderStage.VERTEX; + } + if (fragBinds.includes(currGrpEntryLayout.binding) && !(currGrpEntryLayout.visibility & GPUShaderStage.FRAGMENT)) { + currGrpEntryLayout.visibility |= GPUShaderStage.FRAGMENT; + } else if (!fragBinds.includes(currGrpEntryLayout.binding) && (currGrpEntryLayout.visibility & GPUShaderStage.FRAGMENT)) { + currGrpEntryLayout.visibility ^= GPUShaderStage.FRAGMENT; + } + this._prepareEntries.push(currGrpEntryLayout); + }); + } else { + this._prepareEntries = Array.from(this._bindGrpLayoutEntries.values()); + } + this._hasChange = true; + const nativeDevice = WebGPUDeviceManager.instance.nativeDevice; + const bindGrpLayout = nativeDevice?.createBindGroupLayout({ entries: this._prepareEntries }); + this._gpuDescriptorSetLayout!.bindGroupLayout = bindGrpLayout!; + } + + public clear (): void { + this.buffers.clear(); + this.textures.clear(); + this.samplers.clear(); + this._bindGrpLayoutEntries.clear(); + } + + public destroy (): void { + this._bindings.length = 0; + this.clear(); + this._gpuDescriptorSetLayout = null; + } +} diff --git a/cocos/gfx/webgpu/webgpu-descriptor-set.ts b/cocos/gfx/webgpu/webgpu-descriptor-set.ts new file mode 100644 index 0000000000..c4800ff96a --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-descriptor-set.ts @@ -0,0 +1,302 @@ +/* + Copyright (c) 2024 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. +*/ + +import { DescriptorSet } from '../base/descriptor-set'; +import { WebGPUBuffer } from './webgpu-buffer'; +import { IWebGPUGPUDescriptorSet, IWebGPUGPUDescriptor, IWebGPUGPUBuffer } from './webgpu-gpu-objects'; +import { WebGPUSampler } from './webgpu-sampler'; +import { WebGPUTexture } from './webgpu-texture'; +import { FormatToWGPUFormatType, WebGPUDescriptorSetLayout } from './webgpu-descriptor-set-layout'; +import { + DescriptorSetInfo, + DESCRIPTOR_BUFFER_TYPE, + DESCRIPTOR_SAMPLER_TYPE, + DescriptorSetLayoutBinding, + DescriptorType, + ShaderStageFlagBit, +} from '../base/define'; +import { DescUpdateFrequency, WebGPUDeviceManager, isBound } from './define'; +import { SEPARATE_SAMPLER_BINDING_OFFSET } from './webgpu-commands'; + +export class WebGPUDescriptorSet extends DescriptorSet { + get gpuDescriptorSet (): IWebGPUGPUDescriptorSet { + return this._gpuDescriptorSet as IWebGPUGPUDescriptorSet; + } + + private _gpuDescriptorSet: IWebGPUGPUDescriptorSet | null = null; + private _bindGroupEntries: Map = new Map(); + private _prepareEntries: GPUBindGroupEntry[] = []; + private _currBinds: number[] = []; + private _needUpdate: boolean = false; + private _prepareDynOffsets: number[] = []; + private _dynamicOffsets: number[] = []; + private _dynamicOffsetNum: number = 0; + + get dynamicOffsetCount (): number { + return this._dynamicOffsetNum; + } + + public initialize (info: Readonly): void { + const layout = this._layout = info.layout as WebGPUDescriptorSetLayout; + layout.addRef(this); + const { bindings, descriptorIndices, descriptorCount } = layout.gpuDescriptorSetLayout!; + + this._buffers = Array(descriptorCount).fill(null); + this._textures = Array(descriptorCount).fill(null); + this._samplers = Array(descriptorCount).fill(null); + + const gpuDescriptors: IWebGPUGPUDescriptor[] = []; + const bindGroup = null!; + const bindGroupLayout = null!; + this._gpuDescriptorSet = { gpuDescriptors, descriptorIndices, bindGroup, bindGroupLayout }; + const bindingSize = bindings.length; + for (let i = 0; i < bindingSize; ++i) { + const binding = bindings[i]; + const bindCount = binding.count; + for (let j = 0; j < bindCount; j++) { + gpuDescriptors.push({ + type: binding.descriptorType, + gpuBuffer: null, + gpuTexture: null, + gpuSampler: null, + }); + } + } + } + + public destroy (): void { + const layout = (this._layout as WebGPUDescriptorSetLayout);// .removeRef(this); + layout.removeRef(this); + this._layout = null; + this._gpuDescriptorSet = null; + this._buffers.length = 0; + this._textures.length = 0; + this._samplers.length = 0; + this._bindGroupEntries.clear(); + } + + private _bindBufferEntry (bind: DescriptorSetLayoutBinding, buffer: WebGPUBuffer): void { + const destBind = this._gpuDescriptorSet!.gpuDescriptors[bind.binding]; + if (destBind) { + destBind.gpuBuffer = buffer.gpuBuffer; + } + const layout = this._layout as WebGPUDescriptorSetLayout; + const nativeBuffer = buffer.gpuBuffer.gpuBuffer; + const bindGrpEntry: GPUBindGroupEntry = { + binding: bind.binding, + resource: { + buffer: nativeBuffer!, + offset: buffer.gpuBuffer.gpuOffset, + size: buffer.gpuBuffer.size, + }, + }; + layout.updateBindGroupLayout(bind, buffer, null, null); + this._bindGroupEntries.set(bindGrpEntry.binding, bindGrpEntry); + buffer.resetChange(); + } + + private _bindTextureEntry (bind: DescriptorSetLayoutBinding, texture: WebGPUTexture): void { + this._gpuDescriptorSet!.gpuDescriptors[bind.binding].gpuTexture = texture.gpuTexture; + const layout = this._layout as WebGPUDescriptorSetLayout; + const nativeTexView = texture.getNativeTextureView()!; + const bindGrpEntry: GPUBindGroupEntry = { + binding: bind.binding, + resource: nativeTexView, + }; + layout.updateBindGroupLayout(bind, null, texture, null); + this._bindGroupEntries.set(bindGrpEntry.binding, bindGrpEntry); + texture.resetChange(); + } + + private _bindSamplerEntry (bind: DescriptorSetLayoutBinding, sampler: WebGPUSampler): void { + const samplerIdx = bind.binding + SEPARATE_SAMPLER_BINDING_OFFSET; + this._gpuDescriptorSet!.gpuDescriptors[bind.binding].gpuSampler = sampler.gpuSampler; + const layout = this._layout as WebGPUDescriptorSetLayout; + sampler.createGPUSampler(this._textures[bind.binding].levelCount); + const bindSamplerGrpEntry: GPUBindGroupEntry = { + binding: samplerIdx, + resource: sampler.gpuSampler?.gpuSampler as GPUSampler, + }; + layout.updateBindGroupLayout(bind, null, null, sampler); + this._bindGroupEntries.set(samplerIdx, bindSamplerGrpEntry); + sampler.resetChange(); + } + + private _bindResourceEntry (bind: number, resource: WebGPUBuffer | WebGPUTexture | WebGPUSampler): void { + const gpuSetLayout = this.layout as WebGPUDescriptorSetLayout; + const binding = gpuSetLayout.bindings[bind]; + if (resource instanceof WebGPUBuffer) { + this._bindBufferEntry(binding, resource); + } else if (resource instanceof WebGPUTexture) { + this._bindTextureEntry(binding, resource); + } else if (resource instanceof WebGPUSampler) { + this._bindSamplerEntry(binding, resource); + } + } + + private _applyBindGroup (): void { + if (this._isDirty && this._gpuDescriptorSet) { + const layout = this._layout as WebGPUDescriptorSetLayout; + this._bindGroupEntries.clear(); + this._dynamicOffsets.length = 0; + const descriptors = this._gpuDescriptorSet.gpuDescriptors; + const descCount = descriptors.length; + for (let i = 0; i < descCount; ++i) { + const binding = layout.gpuDescriptorSetLayout!.bindings[i]; + const bindIdx = binding.binding; + // const isNeedBind = this._isNeedBindFromLayout(bindIdx); + if (descriptors[i].type & DESCRIPTOR_BUFFER_TYPE) { + const buffer = this._buffers[i] as WebGPUBuffer; + if (buffer) { + this._bindBufferEntry(binding, buffer); + if (descriptors[i].type & (DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER)) { + this._dynamicOffsets.push(bindIdx); + } + } + } else if (descriptors[i].type & DESCRIPTOR_SAMPLER_TYPE) { + // texture + const currTex = this._textures[i] as WebGPUTexture; + if (currTex) { + this._bindTextureEntry(binding, currTex); + } + // sampler + const currSampler = this._samplers[i] as WebGPUSampler; + if (currSampler) { + this._bindSamplerEntry(binding, currSampler); + } + } + } + this._isDirty = false; + this._needUpdate = true; + } + } + + private _resetPrepareDynOffsets (): void { + this._prepareDynOffsets.length = 0; + this._dynamicOffsetNum = 0; + } + + private _hasIncludeDynamic (): boolean { + if (!this._dynamicOffsets.length) { + this._resetPrepareDynOffsets(); + return true; + } + for (const entry of this._prepareEntries) { + if (this._dynamicOffsets.includes(entry.binding) && !this._prepareDynOffsets.includes(entry.binding)) { + return false; + } + } + return true; + } + + private _hasResourceChange (bind: number, resource: WebGPUBuffer | WebGPUTexture | WebGPUSampler): boolean { + if (resource && resource.hasChange) { + this._bindResourceEntry(bind, resource); + return true; + } + return false; + } + + private _isResourceChange (binds: number[]): boolean { + return binds.every((bind) => { + const resource = this._buffers[bind] as WebGPUBuffer || this._textures[bind] || this._samplers[bind]; + return !this._hasResourceChange(bind, resource); + }); + } + + public prepare (frequency: DescUpdateFrequency, binds: number[], vertBinds: number[] = [], fragBinds: number[] = []): void { + // set null + const layout = this._layout as WebGPUDescriptorSetLayout; + if (!binds) { + const device = WebGPUDeviceManager.instance; + if (!this._bindGroupEntries.size) { + const gpuSetLayout = device.defaultResource.setLayout as WebGPUDescriptorSetLayout; + const binding = gpuSetLayout.bindings[0]; + this._bindBufferEntry(binding, device.defaultResource.buffer); + this._needUpdate = true; + this.prepare(frequency, [-1]); + } else { + this.prepare(frequency, [-1]); + } + // this._resetPrepareDynOffsets(); + return; + } + const isLowFrequency = frequency === DescUpdateFrequency.LOW; + const breakUpdate = !this._needUpdate && (isLowFrequency ? this._gpuDescriptorSet!.bindGroup + : (isBound(binds, this._currBinds) && isBound(binds, layout.currBinds))) + && this._hasIncludeDynamic() && this._isResourceChange(binds); + if (breakUpdate) return; + this._needUpdate = false; + this._currBinds = binds; + this._resetPrepareDynOffsets(); + this._prepareEntries.length = 0; + if (!isLowFrequency) { + binds.forEach((bind: number) => { + const currBind = bind < 0 ? 0 : bind; + let currGrpEntry = this._bindGroupEntries.get(currBind)!; + if (!currGrpEntry && bind < 0) { + currGrpEntry = Array.from(this._bindGroupEntries.values())[0]; + } + if (this._dynamicOffsets.includes(currGrpEntry.binding)) { + this._prepareDynOffsets.push(currGrpEntry.binding); + this._dynamicOffsetNum++; + } + this._prepareEntries.push(currGrpEntry); + }); + } else { + this._bindGroupEntries.forEach((val, currBind) => { + if (val.resource instanceof GPUTextureView) { + const currTex = this._textures[currBind] as WebGPUTexture; + const texFormat = FormatToWGPUFormatType(currTex.format); + if (layout.bindGrpLayoutEntries.get(currBind)?.texture?.sampleType !== texFormat) { + layout.updateBindGroupLayout(layout.gpuDescriptorSetLayout!.bindings[currBind], null, currTex, null); + } + } + this._prepareEntries.push(val); + if (this._dynamicOffsets.includes(currBind)) { + this._prepareDynOffsets.push(currBind); + this._dynamicOffsetNum++; + } + }); + } + layout.prepare(frequency, binds, vertBinds, fragBinds); + this._createBindGroup(); + } + + private _createBindGroup (): void { + const device = WebGPUDeviceManager.instance; + const nativeDevice = device.nativeDevice; + const layout = this._layout as WebGPUDescriptorSetLayout; + const bindGroup = nativeDevice?.createBindGroup({ + layout: layout.gpuDescriptorSetLayout!.bindGroupLayout!, + entries: this._prepareEntries, + }); + this._gpuDescriptorSet!.bindGroupLayout = layout.gpuDescriptorSetLayout!.bindGroupLayout!; + this._gpuDescriptorSet!.bindGroup = bindGroup!; + } + + public update (): void { + this._applyBindGroup(); + } +} diff --git a/cocos/gfx/webgpu/webgpu-device.ts b/cocos/gfx/webgpu/webgpu-device.ts new file mode 100644 index 0000000000..9f992a35a4 --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-device.ts @@ -0,0 +1,788 @@ +/* + Copyright (c) 2024 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. +*/ + +import { fetchUrl } from 'pal/wasm'; +import glslangUrl from 'external:emscripten/webgpu/glslang.wasm'; +import twgslUrl from 'external:emscripten/webgpu/twgsl.wasm'; +import glslangLoader from 'external:emscripten/webgpu/glslang.js'; +import twgslLoader from 'external:emscripten/webgpu/twgsl.js'; +import { DescriptorSet } from '../base/descriptor-set'; +import { Buffer } from '../base/buffer'; +import { CommandBuffer } from '../base/command-buffer'; +import { Device } from '../base/device'; +import { Framebuffer } from '../base/framebuffer'; +import { InputAssembler } from '../base/input-assembler'; +import { PipelineState, PipelineStateInfo } from '../base/pipeline-state'; +import { Queue } from '../base/queue'; +import { RenderPass } from '../base/render-pass'; +import { Sampler } from '../base/states/sampler'; +import { Shader } from '../base/shader'; +import { PipelineLayout } from '../base/pipeline-layout'; +import { DescriptorSetLayout } from '../base/descriptor-set-layout'; +import { Texture } from '../base/texture'; +import { WebGPUDescriptorSet } from './webgpu-descriptor-set'; +import { WebGPUBuffer } from './webgpu-buffer'; +import { WebGPUCommandBuffer } from './webgpu-command-buffer'; +import { WebGPUFramebuffer } from './webgpu-framebuffer'; +import { WebGPUInputAssembler } from './webgpu-input-assembler'; +import { WebGPUDescriptorSetLayout } from './webgpu-descriptor-set-layout'; +import { WebGPUPipelineLayout } from './webgpu-pipeline-layout'; +import { WebGPUPipelineState } from './webgpu-pipeline-state'; +import { WebGPUQueue } from './webgpu-queue'; +import { WebGPURenderPass } from './webgpu-render-pass'; +import { WebGPUSampler } from './webgpu-sampler'; +import { WebGPUShader } from './webgpu-shader'; +import { WebGPUStateCache } from './webgpu-state-cache'; +import { WebGPUTexture } from './webgpu-texture'; +import { DefaultResources, DescUpdateFrequency, hashCombineNum, hashCombineStr, WebGPUDeviceManager } from './define'; +import { + Filter, Format, + QueueType, Feature, BufferTextureCopy, Rect, DescriptorSetInfo, + BufferInfo, BufferViewInfo, CommandBufferInfo, DeviceInfo, BindingMappingInfo, + FramebufferInfo, InputAssemblerInfo, QueueInfo, RenderPassInfo, SamplerInfo, + ShaderInfo, PipelineLayoutInfo, DescriptorSetLayoutInfo, TextureInfo, TextureViewInfo, GeneralBarrierInfo, TextureBarrierInfo, + SwapchainInfo, + BufferBarrierInfo, + API, + FormatFeatureBit, + FormatFeature, + TextureType, + TextureUsageBit, + TextureFlagBit, + SampleCount, + BufferUsageBit, + MemoryUsageBit, + BufferFlagBit, + DescriptorSetLayoutBinding, + DescriptorType, + ShaderStageFlagBit, +} from '../base/define'; +import { WebGPUCommandAllocator } from './webgpu-command-allocator'; +import { GeneralBarrier } from '../base/states/general-barrier'; +import { TextureBarrier } from '../base/states/texture-barrier'; +import { BufferBarrier } from '../base/states/buffer-barrier'; +import { Swapchain } from '../base/swapchain'; +import { WebGPUSwapchain } from './webgpu-swapchain'; + +import { IWebGPUBindingMapping, IWebGPUGPUBuffer as IWebGPUBuffer, IWebGPUGPUSampler as IWebGPUSampler, IWebGPUTexture } from './webgpu-gpu-objects'; +import { debug, warn } from '../../core'; +import { WebGPUCmdFuncCopyBuffersToTexture, WebGPUCmdFuncCopyTexImagesToTexture, WebGPUCmdFuncCopyTextureToBuffer } from './webgpu-commands'; + +export class WebGPUDevice extends Device { + public createSwapchain (info: Readonly): Swapchain { + const swapchain = new WebGPUSwapchain(); + this._swapchain = swapchain; + swapchain.initialize(info); + return swapchain; + } + public getSampler (info: Readonly): Sampler { + const hash = Sampler.computeHash(info); + if (!this._samplers.has(hash)) { + this._samplers.set(hash, new WebGPUSampler(info, hash)); + } + return this._samplers.get(hash)!; + } + public getSwapchains (): readonly Swapchain[] { + return [this._swapchain as Swapchain]; + } + public getGeneralBarrier (info: Readonly): GeneralBarrier { + const hash = GeneralBarrier.computeHash(info); + if (!this._generalBarrierss.has(hash)) { + this._generalBarrierss.set(hash, new GeneralBarrier(info, hash)); + } + return this._generalBarrierss.get(hash)!; + } + public getTextureBarrier (info: Readonly): TextureBarrier { + const hash = TextureBarrier.computeHash(info); + if (!this._textureBarriers.has(hash)) { + this._textureBarriers.set(hash, new TextureBarrier(info, hash)); + } + return this._textureBarriers.get(hash)!; + } + public getBufferBarrier (info: Readonly): BufferBarrier { + const hash = BufferBarrier.computeHash(info); + if (!this._bufferBarriers.has(hash)) { + this._bufferBarriers.set(hash, new BufferBarrier(info, hash)); + } + return this._bufferBarriers.get(hash)!; + } + public async copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: readonly BufferTextureCopy[]): Promise { + await WebGPUCmdFuncCopyTextureToBuffer(this, (texture as WebGPUTexture).gpuTexture, buffers, regions); + } + public flushCommands (cmdBuffs: CommandBuffer[]): void { + // noop + } + + get isPremultipliedAlpha (): boolean { + if (!this._gpuConfig) { + return false; + } + return this._gpuConfig.alphaMode === 'premultiplied'; + } + + get multiDrawIndirectSupport (): boolean { + return this._multiDrawIndirect; + } + + get bindingMappings (): IWebGPUBindingMapping { + return this._bindingMappings!; + } + + get context (): GPUCanvasContext { + return this._context!; + } + + public stateCache: WebGPUStateCache = new WebGPUStateCache(); + public cmdAllocator: WebGPUCommandAllocator = new WebGPUCommandAllocator(); + public nullTex2D: WebGPUTexture | null = null; + public nullTexCube: WebGPUTexture | null = null; + public defaultResource: DefaultResources = new DefaultResources(); + + private _adapter: GPUAdapter | null | undefined = null; + private _device: GPUDevice | null | undefined = null; + private _context: GPUCanvasContext | null = null; + private _swapchain: WebGPUSwapchain | null = null; + private _glslang; + private _twgsl; + private _bindingMappings: IWebGPUBindingMapping | null = null; + private _multiDrawIndirect = false; + private _gpuConfig: GPUCanvasConfiguration | null = null; + protected _textureExclusive = new Array(Format.COUNT); + + public async initialize (info: Readonly): Promise { + WebGPUDeviceManager.setInstance(this); + return this.initDevice(info); + } + + set gpuConfig (config: GPUCanvasConfiguration) { + this._gpuConfig = config; + } + + get gpuConfig (): GPUCanvasConfiguration { + return this._gpuConfig!; + } + + get swapchainFormat (): GPUTextureFormat { + return 'rgba8unorm'; + } + + protected initFormatFeatures (exts: GPUSupportedFeatures): void { + this._formatFeatures.fill(FormatFeatureBit.NONE); + + this._textureExclusive.fill(true); + + let tempFeature: FormatFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE + | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.LINEAR_FILTER | FormatFeatureBit.VERTEX_ATTRIBUTE; + + this._formatFeatures[Format.R8] = tempFeature; + this._formatFeatures[Format.RG8] = tempFeature; + this._formatFeatures[Format.RGB8] = tempFeature; + this._formatFeatures[Format.RGBA8] = tempFeature; + + tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE + | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.LINEAR_FILTER; + + this._formatFeatures[Format.R8SN] = tempFeature; + this._formatFeatures[Format.RG8SN] = tempFeature; + this._formatFeatures[Format.RGB8SN] = tempFeature; + this._formatFeatures[Format.RGBA8SN] = tempFeature; + this._formatFeatures[Format.R5G6B5] = tempFeature; + this._formatFeatures[Format.RGBA4] = tempFeature; + this._formatFeatures[Format.RGB5A1] = tempFeature; + this._formatFeatures[Format.RGB10A2] = tempFeature; + + this._formatFeatures[Format.SRGB8] = tempFeature; + this._formatFeatures[Format.SRGB8_A8] = tempFeature; + + this._formatFeatures[Format.R11G11B10F] = tempFeature; + this._formatFeatures[Format.RGB9E5] = tempFeature; + + this._formatFeatures[Format.DEPTH] = tempFeature; + this._formatFeatures[Format.DEPTH_STENCIL] = tempFeature; + + this._formatFeatures[Format.RGB10A2UI] = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE + | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER; + + tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE + | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.VERTEX_ATTRIBUTE; + + this._formatFeatures[Format.R16F] = tempFeature; + this._formatFeatures[Format.RG16F] = tempFeature; + this._formatFeatures[Format.RGB16F] = tempFeature; + this._formatFeatures[Format.RGBA16F] = tempFeature; + + tempFeature = FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.RENDER_TARGET + | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.VERTEX_ATTRIBUTE; + + this._formatFeatures[Format.R32F] = tempFeature; + this._formatFeatures[Format.RG32F] = tempFeature; + this._formatFeatures[Format.RGB32F] = tempFeature; + this._formatFeatures[Format.RGBA32F] = tempFeature; + + this._formatFeatures[Format.RGB10A2UI] = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE + | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER; + + tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE + | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER | FormatFeatureBit.VERTEX_ATTRIBUTE; + + this._formatFeatures[Format.R8I] = tempFeature; + this._formatFeatures[Format.R8UI] = tempFeature; + this._formatFeatures[Format.R16I] = tempFeature; + this._formatFeatures[Format.R16UI] = tempFeature; + this._formatFeatures[Format.R32I] = tempFeature; + this._formatFeatures[Format.R32UI] = tempFeature; + + this._formatFeatures[Format.RG8I] = tempFeature; + this._formatFeatures[Format.RG8UI] = tempFeature; + this._formatFeatures[Format.RG16I] = tempFeature; + this._formatFeatures[Format.RG16UI] = tempFeature; + this._formatFeatures[Format.RG32I] = tempFeature; + this._formatFeatures[Format.RG32UI] = tempFeature; + + this._formatFeatures[Format.RGB8I] = tempFeature; + this._formatFeatures[Format.RGB8UI] = tempFeature; + this._formatFeatures[Format.RGB16I] = tempFeature; + this._formatFeatures[Format.RGB16UI] = tempFeature; + this._formatFeatures[Format.RGB32I] = tempFeature; + this._formatFeatures[Format.RGB32UI] = tempFeature; + + this._formatFeatures[Format.RGBA8I] = tempFeature; + this._formatFeatures[Format.RGBA8UI] = tempFeature; + this._formatFeatures[Format.RGBA16I] = tempFeature; + this._formatFeatures[Format.RGBA16UI] = tempFeature; + this._formatFeatures[Format.RGBA32I] = tempFeature; + this._formatFeatures[Format.RGBA32UI] = tempFeature; + + this._textureExclusive[Format.R8] = false; + this._textureExclusive[Format.RG8] = false; + this._textureExclusive[Format.RGB8] = false; + this._textureExclusive[Format.R5G6B5] = false; + this._textureExclusive[Format.RGBA4] = false; + + this._textureExclusive[Format.RGB5A1] = false; + this._textureExclusive[Format.RGBA8] = false; + this._textureExclusive[Format.RGB10A2] = false; + this._textureExclusive[Format.RGB10A2UI] = false; + this._textureExclusive[Format.SRGB8_A8] = false; + + this._textureExclusive[Format.R8I] = false; + this._textureExclusive[Format.R8UI] = false; + this._textureExclusive[Format.R16I] = false; + this._textureExclusive[Format.R16UI] = false; + this._textureExclusive[Format.R32I] = false; + this._textureExclusive[Format.R32UI] = false; + + this._textureExclusive[Format.RG8I] = false; + this._textureExclusive[Format.RG8UI] = false; + this._textureExclusive[Format.RG16I] = false; + this._textureExclusive[Format.RG16UI] = false; + this._textureExclusive[Format.RG32I] = false; + this._textureExclusive[Format.RG32UI] = false; + + this._textureExclusive[Format.RGBA8I] = false; + this._textureExclusive[Format.RGBA8UI] = false; + this._textureExclusive[Format.RGBA16I] = false; + this._textureExclusive[Format.RGBA16UI] = false; + this._textureExclusive[Format.RGBA32I] = false; + this._textureExclusive[Format.RGBA32UI] = false; + + this._textureExclusive[Format.DEPTH] = false; + this._textureExclusive[Format.DEPTH_STENCIL] = false; + + if (exts.has('float32-filterable')) { + this._formatFeatures[Format.R32F] |= FormatFeatureBit.RENDER_TARGET; + this._formatFeatures[Format.RG32F] |= FormatFeatureBit.RENDER_TARGET; + this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.RENDER_TARGET; + + this._textureExclusive[Format.R32F] = false; + this._textureExclusive[Format.RG32F] = false; + this._textureExclusive[Format.RGBA32F] = false; + + this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.LINEAR_FILTER; + this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.LINEAR_FILTER; + this._formatFeatures[Format.R32F] |= FormatFeatureBit.LINEAR_FILTER; + this._formatFeatures[Format.RG32F] |= FormatFeatureBit.LINEAR_FILTER; + } + + if (exts.has('shader-f16')) { + this._textureExclusive[Format.R16F] = false; + this._textureExclusive[Format.RG16F] = false; + this._textureExclusive[Format.RGBA16F] = false; + + this._formatFeatures[Format.RGB16F] |= FormatFeatureBit.LINEAR_FILTER; + this._formatFeatures[Format.RGBA16F] |= FormatFeatureBit.LINEAR_FILTER; + this._formatFeatures[Format.R16F] |= FormatFeatureBit.LINEAR_FILTER; + this._formatFeatures[Format.RG16F] |= FormatFeatureBit.LINEAR_FILTER; + } + + const compressedFeature: FormatFeature = FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER; + + if (exts.has('texture-compression-etc2')) { + this._formatFeatures[Format.ETC2_RGB8] = compressedFeature; + this._formatFeatures[Format.ETC2_RGBA8] = compressedFeature; + this._formatFeatures[Format.ETC2_SRGB8] = compressedFeature; + this._formatFeatures[Format.ETC2_SRGB8_A8] = compressedFeature; + this._formatFeatures[Format.ETC2_RGB8_A1] = compressedFeature; + this._formatFeatures[Format.ETC2_SRGB8_A1] = compressedFeature; + } + + if (exts.has('texture-compression-bc')) { + this._formatFeatures[Format.BC1] = compressedFeature; + this._formatFeatures[Format.BC1_ALPHA] = compressedFeature; + this._formatFeatures[Format.BC1_SRGB] = compressedFeature; + this._formatFeatures[Format.BC1_SRGB_ALPHA] = compressedFeature; + this._formatFeatures[Format.BC2] = compressedFeature; + this._formatFeatures[Format.BC2_SRGB] = compressedFeature; + this._formatFeatures[Format.BC3] = compressedFeature; + this._formatFeatures[Format.BC3_SRGB] = compressedFeature; + } + + if (exts.has('texture-compression-astc')) { + this._formatFeatures[Format.ASTC_RGBA_4X4] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_5X4] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_5X5] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_6X5] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_6X6] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_8X5] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_8X6] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_8X8] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_10X5] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_10X6] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_10X8] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_10X10] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_12X10] = compressedFeature; + this._formatFeatures[Format.ASTC_RGBA_12X12] = compressedFeature; + + this._formatFeatures[Format.ASTC_SRGBA_4X4] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_5X4] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_5X5] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_6X5] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_6X6] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_8X5] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_8X6] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_8X8] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_10X5] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_10X6] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_10X8] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_10X10] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_12X10] = compressedFeature; + this._formatFeatures[Format.ASTC_SRGBA_12X12] = compressedFeature; + } + } + + public getDefaultDescResources ( + entry: GPUBindGroupLayoutEntry, + resourceInfo: IWebGPUBuffer | IWebGPUTexture | IWebGPUSampler, + ): WebGPUBuffer | WebGPUTexture | WebGPUSampler | undefined { + let currHash = hashCombineNum(entry.visibility, 0); + const defaultRes = this.defaultResource; + if (entry.buffer) { + currHash = hashCombineStr(entry.buffer.type!, currHash); + if (entry.buffer.hasDynamicOffset) currHash = hashCombineNum(entry.buffer.hasDynamicOffset ? 1 : 0, currHash); + if (entry.buffer.minBindingSize !== undefined) currHash = hashCombineNum(entry.buffer.minBindingSize, currHash); + if (defaultRes.buffersDescLayout.has(currHash)) { + return defaultRes.buffersDescLayout.get(currHash); + } + resourceInfo = resourceInfo as IWebGPUBuffer; + const bufferInfo = new BufferInfo(); + bufferInfo.usage = resourceInfo.usage; + bufferInfo.size = bufferInfo.stride = 16; + bufferInfo.memUsage = resourceInfo.memUsage; + bufferInfo.flags = resourceInfo.flags!; + defaultRes.buffersDescLayout.set(currHash, this.createBuffer(bufferInfo) as WebGPUBuffer); + return defaultRes.buffersDescLayout.get(currHash); + } else if (entry.texture) { + resourceInfo = resourceInfo as IWebGPUTexture; + currHash = hashCombineStr(entry.texture.sampleType!, currHash); + currHash = hashCombineStr(entry.texture.viewDimension!, currHash); + currHash = hashCombineNum(entry.texture.multisampled ? 1 : 0, currHash); + currHash = hashCombineNum(resourceInfo.mipLevel, currHash); + currHash = hashCombineNum(resourceInfo.arrayLayer, currHash); + if (defaultRes.texturesDescLayout.has(currHash)) { + return defaultRes.texturesDescLayout.get(currHash); + } + const texInfo = new TextureInfo( + resourceInfo.type, + resourceInfo.usage, + resourceInfo.format, + 2 ** (resourceInfo.mipLevel - 1), + 2 ** (resourceInfo.mipLevel - 1), + resourceInfo.flags, + resourceInfo.arrayLayer, + resourceInfo.mipLevel, + resourceInfo.samples, + 1, + ); + defaultRes.texturesDescLayout.set(currHash, this.createTexture(texInfo) as WebGPUTexture); + return defaultRes.texturesDescLayout.get(currHash); + } else if (entry.sampler) { + resourceInfo = resourceInfo as IWebGPUSampler; + currHash = hashCombineStr(entry.sampler.type!, currHash); + if (defaultRes.samplersDescLayout.has(currHash)) { + return defaultRes.samplersDescLayout.get(currHash); + } + const samplerInfo = new SamplerInfo(); + samplerInfo.minFilter = resourceInfo.minFilter; + samplerInfo.magFilter = resourceInfo.magFilter; + samplerInfo.mipFilter = resourceInfo.mipFilter; + samplerInfo.addressU = resourceInfo.addressU; + samplerInfo.addressV = resourceInfo.addressV; + samplerInfo.addressW = resourceInfo.addressW; + + defaultRes.samplersDescLayout.set(currHash, this.getSampler(samplerInfo) as WebGPUSampler); + return defaultRes.samplersDescLayout.get(currHash); + } + return undefined; + } + + private _createDefaultDescSet (): void { + const defaultResource = this.defaultResource; + // default set layout + const layoutInfo = new DescriptorSetLayoutInfo(); + const layoutBinding = new DescriptorSetLayoutBinding(); + layoutBinding.binding = 0; + layoutBinding.count = 1; + layoutBinding.descriptorType = DescriptorType.UNIFORM_BUFFER; + layoutBinding.stageFlags = ShaderStageFlagBit.VERTEX; + layoutInfo.bindings.push(layoutBinding); + defaultResource.setLayout = this.createDescriptorSetLayout(layoutInfo); + // default set + const descInfo = new DescriptorSetInfo(); + descInfo.layout = defaultResource.setLayout; + defaultResource.descSet = this.createDescriptorSet(descInfo); + defaultResource.descSet.bindBuffer(0, defaultResource.buffer); + defaultResource.descSet.update(); + (defaultResource.descSet as WebGPUDescriptorSet).prepare(DescUpdateFrequency.NORMAL, [0]); + } + + private async initDevice (info: Readonly): Promise { + const gpu = navigator.gpu; + this._adapter = await gpu?.requestAdapter(); + const maxVertAttrs = this._adapter!.limits.maxVertexAttributes; + const maxSampledTexPerShaderStage = this._adapter!.limits.maxSampledTexturesPerShaderStage; + const submitFeatures: GPUFeatureName[] = []; + if (this._adapter!.features.has('float32-filterable')) { + submitFeatures.push('float32-filterable'); + } else { + warn('Filterable 32-bit float textures support is not available'); + } + this._device = await this._adapter?.requestDevice({ + requiredLimits: { + // Must be changed, default support for 16 is not enough + maxVertexAttributes: maxVertAttrs, + maxSampledTexturesPerShaderStage: maxSampledTexPerShaderStage, + }, + requiredFeatures: submitFeatures, + }); + + this._glslang = await glslangLoader(await fetchUrl(glslangUrl)); + this._twgsl = await twgslLoader(await fetchUrl(twgslUrl)); + + this._gfxAPI = API.WEBGPU; + + const mapping = this._bindingMappingInfo = info.bindingMappingInfo; + const blockOffsets: number[] = []; + const samplerTextureOffsets: number[] = []; + const firstSet = mapping.setIndices[0]; + blockOffsets[firstSet] = 0; + samplerTextureOffsets[firstSet] = 0; + const mappingIdxSize = mapping.setIndices.length; + for (let i = 1; i < mappingIdxSize; ++i) { + const curSet = mapping.setIndices[i]; + const prevSet = mapping.setIndices[i - 1]; + // accumulate the per set offset according to the specified capacity + blockOffsets[curSet] = mapping.maxBlockCounts[prevSet] + blockOffsets[prevSet]; + samplerTextureOffsets[curSet] = mapping.maxSamplerTextureCounts[prevSet] + samplerTextureOffsets[prevSet]; + } + for (let i = 0; i < mappingIdxSize; ++i) { + const curSet = mapping.setIndices[i]; + // textures always come after UBOs + samplerTextureOffsets[curSet] -= mapping.maxBlockCounts[curSet]; + } + this._bindingMappings = { + blockOffsets, + samplerTextureOffsets, + flexibleSet: mapping.setIndices[mappingIdxSize - 1], + }; + + const canvas = Device.canvas; + this._context = canvas.getContext('webgpu')!; + const device: GPUDevice = this._device as GPUDevice; + + const adapterInfo = await this._adapter!.requestAdapterInfo(); + this._vendor = adapterInfo.vendor; + this._renderer = adapterInfo.device; + const description = adapterInfo.description; + + const limits = this._adapter!.limits; + this._caps.clipSpaceMinZ = 0.0; + this._caps.screenSpaceSignY = -1.0; + this._caps.uboOffsetAlignment = 256; + this._caps.maxUniformBufferBindings = 12; + this._caps.maxVertexAttributes = limits.maxVertexAttributes; + this._caps.maxUniformBufferBindings = limits.maxUniformBufferBindingSize; + this._caps.maxTextureSize = limits.maxTextureDimension2D; + this._caps.maxArrayTextureLayers = limits.maxTextureArrayLayers; + this._caps.max3DTextureSize = limits.maxTextureDimension3D; + this._caps.uboOffsetAlignment = limits.minUniformBufferOffsetAlignment; + + const features = this._adapter!.features; + // FIXME: require by query + this._multiDrawIndirect = false; + + this._features.fill(false); + this._features[Feature.ELEMENT_INDEX_UINT] = true; + this._features[Feature.INSTANCED_ARRAYS] = true; + this._features[Feature.MULTIPLE_RENDER_TARGETS] = true; + this._features[Feature.BLEND_MINMAX] = true; + this.initFormatFeatures(features); + + this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS)); + this._cmdBuff = this.createCommandBuffer(new CommandBufferInfo(this._queue)); + + const texInfo = new TextureInfo( + TextureType.TEX2D, + TextureUsageBit.NONE, + Format.RGBA8, + 16, + 16, + TextureFlagBit.NONE, + 1, + 1, + SampleCount.X1, + 1, + ); + const defaultDescTexResc = this.createTexture(texInfo); + + const bufferInfo = new BufferInfo( + BufferUsageBit.NONE, + MemoryUsageBit.NONE, + 16, + 16, // in bytes + BufferFlagBit.NONE, + ); + const defaultDescBuffResc = this.createBuffer(bufferInfo); + + const samplerInfo = new SamplerInfo(); + const defaultDescSmplResc = this.getSampler(samplerInfo); + const defaultResource = this.defaultResource; + defaultResource.buffer = defaultDescBuffResc as WebGPUBuffer; + defaultResource.texture = defaultDescTexResc as WebGPUTexture; + defaultResource.sampler = defaultDescSmplResc as WebGPUSampler; + this._createDefaultDescSet(); + + let compressedFormat = ''; + + if (this.getFormatFeatures(Format.ETC_RGB8)) { + compressedFormat += 'etc1 '; + } + + if (this.getFormatFeatures(Format.ETC2_RGB8)) { + compressedFormat += 'etc2 '; + } + + if (this.getFormatFeatures(Format.BC1)) { + compressedFormat += 'dxt '; + } + + if (this.getFormatFeatures(Format.PVRTC_RGB2)) { + compressedFormat += 'pvrtc '; + } + + if (this.getFormatFeatures(Format.ASTC_RGBA_4X4)) { + compressedFormat += 'astc '; + } + debug('WebGPU device initialized.'); + debug(`RENDERER: ${this._renderer}`); + debug(`VENDOR: ${this._vendor}`); + debug(`DESCRIPTION: ${description}`); + debug(`COMPRESSED_FORMAT: ${compressedFormat}`); + return Promise.resolve(true); + } + + public destroy (): void { + if (this._queue) { + this._queue.destroy(); + this._queue = null; + } + + if (this._cmdBuff) { + this._cmdBuff.destroy(); + this._cmdBuff = null; + } + + const it = this._samplers.values(); + let res = it.next(); + while (!res.done) { + (res.value as WebGPUSampler).destroy(); + res = it.next(); + } + + this._swapchain = null; + } + + public resize (width: number, height: number): void { + // noop + } + + public acquire (): void { + // noop + } + + get nativeDevice (): GPUDevice | null | undefined { + return this._device; + } + + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + public get glslang () { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this._glslang; + } + + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + public get twgsl () { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this._twgsl; + } + + public present (): void { + const queue = (this._queue as unknown as WebGPUQueue); + this._numDrawCalls = queue.numDrawCalls; + this._numInstances = queue.numInstances; + this._numTris = queue.numTris; + queue.clear(); + } + + public createCommandBuffer (info: CommandBufferInfo): CommandBuffer { + const cmdBuff = new WebGPUCommandBuffer(); + if (cmdBuff.initialize(info)) { + return cmdBuff; + } + return null!; + } + + public createBuffer (info: Readonly | Readonly): Buffer { + const buffer = new WebGPUBuffer(); + buffer.initialize(info); + return buffer; + } + + public createTexture (info: Readonly | Readonly): Texture { + const texture = new WebGPUTexture(); + texture.initialize(info); + return texture; + } + + public createDescriptorSet (info: Readonly): DescriptorSet { + const descriptorSet = new WebGPUDescriptorSet(); + descriptorSet.initialize(info); + return descriptorSet; + } + + public createShader (info: Readonly): Shader { + const shader = new WebGPUShader(); + shader.initialize(info); + return shader; + } + + public createInputAssembler (info: Readonly): InputAssembler { + const inputAssembler = new WebGPUInputAssembler(); + inputAssembler.initialize(info); + return inputAssembler; + } + + public createRenderPass (info: Readonly): RenderPass { + const renderPass = new WebGPURenderPass(); + renderPass.initialize(info); + return renderPass; + } + + public createFramebuffer (info: Readonly): Framebuffer { + const framebuffer = new WebGPUFramebuffer(); + framebuffer.initialize(info); + return framebuffer; + } + + public createDescriptorSetLayout (info: Readonly): DescriptorSetLayout { + const descriptorSetLayout = new WebGPUDescriptorSetLayout(); + descriptorSetLayout.initialize(info); + return descriptorSetLayout; + } + + public createPipelineLayout (info: PipelineLayoutInfo): PipelineLayout { + const pipelineLayout = new WebGPUPipelineLayout(); + if (pipelineLayout.initialize(info)) { + return pipelineLayout; + } + return null!; + } + + public createPipelineState (info: Readonly): PipelineState { + const pipelineState = new WebGPUPipelineState(); + pipelineState.initialize(info); + return pipelineState; + } + + public createQueue (info: QueueInfo): Queue { + const queue = new WebGPUQueue(); + if (queue.initialize(info)) { + return queue; + } + return null!; + } + + public copyBuffersToTexture (buffers: ArrayBufferView[], texture: Texture, regions: BufferTextureCopy[]): void { + WebGPUCmdFuncCopyBuffersToTexture( + this, + buffers, + (texture as unknown as WebGPUTexture).gpuTexture, + regions, + ); + } + + public copyTexImagesToTexture ( + texImages: TexImageSource[], + texture: Texture, + regions: BufferTextureCopy[], + ): void { + WebGPUCmdFuncCopyTexImagesToTexture( + this, + texImages, + (texture as unknown as WebGPUTexture).gpuTexture, + regions, + ); + } + + public copyFramebufferToBuffer ( + srcFramebuffer: Framebuffer, + dstBuffer: ArrayBuffer, + regions: BufferTextureCopy[], + ): void { + // noop + } + + public blitFramebuffer (src: Framebuffer, dst: Framebuffer, srcRect: Rect, dstRect: Rect, filter: Filter): void { + // noop + } +} diff --git a/cocos/gfx/webgpu/webgpu-framebuffer.ts b/cocos/gfx/webgpu/webgpu-framebuffer.ts new file mode 100644 index 0000000000..3445fbddcb --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-framebuffer.ts @@ -0,0 +1,100 @@ +/* + Copyright (c) 2024 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. +*/ + +import { Framebuffer } from '../base/framebuffer'; +import { IWebGPUGPUFramebuffer, IWebGPUTexture } from './webgpu-gpu-objects'; +import { WebGPURenderPass } from './webgpu-render-pass'; +import { WebGPUTexture } from './webgpu-texture'; +import { FramebufferInfo } from '../base/define'; + +export class WebGPUFramebuffer extends Framebuffer { + get gpuFramebuffer (): IWebGPUGPUFramebuffer { + return this._gpuFramebuffer!; + } + + private _gpuFramebuffer: IWebGPUGPUFramebuffer | null = null; + public initialize (info: Readonly): void { + this._renderPass = info.renderPass; + this._colorTextures = info.colorTextures || []; + this._depthStencilTexture = info.depthStencilTexture || null; + + const gpuColorTextures: IWebGPUTexture[] = []; + let isOffscreen = true; + const colorTexSize = info.colorTextures.length; + for (let i = 0; i < colorTexSize; i++) { + const colorTexture = info.colorTextures[i] as WebGPUTexture; + if (colorTexture) { + const gpuTex = colorTexture.gpuTexture; + gpuColorTextures.push(gpuTex); + if (gpuTex.isSwapchainTexture) { + isOffscreen = false; + } + } + } + + let gpuDepthStencilTexture: IWebGPUTexture | null = null; + if (info.depthStencilTexture) { + gpuDepthStencilTexture = (info.depthStencilTexture as WebGPUTexture).gpuTexture; + } + let width = Number.MAX_SAFE_INTEGER; + let height = Number.MAX_SAFE_INTEGER; + this._gpuFramebuffer = { + gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass, + gpuColorTextures, + gpuDepthStencilTexture, + gpuFramebuffer: null, + isOffscreen, + get width (): number { + if (this.gpuColorTextures.length > 0) { + return this.gpuColorTextures[0].width; + } else if (this.gpuDepthStencilTexture) { + return this.gpuDepthStencilTexture.width; + } + return width; + }, + set width (val) { + width = val; + }, + get height (): number { + if (this.gpuColorTextures.length > 0) { + return this.gpuColorTextures[0].height; + } else if (this.gpuDepthStencilTexture) { + return this.gpuDepthStencilTexture.height; + } + return height; + }, + set height (val) { + height = val; + }, + }; + this._width = this._gpuFramebuffer.width; + this._height = this._gpuFramebuffer.height; + } + + public destroy (): void { + if (this._gpuFramebuffer) { + this._gpuFramebuffer = null; + } + } +} diff --git a/cocos/gfx/webgpu/webgpu-gpu-objects.ts b/cocos/gfx/webgpu/webgpu-gpu-objects.ts new file mode 100644 index 0000000000..62d687505f --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-gpu-objects.ts @@ -0,0 +1,308 @@ +/* + Copyright (c) 2024 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. +*/ + +import { + Address, + DescriptorType, + BufferUsage, + Filter, + Format, + MemoryUsage, + SampleCount, + ShaderStageFlagBit, + TextureFlags, + TextureType, + TextureUsage, + Type, + DynamicStateFlagBit, + DrawInfo, + Attribute, + ColorAttachment, + DepthStencilAttachment, + UniformBlock, + UniformSampler, + DescriptorSetLayoutBinding, + BufferFlags, + ComparisonFunc, +} from '../base/define'; +import { DescriptorSetLayout } from '../base/descriptor-set-layout'; +import { BlendState, DepthStencilState, RasterizerState } from '../base/pipeline-state'; +import { WebGPUDeviceManager } from './define'; +import { WebGPUFramebuffer } from './webgpu-framebuffer'; + +export interface IWebGPUGPUUniformInfo { + name: string; + type: Type; + count: number; + offset: number; + view: Float32Array | Int32Array; + isDirty: boolean; +} + +export interface IWebGPUGPUBuffer { + usage: BufferUsage; + memUsage: MemoryUsage; + size: number; + stride: number; + + gpuTarget: number; + gpuBuffer: GPUBuffer | null; + gpuOffset: number; + flags: BufferFlags | null; + buffer: ArrayBufferView | null; + indirects: DrawInfo[]; + drawIndirectByIndex: boolean; +} + +export interface IWebGPUTexture { + type: TextureType; + format: Format; + usage: TextureUsage; + width: number; + height: number; + depth: number; + size: number; + arrayLayer: number; + mipLevel: number; + samples: SampleCount; + flags: TextureFlags; + isPowerOf2: boolean; + + gpuTarget: GPUTextureViewDimension; // 1d, 2d, 3d + gpuInternalFmt: GPUTextureFormat;// rgba8unorm + gpuFormat: GPUTextureFormat; + gpuType: number; // data type, => gl.UNSIGNED_BYTE + gpuUsage: GPUTextureUsageFlags; // webgl:DYNIMIC_DRAW... -> webGPU:COPY_DST/STORAGE... + gpuTexture: GPUTexture | undefined; // native tex handler + gpuRenderbuffer: null; // not suitable for webgpu + gpuWrapS: GPUAddressMode; // clamp-to-edge, repeat... + gpuWrapT: GPUAddressMode; + gpuMinFilter: GPUFilterMode; // linear, nearest + gpuMagFilter: GPUFilterMode; + + isSwapchainTexture: boolean; + getTextureView: () => GPUTextureView | null; +} + +export interface IWebGPUGPURenderPass { + colorAttachments: ColorAttachment[]; + depthStencilAttachment: DepthStencilAttachment | null; + nativeRenderPass: GPURenderPassDescriptor | null; + originalRP: GPURenderPassDescriptor | null; +} + +export interface IWebGPUGPUFramebuffer { + gpuRenderPass: IWebGPUGPURenderPass; + gpuColorTextures: IWebGPUTexture[]; + gpuDepthStencilTexture: IWebGPUTexture | null; + isOffscreen?: boolean; + gpuFramebuffer: WebGPUFramebuffer | null; + width: number; + height: number; +} + +export interface IWebGPUGPUSampler { + gpuSampler: GPUSampler | null; + compare: ComparisonFunc; + minFilter: Filter; + magFilter: Filter; + mipFilter: Filter; + addressU: Address; + addressV: Address; + addressW: Address; + mipLevel: number; + maxAnisotropy: number; + + gpuMinFilter: GPUFilterMode; + gpuMagFilter: GPUFilterMode; + gpuMipFilter: GPUFilterMode; + gpuWrapS: GPUAddressMode; + gpuWrapT: GPUAddressMode; + gpuWrapR: GPUAddressMode; +} + +export interface IWebGPUGPUInput { + name: string; + type: Type; + stride: number; + count: number; + size: number; + + gpuType: number; + gpuLoc: number; +} + +export interface IWebGPUGPUUniform { + binding: number; + name: string; + type: Type; + stride: number; + count: number; + size: number; + offset: number; + + gpuType: number; + gpuLoc: number; + array: number[]; + begin: number; +} + +export interface IWebGPUGPUUniformBlock { + set: number; + binding: number; + idx: number; + name: string; + size: number; + gpuBinding: number; +} + +export interface IWebGPUGPUUniformSampler { + set: number; + binding: number; + name: string; + type: Type; + count: number; + units: number[]; + gpuUnits: Int32Array; + + gpuType: number; + gpuLoc: number; +} + +export interface IWebGPUGPUShaderStage { + type: ShaderStageFlagBit; + source: string; + gpuShader: GPUProgrammableStage | null; + bindings: number[][]; + attrs: Map; +} + +export interface IWebGPUGPUShader { + name: string; + blocks: UniformBlock[]; + samplers: UniformSampler[]; + + gpuStages: IWebGPUGPUShaderStage[]; + gpuProgram: number | null; + gpuInputs: IWebGPUGPUInput[]; + gpuUniforms: IWebGPUGPUUniform[]; + gpuBlocks: IWebGPUGPUUniformBlock[]; + gpuSamplers: IWebGPUGPUUniformSampler[]; + bindings: Map; +} + +export interface IWebGPUGPUDescriptorSetLayout { + bindings: DescriptorSetLayoutBinding[]; + dynamicBindings: number[]; + descriptorIndices: number[]; + descriptorCount: number; + bindGroupLayout: GPUBindGroupLayout | null; +} + +export interface IWebGPUGPUPipelineLayout { + setLayouts: DescriptorSetLayout[]; + gpuSetLayouts: IWebGPUGPUDescriptorSetLayout[]; + gpuBindGroupLayouts: GPUBindGroupLayout[]; + dynamicOffsetCount: number; + dynamicOffsetIndices: number[][]; + nativePipelineLayout: GPUPipelineLayout; +} + +export interface IWebGPUGPUPipelineState { + gpuPrimitive: GPUPrimitiveTopology; + gpuShader: IWebGPUGPUShader | null; + gpuPipelineLayout: IWebGPUGPUPipelineLayout | null; + rs: RasterizerState; + dss: DepthStencilState; + stencilRef: number; + bs: BlendState; + dynamicStates: DynamicStateFlagBit[]; + gpuRenderPass: IWebGPUGPURenderPass | null; + pipelineState: GPURenderPipelineDescriptor | undefined; + nativePipeline: GPUPipelineBase | undefined; +} + +export interface IWebGPUGPUDescriptor { + type: DescriptorType; + gpuBuffer: IWebGPUGPUBuffer | null; + gpuTexture: IWebGPUTexture | null; + gpuSampler: IWebGPUGPUSampler | null; +} + +export interface IWebGPUGPUDescriptorSet { + gpuDescriptors: IWebGPUGPUDescriptor[]; + descriptorIndices: number[]; + bindGroup: GPUBindGroup; + bindGroupLayout: GPUBindGroupLayout; +} + +export interface IWebGPUAttrib { + name: string; + gpuBuffer: GPUBuffer | null; + gpuType: number; + size: number; + count: number; + stride: number; + componentCount: number; + isNormalized: boolean; + isInstanced: boolean; + offset: number; +} + +export interface IWebGPUGPUInputAssembler { + attributes: Attribute[]; + gpuVertexBuffers: IWebGPUGPUBuffer[]; + gpuIndexBuffer: IWebGPUGPUBuffer | null; + gpuIndirectBuffer: IWebGPUGPUBuffer | null; + + gpuAttribs: IWebGPUAttrib[]; + gpuIndexType: GPUIndexFormat; +} + +export interface IWebGPUBindingMapping { + blockOffsets: number[]; + samplerTextureOffsets: number[]; + flexibleSet: number; +} + +export class IWebGPUBlitManager { + private _srcFramebuffer: WebGPUFramebuffer | null = null; + private _dstFramebuffer: WebGPUFramebuffer | null = null; + + get srcFramebuffer (): WebGPUFramebuffer | null { + return this._srcFramebuffer; + } + + get dstFramebuffer (): WebGPUFramebuffer | null { + return this._dstFramebuffer; + } + + constructor () { + const device = WebGPUDeviceManager.instance; + } + + destroy (): void { + // noop + } +} diff --git a/cocos/gfx/webgpu/webgpu-input-assembler.ts b/cocos/gfx/webgpu/webgpu-input-assembler.ts new file mode 100644 index 0000000000..263376eb3a --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-input-assembler.ts @@ -0,0 +1,115 @@ +/* + Copyright (c) 2024 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. +*/ + +import { InputAssembler } from '../base/input-assembler'; +import { WebGPUBuffer } from './webgpu-buffer'; +import { WebGPUCmdFuncCreateInputAssember, WebGPUCmdFuncDestroyInputAssembler } from './webgpu-commands'; +import { IWebGPUGPUInputAssembler, IWebGPUGPUBuffer } from './webgpu-gpu-objects'; +import { InputAssemblerInfo } from '../base/define'; +import { WebGPUDeviceManager } from './define'; +import { error } from '../../core'; + +export class WebGPUInputAssembler extends InputAssembler { + public get gpuInputAssembler (): IWebGPUGPUInputAssembler { + return this._gpuInputAssembler!; + } + + private _gpuInputAssembler: IWebGPUGPUInputAssembler | null = null; + + public initialize (info: Readonly): void { + if (info.vertexBuffers.length === 0) { + error('InputAssemblerInfo.vertexBuffers is null.'); + return; + } + + this._attributes = info.attributes; + this._attributesHash = this.computeAttributesHash(); + this._vertexBuffers = info.vertexBuffers; + + if (info.indexBuffer) { + this._indexBuffer = info.indexBuffer; + this.drawInfo.indexCount = this._indexBuffer.size / this._indexBuffer.stride; + this.drawInfo.firstIndex = 0; + } else { + const vertBuff = this._vertexBuffers[0]; + this.drawInfo.vertexCount = vertBuff.size / vertBuff.stride; + this.drawInfo.firstVertex = 0; + this.drawInfo.vertexOffset = 0; + } + + this._drawInfo.instanceCount = 0; + this._drawInfo.firstInstance = 0; + + this._indirectBuffer = info.indirectBuffer || null; + const vertBuffSize = info.vertexBuffers.length; + const gpuVertexBuffers: IWebGPUGPUBuffer[] = new Array(vertBuffSize); + for (let i = 0; i < vertBuffSize; ++i) { + const vb = info.vertexBuffers[i] as WebGPUBuffer; + if (vb.gpuBuffer) { + gpuVertexBuffers[i] = vb.gpuBuffer; + } + } + + let gpuIndexBuffer: IWebGPUGPUBuffer | null = null; + let gpuIndexType: GPUIndexFormat = 'uint16'; + if (info.indexBuffer) { + gpuIndexBuffer = (info.indexBuffer as WebGPUBuffer).gpuBuffer; + if (gpuIndexBuffer) { + switch (gpuIndexBuffer.stride) { + // case 1: gpuIndexType = 0x1401; break; // => WebGLRenderingContext.UNSIGNED_BYTE + case 2: gpuIndexType = 'uint16'; break; // => WebGLRenderingContext.UNSIGNED_SHORT + case 4: gpuIndexType = 'uint32'; break; // => WebGLRenderingContext.UNSIGNED_INT + default: { + error('Illegal index buffer stride.'); + } + } + } + } + + let gpuIndirectBuffer: IWebGPUGPUBuffer | null = null; + if (info.indirectBuffer) { + gpuIndirectBuffer = (info.indirectBuffer as WebGPUBuffer).gpuBuffer; + } + + this._gpuInputAssembler = { + attributes: info.attributes, + gpuVertexBuffers, + gpuIndexBuffer, + gpuIndirectBuffer, + + gpuAttribs: [], + gpuIndexType, + }; + + WebGPUCmdFuncCreateInputAssember(WebGPUDeviceManager.instance, this._gpuInputAssembler); + } + + public destroy (): void { + const WebGPUDev = WebGPUDeviceManager.instance; + if (this._gpuInputAssembler) { + WebGPUCmdFuncDestroyInputAssembler(WebGPUDev, this._gpuInputAssembler); + } + this._gpuInputAssembler = null; + } +} diff --git a/cocos/gfx/webgpu/webgpu-pipeline-layout.ts b/cocos/gfx/webgpu/webgpu-pipeline-layout.ts new file mode 100644 index 0000000000..2acd08898e --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-pipeline-layout.ts @@ -0,0 +1,109 @@ +/* + Copyright (c) 2024 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. +*/ + +import { PipelineLayout } from '../base/pipeline-layout'; +import { IWebGPUGPUPipelineLayout, IWebGPUGPUDescriptorSetLayout } from './webgpu-gpu-objects'; +import { WebGPUDescriptorSetLayout } from './webgpu-descriptor-set-layout'; +import { PipelineLayoutInfo } from '../base/define'; +import { WebGPUDeviceManager } from './define'; + +export class WebGPUPipelineLayout extends PipelineLayout { + get gpuPipelineLayout (): IWebGPUGPUPipelineLayout | null { return this._gpuPipelineLayout!; } + + private _gpuPipelineLayout: IWebGPUGPUPipelineLayout | null = null; + private _nativePipelineLayout!: GPUPipelineLayout; + private _bindGrpLayouts: GPUBindGroupLayout[] = []; + + public fetchPipelineLayout (resetAll: boolean = true): GPUPipelineLayout { + const gpuPipelineLayout = this._gpuPipelineLayout!; + if (resetAll) { + gpuPipelineLayout.gpuSetLayouts.length = 0; + gpuPipelineLayout.dynamicOffsetIndices.length = 0; + } + const webGPUDevice = WebGPUDeviceManager.instance; + const nativeDevice = webGPUDevice.nativeDevice; + this._bindGrpLayouts.length = 0; + const setLayoutSize = this._setLayouts.length; + for (let i = 0; i < setLayoutSize; i++) { + const setLayout = this._setLayouts[i] as WebGPUDescriptorSetLayout; + const bindGroupLayout = setLayout.gpuDescriptorSetLayout!.bindGroupLayout; + if (bindGroupLayout) { + if (resetAll) { + const dynamicBindings = setLayout.gpuDescriptorSetLayout!.dynamicBindings; + const indices: number[] = Array(setLayout.bindingIndices.length).fill(-1); + const dynBindSize = dynamicBindings.length; + for (let j = 0; j < dynBindSize; j++) { + const binding = dynamicBindings[j]; + if (indices[binding] < 0) indices[binding] = gpuPipelineLayout.dynamicOffsetCount + j; + } + + gpuPipelineLayout.gpuSetLayouts.push(setLayout.gpuDescriptorSetLayout!); + gpuPipelineLayout.dynamicOffsetIndices.push(indices); + gpuPipelineLayout.dynamicOffsetCount += dynBindSize; + } + this._bindGrpLayouts[i] = bindGroupLayout; + } + // setLayout.resetChange(); + } + + this._nativePipelineLayout = nativeDevice?.createPipelineLayout({ bindGroupLayouts: this._bindGrpLayouts }) as GPUPipelineLayout; + return this._nativePipelineLayout; + } + + public initialize (info: PipelineLayoutInfo): boolean { + Array.prototype.push.apply(this._setLayouts, info.setLayouts); + + const dynamicOffsetIndices: number[][] = []; + + const gpuSetLayouts: IWebGPUGPUDescriptorSetLayout[] = []; + + const dynamicOffsetCount = 0; + + // eslint-disable-next-line @typescript-eslint/no-this-alias + const that = this; + this._gpuPipelineLayout = { + setLayouts: this._setLayouts, + gpuSetLayouts, + dynamicOffsetIndices, + dynamicOffsetCount, + gpuBindGroupLayouts: this._bindGrpLayouts, + // In order to avoid binding exceeding the number specified by webgpu, + // gpulayout changes dynamically instead of binding everything at once. + get nativePipelineLayout (): GPUPipelineLayout { + return that._nativePipelineLayout; + }, + + }; + this.fetchPipelineLayout(); + return true; + } + + public changeSetLayout (idx: number, setLayout: WebGPUDescriptorSetLayout): void { + this._setLayouts[idx] = setLayout; + } + + public destroy (): void { + this._setLayouts.length = 0; + } +} diff --git a/cocos/gfx/webgpu/webgpu-pipeline-state.ts b/cocos/gfx/webgpu/webgpu-pipeline-state.ts new file mode 100644 index 0000000000..e360035633 --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-pipeline-state.ts @@ -0,0 +1,282 @@ +/* + Copyright (c) 2024 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. +*/ + +import { PipelineState, PipelineStateInfo } from '../base/pipeline-state'; +import { IWebGPUGPUInputAssembler, IWebGPUGPUPipelineState } from './webgpu-gpu-objects'; +import { WebGPURenderPass } from './webgpu-render-pass'; +import { WebGPUShader } from './webgpu-shader'; +import { BlendOp, CullMode, DynamicStateFlagBit, FormatInfos, PrimitiveMode, ShaderStageFlagBit } from '../base/define'; +import { WebGPUPipelineLayout } from './webgpu-pipeline-layout'; +import { + GFXFormatToWGPUFormat, + WebGPUBlendFactors, + WebGPUBlendOps, + WebGPUCompereFunc, + WebGPUStencilOp, + GFXFormatToWGPUVertexFormat, + WebGPUBlendMask, +} from './webgpu-commands'; +import { WebGPUDeviceManager } from './define'; + +const WebPUPrimitives: GPUPrimitiveTopology[] = [ + 'point-list', + 'line-list', + 'line-strip', + 'line-strip', // no line_loop in webgpu + 'line-list', + 'line-strip', + 'line-list', + 'triangle-list', + 'triangle-strip', + 'triangle-strip', + 'triangle-list', + 'triangle-strip', + 'triangle-strip', + 'triangle-strip', // no quad +]; + +export class WebGPUPipelineState extends PipelineState { + get gpuPipelineState (): IWebGPUGPUPipelineState { + return this._gpuPipelineState!; + } + + private _gpuPipelineState: IWebGPUGPUPipelineState | null = null; + private _locations: Map = new Map(); + public initialize (info: Readonly): void { + this._primitive = info.primitive; + this._shader = info.shader; + this._pipelineLayout = info.pipelineLayout; + this._rs = info.rasterizerState; + this._dss = info.depthStencilState; + this._bs = info.blendState; + this._is = info.inputState; + this._renderPass = info.renderPass; + this._dynamicStates = info.dynamicStates; + + const dynamicStates: DynamicStateFlagBit[] = []; + for (let i = 0; i < 31; i++) { + if (this._dynamicStates & (1 << i)) { + dynamicStates.push(1 << i); + } + } + + // colorstates + const colorAttachments = this._renderPass.colorAttachments; + const colorDescs: GPUColorTargetState[] = []; + const colAttachmentSize = colorAttachments.length; + for (let i = 0; i < colAttachmentSize; i++) { + const colDesc: GPUColorTargetState = { + format: GFXFormatToWGPUFormat(colorAttachments[i].format), + writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask), + }; + if (this._bs.targets[i].blend) { + colDesc.blend = { + color: { + dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst], + operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq], + srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc], + }, + alpha: { + dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha], + operation: WebGPUBlendOps[this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq], + srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha], + }, + }; + } + colorDescs.push(colDesc); + } + + let vertexStage: GPUProgrammableStage; + let fragmentStage: GPUProgrammableStage; + const shaderStages = (this._shader as WebGPUShader).gpuShader.gpuStages; + const stageSize = shaderStages.length; + for (let i = 0; i < stageSize; i++) { + if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; } + if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; } + } + + const gpuShader = info.shader as WebGPUShader; + + const shaderAttrs = gpuShader.attributes; + const attrsSize = shaderAttrs.length; + for (let i = 0; i < attrsSize; i++) { + this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location); + } + const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP); + const renderPplDesc: GPURenderPipelineDescriptor = { + layout: 'auto', // later + vertex: { + module: vertexStage!.module, + entryPoint: 'main', + buffers: [], + }, + primitive: { + topology: WebPUPrimitives[info.primitive], + frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw', + cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back', + }, + + fragment: { + module: fragmentStage!.module, + entryPoint: 'main', + targets: colorDescs, + }, + }; + if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16'; + + // depthstencil states + let stencilRef = 0; + if (this._renderPass.depthStencilAttachment) { + const dssDesc = {} as GPUDepthStencilState; + dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment.format); + dssDesc.depthWriteEnabled = this._dss.depthWrite; + dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always'; + let stencilReadMask = 0; + let stencilWriteMask = 0; + + if (this._dss.stencilTestFront) { + dssDesc.stencilFront = { + compare: WebGPUCompereFunc[this._dss.stencilFuncFront], + depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront], + passOp: WebGPUStencilOp[this._dss.stencilPassOpFront], + failOp: WebGPUStencilOp[this._dss.stencilFailOpFront], + }; + stencilReadMask |= this._dss.stencilReadMaskFront; + stencilWriteMask |= this._dss.stencilWriteMaskFront; + stencilRef |= this._dss.stencilRefFront; + } + if (this._dss.stencilTestBack) { + dssDesc.stencilBack = { + compare: WebGPUCompereFunc[this._dss.stencilFuncBack], + depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack], + passOp: WebGPUStencilOp[this._dss.stencilPassOpBack], + failOp: WebGPUStencilOp[this._dss.stencilFailOpBack], + }; + stencilReadMask |= this._dss.stencilReadMaskBack; + stencilWriteMask |= this._dss.stencilWriteMaskBack; + stencilRef |= this._dss.stencilRefBack; + } + dssDesc.stencilReadMask = stencilReadMask; + dssDesc.stencilWriteMask = stencilWriteMask; + dssDesc.depthBias = this._rs.depthBias; + dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop; + dssDesc.depthBiasClamp = this._rs.depthBiasClamp; + renderPplDesc.depthStencil = dssDesc; + } + + this._gpuPipelineState = { + gpuPrimitive: WebPUPrimitives[info.primitive], + gpuShader: gpuShader.gpuShader, + gpuPipelineLayout: (info.pipelineLayout as WebGPUPipelineLayout).gpuPipelineLayout, + rs: info.rasterizerState, + dss: info.depthStencilState, + stencilRef, + bs: info.blendState, + gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass, + dynamicStates, + pipelineState: renderPplDesc, + nativePipeline: undefined, + }; + } + + protected _getShaderLocation (name: string): number | undefined { + return this._locations.get(name); + } + + public updatePipelineLayout (): void { + if (this._gpuPipelineState && this._gpuPipelineState.pipelineState) { + this._gpuPipelineState.pipelineState.layout = (this._pipelineLayout as WebGPUPipelineLayout).gpuPipelineLayout!.nativePipelineLayout; + } + } + + public prepare (ia: IWebGPUGPUInputAssembler, forceUpdate: boolean = false): void { + if (this._gpuPipelineState!.nativePipeline && !forceUpdate) { + return; + } + const gpuShader = this.shader; + const shaderAttrs = gpuShader.attributes; + const pipelineState = this._gpuPipelineState!.pipelineState!; + const vertexAttrs: GPUVertexBufferLayout[] = []; + const emptyPushAttr: string[] = []; + const streamCount = ia.gpuVertexBuffers.length; + for (let i = 0; i < streamCount; i++) { + const currBufferLayout: GPUVertexBufferLayout = { + arrayStride: 0, + attributes: [], + }; + const currAttrs: GPUVertexAttribute[] = []; + const shaderAttrSize = shaderAttrs.length; + for (let j = 0; j < shaderAttrSize; j++) { + const shaderAttr = shaderAttrs[j]; + let hasAttr = false; + const gpuAttrSize = ia.gpuAttribs.length; + for (let k = 0; k < gpuAttrSize; k++) { + const gpuAttr = ia.gpuAttribs[k]; + const attr = ia.attributes[k]; + if (attr.name === shaderAttr.name) { + hasAttr = true; + const loc = shaderAttr.location; + if (attr.stream === i) { + currBufferLayout.arrayStride = gpuAttr.stride; + currBufferLayout.stepMode = attr.isInstanced ? 'instance' : 'vertex'; + const attrLayout: GPUVertexAttribute = { + format: GFXFormatToWGPUVertexFormat(attr.format), + offset: gpuAttr.offset, + shaderLocation: loc, + }; + currAttrs.push(attrLayout); + } + break; + } + } + const format = shaderAttr.format; + if (!hasAttr && !emptyPushAttr.includes(shaderAttr.name) + && (FormatInfos[format].size <= ia.gpuVertexBuffers[i].stride)) { + emptyPushAttr.push(shaderAttr.name); + const attrLayout: GPUVertexAttribute = { + format: GFXFormatToWGPUVertexFormat(format), + offset: 0, + shaderLocation: shaderAttr.location, + }; + currAttrs.push(attrLayout); + } + } + + if (currAttrs.length) { + currBufferLayout.attributes = currAttrs; + vertexAttrs.push(currBufferLayout); + } + } + + pipelineState.vertex.buffers = vertexAttrs; + const webgpuDevice = (WebGPUDeviceManager.instance); + const nativeDevice = webgpuDevice.nativeDevice; + const nativePipeline = nativeDevice?.createRenderPipeline(pipelineState); + this._gpuPipelineState!.nativePipeline = nativePipeline; + } + + public destroy (): void { + this._gpuPipelineState = null; + } +} diff --git a/cocos/gfx/webgpu/webgpu-queue.ts b/cocos/gfx/webgpu/webgpu-queue.ts new file mode 100644 index 0000000000..4df451c765 --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-queue.ts @@ -0,0 +1,65 @@ +/* + Copyright (c) 2024 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. +*/ + +import { CommandBuffer } from '../base/command-buffer'; +import { Queue } from '../base/queue'; +import { WebGPUCommandBuffer } from './webgpu-command-buffer'; +import { QueueInfo } from '../base/define'; + +export class WebGPUQueue extends Queue { + public numDrawCalls = 0; + public numInstances = 0; + public numTris = 0; + + private _nativeQueue: GPUQueue | null = null; + private _isAsync = false; + public initialize (info: QueueInfo): boolean { + this._type = info.type; + + return true; + } + + public destroy (): void { + // noop + } + + public submit (cmdBuffs: CommandBuffer[]): void { + // TODO: Async + if (!this._isAsync) { + const cmdBuffSize = cmdBuffs.length; + for (let i = 0; i < cmdBuffSize; i++) { + const cmdBuff = cmdBuffs[i] as WebGPUCommandBuffer; + this.numDrawCalls += cmdBuff.numDrawCalls; + this.numInstances += cmdBuff.numInstances; + this.numTris += cmdBuff.numTris; + } + } + } + + public clear (): void { + this.numDrawCalls = 0; + this.numInstances = 0; + this.numTris = 0; + } +} diff --git a/cocos/gfx/webgpu/webgpu-render-pass.ts b/cocos/gfx/webgpu/webgpu-render-pass.ts new file mode 100644 index 0000000000..b5591b71a1 --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-render-pass.ts @@ -0,0 +1,90 @@ +/* + Copyright (c) 2024 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. +*/ + +import { RenderPass } from '../base/render-pass'; +import { IWebGPUGPURenderPass } from './webgpu-gpu-objects'; +import { LoadOp, StoreOp, RenderPassInfo, DepthStencilAttachment, ColorAttachment } from '../base/define'; + +export class WebGPURenderPass extends RenderPass { + public get gpuRenderPass (): IWebGPUGPURenderPass { + return this._gpuRenderPass!; + } + + private _gpuRenderPass: IWebGPUGPURenderPass | null = null; + private _generateColorAttachment (colorAttachment: ColorAttachment): GPURenderPassColorAttachment { + return { + view: {} as GPUTextureView, // later + loadOp: colorAttachment.loadOp === LoadOp.LOAD ? 'load' : 'clear', // what ever as long as not 'load' + storeOp: colorAttachment.storeOp === StoreOp.STORE ? 'store' : 'discard', + }; + } + private _generateDSAttachment (dsAttachment: DepthStencilAttachment): GPURenderPassDepthStencilAttachment { + const depthStencilDescriptor = {} as GPURenderPassDepthStencilAttachment; + depthStencilDescriptor.depthClearValue = 1.0; + depthStencilDescriptor.depthLoadOp = dsAttachment.depthLoadOp === LoadOp.CLEAR ? 'clear' : 'load'; + depthStencilDescriptor.depthStoreOp = dsAttachment.depthStoreOp === StoreOp.STORE ? 'store' : 'discard'; + depthStencilDescriptor.stencilClearValue = 0.0; + depthStencilDescriptor.stencilLoadOp = dsAttachment.stencilLoadOp === LoadOp.CLEAR ? 'clear' : 'load'; + depthStencilDescriptor.stencilStoreOp = dsAttachment.stencilStoreOp === StoreOp.STORE ? 'store' : 'discard'; + depthStencilDescriptor.view = {} as GPUTextureView; + return depthStencilDescriptor; + } + public initialize (info: Readonly): void { + this._colorInfos = info.colorAttachments; + this._depthStencilInfo = info.depthStencilAttachment; + this._subpasses = info.subpasses; + + const colorDescriptions: GPURenderPassColorAttachment[] = []; + const originalColorDesc: GPURenderPassColorAttachment[] = []; + for (const attachment of info.colorAttachments) { + originalColorDesc[colorDescriptions.length] = this._generateColorAttachment(attachment); + colorDescriptions[colorDescriptions.length] = this._generateColorAttachment(attachment); + } + + const renderPassDesc: GPURenderPassDescriptor = { + colorAttachments: colorDescriptions, + }; + const originalRPDesc: GPURenderPassDescriptor = { + colorAttachments: originalColorDesc, + }; + + if (info.depthStencilAttachment) { + const depthStencilDescriptor = this._generateDSAttachment(info.depthStencilAttachment); + const originalDepthStencilDesc = this._generateDSAttachment(info.depthStencilAttachment); + renderPassDesc.depthStencilAttachment = depthStencilDescriptor; + originalRPDesc.depthStencilAttachment = originalDepthStencilDesc; + } + + this._gpuRenderPass = { + colorAttachments: this._colorInfos, + depthStencilAttachment: this._depthStencilInfo, + nativeRenderPass: renderPassDesc, + originalRP: originalRPDesc, + }; + } + + public destroy (): void { + this._gpuRenderPass = null; + } +} diff --git a/cocos/gfx/webgpu/webgpu-sampler.ts b/cocos/gfx/webgpu/webgpu-sampler.ts new file mode 100644 index 0000000000..4a921d15da --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-sampler.ts @@ -0,0 +1,85 @@ +/* + Copyright (c) 2024 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. +*/ + +import { Sampler } from '../base/states/sampler'; +import { WebGPUCmdFuncCreateSampler, WebGPUCmdFuncDestroySampler } from './webgpu-commands'; +import { IWebGPUGPUSampler } from './webgpu-gpu-objects'; +import { SamplerInfo } from '../base/define'; +import { WebGPUDeviceManager } from './define'; + +export class WebGPUSampler extends Sampler { + public get gpuSampler (): IWebGPUGPUSampler { + return this._gpuSampler!; + } + + private _gpuSampler: IWebGPUGPUSampler | null = null; + private _hasChange: boolean = false; + get hasChange (): boolean { + return this._hasChange; + } + public resetChange (): void { + this._hasChange = false; + } + constructor (info: Readonly, hash: number) { + super(info, hash); + this._gpuSampler = { + gpuSampler: null, + compare: info.cmpFunc, + minFilter: info.minFilter, + magFilter: info.magFilter, + mipFilter: info.mipFilter, + addressU: info.addressU, + addressV: info.addressV, + addressW: info.addressW, + maxAnisotropy: info.maxAnisotropy, + mipLevel: 1, + + gpuMinFilter: 'linear', + gpuMagFilter: 'linear', + gpuMipFilter: 'linear', + gpuWrapS: 'clamp-to-edge', + gpuWrapT: 'clamp-to-edge', + gpuWrapR: 'clamp-to-edge', + }; + } + + public createGPUSampler (mipLevel: number = 1): void { + if (this._gpuSampler && !this.gpuSampler.gpuSampler) { + this._gpuSampler.mipLevel = mipLevel; + const device = WebGPUDeviceManager.instance; + this._hasChange = true; + WebGPUCmdFuncCreateSampler(device, this._gpuSampler); + } + } + + public destroy (): void { + if (!this._gpuSampler) { + return; + } + this._hasChange = true; + const device = WebGPUDeviceManager.instance; + WebGPUCmdFuncDestroySampler(device, this._gpuSampler); + this._gpuSampler = null; + } +} diff --git a/cocos/gfx/webgpu/webgpu-shader.ts b/cocos/gfx/webgpu/webgpu-shader.ts new file mode 100644 index 0000000000..73087c1200 --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-shader.ts @@ -0,0 +1,81 @@ +/* + Copyright (c) 2024 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. +*/ + +import { Shader } from '../base/shader'; +import { WebGPUCmdFuncCreateGPUShader, WebGPUCmdFuncDestroyShader } from './webgpu-commands'; +import { IWebGPUGPUShader, IWebGPUGPUShaderStage } from './webgpu-gpu-objects'; +import { ShaderInfo } from '../base/define'; +import { WebGPUDeviceManager } from './define'; + +export class WebGPUShader extends Shader { + get gpuShader (): IWebGPUGPUShader { + return this._gpuShader!; + } + + private _gpuShader: IWebGPUGPUShader | null = null; + + public initialize (info: Readonly): void { + this._name = info.name; + this._stages = info.stages; + this._attributes = info.attributes; + this._blocks = info.blocks; + this._samplers = info.samplers; + const stageSize = info.stages.length; + this._gpuShader = { + name: info.name, + blocks: info.blocks.slice(), + samplers: info.samplers, + + gpuStages: new Array(stageSize), + gpuProgram: null, + gpuInputs: [], + gpuUniforms: [], + gpuBlocks: [], + gpuSamplers: [], + bindings: new Map(), + }; + + for (let i = 0; i < stageSize; ++i) { + const stage = info.stages[i]; + this._gpuShader.gpuStages[i] = { + type: stage.stage, + source: stage.source, + gpuShader: null, + bindings: [], + attrs: new Map(), + }; + } + const device = WebGPUDeviceManager.instance; + WebGPUCmdFuncCreateGPUShader(device, this._gpuShader); + } + + public destroy (): void { + if (!this._gpuShader) { + return; + } + const device = WebGPUDeviceManager.instance; + WebGPUCmdFuncDestroyShader(device, this._gpuShader); + this._gpuShader = null; + } +} diff --git a/cocos/gfx/webgpu/webgpu-state-cache.ts b/cocos/gfx/webgpu/webgpu-state-cache.ts new file mode 100644 index 0000000000..6b8e2d18a7 --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-state-cache.ts @@ -0,0 +1,76 @@ +/* + Copyright (c) 2024 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. +*/ + +import { Rect, Viewport } from '../base/define'; +import { BlendState, DepthStencilState, RasterizerState } from '../base/pipeline-state'; +import { WebGPUBuffer } from './webgpu-buffer'; +import { WebGPUFramebuffer } from './webgpu-framebuffer'; +import { WebGPUInputAssembler } from './webgpu-input-assembler'; +import { WebGPUSampler } from './webgpu-sampler'; +import { WebGPUTexture } from './webgpu-texture'; + +export interface IWebGPUTexUnit { + gpuTexture: WebGPUTexture | null; +} + +export class WebGPUStateCache { + public gpuArrayBuffer: WebGPUBuffer | null = null; + public gpuElementArrayBuffer: WebGPUBuffer | null = null; + public gpuUniformBuffer: WebGPUBuffer | null = null; + public gpuBindUBOs: (WebGPUBuffer | null)[] = []; + public gpuBindUBOOffsets: number[] = []; + public texUnit: number = 0; + public gpuTexUnits: IWebGPUTexUnit[] = []; + public gpuSamplerUnits: (WebGPUSampler | null)[] = []; + public gpuFramebuffer: WebGPUFramebuffer | null = null; + public gpuReadFramebuffer: WebGPUFramebuffer | null = null; + public gpuInputAssembler: WebGPUInputAssembler | null = null; + public viewport = new Viewport(); + public scissorRect = new Rect(0, 0, 0, 0); + public rs = new RasterizerState(); + public dss = new DepthStencilState(); + public bs = new BlendState(); + public gpuEnabledAttribLocs: boolean[] = []; + public gpuCurrentAttribLocs: boolean[] = []; + public texUnitCacheMap: Record = {}; + + initialize (texUnit: number, bufferBindings: number, vertexAttributes: number): void { + for (let i = 0; i < texUnit; ++i) this.gpuTexUnits.push({ gpuTexture: null }); + + this.gpuSamplerUnits.length = texUnit; + this.gpuSamplerUnits.fill(null); + + this.gpuBindUBOs.length = bufferBindings; + this.gpuBindUBOs.fill(null); + + this.gpuBindUBOOffsets.length = bufferBindings; + this.gpuBindUBOOffsets.fill(0); + + this.gpuEnabledAttribLocs.length = vertexAttributes; + this.gpuEnabledAttribLocs.fill(false); + + this.gpuCurrentAttribLocs.length = vertexAttributes; + this.gpuCurrentAttribLocs.fill(false); + } +} diff --git a/cocos/gfx/webgpu/webgpu-swapchain.ts b/cocos/gfx/webgpu/webgpu-swapchain.ts new file mode 100644 index 0000000000..4deaf1a1bd --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-swapchain.ts @@ -0,0 +1,209 @@ +/* + Copyright (c) 2024 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. +*/ + +import { BufferTextureCopy, Format, SurfaceTransform, SwapchainInfo, + TextureFlagBit, TextureInfo, TextureType, TextureUsageBit } from '../base/define'; +import { Texture } from '../base/texture'; +import { Swapchain } from '../base/swapchain'; +import { WebGPUTexture } from './webgpu-texture'; +import { debug, warn, warnID } from '../../core'; +import { WebGPUDeviceManager } from './define'; +import { WGPUFormatToGFXFormat } from './webgpu-commands'; +import { IWebGPUBlitManager } from './webgpu-gpu-objects'; +/** + * @en GFX Swapchain implementation based on WebGPU. + * @zh 基于 WebGPU 的 GFX 交换链实现。 + */ +export class WebGPUSwapchain extends Swapchain { + public nullTex2D: WebGPUTexture = null!; + public nullTexCube: WebGPUTexture = null!; + private _canvas: HTMLCanvasElement | null = null; + private _blitManager: IWebGPUBlitManager | null = null; + get blitManager (): IWebGPUBlitManager | null { + return this._blitManager; + } + private _webGPUDeviceLostHandler: ((info: GPUDeviceLostInfo) => void) | null = null; + public initialize (info: Readonly): void { + this._canvas = info.windowHandle; + const { width, height } = info; + this._canvas.width = width; + this._canvas.height = height; + + this._webGPUDeviceLostHandler = this._onWebGPUDeviceLost.bind(this); + const device = WebGPUDeviceManager.instance; + const nativeDevice = device.nativeDevice as GPUDevice; + nativeDevice.lost.then(this._webGPUDeviceLostHandler).catch((reasons) => { + // noop + }); + const capabilities = device.capabilities; + device.stateCache.initialize( + capabilities.maxTextureUnits, + capabilities.maxUniformBufferBindings, + capabilities.maxVertexAttributes, + ); + + this._createTexture(width, height); + this._depthStencilTexture = this._createDepthStencilTexture(width, height); + this.nullTex2D = device.createTexture(new TextureInfo( + TextureType.TEX2D, + TextureUsageBit.SAMPLED, + Format.RGBA8, + 2, + 2, + TextureFlagBit.NONE, + )) as WebGPUTexture; + this.nullTexCube = device.createTexture(new TextureInfo( + TextureType.CUBE, + TextureUsageBit.SAMPLED, + Format.RGBA8, + 2, + 2, + TextureFlagBit.NONE, + 6, + )) as WebGPUTexture; + + const nullTexRegion = new BufferTextureCopy(); + nullTexRegion.texExtent.width = 2; + nullTexRegion.texExtent.height = 2; + + const nullTexBuff = new Uint8Array(this.nullTex2D.size); + nullTexBuff.fill(0); + device.copyBuffersToTexture([nullTexBuff], this.nullTex2D, [nullTexRegion]); + + nullTexRegion.texSubres.layerCount = 6; + device.copyBuffersToTexture( + [nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff], + this.nullTexCube, + [nullTexRegion], + ); + + this._blitManager = new IWebGPUBlitManager(); + } + + public override resize (width: number, height: number, surfaceTransform: SurfaceTransform): void { + const device = WebGPUDeviceManager.instance.nativeDevice!; + // Make sure it's valid for WebGPU + width = Math.max(1, Math.min(width, device.limits.maxTextureDimension2D)); + height = Math.max(1, Math.min(height, device.limits.maxTextureDimension2D)); + + if (this._colorTexture.width !== width || this._colorTexture.height !== height) { + debug(`Resizing swapchain: ${width}x${height}`); + this._canvas!.width = width; + this._canvas!.height = height; + this._colorTexture.resize(width, height); + this._depthStencilTexture.resize(width, height); + } + } + + public override destroy (): void { + if (this._canvas && this._webGPUDeviceLostHandler) { + this._webGPUDeviceLostHandler = null; + } + + if (this.nullTex2D) { + this.nullTex2D.destroy(); + this.nullTex2D = null!; + } + + if (this.nullTexCube) { + this.nullTexCube.destroy(); + this.nullTexCube = null!; + } + + if (this._blitManager) { + this._blitManager.destroy(); + this._blitManager = null; + } + this._canvas = null; + } + + public get colorTexture (): Texture { + (this._colorTexture as WebGPUTexture).gpuTexture.gpuTexture = WebGPUDeviceManager.instance.context.getCurrentTexture(); + return this._colorTexture; + } + + public get colorGPUTexture (): GPUTexture { + (this._colorTexture as WebGPUTexture).gpuTexture.gpuTexture = WebGPUDeviceManager.instance.context.getCurrentTexture(); + return (this._colorTexture as WebGPUTexture).gpuTexture.gpuTexture!; + } + + public get colorGPUTextureView (): GPUTextureView { + (this._colorTexture as WebGPUTexture).gpuTexture.gpuTexture = WebGPUDeviceManager.instance.context.getCurrentTexture(); + return (this._colorTexture as WebGPUTexture).gpuTexture.gpuTexture!.createView(); + } + + public get depthStencilTexture (): Texture { + return this._depthStencilTexture; + } + + public get gpuDepthStencilTexture (): GPUTexture { + return (this._depthStencilTexture as WebGPUTexture).gpuTexture.gpuTexture!; + } + + public get gpuDepthStencilTextureView (): GPUTextureView { + return (this._depthStencilTexture as WebGPUTexture).gpuTexture.gpuTexture!.createView(); + } + + private _createTexture (width: number, height: number): WebGPUTexture { + const device = WebGPUDeviceManager.instance; + const swapchainFormat = device.swapchainFormat;// navigator.gpu.getPreferredCanvasFormat(); + if (!this._colorTexture) { + const nativeDevice = device.nativeDevice as GPUDevice; + const gpuConfig: GPUCanvasConfiguration = { + device: nativeDevice, + format: swapchainFormat, + alphaMode: 'opaque', + }; + device.gpuConfig = gpuConfig; + device.context.configure(gpuConfig); + } + this._colorTexture = new WebGPUTexture(); + this._colorTexture.initAsSwapchainTexture({ + swapchain: this, + format: WGPUFormatToGFXFormat(swapchainFormat), + width, + height, + }); + (this._colorTexture as WebGPUTexture).gpuTexture.gpuTexture = device.context.getCurrentTexture(); + return (this._colorTexture as WebGPUTexture); + } + + private _createDepthStencilTexture (width: number, height: number): WebGPUTexture { + const device = WebGPUDeviceManager.instance; + const depthInfo = new TextureInfo( + TextureType.TEX2D, + TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, + Format.DEPTH_STENCIL, + width, + height, + ); + const depthTexture = device.createTexture(depthInfo); + return depthTexture as WebGPUTexture; + } + + private _onWebGPUDeviceLost (info: GPUDeviceLostInfo): void { + warnID(11000); + warn('webgpu device lost'); + } +} diff --git a/cocos/gfx/webgpu/webgpu-texture.ts b/cocos/gfx/webgpu/webgpu-texture.ts new file mode 100644 index 0000000000..2cc4bd2d8b --- /dev/null +++ b/cocos/gfx/webgpu/webgpu-texture.ts @@ -0,0 +1,220 @@ +/* + Copyright (c) 2024 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. +*/ + +import { + FormatSurfaceSize, + TextureInfo, + IsPowerOf2, + TextureViewInfo, + ISwapchainTextureInfo, + TextureHandle, + FormatInfos, + TextureUsageBit, +} from '../base/define'; +import { Texture } from '../base/texture'; +import { WebGPUDeviceManager } from './define'; +import { + GFXFormatToWGPUFormat, + WebGPUCmdFuncCreateTexture, + WebGPUCmdFuncDestroyTexture, + WebGPUCmdFuncResizeTexture, + WGPUFormatToGFXFormat, +} from './webgpu-commands'; +import { IWebGPUTexture } from './webgpu-gpu-objects'; + +export class WebGPUTexture extends Texture { + public getTextureHandle (): TextureHandle { + const gpuTexture = this._gpuTexture; + if (!gpuTexture) { + return 0; + } + if (gpuTexture.gpuTexture) { + return gpuTexture.gpuTexture; + } + return 0; + } + public initAsSwapchainTexture (info: Readonly): void { + const texInfo = new TextureInfo(); + texInfo.format = info.format; + texInfo.usage = FormatInfos[info.format].hasDepth ? TextureUsageBit.DEPTH_STENCIL_ATTACHMENT : TextureUsageBit.COLOR_ATTACHMENT; + texInfo.width = info.width; + texInfo.height = info.height; + this.initialize(texInfo, true); + } + get gpuTexture (): IWebGPUTexture { + return this._gpuTexture!; + } + + private _gpuTexture: IWebGPUTexture | null = null; + private _texDescriptor: GPUTextureDescriptor | null = null; + private _lodLevel = 0; + private _hasChange = false; + get lodLevel (): number { + return this._lodLevel; + } + get hasChange (): boolean { + return this._hasChange; + } + public resetChange (): void { + this._hasChange = false; + } + public initialize (info: Readonly | Readonly, isSwapchainTexture?: boolean): void { + let texInfo = info as Readonly; + const viewInfo = info as Readonly; + if ('texture' in info) { + texInfo = viewInfo.texture.info; + this._isTextureView = true; + } + + this._info.copy(texInfo); + this._isPowerOf2 = IsPowerOf2(this._info.width) && IsPowerOf2(this._info.height); + this._size = FormatSurfaceSize( + this._info.format, + this.width, + this.height, + this.depth, + this._info.levelCount, + ) * this._info.layerCount; + if (!this._isTextureView) { + this._gpuTexture = { + type: texInfo.type, + format: texInfo.format, + usage: texInfo.usage, + width: texInfo.width, + height: texInfo.height, + depth: texInfo.depth, + size: this._size, + arrayLayer: texInfo.layerCount, + mipLevel: texInfo.levelCount, + samples: texInfo.samples, + flags: texInfo.flags, + isPowerOf2: this._isPowerOf2, + + // default value, filled in when texture is created. + gpuTarget: '2d', + gpuInternalFmt: 'rgba8unorm', + gpuFormat: 'rgba8unorm', + gpuType: 0, + gpuUsage: GPUTextureUsage.RENDER_ATTACHMENT, + gpuTexture: undefined, + gpuRenderbuffer: null, + gpuWrapS: 'clamp-to-edge', + gpuWrapT: 'clamp-to-edge', + gpuMinFilter: 'linear', + gpuMagFilter: 'linear', + getTextureView: this.getNativeTextureView.bind(this), + + isSwapchainTexture: isSwapchainTexture || false, + }; + if (!isSwapchainTexture) { + const device = WebGPUDeviceManager.instance; + WebGPUCmdFuncCreateTexture(device, this._gpuTexture); + device.memoryStatus.textureSize += this._size; + } else { + this._gpuTexture.gpuInternalFmt = GFXFormatToWGPUFormat(this._gpuTexture.format); + this._gpuTexture.gpuFormat = this._gpuTexture.gpuInternalFmt; + } + this._viewInfo.texture = this; + this._viewInfo.type = info.type; + this._viewInfo.format = info.format; + this._viewInfo.baseLevel = 0; + this._viewInfo.levelCount = info.levelCount; + this._viewInfo.baseLayer = 0; + this._viewInfo.layerCount = info.layerCount; + } else { + this._viewInfo.copy(viewInfo); + this._lodLevel = viewInfo.baseLevel; + this._gpuTexture = (viewInfo.texture as WebGPUTexture)._gpuTexture; + } + } + + set gpuFormat (val: GPUTextureFormat) { + if (!this._isTextureView && this._gpuTexture && !this._gpuTexture.isSwapchainTexture) { + WebGPUCmdFuncDestroyTexture(this._gpuTexture); + const device = WebGPUDeviceManager.instance; + this._gpuTexture.format = WGPUFormatToGFXFormat(val); + WebGPUCmdFuncCreateTexture(device, this._gpuTexture); + this._hasChange = true; + } + } + + public getNativeTextureView (): GPUTextureView | null { + if (!this._gpuTexture || !this._gpuTexture.gpuTexture) { + return null; + } + return this._gpuTexture.gpuTexture.createView({ + format: this.gpuTexture.gpuFormat, + dimension: this._gpuTexture.gpuTarget, + mipLevelCount: this._gpuTexture.mipLevel, + arrayLayerCount: this.viewInfo.layerCount, + baseMipLevel: 0, + baseArrayLayer: 0, + }); + } + + public destroy (): void { + if (this._isTextureView || (!this._isTextureView && !this._gpuTexture)) { + return; + } + WebGPUCmdFuncDestroyTexture(this._gpuTexture!); + const device = WebGPUDeviceManager.instance; + device.memoryStatus.textureSize -= this._size; + this._gpuTexture = null; + this._hasChange = true; + } + + public resize (width: number, height: number): void { + if (this._info.width === width && this._info.height === height) { + return; + } + if (this._info.levelCount === WebGPUTexture.getLevelCount(this._info.width, this._info.height)) { + this._info.levelCount = WebGPUTexture.getLevelCount(width, height); + } else if (this._info.levelCount > 1) { + this._info.levelCount = Math.min(this._info.levelCount, WebGPUTexture.getLevelCount(width, height)); + } + this._hasChange = true; + const oldSize = this._size; + this._info.width = width; + this._info.height = height; + this._size = FormatSurfaceSize( + this.info.format, + this.width, + this.height, + this.depth, + this.info.levelCount, + ) * this.info.layerCount; + + if (!this._isTextureView && this._gpuTexture) { + this._gpuTexture.width = width; + this._gpuTexture.height = height; + this._gpuTexture.size = this._size; + if (!this._gpuTexture.isSwapchainTexture) { + const device = WebGPUDeviceManager.instance; + WebGPUCmdFuncResizeTexture(device, this._gpuTexture); + device.memoryStatus.textureSize -= oldSize; + device.memoryStatus.textureSize += this._size; + } + } + } +} diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index 677392ec57..dfeeb7b4fd 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -1166,7 +1166,7 @@ function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = fa const bindId = getDescBinding(key, descriptorSetData); if (bindId === -1) { continue; } const tex = descriptorSet.getTexture(bindId); - if (!tex || (isUpdate && value !== pipeline.defaultTexture) + if (!tex || (isUpdate && value !== pipeline.defaultShadowTexture) // @ts-ignore || (!tex.gpuTexture && !(tex.gpuTextureView && tex.gpuTextureView.gpuTexture))) { bindGlobalDesc(descriptorSet, bindId, value); diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index e2919cc98d..7cccfb98ba 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -38,7 +38,7 @@ import { Executor } from './executor'; import { RenderWindow } from '../../render-scene/core/render-window'; import { MacroRecord, RenderScene } from '../../render-scene'; import { GlobalDSManager } from '../global-descriptor-set-manager'; -import { supportsR32FloatTexture, supportsRGBA16HalfFloatTexture, UBOSkinning } from '../define'; +import { getDefaultShadowTexture, supportsR32FloatTexture, supportsRGBA16HalfFloatTexture, UBOSkinning } from '../define'; import { OS } from '../../../pal/system-info/enum-type'; import { Compiler } from './compiler'; import { PipelineUBO } from '../pipeline-ubo'; @@ -962,13 +962,13 @@ function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Reado setter.setSampler('cc_shadowMap', pipeline.defaultSampler); } if (!setter.hasTexture('cc_shadowMap')) { - setter.setTexture('cc_shadowMap', pipeline.defaultTexture); + setter.setTexture('cc_shadowMap', pipeline.defaultShadowTexture); } if (!setter.hasSampler('cc_spotShadowMap')) { setter.setSampler('cc_spotShadowMap', pipeline.defaultSampler); } if (!setter.hasTexture('cc_spotShadowMap')) { - setter.setTexture('cc_spotShadowMap', pipeline.defaultTexture); + setter.setTexture('cc_spotShadowMap', pipeline.defaultShadowTexture); } } @@ -2012,8 +2012,8 @@ export class WebPipeline implements BasicPipeline { return this._defaultSampler; } - get defaultTexture (): Texture { - return builtinResMgr.get('default-texture').getGFXTexture()!; + get defaultShadowTexture (): Texture { + return getDefaultShadowTexture(this.device); } private _compileMaterial (): void { diff --git a/cocos/rendering/define.ts b/cocos/rendering/define.ts index 7439362c18..4d0a99487f 100644 --- a/cocos/rendering/define.ts +++ b/cocos/rendering/define.ts @@ -29,6 +29,12 @@ import { Layers } from '../scene-graph/layers'; import { cclegacy } from '../core'; import { BindingMappingInfo, DescriptorType, Type, ShaderStageFlagBit, UniformStorageBuffer, DescriptorSetLayoutBinding, Uniform, UniformBlock, UniformSamplerTexture, UniformStorageImage, Device, FormatFeatureBit, Format, API, + Texture, + TextureInfo, + TextureType, + TextureUsageBit, + TextureFlagBit, + SampleCount, } from '../gfx'; export const PIPELINE_FLOW_MAIN = 'MainFlow'; @@ -812,6 +818,25 @@ export function supportsR16HalfFloatTexture (device: Device): boolean { === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE); } +let dftShadowTexture: Texture; +export function getDefaultShadowTexture (device: Device): Texture { + if (dftShadowTexture) return dftShadowTexture; + const texInfo = new TextureInfo( + TextureType.TEX2D, + TextureUsageBit.NONE, + supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8, + 16, + 16, + TextureFlagBit.NONE, + 1, + 1, + SampleCount.X1, + 1, + ); + dftShadowTexture = device.createTexture(texInfo); + return dftShadowTexture; +} + /** * @en Does the device support single-channeled float texture? (for both color attachment and sampling) * @zh 当前设备是否支持单通道浮点贴图?(颜色输出和采样) diff --git a/cocos/rendering/forward/forward-pipeline.ts b/cocos/rendering/forward/forward-pipeline.ts index 48322d0c13..203163e80e 100644 --- a/cocos/rendering/forward/forward-pipeline.ts +++ b/cocos/rendering/forward/forward-pipeline.ts @@ -28,12 +28,11 @@ import { RenderPipeline, IRenderPipelineInfo } from '../render-pipeline'; import { ForwardFlow } from './forward-flow'; import { RenderTextureConfig } from '../pipeline-serialization'; import { ShadowFlow } from '../shadow/shadow-flow'; -import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from '../define'; +import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, + UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, getDefaultShadowTexture } from '../define'; import { Swapchain, RenderPass } from '../../gfx'; -import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; -import { Texture2D } from '../../asset/assets/texture-2d'; import { Camera } from '../../render-scene/scene'; -import { errorID } from '../../core/platform/debug'; +import { errorID, log } from '../../core/platform/debug'; import { PipelineSceneData } from '../pipeline-scene-data'; import { ReflectionProbeFlow } from '../reflection-probe/reflection-probe-flow'; @@ -83,7 +82,7 @@ export class ForwardPipeline extends RenderPipeline { } public activate (swapchain: Swapchain): boolean { - if (EDITOR) { console.info('Forward render pipeline initialized.'); } + if (EDITOR) { log('Forward render pipeline initialized.'); } this._macros = { CC_PIPELINE_TYPE: PIPELINE_TYPE }; this._pipelineSceneData = new PipelineSceneData(); @@ -136,9 +135,9 @@ export class ForwardPipeline extends RenderPipeline { const shadowMapSampler = this.globalDSManager.pointSampler; this._descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, shadowMapSampler); - this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); + this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, getDefaultShadowTexture(this.device)); this._descriptorSet.bindSampler(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, shadowMapSampler); - this._descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); + this._descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, getDefaultShadowTexture(this.device)); this._descriptorSet.update(); return true; diff --git a/cocos/rendering/forward/forward-stage.ts b/cocos/rendering/forward/forward-stage.ts index 86a6f2dde0..098eb87f93 100644 --- a/cocos/rendering/forward/forward-stage.ts +++ b/cocos/rendering/forward/forward-stage.ts @@ -126,9 +126,10 @@ export class ForwardStage extends RenderStage { } public render (camera: Camera): void { - this._instancedQueue.clear(); const pipeline = this._pipeline as ForwardPipeline; const device = pipeline.device; + this._instancedQueue.clear(); + this._renderQueues.forEach(renderQueueClearFunc); const renderObjects = pipeline.pipelineSceneData.renderObjects; diff --git a/cocos/rendering/pipeline-ubo.ts b/cocos/rendering/pipeline-ubo.ts index e1888383a3..6f28a2cb48 100644 --- a/cocos/rendering/pipeline-ubo.ts +++ b/cocos/rendering/pipeline-ubo.ts @@ -23,7 +23,8 @@ */ import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, - supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UBOCSM, isEnableEffect } from './define'; + supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UBOCSM, isEnableEffect, + getDefaultShadowTexture } from './define'; import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../gfx'; import { Camera } from '../render-scene/scene/camera'; import { Mat4, Vec3, Vec4, Color, toRadian, cclegacy } from '../core'; @@ -32,8 +33,6 @@ import { CSMLevel, PCFType, Shadows, ShadowType } from '../render-scene/scene/sh import { Light, LightType } from '../render-scene/scene/light'; import { DirectionalLight, SpotLight } from '../render-scene/scene'; import { RenderWindow } from '../render-scene/core/render-window'; -import { builtinResMgr } from '../asset/asset-manager/builtin-res-mgr'; -import { Texture2D } from '../asset/assets'; import { DebugViewCompositeType } from './debug-view'; import { getDescBindingFromName } from './custom/define'; import { Root } from '../root'; @@ -537,15 +536,16 @@ export class PipelineUBO { const shadowInfo = sceneData.shadows; if (!shadowInfo.enabled) return; + const globalDSManager = this._pipeline.globalDSManager; const ds = this._pipeline.descriptorSet; const cmdBuffer = this._pipeline.commandBuffers; const shadowFrameBufferMap = sceneData.shadowFrameBufferMap; const mainLight = camera.scene!.mainLight; if (mainLight && shadowFrameBufferMap.has(mainLight)) { - ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); + globalDSManager.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); } PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, this._csmUBO, camera); - ds.update(); + globalDSManager.update(); const binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING; cmdBuffer[0].updateBuffer(ds.getBuffer(binding), this._shadowUBO); const csmBinding = isEnableEffect() ? getDescBindingFromName('CCCSM') : UBOCSM.BINDING; @@ -554,8 +554,8 @@ export class PipelineUBO { public updateShadowUBOLight (globalDS: DescriptorSet, light: Light, level = 0): void { PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light, level); - globalDS.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); - globalDS.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); + globalDS.bindTexture(UNIFORM_SHADOWMAP_BINDING, getDefaultShadowTexture(this._pipeline.device)); + globalDS.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, getDefaultShadowTexture(this._pipeline.device)); globalDS.update(); const binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING; this._pipeline.commandBuffers[0].updateBuffer(globalDS.getBuffer(binding), this._shadowUBO); diff --git a/cocos/rendering/render-additive-light-queue.ts b/cocos/rendering/render-additive-light-queue.ts index 337763dd1a..c2aaa8c1e7 100644 --- a/cocos/rendering/render-additive-light-queue.ts +++ b/cocos/rendering/render-additive-light-queue.ts @@ -443,7 +443,7 @@ export class RenderAdditiveLightQueue { if (shadowFrameBufferMap.has(light)) { const texture = shadowFrameBufferMap.get(light)?.colorTextures[0]; if (texture) { - descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, texture); + globalDSManager.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, texture); } } break; @@ -470,7 +470,7 @@ export class RenderAdditiveLightQueue { } default: } - descriptorSet.update(); + globalDSManager.update(); const binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING; cmdBuff.updateBuffer(descriptorSet.getBuffer(binding)!, this._shadowUBO); } diff --git a/editor/assets/chunks/common/shadow/native-pcf.chunk b/editor/assets/chunks/common/shadow/native-pcf.chunk index ab56782a84..0604750853 100644 --- a/editor/assets/chunks/common/shadow/native-pcf.chunk +++ b/editor/assets/chunks/common/shadow/native-pcf.chunk @@ -4,13 +4,20 @@ #pragma define CC_SHADOW_PCF_SOFT 1 #pragma define CC_SHADOW_PCF_SOFT_3X 2 #pragma define CC_SHADOW_PCF_SOFT_5X 3 - +#pragma extension([GL_EXT_shader_texture_lod, __VERSION__ < 130]) +vec4 shadowTexure(highp sampler2D shadowMap, vec2 coord) { + #if defined(CC_USE_WGPU) + return textureLod(shadowMap, coord, 0.0); + #else + return texture(shadowMap, coord); + #endif +} float SampleShadowMap (vec3 shadowNDCPos, highp sampler2D shadowMap) { #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 - return unpackRGBAToDepth(texture(shadowMap, shadowNDCPos.xy)); + return unpackRGBAToDepth(shadowTexure(shadowMap, shadowNDCPos.xy)); #else - return texture(shadowMap, shadowNDCPos.xy).x; + return shadowTexure(shadowMap, shadowNDCPos.xy).x; #endif } @@ -38,9 +45,9 @@ float SampleShadowMapSoft (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 sh float NativePCFShadowFactorHard (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 shadowMapResolution) { #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 - return step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, shadowNDCPos.xy))); + return step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, shadowNDCPos.xy))); #else - return step(shadowNDCPos.z, texture(shadowMap, shadowNDCPos.xy).x); + return step(shadowNDCPos.z, shadowTexure(shadowMap, shadowNDCPos.xy).x); #endif } @@ -51,15 +58,15 @@ float NativePCFShadowFactorSoft (vec3 shadowNDCPos, highp sampler2D shadowMap, v float block0, block1, block2, block3; #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 - block0 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)))); - block1 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos.y)))); - block2 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset.y)))); - block3 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos_offset.y)))); + block0 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)))); + block1 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos.y)))); + block2 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset.y)))); + block3 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos_offset.y)))); #else - block0 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)).x); - block1 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos.y)).x); - block2 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset.y)).x); - block3 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos_offset.y)).x); + block0 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)).x); + block1 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos.y)).x); + block2 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset.y)).x); + block3 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos_offset.y)).x); #endif float coefX = mod(shadowNDCPos.x, oneTap.x) * shadowMapResolution.x; @@ -80,25 +87,25 @@ float NativePCFShadowFactorSoft3X (vec3 shadowNDCPos, highp sampler2D shadowMap, float block0, block1, block2, block3, block4, block5, block6, block7, block8; #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 - block0 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_U)))); - block1 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_U)))); - block2 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_U)))); - block3 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos.y)))); - block4 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)))); - block5 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos.y)))); - block6 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_D)))); - block7 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_D)))); - block8 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_D)))); + block0 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_U)))); + block1 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_U)))); + block2 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_U)))); + block3 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos.y)))); + block4 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)))); + block5 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos.y)))); + block6 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_D)))); + block7 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_D)))); + block8 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_D)))); #else - block0 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_U)).x); - block1 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_U)).x); - block2 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_U)).x); - block3 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos.y)).x); - block4 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)).x); - block5 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos.y)).x); - block6 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_D)).x); - block7 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_D)).x); - block8 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_D)).x); + block0 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_U)).x); + block1 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_U)).x); + block2 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_U)).x); + block3 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos.y)).x); + block4 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)).x); + block5 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos.y)).x); + block6 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_D)).x); + block7 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_D)).x); + block8 = step(shadowNDCPos.z, shadowTexure(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_D)).x); #endif float coefX = mod(shadowNDCPos.x, oneTap.x) * shadowMapResolution.x; @@ -157,57 +164,57 @@ float NativePCFShadowFactorSoft5X (vec3 shadowNDCPos, highp sampler2D shadowMap, float block1, block2, block3, block4, block5, block6, block7, block8, block9, block10, block11, block12, block13, block14, block15, block16, block17, block18, block19, block20, block21, block22, block23, block24, block25; #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 - block1 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset1))); - block2 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset2))); - block3 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset3))); - block4 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset4))); - block5 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset5))); - block6 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset6))); - block7 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset7))); - block8 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset8))); - block9 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset9))); - block10 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset10))); - block11 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset11))); - block12 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset12))); - block13 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset13))); - block14 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset14))); - block15 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset15))); - block16 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset16))); - block17 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset17))); - block18 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset18))); - block19 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset19))); - block20 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset20))); - block21 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset21))); - block22 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset22))); - block23 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset23))); - block24 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset24))); - block25 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset25))); + block1 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset1))); + block2 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset2))); + block3 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset3))); + block4 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset4))); + block5 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset5))); + block6 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset6))); + block7 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset7))); + block8 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset8))); + block9 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset9))); + block10 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset10))); + block11 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset11))); + block12 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset12))); + block13 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset13))); + block14 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset14))); + block15 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset15))); + block16 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset16))); + block17 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset17))); + block18 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset18))); + block19 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset19))); + block20 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset20))); + block21 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset21))); + block22 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset22))); + block23 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset23))); + block24 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset24))); + block25 = step(shadowNDCPos.z, unpackRGBAToDepth(shadowTexure(shadowMap, offset25))); #else - block1 = step(shadowNDCPos.z, texture(shadowMap, offset1).x); - block2 = step(shadowNDCPos.z, texture(shadowMap, offset2).x); - block3 = step(shadowNDCPos.z, texture(shadowMap, offset3).x); - block4 = step(shadowNDCPos.z, texture(shadowMap, offset4).x); - block5 = step(shadowNDCPos.z, texture(shadowMap, offset5).x); - block6 = step(shadowNDCPos.z, texture(shadowMap, offset6).x); - block7 = step(shadowNDCPos.z, texture(shadowMap, offset7).x); - block8 = step(shadowNDCPos.z, texture(shadowMap, offset8).x); - block9 = step(shadowNDCPos.z, texture(shadowMap, offset9).x); - block10 = step(shadowNDCPos.z, texture(shadowMap, offset10).x); - block11 = step(shadowNDCPos.z, texture(shadowMap, offset11).x); - block12 = step(shadowNDCPos.z, texture(shadowMap, offset12).x); - block13 = step(shadowNDCPos.z, texture(shadowMap, offset13).x); - block14 = step(shadowNDCPos.z, texture(shadowMap, offset14).x); - block15 = step(shadowNDCPos.z, texture(shadowMap, offset15).x); - block16 = step(shadowNDCPos.z, texture(shadowMap, offset16).x); - block17 = step(shadowNDCPos.z, texture(shadowMap, offset17).x); - block18 = step(shadowNDCPos.z, texture(shadowMap, offset18).x); - block19 = step(shadowNDCPos.z, texture(shadowMap, offset19).x); - block20 = step(shadowNDCPos.z, texture(shadowMap, offset20).x); - block21 = step(shadowNDCPos.z, texture(shadowMap, offset21).x); - block22 = step(shadowNDCPos.z, texture(shadowMap, offset22).x); - block23 = step(shadowNDCPos.z, texture(shadowMap, offset23).x); - block24 = step(shadowNDCPos.z, texture(shadowMap, offset24).x); - block25 = step(shadowNDCPos.z, texture(shadowMap, offset25).x); + block1 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset1).x); + block2 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset2).x); + block3 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset3).x); + block4 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset4).x); + block5 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset5).x); + block6 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset6).x); + block7 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset7).x); + block8 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset8).x); + block9 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset9).x); + block10 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset10).x); + block11 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset11).x); + block12 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset12).x); + block13 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset13).x); + block14 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset14).x); + block15 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset15).x); + block16 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset16).x); + block17 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset17).x); + block18 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset18).x); + block19 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset19).x); + block20 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset20).x); + block21 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset21).x); + block22 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset22).x); + block23 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset23).x); + block24 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset24).x); + block25 = step(shadowNDCPos.z, shadowTexure(shadowMap, offset25).x); #endif vec2 coef = fract(shadowNDCPos.xy * shadowMapResolution); diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index da0f3398da..f5aebf4ced 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -24,6 +24,12 @@ "category": "graphics", "enginePlugin": true }, + "gfx-webgpu": { + "label": "i18n:ENGINE.features.gfx_webgpu.label", + "description": "i18n:ENGINE.features.gfx_webgpu.description", + "category": "graphics", + "enginePlugin": true + }, "animation": { "label": "i18n:ENGINE.features.animation.label", "description": "i18n:ENGINE.features.animation.description", diff --git a/exports/gfx-webgpu.ts b/exports/gfx-webgpu.ts new file mode 100644 index 0000000000..cc537ed0ad --- /dev/null +++ b/exports/gfx-webgpu.ts @@ -0,0 +1,10 @@ +/** + * @packageDocumentation + * @hidden + */ + +import { WebGPUDevice } from '../cocos/gfx/webgpu/webgpu-device'; +import { legacyCC } from '../cocos/core/global-exports'; + +export { WebGPUDevice }; +legacyCC.WebGPUDevice = WebGPUDevice; diff --git a/pal/wasm/wasm-minigame.ts b/pal/wasm/wasm-minigame.ts index fa46f5ea82..687babefc4 100644 --- a/pal/wasm/wasm-minigame.ts +++ b/pal/wasm/wasm-minigame.ts @@ -54,6 +54,17 @@ export function fetchBuffer (binaryUrl: string): Promise { }); } +export function fetchUrl (binaryUrl: string): Promise { + return new Promise((resolve, reject) => { + getPlatformBinaryUrl(binaryUrl).then((url) => { + resolve(url); + // eslint-disable-next-line @typescript-eslint/no-empty-function + }).catch((e) => { + reject(e); + }); + }); +} + function loadSubpackage (name: string): Promise { return new Promise((resolve, reject) => { if (minigame.loadSubpackage) { diff --git a/pal/wasm/wasm-native.ts b/pal/wasm/wasm-native.ts index 57a9d3ef8a..8a02da18c7 100644 --- a/pal/wasm/wasm-native.ts +++ b/pal/wasm/wasm-native.ts @@ -51,6 +51,26 @@ export function fetchBuffer (binaryUrl: string): Promise { }); } +export function fetchUrl (binaryUrl: string): Promise { + return new Promise((resolve, reject) => { + try { + // NOTE: when it's in EDITOR, binaryUrl is a url with `external:` protocol. + if (EDITOR) { + Editor.Message.request('engine', 'query-engine-info').then((info) => { + const externalRoot = `${info.native.path}/external/`; + binaryUrl = binaryUrl.replace('external:', externalRoot); + resolve(binaryUrl); + }); + return; + } + binaryUrl = `src/cocos-js/${binaryUrl}`; + resolve(binaryUrl); + } catch (e) { + reject(e); + } + }); +} + export function ensureWasmModuleReady (): Promise { return Promise.resolve(); } diff --git a/pal/wasm/wasm-web.ts b/pal/wasm/wasm-web.ts index b3912a369a..32c086f637 100644 --- a/pal/wasm/wasm-web.ts +++ b/pal/wasm/wasm-web.ts @@ -48,14 +48,50 @@ export function fetchBuffer (binaryUrl: string): Promise { return; } else if (PREVIEW) { // NOTE: we resolve '/engine_external/' in in editor preview server. - fetch(`/engine_external/?url=${binaryUrl}`).then((response) => response.arrayBuffer().then(resolve)).catch((e) => {}); + fetch(`/engine_external/?url=${binaryUrl}`).then((response) => response.arrayBuffer().then(resolve)).catch((e) => { + // noop + }); return; } // here is in the BUILD mode // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore NOTE: we need to use 'import.meta' here, but the tsc won't allow this, so we need to force ignoring this error here. binaryUrl = new URL(binaryUrl, import.meta.url).href; - fetch(binaryUrl).then((response) => response.arrayBuffer().then(resolve)).catch((e) => {}); + fetch(binaryUrl).then((response) => response.arrayBuffer().then(resolve)).catch((e) => { + // noop + }); + } catch (e) { + reject(e); + } + }); +} + +/** + * @en Translate virtual addresses within the engine to actual addresses of paths, such as external:emscripten/webgpu/glslang.wasm + * @zh 把引擎内部的虚拟地址转为路径的实际地址,如external:emscripten/webgpu/glslang.wasm + */ +export function fetchUrl (binaryUrl: string): Promise { + return new Promise((resolve, reject) => { + try { + // NOTE: when it's in EDITOR or PREVIEW, binaryUrl is a url with `external:` protocol. + if (EDITOR) { + Editor.Message.request('engine', 'query-engine-info').then((info) => { + const externalRoot = `${info.native.path}/external/`; + binaryUrl = binaryUrl.replace('external:', externalRoot); + // IDEA: it's better we implement another PAL for nodejs platform. + // eslint-disable-next-line @typescript-eslint/no-var-requires + resolve(binaryUrl); + }); + return; + } else if (PREVIEW) { + resolve(`/engine_external/?url=${binaryUrl}`); + return; + } + // here is in the BUILD mode + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore NOTE: we need to use 'import.meta' here, but the tsc won't allow this, so we need to force ignoring this error here. + binaryUrl = new URL(binaryUrl, import.meta.url).href; + resolve(binaryUrl); } catch (e) { reject(e); } diff --git a/tsconfig.json b/tsconfig.json index a5c25c11c6..f2fbdeb237 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -27,6 +27,7 @@ "./@types/editor-extends", "./@types/webGL.extras", "./@types/webGL2.extras", + "./@types/webGPU", "./node_modules/@cocos/cannon/CANNON", "./node_modules/@types/jest/index",