mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-20 23:52:40 +08:00
Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff0f46ff81 | |||
| 0616a948ef | |||
| ee89a99a9b | |||
| f620989ce7 | |||
| 661de759ef | |||
| 0ab8246486 | |||
| 67642997f7 | |||
| 3be9ebc5b7 | |||
| 47ebc462e5 | |||
| b4bea55859 | |||
| 82f13c86e9 | |||
| 0fd910220e | |||
| 557b06f7e6 | |||
| b46553e615 | |||
| fffd9a514a | |||
| 5678d0d17c | |||
| 2ce7b89be5 | |||
| 6b455561f4 | |||
| 60f9352c56 | |||
| f66365f959 | |||
| a3c3fcbea5 | |||
| 2a75cfb9da | |||
| 0c3f4534b8 | |||
| 7f806abad6 | |||
| df98a99bb6 | |||
| a5090e5ae4 | |||
| 3b71bf6935 | |||
| 54fd070848 | |||
| 6722aac669 | |||
| 68552314c0 | |||
| 550eb15641 | |||
| c438c2d3f8 | |||
| f5eaf97ce7 | |||
| 69d3d6033a | |||
| 469614cf0b | |||
| f81094f226 | |||
| 825362fac1 | |||
| 609512f8da | |||
| 09b63786f4 | |||
| 2b7b438768 | |||
| 6b5c8556a2 | |||
| ff436d6a27 |
+1
-1
@@ -3983,4 +3983,4 @@ Spine version not supported.
|
||||
|
||||
### 16420
|
||||
|
||||
Start time must bigger than end time.
|
||||
End time must bigger than start time.
|
||||
|
||||
@@ -115,7 +115,7 @@ export class TextProcessing {
|
||||
const maxValue = Math.max(outputLayoutData.canvasSize.width, outputLayoutData.canvasSize.height);
|
||||
const canvasScaleToMaxSizeRatio = MAX_SIZE / maxValue;
|
||||
this._fontScale *= canvasScaleToMaxSizeRatio;
|
||||
this._fontScale = Math.max(1, this._fontScale);
|
||||
this._fontScale = Math.max(0.1, this._fontScale);
|
||||
}
|
||||
|
||||
this._updatePaddingRect(style, outputLayoutData);
|
||||
|
||||
@@ -172,13 +172,18 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
|
||||
// Fill index buffer.
|
||||
let indexBuffer: ArrayBuffer | null = null;
|
||||
let idxCount = 0;
|
||||
const idxStride = 2;
|
||||
let idxStride = 2;
|
||||
let indexFormat = Format.R16UI;
|
||||
if (geometry.indices) {
|
||||
const { indices } = geometry;
|
||||
idxCount = indices.length;
|
||||
if (indices.some((i) => i > 0xFFFF)) {
|
||||
idxStride = 4;
|
||||
indexFormat = Format.R32UI;
|
||||
}
|
||||
indexBuffer = new ArrayBuffer(idxStride * idxCount);
|
||||
const indexBufferView = new DataView(indexBuffer);
|
||||
writeBuffer(indexBufferView, indices, Format.R16UI);
|
||||
writeBuffer(indexBufferView, indices, indexFormat);
|
||||
}
|
||||
|
||||
// Create primitive.
|
||||
|
||||
@@ -106,6 +106,13 @@ export class BakedSkinningModel extends MorphModel {
|
||||
UBOSkinningTexture.SIZE,
|
||||
));
|
||||
}
|
||||
|
||||
// The animation buffer belongs to the skinning root. Refresh its binding without
|
||||
// rebuilding the instanced attribute block, which would erase custom attribute values.
|
||||
for (let i = 0; i < this._subModels.length; i++) {
|
||||
this._updateLocalDescriptors(i, this._subModels[i].descriptorSet);
|
||||
}
|
||||
this.updateInstancedJointTextureInfo();
|
||||
}
|
||||
|
||||
// Override
|
||||
|
||||
@@ -142,6 +142,7 @@ export class SkinningModel extends MorphModel {
|
||||
}
|
||||
this._bufferIndices = null; this._joints.length = 0;
|
||||
if (!skeleton || !skinningRoot || !mesh) { return; }
|
||||
const prevRealTimeTextureMode = this._realTimeTextureMode;
|
||||
this._realTimeTextureMode = false;
|
||||
if (UBOSkinning.JOINT_UNIFORM_CAPACITY < skeleton.joints.length) { this._realTimeTextureMode = true; }
|
||||
this.transform = skinningRoot;
|
||||
@@ -161,6 +162,15 @@ export class SkinningModel extends MorphModel {
|
||||
if (!jointMaps) { indices.push(index); buffers.push(0); } else { getRelevantBuffers(indices, buffers, jointMaps, index); }
|
||||
this._joints.push({ indices, buffers, bound, target, bindpose, transform });
|
||||
}
|
||||
|
||||
// Rebind recreated joint resources without resetting user-provided instanced attributes.
|
||||
const subModelCount = Math.min(this._subModels.length, this._bufferIndices.length);
|
||||
if (subModelCount && prevRealTimeTextureMode !== this._realTimeTextureMode) {
|
||||
this.onMacroPatchesStateChanged();
|
||||
}
|
||||
for (let i = 0; i < subModelCount; i++) {
|
||||
this._updateLocalDescriptors(i, this._subModels[i].descriptorSet);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -177,21 +177,21 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer {
|
||||
@override
|
||||
@visible(false)
|
||||
get mesh (): Mesh | null {
|
||||
return super.mesh;
|
||||
return Reflect.get(SkinnedMeshRenderer.prototype, 'mesh', this);
|
||||
}
|
||||
|
||||
set mesh (val) {
|
||||
super.mesh = val;
|
||||
Reflect.set(SkinnedMeshRenderer.prototype, 'mesh', val, this);
|
||||
}
|
||||
|
||||
@override
|
||||
@visible(false)
|
||||
get skeleton (): Skeleton | null {
|
||||
return super.skeleton;
|
||||
return Reflect.get(SkinnedMeshRenderer.prototype, 'skeleton', this);
|
||||
}
|
||||
|
||||
set skeleton (val) {
|
||||
super.skeleton = val;
|
||||
Reflect.set(SkinnedMeshRenderer.prototype, 'skeleton', val, this);
|
||||
}
|
||||
|
||||
public onLoad (): void {
|
||||
|
||||
@@ -76,10 +76,11 @@ simpleTextureProto._onGFXTextureUpdated = function (gfxTexture) {
|
||||
simpleTextureProto._onAfterAssignImage = function (image) {
|
||||
if (macro.CLEANUP_IMAGE_CACHE) {
|
||||
const deps = dependUtil.getDeps(this._uuid);
|
||||
const index = deps.indexOf(image._uuid);
|
||||
if (index !== -1) {
|
||||
let index = deps.indexOf(image._uuid);
|
||||
while (index !== -1) {
|
||||
js.array.fastRemoveAt(deps, index);
|
||||
image.decRef();
|
||||
index = deps.indexOf(image._uuid);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -194,10 +194,12 @@ export class SimpleTexture extends TextureBase {
|
||||
|
||||
if (macro.CLEANUP_IMAGE_CACHE) {
|
||||
const deps = dependUtil.getDeps(this._uuid);
|
||||
const index = deps.indexOf(image._uuid);
|
||||
if (index !== -1) {
|
||||
let index = deps.indexOf(image._uuid);
|
||||
while (index !== -1) {
|
||||
js.array.fastRemoveAt(deps, index);
|
||||
image.decRef();
|
||||
// The same UUID may occur more than once; find the next dependency edge.
|
||||
index = deps.indexOf(image._uuid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,14 @@ export abstract class CommandBuffer extends GFXObject {
|
||||
return this._numTris;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Number of compute dispatches currently recorded.
|
||||
* @zh 计算调度(dispatch)次数。
|
||||
*/
|
||||
get numDispatches (): number {
|
||||
return this._numDispatches;
|
||||
}
|
||||
|
||||
/** @mangle */
|
||||
protected _queue: Queue | null = null;
|
||||
/** @mangle */
|
||||
@@ -95,6 +103,8 @@ export abstract class CommandBuffer extends GFXObject {
|
||||
/** @mangle */
|
||||
protected _numDrawCalls = 0;
|
||||
/** @mangle */
|
||||
protected _numDispatches = 0;
|
||||
/** @mangle */
|
||||
protected _numInstances = 0;
|
||||
/** @mangle */
|
||||
protected _numTris = 0;
|
||||
|
||||
@@ -127,6 +127,14 @@ export abstract class Device {
|
||||
return this._numTris;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Number of compute dispatches currently recorded.
|
||||
* @zh 计算调度(dispatch)次数。
|
||||
*/
|
||||
get numDispatches (): number {
|
||||
return this._numDispatches;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Total memory size currently allocated.
|
||||
* @zh 内存状态。
|
||||
@@ -168,6 +176,8 @@ export abstract class Device {
|
||||
/** @mangle */
|
||||
protected _numDrawCalls = 0;
|
||||
/** @mangle */
|
||||
protected _numDispatches = 0;
|
||||
/** @mangle */
|
||||
protected _numInstances = 0;
|
||||
/** @mangle */
|
||||
protected _numTris = 0;
|
||||
|
||||
@@ -2702,7 +2702,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
|
||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
||||
@@ -2773,7 +2773,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
|
||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||
stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
|
||||
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
||||
|
||||
@@ -2811,7 +2811,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
||||
@@ -2883,7 +2883,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||
extent.depth = 1;
|
||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||
@@ -2965,7 +2965,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||
offset.z = regionTexOffset.z;
|
||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||
extent.depth = regionTexExtent.depth;
|
||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||
@@ -2986,7 +2986,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
||||
|
||||
if (!isCompressed) {
|
||||
gl.texSubImage3D(
|
||||
WebGLConstants.TEXTURE_2D_ARRAY,
|
||||
WebGLConstants.TEXTURE_3D,
|
||||
mipLevel,
|
||||
offset.x,
|
||||
offset.y,
|
||||
@@ -3000,7 +3000,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
||||
);
|
||||
} else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) {
|
||||
gl.compressedTexSubImage3D(
|
||||
WebGLConstants.TEXTURE_2D_ARRAY,
|
||||
WebGLConstants.TEXTURE_3D,
|
||||
mipLevel,
|
||||
offset.x,
|
||||
offset.y,
|
||||
@@ -3013,7 +3013,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
||||
);
|
||||
} else { // WEBGL_compressed_texture_etc1
|
||||
gl.compressedTexImage3D(
|
||||
WebGLConstants.TEXTURE_2D_ARRAY,
|
||||
WebGLConstants.TEXTURE_3D,
|
||||
mipLevel,
|
||||
gpuTexture.glInternalFmt,
|
||||
destWidth,
|
||||
@@ -3043,7 +3043,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
TextureBlit,
|
||||
DescriptorSetInfo,
|
||||
Format,
|
||||
DispatchInfo,
|
||||
} from '../base/define';
|
||||
import { Framebuffer } from '../base/framebuffer';
|
||||
import { InputAssembler } from '../base/input-assembler';
|
||||
@@ -179,6 +180,7 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
||||
private _wgpuRenderPass!: WebGPURenderPass;
|
||||
|
||||
private _renderPassFuncQueue: ((renPassEncoder: GPURenderPassEncoder) => void)[] = [];
|
||||
private _computeFuncQueue: ((computePassEncoder: GPUComputePassEncoder) => void)[] = [];
|
||||
|
||||
public initialize (info: CommandBufferInfo): boolean {
|
||||
this._type = info.type;
|
||||
@@ -222,13 +224,16 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
||||
this._curStencilWriteMask = null;
|
||||
this._curStencilCompareMask = null;
|
||||
this._numDrawCalls = 0;
|
||||
this._numDispatches = 0;
|
||||
this._numInstances = 0;
|
||||
this._numTris = 0;
|
||||
this._computeFuncQueue.length = 0;
|
||||
}
|
||||
|
||||
public end (): void {
|
||||
this._isStateValid = false;
|
||||
this._isInRenderPass = false;
|
||||
this._computeFuncQueue.length = 0;
|
||||
}
|
||||
|
||||
public beginRenderPass (
|
||||
@@ -650,22 +655,20 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
||||
this.cmdPackage.cmds.concat(cmdPackage.cmds.array);
|
||||
|
||||
this._numDrawCalls += WebGPUCmdBuff._numDrawCalls;
|
||||
this._numDispatches += WebGPUCmdBuff._numDispatches;
|
||||
this._numInstances += WebGPUCmdBuff._numInstances;
|
||||
this._numTris += WebGPUCmdBuff._numTris;
|
||||
}
|
||||
}
|
||||
|
||||
protected bindStates (): void {
|
||||
if (!this._curGPUPipelineState) {
|
||||
return;
|
||||
}
|
||||
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
|
||||
private _prepareDescriptorSets (): void {
|
||||
const wgpuPipLayout = (currPipelineState?.pipelineLayout as WebGPUPipelineLayout);
|
||||
const device = WebGPUDeviceManager.instance;
|
||||
for (let i = 0; i < groupSets.length; i++) {
|
||||
const currSetIdx = groupSets[i];
|
||||
const currDesc = descriptorSets[currSetIdx];
|
||||
if (currDesc && currDesc.gpuDescriptorSet) {
|
||||
// prepare() builds the bind group if it was never created, or rebuilds it on resource change.
|
||||
currDesc.prepare();
|
||||
} else {
|
||||
const currLayout = wgpuPipLayout.setLayouts[currSetIdx];
|
||||
@@ -675,23 +678,13 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
||||
newDescSet.prepare(true);
|
||||
}
|
||||
}
|
||||
const gpuIA = this._curGPUInputAssembler!;
|
||||
// only 4x MSAA is supported
|
||||
gpuIA.samples = samples > 1 ? 4 : 1;
|
||||
this._curWebGPUPipelineState!.prepare(gpuIA);
|
||||
// ----------------------------wgpu pipline state-----------------------------
|
||||
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
|
||||
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
|
||||
passEncoder.setPipeline(wgpuPipeline);
|
||||
};
|
||||
this._renderPassFuncQueue.push(pplFunc);
|
||||
if (this._curGPUPipelineState.pipelineState?.depthStencil) {
|
||||
const stencilRef = this._curGPUPipelineState.stencilRef;
|
||||
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
|
||||
passEncoder.setStencilReference(stencilRef);
|
||||
};
|
||||
this._renderPassFuncQueue.push(stencilRefFunc);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect the bind groups and dynamic offsets for the currently bound descriptor sets.
|
||||
* Shared by the draw (bindStates) and compute (dispatch) paths.
|
||||
*/
|
||||
private _collectBindGroups (): { wgpuBindGroups: GPUBindGroup[]; wgpuDynOffsets: number[][] } {
|
||||
const currGPUDescSize = groupSets.length;
|
||||
const wgpuBindGroups = new Array<GPUBindGroup>(currGPUDescSize);
|
||||
const wgpuDynOffsets = new Array<number[]>(currGPUDescSize);
|
||||
@@ -703,7 +696,7 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
||||
wgpuDynOffsets[currSetIdx] = [...this._curDynamicOffsets[currSetIdx]];
|
||||
if (!descObj.dynamicOffsetCount) {
|
||||
wgpuDynOffsets[currSetIdx] = [];
|
||||
} else if (descObj && descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
|
||||
} else if (descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
|
||||
wgpuDynOffsets[currSetIdx].length = descObj.dynamicOffsetCount;
|
||||
for (let j = 0; j < descObj.dynamicOffsetCount; j++) {
|
||||
const currOffset = wgpuDynOffsets[currSetIdx][j];
|
||||
@@ -719,16 +712,84 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
||||
}
|
||||
}
|
||||
}
|
||||
return { wgpuBindGroups, wgpuDynOffsets };
|
||||
}
|
||||
|
||||
public dispatch (info: DispatchInfo): void {
|
||||
if (!this._curGPUPipelineState) {
|
||||
return;
|
||||
}
|
||||
// Prepare descriptor sets (same logic as bindStates)
|
||||
this._prepareDescriptorSets();
|
||||
|
||||
// Create compute pipeline
|
||||
this._curWebGPUPipelineState!.prepare(null!);
|
||||
|
||||
const computePipeline = this._curGPUPipelineState.nativePipeline as GPUComputePipeline;
|
||||
|
||||
// Build bind groups for compute pass
|
||||
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
|
||||
|
||||
const func = (passEncoder: GPUComputePassEncoder): void => {
|
||||
passEncoder.setPipeline(computePipeline);
|
||||
const gpuBindGroupSize = wgpuBindGroups.length;
|
||||
for (let i = 0; i < gpuBindGroupSize; i++) {
|
||||
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
|
||||
}
|
||||
passEncoder.dispatchWorkgroups(info.groupCountX, info.groupCountY, info.groupCountZ);
|
||||
};
|
||||
this._computeFuncQueue.push(func);
|
||||
++this._numDispatches;
|
||||
this._isStateValid = false;
|
||||
}
|
||||
|
||||
public submitComputePass (): void {
|
||||
if (this._computeFuncQueue.length === 0) {
|
||||
return;
|
||||
}
|
||||
const device = WebGPUDeviceManager.instance;
|
||||
const nativeDevice = device.nativeDevice!;
|
||||
const cmdEncoder = nativeDevice.createCommandEncoder();
|
||||
const computePassEncoder = cmdEncoder.beginComputePass();
|
||||
this._computeFuncQueue.forEach((cb) => {
|
||||
cb(computePassEncoder);
|
||||
});
|
||||
computePassEncoder.end();
|
||||
nativeDevice.queue.submit([cmdEncoder.finish()]);
|
||||
this._computeFuncQueue.length = 0;
|
||||
}
|
||||
|
||||
protected bindStates (): void {
|
||||
if (!this._curGPUPipelineState) {
|
||||
return;
|
||||
}
|
||||
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
|
||||
this._prepareDescriptorSets();
|
||||
const gpuIA = this._curGPUInputAssembler!;
|
||||
// only 4x MSAA is supported
|
||||
gpuIA.samples = samples > 1 ? 4 : 1;
|
||||
this._curWebGPUPipelineState!.prepare(gpuIA);
|
||||
// ----------------------------wgpu pipline state-----------------------------
|
||||
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
|
||||
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
|
||||
passEncoder.setPipeline(wgpuPipeline);
|
||||
};
|
||||
this._renderPassFuncQueue.push(pplFunc);
|
||||
const pipelineDesc = this._curGPUPipelineState.pipelineState;
|
||||
if (pipelineDesc && 'depthStencil' in pipelineDesc && pipelineDesc.depthStencil) {
|
||||
const stencilRef = this._curGPUPipelineState.stencilRef;
|
||||
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
|
||||
passEncoder.setStencilReference(stencilRef);
|
||||
};
|
||||
this._renderPassFuncQueue.push(stencilRefFunc);
|
||||
}
|
||||
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
|
||||
|
||||
const bgfunc = (passEncoder: GPURenderPassEncoder): void => {
|
||||
const gpuBindGroupSize = wgpuBindGroups.length;
|
||||
for (let i = 0; i < gpuBindGroupSize; i++) {
|
||||
let currBindGroup = wgpuBindGroups[i];
|
||||
if (!currBindGroup) {
|
||||
currBindGroup = (device.defaultResource.descSet as WebGPUDescriptorSet).gpuDescriptorSet.bindGroup;
|
||||
}
|
||||
// FIXME: this is a special sentence that 2 in 3 parameters I'm not certain.
|
||||
passEncoder.setBindGroup(i, currBindGroup, wgpuDynOffsets[i]);
|
||||
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
|
||||
}
|
||||
};
|
||||
this._renderPassFuncQueue.push(bgfunc);
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
TextureUsageBit,
|
||||
ShaderStageFlags,
|
||||
DescriptorType,
|
||||
MemoryAccessBit,
|
||||
Color, Rect, Viewport, BufferTextureCopy,
|
||||
SamplerInfo,
|
||||
FormatSize,
|
||||
@@ -1423,11 +1424,15 @@ export function createBindGroupLayoutEntry (currBind: DescriptorSetLayoutBinding
|
||||
|
||||
case DescriptorType.STORAGE_BUFFER:
|
||||
case DescriptorType.DYNAMIC_STORAGE_BUFFER:
|
||||
entry.buffer = {
|
||||
type: 'storage',
|
||||
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
|
||||
minBindingSize: undefined,
|
||||
};
|
||||
{
|
||||
const readOnly = (currBind.access & MemoryAccessBit.READ_ONLY) !== 0
|
||||
&& (currBind.access & MemoryAccessBit.WRITE_ONLY) === 0;
|
||||
entry.buffer = {
|
||||
type: readOnly ? 'read-only-storage' : 'storage',
|
||||
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
|
||||
minBindingSize: undefined,
|
||||
};
|
||||
}
|
||||
break;
|
||||
|
||||
case DescriptorType.SAMPLER_TEXTURE:
|
||||
|
||||
@@ -170,9 +170,17 @@ export class WebGPUDescriptorSet extends DescriptorSet {
|
||||
if (descType & (DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER)) {
|
||||
this._dynamicOffsets.push(bindIdx);
|
||||
}
|
||||
} else if (descType & DESCRIPTOR_SAMPLER_TYPE) {
|
||||
if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
|
||||
// texture
|
||||
} else if (descType & (DESCRIPTOR_SAMPLER_TYPE | DescriptorType.STORAGE_IMAGE)) {
|
||||
const isStorageImage = (descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE;
|
||||
if (isStorageImage) {
|
||||
// storage texture (compute read/write): bind the texture view, no sampler
|
||||
let currTex = this._textures[i] as WebGPUTexture;
|
||||
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
|
||||
currTex = device.defaultResource.texture;
|
||||
}
|
||||
this._bindTextureEntry(binding, currTex);
|
||||
} else if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
|
||||
// sampled texture
|
||||
let currTex = this._textures[i] as WebGPUTexture;
|
||||
// null or destroyed?
|
||||
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
|
||||
@@ -185,9 +193,9 @@ export class WebGPUDescriptorSet extends DescriptorSet {
|
||||
this._bindTextureEntry(binding, currTex);
|
||||
}
|
||||
|
||||
if (!((descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE
|
||||
|| (descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|
||||
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
|
||||
if (!isStorageImage
|
||||
&& !((descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|
||||
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
|
||||
// sampler
|
||||
const currSampler = (this._samplers[i] || device.defaultResource.sampler) as WebGPUSampler;
|
||||
this._bindSamplerEntry(binding, currSampler);
|
||||
@@ -219,7 +227,12 @@ export class WebGPUDescriptorSet extends DescriptorSet {
|
||||
}
|
||||
|
||||
public prepare (force: boolean = false): void {
|
||||
const breakUpdate = !this._isResourceChange() && !force;
|
||||
const gpuDescriptorSet = this._gpuDescriptorSet;
|
||||
if (!gpuDescriptorSet) {
|
||||
return;
|
||||
}
|
||||
// Rebuild when forced, when the bind group has never been built, or when resources changed.
|
||||
const breakUpdate = gpuDescriptorSet.bindGroup && !this._isResourceChange() && !force;
|
||||
if (breakUpdate) return;
|
||||
this._isDirty = true;
|
||||
this._applyBindGroup();
|
||||
|
||||
@@ -53,7 +53,7 @@ import { WebGPUTexture } from './webgpu-texture';
|
||||
import { DefaultResources, hashCombineNum, hashCombineStr, webGPU, WebGPUDeviceManager } from './define';
|
||||
import {
|
||||
Filter, Format,
|
||||
QueueType, Feature, BufferTextureCopy, Rect, DescriptorSetInfo,
|
||||
QueueType, Feature, BufferTextureCopy, Rect, Size, DescriptorSetInfo,
|
||||
BufferInfo, BufferViewInfo, CommandBufferInfo, DeviceInfo,
|
||||
FramebufferInfo, InputAssemblerInfo, QueueInfo, RenderPassInfo, SamplerInfo,
|
||||
ShaderInfo, PipelineLayoutInfo, DescriptorSetLayoutInfo, TextureInfo, TextureViewInfo, GeneralBarrierInfo, TextureBarrierInfo,
|
||||
@@ -552,6 +552,22 @@ export class WebGPUDevice extends Device {
|
||||
this._caps.max3DTextureSize = limits.maxTextureDimension3D;
|
||||
this._caps.uboOffsetAlignment = limits.minUniformBufferOffsetAlignment;
|
||||
|
||||
// Compute limits are read from the device (not the adapter): no elevated
|
||||
// compute limits are requested, so these are the values validation enforces.
|
||||
const deviceLimits = device.limits;
|
||||
this._caps.maxComputeSharedMemorySize = deviceLimits.maxComputeWorkgroupStorageSize;
|
||||
this._caps.maxComputeWorkGroupInvocations = deviceLimits.maxComputeInvocationsPerWorkgroup;
|
||||
this._caps.maxComputeWorkGroupSize = new Size(
|
||||
deviceLimits.maxComputeWorkgroupSizeX,
|
||||
deviceLimits.maxComputeWorkgroupSizeY,
|
||||
deviceLimits.maxComputeWorkgroupSizeZ,
|
||||
);
|
||||
this._caps.maxComputeWorkGroupCount = new Size(
|
||||
deviceLimits.maxComputeWorkgroupsPerDimension,
|
||||
deviceLimits.maxComputeWorkgroupsPerDimension,
|
||||
deviceLimits.maxComputeWorkgroupsPerDimension,
|
||||
);
|
||||
|
||||
const features = this._adapter!.features;
|
||||
// FIXME: require by query
|
||||
this._multiDrawIndirect = false;
|
||||
@@ -560,6 +576,7 @@ export class WebGPUDevice extends Device {
|
||||
this._features[Feature.ELEMENT_INDEX_UINT] = true;
|
||||
this._features[Feature.INSTANCED_ARRAYS] = true;
|
||||
this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
|
||||
this._features[Feature.COMPUTE_SHADER] = true;
|
||||
this.initFormatFeatures(features);
|
||||
|
||||
this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
|
||||
@@ -684,6 +701,7 @@ export class WebGPUDevice extends Device {
|
||||
public present (): void {
|
||||
const queue = (this._queue as unknown as WebGPUQueue);
|
||||
this._numDrawCalls = queue.numDrawCalls;
|
||||
this._numDispatches = queue.numDispatches;
|
||||
this._numInstances = queue.numInstances;
|
||||
this._numTris = queue.numTris;
|
||||
queue.clear();
|
||||
|
||||
@@ -241,8 +241,8 @@ export interface IWebGPUGPUPipelineState {
|
||||
bs: BlendState;
|
||||
dynamicStates: DynamicStateFlagBit[];
|
||||
gpuRenderPass: IWebGPUGPURenderPass | null;
|
||||
pipelineState: GPURenderPipelineDescriptor | undefined;
|
||||
nativePipeline: GPUPipelineBase | undefined;
|
||||
pipelineState: GPURenderPipelineDescriptor | GPUComputePipelineDescriptor | undefined;
|
||||
nativePipeline: GPURenderPipeline | GPUComputePipeline | undefined;
|
||||
}
|
||||
|
||||
export interface IWebGPUGPUDescriptor {
|
||||
|
||||
@@ -26,7 +26,7 @@ import { PipelineState, PipelineStateInfo } from '../base/pipeline-state';
|
||||
import { IWebGPUGPUInputAssembler, IWebGPUGPUPipelineState } from './webgpu-gpu-objects';
|
||||
import { WebGPURenderPass } from './webgpu-render-pass';
|
||||
import { WebGPUShader } from './webgpu-shader';
|
||||
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
|
||||
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PipelineBindPoint, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
|
||||
import { WebGPUPipelineLayout } from './webgpu-pipeline-layout';
|
||||
import {
|
||||
GFXFormatToWGPUFormat,
|
||||
@@ -81,124 +81,156 @@ export class WebGPUPipelineState extends PipelineState {
|
||||
}
|
||||
}
|
||||
|
||||
// colorstates
|
||||
const colorAttachments = this._renderPass.colorAttachments;
|
||||
const colorDescs: GPUColorTargetState[] = [];
|
||||
const colAttachmentSize = colorAttachments.length;
|
||||
const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout;
|
||||
for (let i = 0; i < colAttachmentSize; i++) {
|
||||
const colDesc: GPUColorTargetState = {
|
||||
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
|
||||
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
|
||||
};
|
||||
if (this._bs.targets[i].blend) {
|
||||
colDesc.blend = {
|
||||
color: {
|
||||
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
|
||||
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
|
||||
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
|
||||
},
|
||||
alpha: {
|
||||
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
|
||||
operation: WebGPUBlendOps[this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
|
||||
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
|
||||
},
|
||||
};
|
||||
}
|
||||
colorDescs.push(colDesc);
|
||||
}
|
||||
|
||||
let vertexStage: GPUProgrammableStage;
|
||||
let fragmentStage: GPUProgrammableStage;
|
||||
const shaderStages = (this._shader as WebGPUShader).gpuShader.gpuStages;
|
||||
const stageSize = shaderStages.length;
|
||||
for (let i = 0; i < stageSize; i++) {
|
||||
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
|
||||
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
|
||||
}
|
||||
|
||||
const gpuShader = info.shader as WebGPUShader;
|
||||
const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout;
|
||||
const shaderStages = gpuShader.gpuShader.gpuStages;
|
||||
|
||||
const shaderAttrs = gpuShader.attributes;
|
||||
const attrsSize = shaderAttrs.length;
|
||||
for (let i = 0; i < attrsSize; i++) {
|
||||
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
|
||||
}
|
||||
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
|
||||
const renderPplDesc: GPURenderPipelineDescriptor = {
|
||||
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
|
||||
vertex: {
|
||||
module: vertexStage!.module,
|
||||
entryPoint: 'main',
|
||||
buffers: [],
|
||||
},
|
||||
primitive: {
|
||||
topology: WebPUPrimitives[info.primitive],
|
||||
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
|
||||
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
|
||||
},
|
||||
|
||||
fragment: {
|
||||
module: fragmentStage!.module,
|
||||
entryPoint: 'main',
|
||||
targets: colorDescs,
|
||||
},
|
||||
};
|
||||
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
|
||||
|
||||
// depthstencil states
|
||||
let stencilRef = 0;
|
||||
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
|
||||
const dssDesc = {} as GPUDepthStencilState;
|
||||
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
|
||||
dssDesc.depthWriteEnabled = this._dss.depthWrite;
|
||||
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
|
||||
let stencilReadMask = 0;
|
||||
let stencilWriteMask = 0;
|
||||
|
||||
if (this._dss.stencilTestFront) {
|
||||
dssDesc.stencilFront = {
|
||||
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
|
||||
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
|
||||
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
|
||||
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
|
||||
};
|
||||
stencilReadMask |= this._dss.stencilReadMaskFront;
|
||||
stencilWriteMask |= this._dss.stencilWriteMaskFront;
|
||||
stencilRef |= this._dss.stencilRefFront;
|
||||
if (info.bindPoint === PipelineBindPoint.COMPUTE) {
|
||||
// ---- Compute Pipeline ----
|
||||
let computeStage: GPUProgrammableStage | undefined;
|
||||
const stageSize = shaderStages.length;
|
||||
for (let i = 0; i < stageSize; i++) {
|
||||
if (shaderStages[i].type === ShaderStageFlagBit.COMPUTE) {
|
||||
computeStage = shaderStages[i].gpuShader!;
|
||||
}
|
||||
}
|
||||
if (this._dss.stencilTestBack) {
|
||||
dssDesc.stencilBack = {
|
||||
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
|
||||
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
|
||||
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
|
||||
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
|
||||
};
|
||||
stencilReadMask |= this._dss.stencilReadMaskBack;
|
||||
stencilWriteMask |= this._dss.stencilWriteMaskBack;
|
||||
stencilRef |= this._dss.stencilRefBack;
|
||||
}
|
||||
dssDesc.stencilReadMask = stencilReadMask;
|
||||
dssDesc.stencilWriteMask = stencilWriteMask;
|
||||
dssDesc.depthBias = this._rs.depthBias;
|
||||
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
|
||||
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
|
||||
renderPplDesc.depthStencil = dssDesc;
|
||||
}
|
||||
|
||||
this._gpuPipelineState = {
|
||||
gpuPrimitive: WebPUPrimitives[info.primitive],
|
||||
gpuShader: gpuShader.gpuShader,
|
||||
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
|
||||
rs: info.rasterizerState,
|
||||
dss: info.depthStencilState,
|
||||
stencilRef,
|
||||
bs: info.blendState,
|
||||
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
|
||||
dynamicStates,
|
||||
pipelineState: renderPplDesc,
|
||||
nativePipeline: undefined,
|
||||
};
|
||||
const computeDesc: GPUComputePipelineDescriptor = {
|
||||
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
|
||||
compute: computeStage!,
|
||||
};
|
||||
|
||||
this._gpuPipelineState = {
|
||||
gpuPrimitive: 'triangle-list' as GPUPrimitiveTopology,
|
||||
gpuShader: gpuShader.gpuShader,
|
||||
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
|
||||
rs: info.rasterizerState,
|
||||
dss: info.depthStencilState,
|
||||
stencilRef: 0,
|
||||
bs: info.blendState,
|
||||
gpuRenderPass: null,
|
||||
dynamicStates,
|
||||
pipelineState: computeDesc,
|
||||
nativePipeline: undefined,
|
||||
};
|
||||
} else {
|
||||
// ---- Render Pipeline ----
|
||||
// colorstates
|
||||
const colorAttachments = this._renderPass.colorAttachments;
|
||||
const colorDescs: GPUColorTargetState[] = [];
|
||||
const colAttachmentSize = colorAttachments.length;
|
||||
for (let i = 0; i < colAttachmentSize; i++) {
|
||||
const colDesc: GPUColorTargetState = {
|
||||
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
|
||||
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
|
||||
};
|
||||
if (this._bs.targets[i].blend) {
|
||||
colDesc.blend = {
|
||||
color: {
|
||||
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
|
||||
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
|
||||
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
|
||||
},
|
||||
alpha: {
|
||||
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
|
||||
operation: WebGPUBlendOps[
|
||||
this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
|
||||
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
|
||||
},
|
||||
};
|
||||
}
|
||||
colorDescs.push(colDesc);
|
||||
}
|
||||
|
||||
let vertexStage: GPUProgrammableStage;
|
||||
let fragmentStage: GPUProgrammableStage;
|
||||
const stageSize = shaderStages.length;
|
||||
for (let i = 0; i < stageSize; i++) {
|
||||
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
|
||||
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
|
||||
}
|
||||
|
||||
const shaderAttrs = gpuShader.attributes;
|
||||
const attrsSize = shaderAttrs.length;
|
||||
for (let i = 0; i < attrsSize; i++) {
|
||||
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
|
||||
}
|
||||
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
|
||||
const renderPplDesc: GPURenderPipelineDescriptor = {
|
||||
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
|
||||
vertex: {
|
||||
module: vertexStage!.module,
|
||||
entryPoint: 'main',
|
||||
buffers: [],
|
||||
},
|
||||
primitive: {
|
||||
topology: WebPUPrimitives[info.primitive],
|
||||
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
|
||||
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
|
||||
},
|
||||
|
||||
fragment: {
|
||||
module: fragmentStage!.module,
|
||||
entryPoint: 'main',
|
||||
targets: colorDescs,
|
||||
},
|
||||
};
|
||||
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
|
||||
|
||||
// depthstencil states
|
||||
let stencilRef = 0;
|
||||
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
|
||||
const dssDesc = {} as GPUDepthStencilState;
|
||||
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
|
||||
dssDesc.depthWriteEnabled = this._dss.depthWrite;
|
||||
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
|
||||
let stencilReadMask = 0;
|
||||
let stencilWriteMask = 0;
|
||||
|
||||
if (this._dss.stencilTestFront) {
|
||||
dssDesc.stencilFront = {
|
||||
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
|
||||
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
|
||||
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
|
||||
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
|
||||
};
|
||||
stencilReadMask |= this._dss.stencilReadMaskFront;
|
||||
stencilWriteMask |= this._dss.stencilWriteMaskFront;
|
||||
stencilRef |= this._dss.stencilRefFront;
|
||||
}
|
||||
if (this._dss.stencilTestBack) {
|
||||
dssDesc.stencilBack = {
|
||||
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
|
||||
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
|
||||
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
|
||||
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
|
||||
};
|
||||
stencilReadMask |= this._dss.stencilReadMaskBack;
|
||||
stencilWriteMask |= this._dss.stencilWriteMaskBack;
|
||||
stencilRef |= this._dss.stencilRefBack;
|
||||
}
|
||||
dssDesc.stencilReadMask = stencilReadMask;
|
||||
dssDesc.stencilWriteMask = stencilWriteMask;
|
||||
dssDesc.depthBias = this._rs.depthBias;
|
||||
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
|
||||
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
|
||||
renderPplDesc.depthStencil = dssDesc;
|
||||
}
|
||||
|
||||
this._gpuPipelineState = {
|
||||
gpuPrimitive: WebPUPrimitives[info.primitive],
|
||||
gpuShader: gpuShader.gpuShader,
|
||||
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
|
||||
rs: info.rasterizerState,
|
||||
dss: info.depthStencilState,
|
||||
stencilRef,
|
||||
bs: info.blendState,
|
||||
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
|
||||
dynamicStates,
|
||||
pipelineState: renderPplDesc,
|
||||
nativePipeline: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
protected _getShaderLocation (name: string): number | undefined {
|
||||
@@ -215,9 +247,22 @@ export class WebGPUPipelineState extends PipelineState {
|
||||
if (this._gpuPipelineState!.nativePipeline && !forceUpdate) {
|
||||
return;
|
||||
}
|
||||
const webgpuDevice = (WebGPUDeviceManager.instance);
|
||||
const nativeDevice = webgpuDevice.nativeDevice;
|
||||
|
||||
const pipelineState = this._gpuPipelineState!.pipelineState!;
|
||||
// Compute pipeline: no vertex attributes, no multisample
|
||||
if ('compute' in pipelineState) {
|
||||
const nativePipeline = nativeDevice?.createComputePipeline(
|
||||
pipelineState,
|
||||
);
|
||||
this._gpuPipelineState!.nativePipeline = nativePipeline;
|
||||
return;
|
||||
}
|
||||
|
||||
// Render pipeline
|
||||
const gpuShader = this.shader;
|
||||
const shaderAttrs = gpuShader.attributes;
|
||||
const pipelineState = this._gpuPipelineState!.pipelineState!;
|
||||
const vertexAttrs: GPUVertexBufferLayout[] = [];
|
||||
const emptyPushAttr: string[] = [];
|
||||
const streamCount = ia.gpuVertexBuffers.length;
|
||||
@@ -272,8 +317,6 @@ export class WebGPUPipelineState extends PipelineState {
|
||||
|
||||
pipelineState.vertex.buffers = vertexAttrs;
|
||||
pipelineState.multisample = { count: ia.samples };
|
||||
const webgpuDevice = (WebGPUDeviceManager.instance);
|
||||
const nativeDevice = webgpuDevice.nativeDevice;
|
||||
const nativePipeline = nativeDevice?.createRenderPipeline(pipelineState);
|
||||
this._gpuPipelineState!.nativePipeline = nativePipeline;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import { QueueInfo } from '../base/define';
|
||||
|
||||
export class WebGPUQueue extends Queue {
|
||||
public numDrawCalls = 0;
|
||||
public numDispatches = 0;
|
||||
public numInstances = 0;
|
||||
public numTris = 0;
|
||||
|
||||
@@ -51,6 +52,7 @@ export class WebGPUQueue extends Queue {
|
||||
for (let i = 0; i < cmdBuffSize; i++) {
|
||||
const cmdBuff = cmdBuffs[i] as WebGPUCommandBuffer;
|
||||
this.numDrawCalls += cmdBuff.numDrawCalls;
|
||||
this.numDispatches += cmdBuff.numDispatches;
|
||||
this.numInstances += cmdBuff.numInstances;
|
||||
this.numTris += cmdBuff.numTris;
|
||||
}
|
||||
@@ -59,6 +61,7 @@ export class WebGPUQueue extends Queue {
|
||||
|
||||
public clear (): void {
|
||||
this.numDrawCalls = 0;
|
||||
this.numDispatches = 0;
|
||||
this.numInstances = 0;
|
||||
this.numTris = 0;
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ class Particle {
|
||||
public pos = new Vec2(0, 0);
|
||||
public startPos = new Vec2(0, 0);
|
||||
public color = new Color(0, 0, 0, 255);
|
||||
public curColor = { r: 0, g: 0, b: 0, a: 255 };
|
||||
public deltaColor = { r: 0, g: 0, b: 0, a: 255 };
|
||||
public size = 0;
|
||||
public deltaSize = 0;
|
||||
@@ -81,6 +82,8 @@ const pool = new ParticlePool((par: Particle): void => {
|
||||
par.pos.set(Vec2.ZERO);
|
||||
par.startPos.set(Vec2.ZERO);
|
||||
par.color.set(0, 0, 0, 255);
|
||||
par.curColor.r = par.curColor.g = par.curColor.b = 0;
|
||||
par.curColor.a = 255;
|
||||
par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0;
|
||||
par.deltaColor.a = 255;
|
||||
par.size = 0;
|
||||
@@ -111,6 +114,7 @@ export class Simulator {
|
||||
private elapsed = 0;
|
||||
private emitCounter = 0;
|
||||
private _worldRotation = 0;
|
||||
private _parentAlpha = 0.0;
|
||||
private declare sys: ParticleSystem2D;
|
||||
|
||||
constructor (system) {
|
||||
@@ -169,10 +173,10 @@ export class Simulator {
|
||||
const endColor = psys.endColor;
|
||||
const endColorVar = psys.endColorVar;
|
||||
|
||||
particle.color.r = sr = clamp(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
|
||||
particle.color.g = sg = clamp(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
|
||||
particle.color.b = sb = clamp(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
|
||||
particle.color.a = sa = clamp(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
|
||||
particle.curColor.r = sr = clamp(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
|
||||
particle.curColor.g = sg = clamp(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
|
||||
particle.curColor.b = sb = clamp(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
|
||||
particle.curColor.a = sa = clamp(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
|
||||
particle.deltaColor.r = (clamp(endColor.r + endColorVar.r * (random() - 0.5) * 2, 0, 255) - sr) / timeToLive;
|
||||
particle.deltaColor.g = (clamp(endColor.g + endColorVar.g * (random() - 0.5) * 2, 0, 255) - sg) / timeToLive;
|
||||
particle.deltaColor.b = (clamp(endColor.b + endColorVar.b * (random() - 0.5) * 2, 0, 255) - sb) / timeToLive;
|
||||
@@ -329,6 +333,14 @@ export class Simulator {
|
||||
Vec4.toArray(vbuf, _col, offset + 32);
|
||||
}
|
||||
|
||||
private _updateColor (): void {
|
||||
const selfNode = this.sys.node;
|
||||
const parentNode = selfNode.parent;
|
||||
const uiProps = selfNode._uiProps;
|
||||
const parentOpacity = parentNode ? parentNode._uiProps.opacity : 1.0;
|
||||
this._parentAlpha = uiProps.localOpacity * parentOpacity;
|
||||
}
|
||||
|
||||
public step (dt: number): void {
|
||||
const assembler = this.sys.assembler as Particle2DAssembler;
|
||||
const psys = this.sys;
|
||||
@@ -379,6 +391,8 @@ export class Simulator {
|
||||
this.updateUVs();
|
||||
}
|
||||
|
||||
this._updateColor();
|
||||
|
||||
// Used to reduce memory allocation / creation within the loop
|
||||
let particleIdx = 0;
|
||||
while (particleIdx < particles.length) {
|
||||
@@ -431,10 +445,15 @@ export class Simulator {
|
||||
}
|
||||
|
||||
// color
|
||||
particle.color.r += particle.deltaColor.r * dt;
|
||||
particle.color.g += particle.deltaColor.g * dt;
|
||||
particle.color.b += particle.deltaColor.b * dt;
|
||||
particle.color.a += particle.deltaColor.a * dt;
|
||||
particle.curColor.r += particle.deltaColor.r * dt;
|
||||
particle.curColor.g += particle.deltaColor.g * dt;
|
||||
particle.curColor.b += particle.deltaColor.b * dt;
|
||||
particle.curColor.a += particle.deltaColor.a * dt;
|
||||
|
||||
particle.color.r = particle.curColor.r;
|
||||
particle.color.g = particle.curColor.g;
|
||||
particle.color.b = particle.curColor.b;
|
||||
particle.color.a = particle.curColor.a * this._parentAlpha;
|
||||
|
||||
// size
|
||||
particle.size += particle.deltaSize * dt;
|
||||
|
||||
@@ -797,7 +797,7 @@ export class ParticleSystem2D extends UIRenderer {
|
||||
}
|
||||
|
||||
private _startPreview (): void {
|
||||
if (this._preview) {
|
||||
if (!this._preview) {
|
||||
this.resetSystem();
|
||||
}
|
||||
}
|
||||
|
||||
+10
-1
@@ -25,7 +25,7 @@
|
||||
import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable,
|
||||
range, visible, override, displayName } from 'cc.decorator';
|
||||
import { Material, Texture2D } from '../asset/assets';
|
||||
import { Vec3, cclegacy, Vec4, Vec2, CCBoolean } from '../core';
|
||||
import { Vec3, cclegacy, Vec4, Vec2, CCBoolean, Color } from '../core';
|
||||
import { LineModel } from './models/line-model';
|
||||
import { builtinResMgr } from '../asset/asset-manager';
|
||||
import CurveRange from './animator/curve-range';
|
||||
@@ -296,6 +296,15 @@ export class Line extends ModelRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
public updateColor (): void {
|
||||
if (this._color) {
|
||||
if (this._models[0]) {
|
||||
const lineModel = this._models[0] as LineModel;
|
||||
lineModel.addLineVertexData(this._positions, this._width, this._color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected _onMaterialModified (index: number, material: Material | null): void {
|
||||
super._onMaterialModified(index, material);
|
||||
const matIns = this.getMaterialInstance(0);
|
||||
|
||||
+14
-4
@@ -29,7 +29,8 @@ import { Vec2, Vec3 } from '../core/math';
|
||||
* @zh 此类生成噪声纹理。
|
||||
*/
|
||||
export class ParticleNoise {
|
||||
private permutation: number[] = [151, 160, 137, 91, 90, 15,
|
||||
private static readonly DEFAULT_PERMUTATION: readonly number[] = [
|
||||
151, 160, 137, 91, 90, 15,
|
||||
131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
|
||||
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,
|
||||
88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,
|
||||
@@ -44,9 +45,19 @@ export class ParticleNoise {
|
||||
138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
|
||||
];
|
||||
|
||||
private static build512 (src: readonly number[] | number[]): Uint8Array {
|
||||
const p = new Uint8Array(512);
|
||||
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = src[i]; }
|
||||
return p;
|
||||
}
|
||||
|
||||
private permutation: number[] = ParticleNoise.DEFAULT_PERMUTATION as number[];
|
||||
private permutation512: Uint8Array = ParticleNoise.build512(ParticleNoise.DEFAULT_PERMUTATION);
|
||||
|
||||
constructor (permutation?: number[]) {
|
||||
if (permutation) {
|
||||
this.permutation = permutation;
|
||||
this.permutation = permutation.slice();
|
||||
this.permutation512 = ParticleNoise.build512(this.permutation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,8 +72,7 @@ export class ParticleNoise {
|
||||
* @returns @en Texture pixel generated. @zh 返回生成的噪声纹理值。
|
||||
*/
|
||||
public noise (x: number, y: number, z: number, min = 0, max = 1): number {
|
||||
const p: number[] = new Array(512);
|
||||
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = this.permutation[i]; }
|
||||
const p: Uint8Array = this.permutation512;
|
||||
|
||||
const X = Math.floor(x) & 255; // FIND UNIT CUBE THAT
|
||||
const Y = Math.floor(y) & 255; // CONTAINS POINT.
|
||||
|
||||
@@ -42,7 +42,7 @@ import VelocityOvertimeModule from './animator/velocity-overtime';
|
||||
import Burst from './burst';
|
||||
import ShapeModule from './emitter/shape-module';
|
||||
import { ParticleCullingMode, ParticleSpace } from './enum';
|
||||
import { particleEmitZAxis } from './particle-general-function';
|
||||
import { isCurveTwoValues, particleEmitZAxis } from './particle-general-function';
|
||||
import ParticleSystemRenderer from './renderer/particle-system-renderer-data';
|
||||
import TrailModule from './renderer/trail';
|
||||
import { ParticleSystemRendererBase } from './renderer/particle-system-renderer-base';
|
||||
@@ -141,7 +141,7 @@ export class ParticleSystem extends ModelRenderer {
|
||||
@range([0, Number.POSITIVE_INFINITY])
|
||||
@displayOrder(10)
|
||||
@tooltip('i18n:particle_system.startSizeY')
|
||||
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; })
|
||||
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) // eslint-disable-line func-names, comma-dangle
|
||||
public startSizeY = new CurveRange();
|
||||
|
||||
/**
|
||||
@@ -153,7 +153,7 @@ export class ParticleSystem extends ModelRenderer {
|
||||
@range([0, Number.POSITIVE_INFINITY])
|
||||
@displayOrder(10)
|
||||
@tooltip('i18n:particle_system.startSizeZ')
|
||||
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; })
|
||||
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) // eslint-disable-line func-names, comma-dangle
|
||||
public startSizeZ = new CurveRange();
|
||||
|
||||
/**
|
||||
@@ -184,7 +184,7 @@ export class ParticleSystem extends ModelRenderer {
|
||||
@radian
|
||||
@displayOrder(12)
|
||||
@tooltip('i18n:particle_system.startRotationX')
|
||||
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; })
|
||||
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) // eslint-disable-line func-names, comma-dangle
|
||||
public startRotationX = new CurveRange();
|
||||
|
||||
/**
|
||||
@@ -196,7 +196,7 @@ export class ParticleSystem extends ModelRenderer {
|
||||
@radian
|
||||
@displayOrder(12)
|
||||
@tooltip('i18n:particle_system.startRotationY')
|
||||
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; })
|
||||
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) // eslint-disable-line func-names, comma-dangle
|
||||
public startRotationY = new CurveRange();
|
||||
|
||||
/**
|
||||
@@ -1455,16 +1455,18 @@ export class ParticleSystem extends ModelRenderer {
|
||||
|
||||
if (!self._isEmitting) return;
|
||||
|
||||
const randTime = isCurveTwoValues(self.rateOverTime) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
|
||||
// emit by rateOverTime
|
||||
self._emitRateTimeCounter += self.rateOverTime.evaluate(self._time / self.duration, 1)! * dt;
|
||||
self._emitRateTimeCounter += self.rateOverTime.evaluate(self._time / self.duration, randTime)! * dt;
|
||||
if (self._emitRateTimeCounter > 1) {
|
||||
const emitNum = Math.floor(self._emitRateTimeCounter);
|
||||
self._emitRateTimeCounter -= emitNum;
|
||||
self.emit(emitNum, dt);
|
||||
}
|
||||
|
||||
const randDist = isCurveTwoValues(self.rateOverDistance) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
|
||||
// emit by rateOverDistance
|
||||
const rateOverDistance = self.rateOverDistance.evaluate(self._time / self.duration, 1)!;
|
||||
const rateOverDistance = self.rateOverDistance.evaluate(self._time / self.duration, randDist)!;
|
||||
if (rateOverDistance > 0) {
|
||||
Vec3.copy(self._oldWPos, self._curWPos);
|
||||
self.node.getWorldPosition(self._curWPos);
|
||||
|
||||
@@ -60,6 +60,7 @@ interface IProfilerState {
|
||||
frame: ICounterOption;
|
||||
fps: ICounterOption;
|
||||
draws: ICounterOption;
|
||||
dispatches: ICounterOption;
|
||||
instances: ICounterOption;
|
||||
tricount: ICounterOption;
|
||||
logic: ICounterOption;
|
||||
@@ -73,6 +74,7 @@ interface IProfilerState {
|
||||
const _profileInfo = {
|
||||
fps: { desc: `Framerate (FPS)`, below: 30, average: _average, isInteger: true },
|
||||
draws: { desc: 'Draw call', isInteger: true },
|
||||
dispatches: { desc: 'Dispatch call', isInteger: true },
|
||||
frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: _average },
|
||||
instances: { desc: 'Instance Count', isInteger: true },
|
||||
tricount: { desc: 'Triangle', isInteger: true },
|
||||
@@ -586,6 +588,8 @@ export class Profiler extends System {
|
||||
|
||||
const device = this._device!;
|
||||
(profilerStats.draws.counter as PerfCounter).value = device.numDrawCalls;
|
||||
// Native (JSB) devices expose no dispatch stats yet; WebGPU does. Treat missing as 0.
|
||||
(profilerStats.dispatches.counter as PerfCounter).value = device.numDispatches ?? 0;
|
||||
(profilerStats.instances.counter as PerfCounter).value = device.numInstances;
|
||||
(profilerStats.bufferMemory.counter as PerfCounter).value = device.memoryStatus.bufferSize / (1024 * 1024);
|
||||
(profilerStats.textureMemory.counter as PerfCounter).value = device.memoryStatus.textureSize / (1024 * 1024);
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
import { Buffer, Framebuffer, Texture, Viewport } from '../../gfx';
|
||||
import { genHashValue } from './define';
|
||||
import { VectorGraphColorMap } from './effect';
|
||||
import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph';
|
||||
import { LayoutGraphData } from './layout-graph';
|
||||
@@ -199,7 +198,6 @@ class PassVisitor implements RenderGraphVisitor {
|
||||
resourceGraph.visitVertex(this._resVisitor, vertID);
|
||||
}
|
||||
}
|
||||
genHashValue(pass);
|
||||
}
|
||||
}
|
||||
applyID (id: number, resId: number): void {
|
||||
@@ -233,7 +231,21 @@ class PassVisitor implements RenderGraphVisitor {
|
||||
compute (value: ComputePass): void {
|
||||
this._currPass = value;
|
||||
const rg = context.renderGraph;
|
||||
if (rg.getValid(this.passID)) {
|
||||
// Avoid revisiting a valid pass and recursive dependency cycles.
|
||||
return;
|
||||
}
|
||||
rg.setValid(this.passID, true);
|
||||
// Trace READ dependencies only; WRITE dependencies are produced by this pass.
|
||||
const resourceGraph = this.context.resourceGraph;
|
||||
for (const [computeName, cViews] of value.computeViews) {
|
||||
if (!cViews.length || cViews[0].accessType !== AccessType.READ) continue;
|
||||
const vertID = resourceGraph.find(computeName);
|
||||
if (vertID !== 0xFFFFFFFF) {
|
||||
this._resVisitor.resID = vertID;
|
||||
resourceGraph.visitVertex(this._resVisitor, vertID);
|
||||
}
|
||||
}
|
||||
}
|
||||
resolve (value: ResolvePass): void {
|
||||
// noop
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
Device,
|
||||
deviceManager,
|
||||
DispatchInfo,
|
||||
Feature,
|
||||
Format,
|
||||
Framebuffer,
|
||||
FramebufferInfo,
|
||||
@@ -56,9 +57,7 @@ import {
|
||||
InputAssemblerInfo,
|
||||
LoadOp,
|
||||
MemoryUsageBit,
|
||||
PipelineBindPoint,
|
||||
PipelineState,
|
||||
PipelineStateInfo,
|
||||
Rect,
|
||||
RenderPass,
|
||||
RenderPassInfo,
|
||||
@@ -1910,26 +1909,23 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor {
|
||||
renderScene.preRecord();
|
||||
}
|
||||
dispatch (value: Dispatch): void {
|
||||
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
|
||||
let pso: PipelineState | null = null;
|
||||
const devicePass = this.currPass as DeviceComputePass;
|
||||
const pass = value.material?.passes[value.passID];
|
||||
pass?.update();
|
||||
const shader = pass?.getShaderVariant();
|
||||
|
||||
if (pass !== null && shader !== null) {
|
||||
const psoInfo = new PipelineStateInfo(
|
||||
shader,
|
||||
pass?.pipelineLayout,
|
||||
);
|
||||
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
|
||||
pso = deviceManager.gfxDevice.createPipelineState(psoInfo);
|
||||
if (pass && shader) {
|
||||
pso = PipelineStateManager.getOrCreateComputePipelineState(deviceManager.gfxDevice, pass, shader);
|
||||
}
|
||||
const cmdBuff = context.commandBuffer;
|
||||
if (pso) {
|
||||
if (pso && pass) {
|
||||
cmdBuff.bindPipelineState(pso);
|
||||
const layoutStage = devicePass.renderLayout;
|
||||
const layoutDesc = layoutStage!.descriptorSet!;
|
||||
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc);
|
||||
cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
|
||||
}
|
||||
|
||||
const gx = value.threadGroupCountX;
|
||||
@@ -1965,10 +1961,12 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor
|
||||
computeSubpass (value: ComputeSubpass): void {
|
||||
// do nothing
|
||||
}
|
||||
resolve (value: ResolvePass): void {
|
||||
// do nothing
|
||||
}
|
||||
compute (value: ComputePass): void {
|
||||
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
|
||||
const cmdBuff = context.commandBuffer;
|
||||
(cmdBuff as any).submitComputePass();
|
||||
}
|
||||
resolve (value: ResolvePass): void {
|
||||
// do nothing
|
||||
}
|
||||
copy (value: CopyPass): void {
|
||||
|
||||
@@ -195,10 +195,13 @@ function sceneCulling (
|
||||
}
|
||||
models.push(model);
|
||||
} else if (probe.probeType === ProbeType.CUBE) {
|
||||
if (!wBounds || !model.bakeToReflectionProbe) {
|
||||
continue;
|
||||
}
|
||||
if (!isVisible(model, visibility)) {
|
||||
continue;
|
||||
}
|
||||
if (wBounds && isIntersectAABB(wBounds, probe.boundingBox!)) {
|
||||
if (isIntersectAABB(wBounds, probe.boundingBox!)) {
|
||||
continue;
|
||||
}
|
||||
models.push(model);
|
||||
@@ -475,7 +478,8 @@ export class SceneCulling {
|
||||
);
|
||||
|
||||
// Get or create render queue
|
||||
const renderQueueID = this.getOrCreateRenderQueue(renderQueueKey, sceneData.flags, sceneData.camera);
|
||||
const renderCamera = sceneData.light.probe ? sceneData.light.probe.camera : sceneData.camera;
|
||||
const renderQueueID = this.getOrCreateRenderQueue(renderQueueKey, sceneData.flags, renderCamera);
|
||||
|
||||
// add render queue query
|
||||
const renderQueueQuery = this.cullingPools.renderQueueQueryRecycle.add();
|
||||
|
||||
@@ -258,9 +258,19 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild
|
||||
|
||||
addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags = SceneFlags.NONE, name = 'Camera'): void {
|
||||
const lightTarget = light.light;
|
||||
this.addScene(camera, sceneFlags, lightTarget);
|
||||
const scene = light.probe?.node?.scene?.renderScene || undefined;
|
||||
this._addScene(camera, sceneFlags, lightTarget, scene, light);
|
||||
}
|
||||
addScene (camera: Camera, sceneFlags = SceneFlags.NONE, light: Light | undefined | null = null, scene: RenderScene | undefined = undefined): SceneBuilder {
|
||||
return this._addScene(camera, sceneFlags, light, scene);
|
||||
}
|
||||
private _addScene (
|
||||
camera: Camera,
|
||||
sceneFlags: SceneFlags,
|
||||
light: Light | undefined | null,
|
||||
scene: RenderScene | undefined,
|
||||
lightInfo: LightInfo | null = null,
|
||||
): SceneBuilder {
|
||||
const sceneData = renderGraphPool.createSceneData(
|
||||
scene || camera.scene,
|
||||
camera,
|
||||
@@ -268,6 +278,9 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild
|
||||
light && !(sceneFlags & SceneFlags.SHADOW_CASTER) ? CullingFlags.CAMERA_FRUSTUM | CullingFlags.LIGHT_BOUNDS : CullingFlags.CAMERA_FRUSTUM,
|
||||
light,
|
||||
);
|
||||
if (lightInfo) {
|
||||
sceneData.light.reset(lightInfo.light, lightInfo.level, lightInfo.culledByLight, lightInfo.probe);
|
||||
}
|
||||
const renderData = renderGraphPool.createRenderData();
|
||||
const sceneId = this._renderGraph.addVertex<RenderGraphValue.Scene>(RenderGraphValue.Scene, sceneData, 'Scene', '', renderData, !DEBUG, this._vertID);
|
||||
if (!(sceneFlags & SceneFlags.NON_BUILTIN)) {
|
||||
@@ -851,7 +864,11 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild
|
||||
this._renderGraph.setName(this._vertID, name);
|
||||
}
|
||||
addTexture (name: string, slotName: string, sampler: Sampler | null = null): void {
|
||||
throw new Error('Method not implemented.');
|
||||
this._addComputeResource(name, AccessType.READ, slotName);
|
||||
if (sampler) {
|
||||
const descriptorID = this._lg.attributeIndex.get(slotName)!;
|
||||
this._data.samplers.set(descriptorID, sampler);
|
||||
}
|
||||
}
|
||||
addStorageBuffer (name: string, accessType: AccessType, slotName: string): void {
|
||||
this._addComputeResource(name, accessType, slotName);
|
||||
@@ -1650,13 +1667,16 @@ export class WebPipeline extends WebSetter implements BasicPipeline {
|
||||
this._compiler = new Compiler(this, this._renderGraph, this._resourceGraph, this._lg);
|
||||
}
|
||||
this._compiler.compile(this._renderGraph);
|
||||
} else {
|
||||
this._renderGraph.x.forEach((vert) => {
|
||||
if (vert.t === RenderGraphValue.RasterPass) {
|
||||
genHashValue(vert.j as RasterPass);
|
||||
}
|
||||
});
|
||||
}
|
||||
this._renderGraph.x.forEach((vert, v) => {
|
||||
if (vert.t !== RenderGraphValue.RasterPass) {
|
||||
return;
|
||||
}
|
||||
if (DEBUG && !this._renderGraph!.getValid(v)) {
|
||||
return;
|
||||
}
|
||||
genHashValue(vert.j as RasterPass);
|
||||
});
|
||||
}
|
||||
|
||||
execute (): void {
|
||||
|
||||
@@ -1264,15 +1264,6 @@ export class WebProgramLibrary implements ProgramLibrary {
|
||||
if (passSet) {
|
||||
info.setLayouts.push(passSet);
|
||||
}
|
||||
const phaseSet = getDescriptorSetLayout(
|
||||
this.layoutGraph,
|
||||
subpassOrPassID,
|
||||
phaseID,
|
||||
UpdateFrequency.PER_PHASE,
|
||||
);
|
||||
if (phaseSet) {
|
||||
info.setLayouts.push(phaseSet);
|
||||
}
|
||||
const batchSet = getProgramDescriptorSetLayout(
|
||||
device,
|
||||
lg,
|
||||
@@ -1293,6 +1284,15 @@ export class WebProgramLibrary implements ProgramLibrary {
|
||||
if (instanceSet) {
|
||||
info.setLayouts.push(instanceSet);
|
||||
}
|
||||
const phaseSet = getDescriptorSetLayout(
|
||||
this.layoutGraph,
|
||||
subpassOrPassID,
|
||||
phaseID,
|
||||
UpdateFrequency.PER_PHASE,
|
||||
);
|
||||
if (phaseSet) {
|
||||
info.setLayouts.push(phaseSet);
|
||||
}
|
||||
programData.pipelineLayout = device.createPipelineLayout(info);
|
||||
return programData.pipelineLayout;
|
||||
}
|
||||
|
||||
@@ -131,6 +131,11 @@ export class InstancedBuffer {
|
||||
stride,
|
||||
shader,
|
||||
descriptorSet,
|
||||
lightingMap,
|
||||
useReflectionProbeType,
|
||||
reflectionProbeCubemap,
|
||||
reflectionProbePlanarMap,
|
||||
reflectionProbeBlendCubemap,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -157,14 +162,20 @@ export class InstancedBuffer {
|
||||
stride: number,
|
||||
shader: Shader,
|
||||
descriptorSet: DescriptorSet,
|
||||
lightingMap: Texture,
|
||||
useReflectionProbeType: number,
|
||||
reflectionProbeCubemap: Texture,
|
||||
reflectionProbePlanarMap: Texture,
|
||||
reflectionProbeBlendCubemap: Texture | null,
|
||||
): void {
|
||||
const newSize = stride * INITIAL_CAPACITY;
|
||||
const vb = this._device.createBuffer(new BufferInfo(
|
||||
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
|
||||
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
|
||||
stride * INITIAL_CAPACITY,
|
||||
newSize,
|
||||
stride,
|
||||
));
|
||||
const data = new Uint8Array(stride * INITIAL_CAPACITY);
|
||||
const data = new Uint8Array(newSize);
|
||||
const vertexBuffers = sourceIA.vertexBuffers.slice();
|
||||
const attributes = sourceIA.attributes.slice();
|
||||
const indexBuffer = sourceIA.indexBuffer;
|
||||
@@ -188,6 +199,11 @@ export class InstancedBuffer {
|
||||
stride,
|
||||
shader,
|
||||
descriptorSet,
|
||||
lightingMap,
|
||||
reflectionProbeCubemap,
|
||||
reflectionProbePlanarMap,
|
||||
useReflectionProbeType,
|
||||
reflectionProbeBlendCubemap,
|
||||
} as IInstancedItem;
|
||||
this.instances.push(instance);
|
||||
let mappedInstances = this._instanceMap.get(key);
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo } from '../gfx';
|
||||
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo, PipelineBindPoint } from '../gfx';
|
||||
import { Pass } from '../render-scene/core/pass';
|
||||
|
||||
export class PipelineStateManager {
|
||||
@@ -30,6 +30,8 @@ export class PipelineStateManager {
|
||||
|
||||
private static _PSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
|
||||
|
||||
private static _computePSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
|
||||
|
||||
// pass is only needed on TS.
|
||||
static getOrCreatePipelineState (device: Device, pass: Pass, shader: Shader, renderPass: RenderPass, ia: InputAssembler): PipelineState {
|
||||
const hash1 = pass.hash;
|
||||
@@ -59,4 +61,33 @@ export class PipelineStateManager {
|
||||
|
||||
return pso;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Get or create a compute pipeline state.
|
||||
* A compute pipeline only depends on the shader variant and the pipeline layout,
|
||||
* both carried by the pass, so the cache key is `pass.hash ^ shader.typedID`,
|
||||
* mirroring the graphics-side hash mechanism without renderPass/inputState factors.
|
||||
* @zh 获取或创建计算管线状态。
|
||||
* 计算管线仅依赖于着色器变体与管线布局(均由 pass 携带),
|
||||
* 因此缓存键为 `pass.hash ^ shader.typedID`,与图形侧哈希机制一致但不包含 renderPass/顶点布局因子。
|
||||
*/
|
||||
static getOrCreateComputePipelineState (device: Device, pass: Pass, shader: Shader): PipelineState {
|
||||
const hash1 = pass.hash;
|
||||
const hash2 = shader.typedID;
|
||||
|
||||
const newHash = hash1 ^ hash2;
|
||||
let pso = this._computePSOHashMap.get(newHash);
|
||||
if (!pso) {
|
||||
const pipelineLayout = pass.pipelineLayout;
|
||||
const psoInfo = new PipelineStateInfo(
|
||||
shader,
|
||||
pipelineLayout,
|
||||
);
|
||||
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
|
||||
pso = device.createPipelineState(psoInfo);
|
||||
this._computePSOHashMap.set(newHash, pso);
|
||||
}
|
||||
|
||||
return pso;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1537,6 +1537,7 @@ export class Terrain extends Component {
|
||||
* @zh 获得地形信息
|
||||
*/
|
||||
@type(TerrainInfo)
|
||||
@visible(false)
|
||||
public get info (): TerrainInfo {
|
||||
const ti = new TerrainInfo();
|
||||
ti.tileSize = this.tileSize;
|
||||
@@ -1815,11 +1816,11 @@ export class Terrain extends Component {
|
||||
* @zh 获得纹理层
|
||||
*/
|
||||
public getLayer (id: number): TerrainLayer | null {
|
||||
if (id === -1) {
|
||||
if (id === -1 || id === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this._layerList[id];
|
||||
return this._layerList[id] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2584,7 +2585,8 @@ export class Terrain extends Component {
|
||||
const index1 = j * this.blockCount[0] + i;
|
||||
|
||||
for (let l = 0; l < TERRAIN_MAX_BLEND_LAYERS; ++l) {
|
||||
layerBuffer[index0 * TERRAIN_MAX_BLEND_LAYERS + l] = this._layerBuffer[index1 * TERRAIN_MAX_BLEND_LAYERS + l];
|
||||
const oldVal = this._layerBuffer[index1 * TERRAIN_MAX_BLEND_LAYERS + l];
|
||||
layerBuffer[index0 * TERRAIN_MAX_BLEND_LAYERS + l] = oldVal !== undefined ? oldVal : -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+54
-7
@@ -93,8 +93,8 @@ enum State {
|
||||
export enum ButtonEventType {
|
||||
/**
|
||||
* @event click
|
||||
* @param {Event.EventCustom} event
|
||||
* @param {Button} button - The Button component.
|
||||
* @param {EventTouch} event - The original touch event, undefined if the click is triggered by XR.
|
||||
*/
|
||||
CLICK = 'click',
|
||||
}
|
||||
@@ -156,16 +156,16 @@ export enum ButtonEventType {
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { log, Node } from 'cc';
|
||||
* import { log } from 'cc';
|
||||
* // Add an event to the button.
|
||||
* button.node.on(Node.EventType.TOUCH_START, (event) => {
|
||||
* log("This is a callback after the trigger event");
|
||||
* });
|
||||
* // You could also add a click event
|
||||
* // Note: In this way, you can't get the touch event info, so use it wisely.
|
||||
* button.node.on(Node.EventType.CLICK, (button) => {
|
||||
* //The event is a custom event, you could get the Button component via first argument
|
||||
* })
|
||||
* // The callback receives the Button component and the original touch event (if available).
|
||||
* button.on(Button.EventType.CLICK, (button, event) => {
|
||||
* log('button clicked');
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
@ccclass('cc.Button')
|
||||
@@ -586,6 +586,53 @@ export class Button extends Component {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
* Register a Button event listener on the component. Button events are dispatched by the owner
|
||||
* node, and this method is a shorthand which forwards the registration to the node, so
|
||||
* `button.on(...)` and `button.node.on(...)` share the same listener registry.
|
||||
* @zh
|
||||
* 在组件上注册 Button 事件监听。Button 的事件由所属节点派发,此方法是 `this.node.on(type, ...)`
|
||||
* 的便捷封装,`button.on(...)` 与 `button.node.on(...)` 共用同一份监听器。
|
||||
* @param type @en Event type, e.g. [[ButtonEventType.CLICK]]. @zh 事件类型,如 [[ButtonEventType.CLICK]]。
|
||||
* @param callback @en The callback, receives the Button component and the original event. @zh 回调函数,参数为 Button 组件与原始事件。
|
||||
* @param target @en The target to be bound with. @zh 绑定的目标对象。
|
||||
* @example
|
||||
* ```ts
|
||||
* button.on(Button.EventType.CLICK, (button, event) => {
|
||||
* // clicked
|
||||
* }, this);
|
||||
* ```
|
||||
*/
|
||||
public on (type: ButtonEventType, callback: (button: Button, event?: EventTouch) => void, target?: unknown): void {
|
||||
this.node.on(type, callback, target);
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
* Remove a Button event listener registered via [[on]] or `button.node.on`. To remove a listener,
|
||||
* the `type`, `callback` and `target` must match the registration.
|
||||
* @zh
|
||||
* 移除通过 [[on]] 或 `button.node.on` 注册的 Button 事件监听。`type`、`callback`、`target`
|
||||
* 需与注册时一致才能正确移除。
|
||||
*/
|
||||
public off (type: ButtonEventType, callback?: (button: Button, event?: EventTouch) => void, target?: unknown): void {
|
||||
this.node.off(type, callback, target);
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
* Remove all Button event listeners registered with the given target.
|
||||
* Note: this forwards to `node.targetOff`, so listeners registered by other components
|
||||
* or by the engine internals on the same node with the same target are removed as well.
|
||||
* @zh
|
||||
* 移除指定 target 上注册的所有 Button 事件监听。注意:此方法会转发到 `node.targetOff`,
|
||||
* 同一节点上其他组件或引擎内部以相同 target 注册的监听也会被一并移除。
|
||||
*/
|
||||
public targetOff (target: unknown): void {
|
||||
this.node.targetOff(target);
|
||||
}
|
||||
|
||||
public __preload (): void {
|
||||
if (!this.target) {
|
||||
this.target = this.node;
|
||||
@@ -892,7 +939,7 @@ export class Button extends Component {
|
||||
|
||||
if (this._pressed) {
|
||||
ComponentEventHandler.emitEvents(this.clickEvents, event);
|
||||
this.node.emit(ButtonEventType.CLICK, this);
|
||||
this.node.emit(ButtonEventType.CLICK, this, event);
|
||||
}
|
||||
this._pressed = false;
|
||||
this._updateState();
|
||||
|
||||
@@ -204,7 +204,7 @@ function align (node: Node, widget: Widget): void {
|
||||
// TODO: type is hack, Change to the type actually used (Node or BaseNode) when BaseNode complete
|
||||
function visitNode (node: any): void {
|
||||
const widget = node.getComponent(Widget);
|
||||
if (widget && widget.enabled) {
|
||||
if (widget && widget.enabled && cclegacy.isValid(widget, true)) {
|
||||
if (DEV) {
|
||||
widget._validateTargetInDEV();
|
||||
}
|
||||
|
||||
@@ -852,6 +852,9 @@ export class Widget extends Component {
|
||||
}
|
||||
|
||||
public onDestroy (): void {
|
||||
// `onDisable` is skipped when the component was never enabled by the scheduler
|
||||
// (`IsOnEnableCalled` unset), so unregister here as well.
|
||||
cclegacy._widgetManager?.remove(this);
|
||||
this._removeParentEvent();
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -145,7 +145,7 @@ void main() {
|
||||
color = packRGBE(color.rgb); // for reflection-map
|
||||
#else
|
||||
color = CCSurfacesDebugDisplayInvalidNumber(color);
|
||||
#if !CC_USE_FLOAT_OUTPUT || CC_IS_TRANSPARENCY_PASS
|
||||
#if !CC_USE_FLOAT_OUTPUT
|
||||
color.rgb = HDRToLDR(color.rgb);
|
||||
color.rgb = LinearToSRGB(color.rgb);
|
||||
#endif
|
||||
|
||||
@@ -669,8 +669,8 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
|
||||
// Rendering
|
||||
const probePass = ppl.addRenderPass(width, height, 'default');
|
||||
probePass.name = `PlanarReflectionProbe${probeID}`;
|
||||
this._buildReflectionProbePass(probePass, cameraConfigs, id, reflectionCamera,
|
||||
colorName, depthStencilName, mainLight, scene);
|
||||
this._buildReflectionProbePass(probePass, cameraConfigs, id, reflectionCamera, probe,
|
||||
colorName, depthStencilName, mainLight);
|
||||
} else if (EDITOR) {
|
||||
for (let faceIdx = 0; faceIdx < probe.bakedCubeTextures.length; faceIdx++) {
|
||||
probe.updateCameraDir(faceIdx);
|
||||
@@ -686,8 +686,8 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
|
||||
// Rendering
|
||||
const probePass = ppl.addRenderPass(width, height, 'default');
|
||||
probePass.name = `CubeProbe${probeID}${faceIdx}`;
|
||||
this._buildReflectionProbePass(probePass, cameraConfigs, id, probe.camera,
|
||||
colorName, depthStencilName, mainLight, scene);
|
||||
this._buildReflectionProbePass(probePass, cameraConfigs, id, probe.camera, probe,
|
||||
colorName, depthStencilName, mainLight);
|
||||
}
|
||||
probe.needRender = false;
|
||||
}
|
||||
@@ -702,10 +702,10 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
|
||||
cameraConfigs: Readonly<CameraConfigs & ForwardPassConfigs>,
|
||||
id: number,
|
||||
camera: renderer.scene.Camera,
|
||||
probe: renderer.scene.ReflectionProbe,
|
||||
colorName: string,
|
||||
depthStencilName: string,
|
||||
mainLight: renderer.scene.DirectionalLight | null,
|
||||
scene: renderer.RenderScene | null = null,
|
||||
): void {
|
||||
const QueueHint = rendering.QueueHint;
|
||||
const SceneFlags = rendering.SceneFlags;
|
||||
@@ -749,11 +749,11 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
|
||||
// TODO(zhouzhenglong): Separate OPAQUE and MASK queue
|
||||
|
||||
// add opaque and mask queue
|
||||
const lightInfo = new rendering.LightInfo(mainLight || null, 0, false, probe);
|
||||
pass.addQueue(QueueHint.NONE, 'reflect-map') // Currently we put OPAQUE and MASK into one queue, so QueueHint is NONE
|
||||
.addScene(camera,
|
||||
SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.REFLECTION_PROBE,
|
||||
mainLight || undefined,
|
||||
scene ? scene : undefined);
|
||||
.addSceneOfCamera(camera,
|
||||
lightInfo,
|
||||
SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.REFLECTION_PROBE);
|
||||
}
|
||||
private _addForwardRadiancePasses(
|
||||
ppl: rendering.BasicPipeline,
|
||||
|
||||
@@ -222,13 +222,22 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ccs
|
||||
// Fill index buffer.
|
||||
ArrayBuffer::Ptr indexBuffer;
|
||||
uint32_t idxCount = 0;
|
||||
const uint32_t idxStride = 2;
|
||||
uint32_t idxStride = 2;
|
||||
gfx::Format indexFormat = gfx::Format::R16UI;
|
||||
if (geometry.indices.has_value()) {
|
||||
const ccstd::vector<uint32_t> &indices = geometry.indices.value();
|
||||
uint32_t maxIndex = 0;
|
||||
for (uint32_t idx : indices) {
|
||||
maxIndex = std::max(maxIndex, idx);
|
||||
}
|
||||
if (maxIndex > std::numeric_limits<uint16_t>::max()) {
|
||||
idxStride = 4;
|
||||
indexFormat = gfx::Format::R32UI;
|
||||
}
|
||||
idxCount = static_cast<uint32_t>(indices.size());
|
||||
indexBuffer = ccnew ArrayBuffer(idxStride * idxCount);
|
||||
DataView indexBufferView(indexBuffer);
|
||||
writeBuffer(indexBufferView, indices, gfx::Format::R16UI);
|
||||
writeBuffer(indexBufferView, indices, indexFormat);
|
||||
}
|
||||
|
||||
// Create primitive.
|
||||
|
||||
@@ -86,6 +86,12 @@ void BakedSkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Me
|
||||
pipeline::UBOSkinning::size,
|
||||
});
|
||||
}
|
||||
|
||||
// JSB synchronizes the new root's animation buffer before calling bindSkeleton.
|
||||
for (index_t i = 0; i < _subModels.size(); ++i) {
|
||||
updateLocalDescriptors(i, _subModels[i]->getDescriptorSet());
|
||||
}
|
||||
updateInstancedJointTextureInfo();
|
||||
}
|
||||
|
||||
void BakedSkinningModel::updateTransform(uint32_t stamp) {
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
****************************************************************************/
|
||||
#include "3d/models/SkinningModel.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "3d/assets/Mesh.h"
|
||||
@@ -80,6 +82,7 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m
|
||||
_joints.clear();
|
||||
|
||||
if (!skeleton || !skinningRoot || !mesh) return;
|
||||
const bool prevRealTimeTextureMode = _realTimeTextureMode;
|
||||
auto jointCount = static_cast<uint32_t>(skeleton->getJoints().size());
|
||||
_realTimeTextureMode = pipeline::SkinningJointCapacity::jointUniformCapacity < jointCount;
|
||||
setTransform(skinningRoot);
|
||||
@@ -113,6 +116,15 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m
|
||||
jointInfo.indices = std::move(indices);
|
||||
_joints.emplace_back(std::move(jointInfo));
|
||||
}
|
||||
|
||||
// Rebind recreated resources without resetting custom instanced attributes.
|
||||
const auto subModelCount = std::min(_subModels.size(), _bufferIndices.size());
|
||||
if (subModelCount && prevRealTimeTextureMode != _realTimeTextureMode) {
|
||||
onMacroPatchesStateChanged();
|
||||
}
|
||||
for (index_t i = 0; i < subModelCount; ++i) {
|
||||
updateLocalDescriptors(i, _subModels[i]->getDescriptorSet());
|
||||
}
|
||||
}
|
||||
|
||||
void SkinningModel::updateTransform(uint32_t stamp) {
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
#include <sys/types.h>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
#include "application/ApplicationManager.h"
|
||||
#include "audio/include/AudioEngine.h"
|
||||
@@ -265,10 +266,11 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu
|
||||
|
||||
auto iter = _callbackMap.find(id);
|
||||
if (iter != _callbackMap.end()) {
|
||||
if (state == IAudioPlayer::State::OVER) {
|
||||
iter->second(id, filePath);
|
||||
}
|
||||
auto callback = std::move(iter->second);
|
||||
_callbackMap.erase(iter);
|
||||
if (state == IAudioPlayer::State::OVER) {
|
||||
callback(id, filePath);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -27,7 +27,9 @@
|
||||
|
||||
#import <OpenAL/al.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include "base/std/container/string.h"
|
||||
|
||||
@@ -40,6 +42,7 @@
|
||||
namespace cc {
|
||||
class AudioEngineImpl;
|
||||
class AudioPlayer;
|
||||
class Scheduler;
|
||||
|
||||
class AudioCache {
|
||||
public:
|
||||
@@ -96,13 +99,15 @@ protected:
|
||||
|
||||
std::mutex _readDataTaskMutex;
|
||||
|
||||
State _state{State::INITIAL};
|
||||
std::atomic<State> _state{State::INITIAL};
|
||||
|
||||
std::shared_ptr<bool> _isDestroyed;
|
||||
// Assigned before the read task is submitted; workers must not look up the current application.
|
||||
std::weak_ptr<Scheduler> _scheduler;
|
||||
std::shared_ptr<std::atomic_bool> _isDestroyed;
|
||||
ccstd::string _fileFullPath;
|
||||
unsigned int _id;
|
||||
bool _isLoadingFinished{false};
|
||||
bool _isSkipReadDataTask{false};
|
||||
std::atomic_bool _isLoadingFinished{false};
|
||||
std::atomic_bool _isSkipReadDataTask{false};
|
||||
|
||||
friend class AudioEngineImpl;
|
||||
friend class AudioPlayer;
|
||||
|
||||
@@ -31,7 +31,6 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <OpenAL/alc.h>
|
||||
#include <thread>
|
||||
#include "application/ApplicationManager.h"
|
||||
#include "base/Scheduler.h"
|
||||
#include "base/memory/Memory.h"
|
||||
|
||||
@@ -85,7 +84,7 @@ unsigned int __idIndex = 0;
|
||||
using namespace cc;
|
||||
|
||||
AudioCache::AudioCache()
|
||||
: _isDestroyed(std::make_shared<bool>(false)), _id(++__idIndex){
|
||||
: _isDestroyed(std::make_shared<std::atomic_bool>(false)), _id(++__idIndex){
|
||||
ALOGVV("AudioCache() %p, id=%u", this, _id);
|
||||
for (int i = 0; i < QUEUEBUFFER_NUM; ++i) {
|
||||
_queBuffers[i] = nullptr;
|
||||
@@ -114,7 +113,7 @@ AudioCache::~AudioCache() {
|
||||
_alBufferId = INVALID_AL_BUFFER_ID;
|
||||
}
|
||||
} else {
|
||||
ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state);
|
||||
ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, static_cast<int>(_state.load()));
|
||||
}
|
||||
|
||||
if (_queBufferFrames > 0) {
|
||||
@@ -267,7 +266,6 @@ void AudioCache::readDataTask(unsigned int selfId) {
|
||||
invokingPlayCallbacks();
|
||||
invokingLoadCallbacks();
|
||||
|
||||
_isLoadingFinished = true;
|
||||
if (_state != State::READY) {
|
||||
_state = State::FAILED;
|
||||
if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId)) {
|
||||
@@ -277,12 +275,13 @@ void AudioCache::readDataTask(unsigned int selfId) {
|
||||
}
|
||||
}
|
||||
|
||||
_isLoadingFinished = true;
|
||||
_readDataTaskMutex.unlock();
|
||||
}
|
||||
|
||||
void AudioCache::addPlayCallback(const std::function<void()> &callback) {
|
||||
std::lock_guard<std::mutex> lk(_playCallbackMutex);
|
||||
switch (_state) {
|
||||
switch (_state.load()) {
|
||||
case State::INITIAL:
|
||||
case State::LOADING:
|
||||
_playCallbacks.push_back(callback);
|
||||
@@ -296,7 +295,7 @@ void AudioCache::addPlayCallback(const std::function<void()> &callback) {
|
||||
break;
|
||||
|
||||
default:
|
||||
ALOGE("Invalid state: %d", _state);
|
||||
ALOGE("Invalid state: %d", static_cast<int>(_state.load()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -312,7 +311,7 @@ void AudioCache::invokingPlayCallbacks() {
|
||||
}
|
||||
|
||||
void AudioCache::addLoadCallback(const std::function<void(bool)> &callback) {
|
||||
switch (_state) {
|
||||
switch (_state.load()) {
|
||||
case State::INITIAL:
|
||||
case State::LOADING:
|
||||
_loadCallbacks.push_back(callback);
|
||||
@@ -326,7 +325,7 @@ void AudioCache::addLoadCallback(const std::function<void(bool)> &callback) {
|
||||
break;
|
||||
|
||||
default:
|
||||
ALOGE("Invalid state: %d", _state);
|
||||
ALOGE("Invalid state: %d", static_cast<int>(_state.load()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -337,18 +336,27 @@ void AudioCache::invokingLoadCallbacks() {
|
||||
return;
|
||||
}
|
||||
|
||||
auto scheduler = _scheduler.lock();
|
||||
if (!scheduler) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto isDestroyed = _isDestroyed;
|
||||
auto scheduler = CC_CURRENT_ENGINE()->getScheduler();
|
||||
scheduler->performFunctionInCocosThread([&, isDestroyed]() {
|
||||
const bool isReady = _state.load() == State::READY;
|
||||
scheduler->performFunctionInCocosThread([this, isDestroyed, isReady]() {
|
||||
if (*isDestroyed) {
|
||||
ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this);
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto &&cb : _loadCallbacks) {
|
||||
cb(_state == State::READY);
|
||||
// A callback may uncache this file or end the audio engine. Do not access the
|
||||
// cache again after invoking user code, and cancel any remaining callbacks.
|
||||
auto callbacks = std::move(_loadCallbacks);
|
||||
for (auto &&cb : callbacks) {
|
||||
if (*isDestroyed) {
|
||||
break;
|
||||
}
|
||||
cb(isReady);
|
||||
}
|
||||
|
||||
_loadCallbacks.clear();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -167,6 +167,13 @@ AudioEngineImpl::~AudioEngineImpl() {
|
||||
sche->unschedule("AudioEngine", this);
|
||||
}
|
||||
|
||||
// AudioEngine::end() has joined the worker pool before deleting this backend.
|
||||
// Queued tasks are discarded by the pool, so their caches will never receive
|
||||
// a read/skip notification from a worker. Unblock those cache destructors.
|
||||
for (auto &entry : _audioCaches) {
|
||||
entry.second.setSkipReadDataTask(true);
|
||||
}
|
||||
|
||||
if (s_ALContext) {
|
||||
alDeleteSources(MAX_AUDIOINSTANCES, _alSources);
|
||||
|
||||
@@ -286,6 +293,7 @@ AudioCache *AudioEngineImpl::preload(const ccstd::string &filePath, std::functio
|
||||
auto it = _audioCaches.find(filePath);
|
||||
if (it == _audioCaches.end()) {
|
||||
audioCache = &_audioCaches[filePath];
|
||||
audioCache->_scheduler = _scheduler;
|
||||
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
|
||||
unsigned int cacheId = audioCache->_id;
|
||||
auto isCacheDestroyed = audioCache->_isDestroyed;
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
#include "audio/common/decoder/AudioDecoder.h"
|
||||
#include "base/Log.h"
|
||||
#include "base/Utils.h"
|
||||
@@ -500,6 +501,7 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void(in
|
||||
}
|
||||
|
||||
void AudioEngineImpl::update(float /*dt*/) {
|
||||
ccstd::vector<std::function<void()>> finishCallbacks;
|
||||
ALint sourceState;
|
||||
int audioID;
|
||||
AudioPlayer *player;
|
||||
@@ -534,7 +536,9 @@ void AudioEngineImpl::update(float /*dt*/) {
|
||||
_threadMutex.unlock();
|
||||
|
||||
if (player->_finishCallbak) {
|
||||
player->_finishCallbak(audioID, filePath); //IDEA: callback will delay 50ms
|
||||
finishCallbacks.emplace_back([callback = std::move(player->_finishCallbak), audioID, filePath]() {
|
||||
callback(audioID, filePath);
|
||||
});
|
||||
}
|
||||
delete player;
|
||||
_alSourceUsed[alSource] = false;
|
||||
@@ -549,6 +553,12 @@ void AudioEngineImpl::update(float /*dt*/) {
|
||||
sche->unschedule("AudioEngine", this);
|
||||
}
|
||||
}
|
||||
|
||||
// Callbacks may play/stop audio or destroy the engine. Finish all access to
|
||||
// player state before invoking them, and keep the callbacks in local storage.
|
||||
for (const auto &callback : finishCallbacks) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
void AudioEngineImpl::uncache(const ccstd::string &filePath) {
|
||||
|
||||
@@ -157,6 +157,7 @@ void Scheduler::schedule(const ccSchedulerFunc &callback, void *target, float in
|
||||
if (iter == _hashForTimers.end()) {
|
||||
element = ccnew HashTimerEntry();
|
||||
element->target = target;
|
||||
element->generation = ++_nextTimerGeneration;
|
||||
|
||||
_hashForTimers[target] = element;
|
||||
|
||||
@@ -368,10 +369,23 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() {
|
||||
void Scheduler::update(float dt) {
|
||||
_updateHashLocked = true;
|
||||
|
||||
// Iterate over all the custom selectors
|
||||
HashTimerEntry *elt = nullptr;
|
||||
for (auto iter = _hashForTimers.begin(); iter != _hashForTimers.end();) {
|
||||
elt = iter->second;
|
||||
// Callbacks can rehash the map or remove and recreate a target. Snapshot
|
||||
// identities, not iterators or entry pointers; new entries start next frame.
|
||||
struct TimerIdentity {
|
||||
void *target;
|
||||
uint64_t generation;
|
||||
};
|
||||
ccstd::vector<TimerIdentity> targets;
|
||||
targets.reserve(_hashForTimers.size());
|
||||
for (const auto &entry : _hashForTimers) {
|
||||
targets.push_back({entry.first, entry.second->generation});
|
||||
}
|
||||
for (const auto &target : targets) {
|
||||
auto iter = _hashForTimers.find(target.target);
|
||||
if (iter == _hashForTimers.end() || iter->second->generation != target.generation) {
|
||||
continue;
|
||||
}
|
||||
auto *elt = iter->second;
|
||||
_currentTarget = elt;
|
||||
_currentTargetSalvaged = false;
|
||||
|
||||
@@ -396,14 +410,9 @@ void Scheduler::update(float dt) {
|
||||
|
||||
// only delete currentTarget if no actions were scheduled during the cycle (issue #481)
|
||||
if (_currentTargetSalvaged && _currentTarget->timers.empty()) {
|
||||
++iter;
|
||||
removeHashElement(_currentTarget);
|
||||
if (iter != _hashForTimers.end()) {
|
||||
++iter;
|
||||
}
|
||||
} else {
|
||||
++iter;
|
||||
}
|
||||
_currentTarget = nullptr;
|
||||
}
|
||||
|
||||
_updateHashLocked = false;
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
|
||||
@@ -278,6 +279,7 @@ private:
|
||||
struct HashTimerEntry {
|
||||
ccstd::vector<Timer *> timers;
|
||||
void *target;
|
||||
uint64_t generation;
|
||||
int timerIndex;
|
||||
Timer *currentTimer;
|
||||
bool currentTimerSalvaged;
|
||||
@@ -291,9 +293,10 @@ private:
|
||||
|
||||
// Used for "selectors with interval"
|
||||
ccstd::unordered_map<void *, HashTimerEntry *> _hashForTimers;
|
||||
uint64_t _nextTimerGeneration = 0;
|
||||
struct HashTimerEntry *_currentTarget = nullptr;
|
||||
bool _currentTargetSalvaged = false;
|
||||
// If true unschedule will not remove anything from a hash. Elements will only be marked for deletion.
|
||||
// True while timer entries are being updated.
|
||||
bool _updateHashLocked = false;
|
||||
|
||||
// Used for "perform Function"
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
#include <bitset>
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include "base/Macros.h"
|
||||
#include "base/TypeDef.h"
|
||||
@@ -145,10 +146,27 @@ CC_FORCE_INLINE Tgt bit_cast(const Src &src) { // NOLINT(readability-identifier-
|
||||
Tgt tgt;
|
||||
// Load src into registers first. This allows the memcpy to be elided by CUDA.
|
||||
const Src staged = src;
|
||||
memcpy(&tgt, &staged, sizeof(Tgt));
|
||||
std::memcpy(&tgt, &staged, sizeof(Tgt));
|
||||
return tgt;
|
||||
}
|
||||
|
||||
// Map a float to a uint32 whose unsigned-integer ordering matches the float's
|
||||
// numeric ordering (the classic radix-sort "flip"):
|
||||
// * non-negative: flip the sign bit
|
||||
// * negative: complement all bits
|
||||
// This maps [-inf, -0.0] to [0, 2^31) and [+0.0, +inf] to [2^31, 2^32), so the
|
||||
// unsigned comparison orders floats correctly. NaN must be excluded by the caller.
|
||||
//
|
||||
// Requires IEEE 754 binary32 (32-bit) floats, which every Cocos platform has.
|
||||
static_assert(sizeof(float) == sizeof(uint32_t), "float must be 32-bit");
|
||||
static_assert(std::numeric_limits<float>::is_iec559, "float must be IEEE 754");
|
||||
|
||||
CC_FORCE_INLINE uint32_t floatToSortableUint(float value) {
|
||||
constexpr uint32_t signBit = 0x80000000U;
|
||||
const auto bits = bit_cast<uint32_t>(value);
|
||||
return (bits & signBit) ? ~bits : (bits ^ signBit);
|
||||
}
|
||||
|
||||
} // namespace numext
|
||||
|
||||
// Following the Arm ACLE arm_neon.h should also include arm_fp16.h but not all
|
||||
@@ -164,7 +182,7 @@ struct HalfRaw {
|
||||
#if defined(CC_HAS_ARM64_FP16_SCALAR_ARITHMETIC)
|
||||
explicit HalfRaw(uint16_t raw) : x(numext::bit_cast<__fp16>(raw)) {
|
||||
}
|
||||
__fp16 x;
|
||||
__fp16 x; // NOLINT(modernize-use-default-member-init)
|
||||
#else
|
||||
explicit constexpr HalfRaw(uint16_t raw) : x(raw) {}
|
||||
uint16_t x; // NOLINT(modernize-use-default-member-init)
|
||||
|
||||
@@ -1184,10 +1184,12 @@ void ScriptEngine::removeUnhandledPromise(v8::Local<v8::Promise> promise) {
|
||||
// Remove handled promises from the list
|
||||
SE_ASSERT(promise->GetIsolate() == _isolate, "Wrong isolate");
|
||||
auto *isolate = promise->GetIsolate();
|
||||
for (auto it = _unhandledPromises.begin(); it != _unhandledPromises.end(); ++it) {
|
||||
for (auto it = _unhandledPromises.begin(); it != _unhandledPromises.end();) {
|
||||
v8::Local<v8::Promise> const unhandledPromise = std::get<0>(*it).Get(isolate);
|
||||
if (unhandledPromise == promise) {
|
||||
_unhandledPromises.erase(it--);
|
||||
it = _unhandledPromises.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -623,7 +623,7 @@ ccstd::unordered_map<uint32_t, ccstd::string> debugInfos = {
|
||||
{ 16417, "'clearTrack' interface can not be invoked in cached mode." },
|
||||
{ 16418, "Debug bones or slots is invalid in cached mode." },
|
||||
{ 16419, "Spine version not supported." },
|
||||
{ 16420, "Start time must bigger than end time." },
|
||||
{ 16420, "End time must bigger than start time." },
|
||||
|
||||
};
|
||||
}//namespace cc
|
||||
|
||||
@@ -751,7 +751,19 @@ void SpineSkeletonInstance::resizeSlotRegion(const spine::String &slotName, uint
|
||||
releaseSlotCacheInfo(cacheInfo);
|
||||
}
|
||||
_slotTextureSet.put(slot, info);
|
||||
|
||||
auto &bones = _skeleton->getBones();
|
||||
const size_t boneCount = bones.size();
|
||||
std::vector<bool> activeBackup(boneCount);
|
||||
for (size_t i = 0; i < boneCount; ++i) {
|
||||
activeBackup[i] = bones[i]->isActive();
|
||||
}
|
||||
|
||||
_skeleton->updateCache();
|
||||
|
||||
for (size_t i = 0; i < boneCount; ++i) {
|
||||
bones[i]->setActive(activeBackup[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void SpineSkeletonInstance::setSlotTexture(const spine::String &slotName, const spine::String& textureUuid) {
|
||||
|
||||
@@ -1007,7 +1007,8 @@ public:
|
||||
for (auto *set : sets) {
|
||||
set->update(oldView, newView);
|
||||
}
|
||||
_gpuBufferViewSet.erase(iter);
|
||||
// Connecting the new view may have rehashed the map.
|
||||
_gpuBufferViewSet.erase(oldView);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1018,7 +1019,8 @@ public:
|
||||
for (auto *set : sets) {
|
||||
set->update(oldView, newView);
|
||||
}
|
||||
_gpuTextureViewSet.erase(iter);
|
||||
// Connecting the new view may have rehashed the map.
|
||||
_gpuTextureViewSet.erase(oldView);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1217,7 +1219,8 @@ public:
|
||||
ia->update(oldBuffer, newBuffer);
|
||||
_ias[newBuffer].insert(ia);
|
||||
}
|
||||
_ias.erase(iter);
|
||||
// Registering the new buffer may have rehashed the map.
|
||||
_ias.erase(oldBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -99,8 +99,8 @@ CCWGPUDevice::CCWGPUDevice() : Device() {
|
||||
|
||||
_caps.maxComputeSharedMemorySize = 32768;
|
||||
_caps.maxComputeWorkGroupInvocations = 256;
|
||||
_caps.maxComputeWorkGroupSize = {65535, 65535, 65535};
|
||||
_caps.maxComputeWorkGroupCount = {256, 256, 64};
|
||||
_caps.maxComputeWorkGroupSize = {256, 256, 64};
|
||||
_caps.maxComputeWorkGroupCount = {65535, 65535, 65535};
|
||||
|
||||
instance = this;
|
||||
}
|
||||
@@ -582,8 +582,8 @@ void CCWGPUDevice::initLimits() {
|
||||
|
||||
_caps.maxComputeSharedMemorySize = limits.maxComputeWorkgroupStorageSize;
|
||||
_caps.maxComputeWorkGroupInvocations = limits.maxComputeInvocationsPerWorkgroup;
|
||||
_caps.maxComputeWorkGroupSize = {limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension};
|
||||
_caps.maxComputeWorkGroupCount = {limits.maxComputeWorkgroupSizeX, limits.maxComputeWorkgroupSizeY, limits.maxComputeWorkgroupSizeZ};
|
||||
_caps.maxComputeWorkGroupSize = {limits.maxComputeWorkgroupSizeX, limits.maxComputeWorkgroupSizeY, limits.maxComputeWorkgroupSizeZ};
|
||||
_caps.maxComputeWorkGroupCount = {limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension};
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -73,6 +73,15 @@ struct CC_DLL RenderPass {
|
||||
uint32_t hash = 0;
|
||||
float depth = 0.0F;
|
||||
uint32_t shaderID = 0;
|
||||
/**
|
||||
* Packed sort keys, computed once in RenderQueue::insertRenderPass so the
|
||||
* comparator degenerates to a single uint64 compare.
|
||||
* opaque: primaryKey = hash, secondaryKey = depthKey << 32 | shaderID
|
||||
* transparent: primaryKey = priority << 32 | hash, secondaryKey = ~depthKey << 32 | shaderID
|
||||
* depthKey is the order-preserving uint32 mapping of depth.
|
||||
*/
|
||||
uint64_t primaryKey = 0;
|
||||
uint64_t secondaryKey = 0;
|
||||
uint32_t passIndex = 0;
|
||||
const scene::SubModel *subModel = nullptr;
|
||||
};
|
||||
@@ -175,35 +184,17 @@ using RenderQueueDescList = ccstd::vector<IntrusivePtr<RenderQueueDesc>>;
|
||||
uint32_t getPhaseID(const ccstd::string &phase);
|
||||
|
||||
inline bool opaqueCompareFn(const RenderPass &a, const RenderPass &b) {
|
||||
if (a.hash != b.hash) {
|
||||
return a.hash < b.hash;
|
||||
if (a.primaryKey != b.primaryKey) {
|
||||
return a.primaryKey < b.primaryKey;
|
||||
}
|
||||
|
||||
CC_ASSERT(!std::isnan(a.depth) && !std::isnan(b.depth));
|
||||
|
||||
if (a.depth != b.depth) {
|
||||
return a.depth < b.depth;
|
||||
}
|
||||
|
||||
return a.shaderID < b.shaderID;
|
||||
return a.secondaryKey < b.secondaryKey;
|
||||
}
|
||||
|
||||
inline bool transparentCompareFn(const RenderPass &a, const RenderPass &b) {
|
||||
if (a.priority != b.priority) {
|
||||
return a.priority < b.priority;
|
||||
if (a.primaryKey != b.primaryKey) {
|
||||
return a.primaryKey < b.primaryKey;
|
||||
}
|
||||
|
||||
if (a.hash != b.hash) {
|
||||
return a.hash < b.hash;
|
||||
}
|
||||
|
||||
CC_ASSERT(!std::isnan(a.depth) && !std::isnan(b.depth));
|
||||
|
||||
if (a.depth != b.depth) {
|
||||
return b.depth < a.depth;
|
||||
}
|
||||
|
||||
return a.shaderID < b.shaderID;
|
||||
return a.secondaryKey < b.secondaryKey;
|
||||
}
|
||||
|
||||
inline uint32_t convertPhase(const ccstd::vector<ccstd::string> &stages) {
|
||||
@@ -688,6 +679,9 @@ static constexpr uint32_t CLUSTER_LIGHT_BINDING = 4;
|
||||
static constexpr uint32_t CLUSTER_LIGHT_INDEX_BINDING = 5;
|
||||
static constexpr uint32_t CLUSTER_LIGHT_GRID_BINDING = 6;
|
||||
|
||||
constexpr const char *GEOMETRY_RENDERER_COMMAND = "geometry-renderer";
|
||||
constexpr const char *DEBUG_RENDERER_COMMAND = "debug-renderer";
|
||||
|
||||
void localDescriptorSetLayoutResizeMaxJoints(uint32_t maxCount);
|
||||
|
||||
} // namespace pipeline
|
||||
|
||||
@@ -22,8 +22,11 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#include "InstancedBuffer.h"
|
||||
#include <algorithm>
|
||||
|
||||
#include "Define.h"
|
||||
#include "InstancedBuffer.h"
|
||||
#include "base/StringUtil.h"
|
||||
#include "gfx-base/GFXBuffer.h"
|
||||
#include "gfx-base/GFXCommandBuffer.h"
|
||||
#include "gfx-base/GFXDescriptorSet.h"
|
||||
@@ -49,6 +52,7 @@ void InstancedBuffer::destroy() {
|
||||
CC_FREE(instance.data);
|
||||
}
|
||||
_instances.clear();
|
||||
_instancesMap.clear();
|
||||
}
|
||||
|
||||
void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx) {
|
||||
@@ -66,9 +70,9 @@ void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Sh
|
||||
auto *lightingMap = descriptorSet->getTexture(LIGHTMAPTEXTURE::BINDING);
|
||||
auto *reflectionProbeCubemap = descriptorSet->getTexture(REFLECTIONPROBECUBEMAP::BINDING);
|
||||
auto *reflectionProbePlanarMap = descriptorSet->getTexture(REFLECTIONPROBEPLANARMAP::BINDING);
|
||||
gfx::Texture *reflectionProbeBlendCubemap = ENABLE_PROBE_BLEND
|
||||
? descriptorSet->getTexture(REFLECTIONPROBEBLENDCUBEMAP::BINDING)
|
||||
: nullptr;
|
||||
auto *reflectionProbeBlendCubemap = ENABLE_PROBE_BLEND
|
||||
? descriptorSet->getTexture(REFLECTIONPROBEBLENDCUBEMAP::BINDING)
|
||||
: nullptr;
|
||||
const uint32_t reflectionProbeType = subModel->getReflectionProbeType();
|
||||
auto *shader = shaderImplant;
|
||||
if (!shader) {
|
||||
@@ -81,65 +85,91 @@ void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Sh
|
||||
_sortRender.hash = hash;
|
||||
_sortRender.shaderID = shaderId;
|
||||
_sortRender.passIndex = passIdx;
|
||||
for (auto &instance : _instances) {
|
||||
if (instance.ia->getIndexBuffer() != sourceIA->getIndexBuffer() || instance.drawInfo.instanceCount >= MAX_CAPACITY) {
|
||||
continue;
|
||||
const ccstd::string key = StringUtil::format("%u/%u/%u/%u/%u/%u/%u",
|
||||
sourceIA->getIndexBuffer() ? sourceIA->getIndexBuffer()->getObjectID() : 0,
|
||||
lightingMap ? lightingMap->getObjectID() : 0,
|
||||
reflectionProbeType,
|
||||
reflectionProbeCubemap ? reflectionProbeCubemap->getObjectID() : 0,
|
||||
reflectionProbePlanarMap ? reflectionProbePlanarMap->getObjectID() : 0,
|
||||
reflectionProbeBlendCubemap ? reflectionProbeBlendCubemap->getObjectID() : 0,
|
||||
stride);
|
||||
const auto iter = _instancesMap.find(key);
|
||||
if (iter != _instancesMap.end()) {
|
||||
for (size_t idx : iter->second) {
|
||||
auto &instance = _instances[idx];
|
||||
if (instance.drawInfo.instanceCount >= MAX_CAPACITY) {
|
||||
continue;
|
||||
}
|
||||
appendInstance(instance, attrs.buffer, shader, descriptorSet);
|
||||
return;
|
||||
}
|
||||
|
||||
// check same binding
|
||||
if (instance.lightingMap != lightingMap) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (instance.reflectionProbeType != reflectionProbeType) {
|
||||
continue;
|
||||
}
|
||||
if (instance.reflectionProbeCubemap != reflectionProbeCubemap) {
|
||||
continue;
|
||||
}
|
||||
if (instance.reflectionProbePlanarMap != reflectionProbePlanarMap) {
|
||||
continue;
|
||||
}
|
||||
if (instance.reflectionProbeBlendCubemap != reflectionProbeBlendCubemap) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (instance.stride != stride) {
|
||||
continue;
|
||||
}
|
||||
if (instance.drawInfo.instanceCount >= instance.capacity) { // resize buffers
|
||||
instance.capacity <<= 1;
|
||||
const auto newSize = instance.stride * instance.capacity;
|
||||
// NOLINTNEXTLINE(bugprone-suspicious-realloc-usage)
|
||||
instance.data = static_cast<uint8_t *>(CC_REALLOC(instance.data, newSize));
|
||||
instance.vb->resize(newSize);
|
||||
}
|
||||
if (instance.shader != shader) {
|
||||
instance.shader = shader;
|
||||
}
|
||||
if (instance.descriptorSet != descriptorSet) {
|
||||
instance.descriptorSet = descriptorSet;
|
||||
}
|
||||
memcpy(instance.data + static_cast<size_t>(instance.stride) * instance.drawInfo.instanceCount++, attrs.buffer.buffer()->getData(), stride);
|
||||
_hasPendingModels = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a new instance
|
||||
createInstance(
|
||||
key,
|
||||
sourceIA,
|
||||
attrs.attributes,
|
||||
attrs.buffer,
|
||||
stride,
|
||||
shader,
|
||||
descriptorSet,
|
||||
lightingMap,
|
||||
reflectionProbeType,
|
||||
reflectionProbeCubemap,
|
||||
reflectionProbePlanarMap,
|
||||
reflectionProbeBlendCubemap);
|
||||
}
|
||||
|
||||
void InstancedBuffer::appendInstance(InstancedItem &instance,
|
||||
Uint8Array &buffer,
|
||||
gfx::Shader *shader,
|
||||
gfx::DescriptorSet *descriptorSet) {
|
||||
if (instance.drawInfo.instanceCount >= instance.capacity) { // resize buffers
|
||||
instance.capacity = std::min(instance.capacity << 1, MAX_CAPACITY);
|
||||
const auto newSize = instance.stride * instance.capacity;
|
||||
// NOLINTNEXTLINE(bugprone-suspicious-realloc-usage)
|
||||
instance.data = static_cast<uint8_t *>(CC_REALLOC(instance.data, newSize));
|
||||
instance.vb->resize(newSize);
|
||||
}
|
||||
if (instance.shader != shader) {
|
||||
instance.shader = shader;
|
||||
}
|
||||
if (instance.descriptorSet != descriptorSet) {
|
||||
instance.descriptorSet = descriptorSet;
|
||||
}
|
||||
auto *destination = instance.data + static_cast<size_t>(instance.stride) * instance.drawInfo.instanceCount;
|
||||
CC_ASSERT(destination);
|
||||
memcpy(destination, buffer.buffer()->getData(), instance.stride);
|
||||
instance.drawInfo.instanceCount++;
|
||||
_hasPendingModels = true;
|
||||
}
|
||||
|
||||
void InstancedBuffer::createInstance(const ccstd::string &key,
|
||||
gfx::InputAssembler *sourceIA,
|
||||
const ccstd::vector<gfx::Attribute> &attributes,
|
||||
Uint8Array &buffer,
|
||||
uint32_t stride,
|
||||
gfx::Shader *shader,
|
||||
gfx::DescriptorSet *descriptorSet,
|
||||
gfx::Texture *lightingMap,
|
||||
uint32_t reflectionProbeType,
|
||||
gfx::Texture *reflectionProbeCubemap,
|
||||
gfx::Texture *reflectionProbePlanarMap,
|
||||
gfx::Texture *reflectionProbeBlendCubemap) {
|
||||
const auto newSize = stride * INITIAL_CAPACITY;
|
||||
auto *vb = _device->createBuffer({
|
||||
gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST,
|
||||
gfx::MemoryUsageBit::DEVICE,
|
||||
gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE,
|
||||
static_cast<uint32_t>(newSize),
|
||||
static_cast<uint32_t>(stride),
|
||||
});
|
||||
|
||||
auto *data = static_cast<uint8_t *>(CC_MALLOC(newSize));
|
||||
auto vertexBuffers = sourceIA->getVertexBuffers();
|
||||
auto attributes = sourceIA->getAttributes();
|
||||
auto iaAttributes = sourceIA->getAttributes();
|
||||
auto *indexBuffer = sourceIA->getIndexBuffer();
|
||||
|
||||
for (const auto &attribute : attrs.attributes) {
|
||||
attributes.emplace_back(gfx::Attribute{
|
||||
for (const auto &attribute : attributes) {
|
||||
iaAttributes.emplace_back(gfx::Attribute{
|
||||
attribute.name,
|
||||
attribute.format,
|
||||
attribute.isNormalized,
|
||||
@@ -147,17 +177,22 @@ void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Sh
|
||||
true,
|
||||
attribute.location});
|
||||
}
|
||||
CC_ASSERT(data);
|
||||
memcpy(data, buffer.buffer()->getData(), stride);
|
||||
|
||||
auto *data = static_cast<uint8_t *>(CC_MALLOC(newSize));
|
||||
memcpy(data, attrs.buffer.buffer()->getData(), stride);
|
||||
vertexBuffers.emplace_back(vb);
|
||||
const gfx::InputAssemblerInfo iaInfo = {attributes, vertexBuffers, indexBuffer};
|
||||
const gfx::InputAssemblerInfo iaInfo = {iaAttributes, vertexBuffers, indexBuffer};
|
||||
auto *ia = _device->createInputAssembler(iaInfo);
|
||||
InstancedItem item = {INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet,
|
||||
lightingMap, reflectionProbeCubemap, reflectionProbePlanarMap, reflectionProbeType, reflectionProbeBlendCubemap,
|
||||
lightingMap,
|
||||
reflectionProbeCubemap,
|
||||
reflectionProbePlanarMap,
|
||||
reflectionProbeType,
|
||||
reflectionProbeBlendCubemap,
|
||||
ia->getDrawInfo()};
|
||||
item.drawInfo.instanceCount = 1;
|
||||
_instances.emplace_back(item);
|
||||
_instancesMap[key].emplace_back(_instances.size() - 1);
|
||||
_hasPendingModels = true;
|
||||
}
|
||||
|
||||
@@ -165,7 +200,16 @@ void InstancedBuffer::uploadBuffers(gfx::CommandBuffer *cmdBuff) const {
|
||||
for (const auto &instance : _instances) {
|
||||
if (!instance.drawInfo.instanceCount) continue;
|
||||
|
||||
cmdBuff->updateBuffer(instance.vb, instance.data, instance.vb->getSize());
|
||||
// `instance.data` is only guaranteed to hold `instance.capacity * instance.stride` bytes.
|
||||
// If `instance.vb` was resized to a larger size than the CPU-side `instance.data`
|
||||
// buffer (e.g. due to a bug in the resize/append logic), copying `instance.vb->getSize()`
|
||||
// bytes from `instance.data` would read out of bounds and crash. Clamp to the smaller
|
||||
// of the two to avoid reading past the end of `instance.data`.
|
||||
const uint32_t dataCapacity = instance.capacity * instance.stride;
|
||||
const uint32_t validSize = instance.drawInfo.instanceCount * instance.stride;
|
||||
CC_ASSERT(validSize <= instance.vb->getSize());
|
||||
CC_ASSERT(validSize <= dataCapacity);
|
||||
cmdBuff->updateBuffer(instance.vb, instance.data, validSize);
|
||||
instance.ia->setInstanceCount(instance.drawInfo.instanceCount);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,14 +78,37 @@ public:
|
||||
inline const DynamicOffsetList &dynamicOffsets() const { return _dynamicOffsets; }
|
||||
|
||||
private:
|
||||
InstancedItemList _instances;
|
||||
RenderPass _sortRender;
|
||||
void appendInstance(InstancedItem &instance,
|
||||
Uint8Array &buffer,
|
||||
gfx::Shader *shader,
|
||||
gfx::DescriptorSet *descriptorSet);
|
||||
void createInstance(const ccstd::string &key,
|
||||
gfx::InputAssembler *sourceIA,
|
||||
const ccstd::vector<gfx::Attribute> &attributes,
|
||||
Uint8Array &buffer,
|
||||
uint32_t stride,
|
||||
gfx::Shader *shader,
|
||||
gfx::DescriptorSet *descriptorSet,
|
||||
gfx::Texture *lightingMap,
|
||||
uint32_t reflectionProbeType,
|
||||
gfx::Texture *reflectionProbeCubemap,
|
||||
gfx::Texture *reflectionProbePlanarMap,
|
||||
gfx::Texture *reflectionProbeBlendCubemap);
|
||||
|
||||
// weak reference
|
||||
const scene::Pass *_pass{nullptr};
|
||||
bool _hasPendingModels{false};
|
||||
DynamicOffsetList _dynamicOffsets;
|
||||
// weak reference
|
||||
gfx::Device *_device{nullptr};
|
||||
|
||||
bool _hasPendingModels{false};
|
||||
|
||||
RenderPass _sortRender;
|
||||
|
||||
InstancedItemList _instances;
|
||||
DynamicOffsetList _dynamicOffsets;
|
||||
// Maps a merge key to the indices (into `_instances`) of items sharing that key.
|
||||
// Storing indices (not copies or references) keeps this in sync with `_instances`
|
||||
// and remains valid across `_instances` reallocation, since indices don't dangle.
|
||||
ccstd::unordered_map<ccstd::string, ccstd::vector<size_t>> _instancesMap;
|
||||
};
|
||||
|
||||
} // namespace pipeline
|
||||
|
||||
@@ -47,6 +47,34 @@
|
||||
namespace cc {
|
||||
namespace pipeline {
|
||||
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
DebugRendererRenderCommand::DebugRendererRenderCommand(PipelineSceneData *sceneData)
|
||||
: _sceneData(sceneData) {
|
||||
}
|
||||
|
||||
void DebugRendererRenderCommand::beginRenderCommand(const RenderCommandContext &ctx) {
|
||||
renderDebugRenderer(ctx.renderPass, ctx.cmdBuff, _sceneData, ctx.camera);
|
||||
}
|
||||
|
||||
void DebugRendererRenderCommand::endRenderCommand(const RenderCommandContext & /*ctx*/) {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
GeometryRendererRenderCommand::GeometryRendererRenderCommand(PipelineSceneData *sceneData)
|
||||
: _sceneData(sceneData) {
|
||||
}
|
||||
|
||||
void GeometryRendererRenderCommand::beginRenderCommand(const RenderCommandContext &ctx) {
|
||||
if (ctx.camera && ctx.camera->getGeometryRenderer()) {
|
||||
ctx.camera->getGeometryRenderer()->render(ctx.renderPass, ctx.cmdBuff, _sceneData);
|
||||
}
|
||||
}
|
||||
|
||||
void GeometryRendererRenderCommand::endRenderCommand(const RenderCommandContext & /*ctx*/) {
|
||||
}
|
||||
#endif
|
||||
|
||||
framegraph::StringHandle RenderPipeline::fgStrHandleOutDepthTexture = framegraph::FrameGraph::stringToHandle("depthTexture");
|
||||
framegraph::StringHandle RenderPipeline::fgStrHandleOutColorTexture = framegraph::FrameGraph::stringToHandle("outputTexture");
|
||||
framegraph::StringHandle RenderPipeline::fgStrHandlePostprocessPass = framegraph::FrameGraph::stringToHandle("pipelinePostPass");
|
||||
@@ -87,6 +115,10 @@ bool RenderPipeline::activate(gfx::Swapchain * /*swapchain*/) {
|
||||
_pipelineSceneData->activate(_device);
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
CC_DEBUG_RENDERER->activate(_device);
|
||||
addRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND, std::make_shared<DebugRendererRenderCommand>(getPipelineSceneData()));
|
||||
#endif
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
addRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND, std::make_shared<GeometryRendererRenderCommand>(getPipelineSceneData()));
|
||||
#endif
|
||||
|
||||
// generate macros here rather than construct func because _clusterEnabled
|
||||
@@ -115,6 +147,15 @@ void RenderPipeline::onGlobalPipelineStateChanged() {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
void RenderPipeline::addRenderCommand(const ccstd::string &name, std::shared_ptr<RenderCommand> ptr) {
|
||||
_renderCommands[name] = std::move(ptr);
|
||||
}
|
||||
|
||||
RenderCommand *RenderPipeline::getRenderCommand(const ccstd::string &name) const {
|
||||
const auto iter = _renderCommands.find(name);
|
||||
return iter == _renderCommands.end() ? nullptr : iter->second.get();
|
||||
}
|
||||
|
||||
void RenderPipeline::destroyQuadInputAssembler() {
|
||||
CC_SAFE_DESTROY_AND_DELETE(_quadIB);
|
||||
|
||||
|
||||
@@ -34,11 +34,14 @@
|
||||
#include "renderer/core/PassUtils.h"
|
||||
#include "scene/Model.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace cc {
|
||||
namespace gfx {
|
||||
class CommandBuffer;
|
||||
class DescriptorSet;
|
||||
class DescriptorSetLayout;
|
||||
class RenderPass;
|
||||
} // namespace gfx
|
||||
namespace scene {
|
||||
class Camera;
|
||||
@@ -54,6 +57,53 @@ class PipelineSceneData;
|
||||
class GlobalDSManager;
|
||||
class RenderStage;
|
||||
class GeometryRenderer;
|
||||
|
||||
struct RenderCommandContext {
|
||||
gfx::RenderPass *renderPass{nullptr};
|
||||
gfx::CommandBuffer *cmdBuff{nullptr};
|
||||
PipelineSceneData *sceneData{nullptr};
|
||||
const scene::Camera *camera{nullptr};
|
||||
};
|
||||
|
||||
class RenderCommand {
|
||||
public:
|
||||
RenderCommand() noexcept = default;
|
||||
RenderCommand(RenderCommand &&rhs) = delete;
|
||||
RenderCommand(RenderCommand const &rhs) = delete;
|
||||
RenderCommand &operator=(RenderCommand &&rhs) = delete;
|
||||
RenderCommand &operator=(RenderCommand const &rhs) = delete;
|
||||
virtual ~RenderCommand() noexcept = default;
|
||||
|
||||
virtual void beginRenderCommand(const RenderCommandContext &ctx) = 0;
|
||||
virtual void endRenderCommand(const RenderCommandContext &ctx) = 0;
|
||||
};
|
||||
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
class DebugRendererRenderCommand final : public RenderCommand {
|
||||
public:
|
||||
explicit DebugRendererRenderCommand(PipelineSceneData *sceneData);
|
||||
|
||||
void beginRenderCommand(const RenderCommandContext &ctx) override;
|
||||
void endRenderCommand(const RenderCommandContext &ctx) override;
|
||||
|
||||
private:
|
||||
PipelineSceneData *_sceneData{nullptr};
|
||||
};
|
||||
#endif
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
class GeometryRendererRenderCommand final : public RenderCommand {
|
||||
public:
|
||||
explicit GeometryRendererRenderCommand(PipelineSceneData *sceneData);
|
||||
|
||||
void beginRenderCommand(const RenderCommandContext &ctx) override;
|
||||
void endRenderCommand(const RenderCommandContext &ctx) override;
|
||||
|
||||
private:
|
||||
PipelineSceneData *_sceneData{nullptr};
|
||||
};
|
||||
#endif
|
||||
|
||||
struct CC_DLL RenderPipelineInfo {
|
||||
uint32_t tag = 0;
|
||||
RenderFlowList flows;
|
||||
@@ -140,6 +190,9 @@ public:
|
||||
#endif
|
||||
}
|
||||
|
||||
void addRenderCommand(const ccstd::string &name, std::shared_ptr<RenderCommand> ptr);
|
||||
RenderCommand *getRenderCommand(const ccstd::string &name) const;
|
||||
|
||||
inline void resetRenderQueue(bool reset) { _resetRenderQueue = reset; }
|
||||
inline bool isRenderQueueReset() const { return _resetRenderQueue; }
|
||||
|
||||
@@ -194,6 +247,7 @@ protected:
|
||||
ccstd::unordered_map<Vec4, gfx::InputAssembler *, Hasher<Vec4>> _quadIA;
|
||||
|
||||
framegraph::FrameGraph _fg;
|
||||
ccstd::unordered_map<ccstd::string, std::shared_ptr<RenderCommand>> _renderCommands;
|
||||
ccstd::unordered_map<gfx::ClearFlags, gfx::RenderPass *> _renderPasses;
|
||||
|
||||
// use cluster culling or not
|
||||
|
||||
@@ -24,10 +24,12 @@
|
||||
|
||||
#include "RenderQueue.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <utility>
|
||||
#include "PipelineSceneData.h"
|
||||
#include "PipelineStateManager.h"
|
||||
#include "RenderPipeline.h"
|
||||
#include "base/Utils.h"
|
||||
#include "gfx-base/GFXCommandBuffer.h"
|
||||
#include "gfx-base/GFXDevice.h"
|
||||
#include "gfx-base/GFXShader.h"
|
||||
@@ -60,7 +62,28 @@ bool RenderQueue::insertRenderPass(const RenderObject &renderObj, uint32_t subMo
|
||||
auto shaderId = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(subModel->getShader(passIdx)));
|
||||
const auto hash = (0 << 30) | (passPriority << 16) | (modelPriority << 8) | passIdx;
|
||||
const auto priority = renderObj.model->getPriority();
|
||||
RenderPass renderPass = {priority, hash, renderObj.depth, shaderId, passIdx, subModel};
|
||||
RenderPass renderPass{};
|
||||
renderPass.priority = priority;
|
||||
renderPass.hash = hash;
|
||||
renderPass.depth = renderObj.depth;
|
||||
renderPass.shaderID = shaderId;
|
||||
renderPass.passIndex = passIdx;
|
||||
renderPass.subModel = subModel;
|
||||
|
||||
/**
|
||||
* Pack the sort keys once here so the comparator only compares uint64 keys.
|
||||
* secondaryKey: depthKey << 32 | shaderID (transparent inverts depth for back-to-front).
|
||||
*/
|
||||
CC_ASSERT(!std::isnan(renderObj.depth));
|
||||
const uint32_t depthKey = utils::numext::floatToSortableUint(renderObj.depth);
|
||||
if (isTransparent) {
|
||||
const uint32_t invertedDepthKey = ~depthKey;
|
||||
renderPass.primaryKey = (static_cast<uint64_t>(priority) << 32) | hash;
|
||||
renderPass.secondaryKey = (static_cast<uint64_t>(invertedDepthKey) << 32) | shaderId;
|
||||
} else {
|
||||
renderPass.primaryKey = hash;
|
||||
renderPass.secondaryKey = (static_cast<uint64_t>(depthKey) << 32) | shaderId;
|
||||
}
|
||||
_queue.emplace_back(renderPass);
|
||||
|
||||
return true;
|
||||
|
||||
@@ -63,6 +63,7 @@ struct CustomRenderGraphContext {
|
||||
const RenderGraph* renderGraph{nullptr};
|
||||
const ResourceGraph* resourceGraph{nullptr};
|
||||
gfx::CommandBuffer* primaryCommandBuffer{nullptr};
|
||||
gfx::RenderPass* currentRenderPass{nullptr};
|
||||
};
|
||||
|
||||
class CustomRenderPass : public Customization {
|
||||
|
||||
@@ -45,10 +45,6 @@
|
||||
#include "details/GslUtils.h"
|
||||
#include "details/Range.h"
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
#include "cocos/renderer/pipeline/GeometryRenderer.h"
|
||||
#endif
|
||||
|
||||
namespace cc {
|
||||
|
||||
namespace render {
|
||||
@@ -702,10 +698,14 @@ struct RenderGraphVisitor : boost::dfs_visitor<> {
|
||||
ctx.cmdBuff, ctx.currentPass, ctx.subpassIndex, sceneData.flags);
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
if (any(sceneData.flags & SceneFlags::GEOMETRY) &&
|
||||
camera && camera->getGeometryRenderer()) {
|
||||
camera->getGeometryRenderer()->render(
|
||||
ctx.currentPass, ctx.cmdBuff, ctx.ppl->getPipelineSceneData());
|
||||
const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, sceneID);
|
||||
if (!renderData.custom.empty()) {
|
||||
const auto& commands = ctx.ppl->custom.renderCommands;
|
||||
auto iter = commands.find(renderData.custom);
|
||||
if (iter != commands.end()) {
|
||||
ctx.customContext.currentRenderPass = ctx.currentPass;
|
||||
iter->second->beginRenderCommand(ctx.customContext, sceneID);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -784,19 +784,19 @@ struct RenderGraphVisitor : boost::dfs_visitor<> {
|
||||
}
|
||||
|
||||
void begin(const Blit& blit, RenderGraph::vertex_descriptor vertID) const {
|
||||
tryBindPassDescriptorSet(vertID);
|
||||
tryBindQueueDescriptorSets(vertID);
|
||||
const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, vertID);
|
||||
if (!renderData.custom.empty()) {
|
||||
const auto& commands = ctx.ppl->custom.renderCommands;
|
||||
auto iter = commands.find(renderData.custom);
|
||||
if (iter != commands.end()) {
|
||||
ctx.customContext.currentRenderPass = ctx.currentPass;
|
||||
iter->second->beginRenderCommand(ctx.customContext, vertID);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
tryBindPassDescriptorSet(vertID);
|
||||
tryBindQueueDescriptorSets(vertID);
|
||||
|
||||
switch (blit.blitType) {
|
||||
case BlitType::FULLSCREEN_QUAD:
|
||||
drawBlit(blit);
|
||||
|
||||
@@ -48,6 +48,10 @@
|
||||
#include "profiler/DebugRenderer.h"
|
||||
#endif
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
#include "cocos/renderer/pipeline/GeometryRenderer.h"
|
||||
#endif
|
||||
|
||||
namespace cc {
|
||||
|
||||
namespace render {
|
||||
@@ -106,6 +110,54 @@ void addSubresourceNode<gfx::Format::DEPTH_STENCIL>(ResourceGraph::vertex_descri
|
||||
|
||||
} // namespace
|
||||
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
namespace {
|
||||
class DebugRendererRenderCommand final : public CustomRenderCommand {
|
||||
public:
|
||||
explicit DebugRendererRenderCommand(pipeline::PipelineSceneData *sceneData)
|
||||
: _sceneData(sceneData) {}
|
||||
|
||||
void beginRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
|
||||
std::ignore = vertID;
|
||||
if (rg.currentRenderPass) {
|
||||
DebugRenderer::getInstance()->render(rg.currentRenderPass, rg.primaryCommandBuffer, _sceneData);
|
||||
}
|
||||
}
|
||||
|
||||
void endRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
|
||||
std::ignore = rg;
|
||||
std::ignore = vertID;
|
||||
}
|
||||
|
||||
private:
|
||||
pipeline::PipelineSceneData *_sceneData{nullptr};
|
||||
};
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
class GeometryRendererRenderCommand final : public CustomRenderCommand {
|
||||
public:
|
||||
explicit GeometryRendererRenderCommand(pipeline::PipelineSceneData *sceneData)
|
||||
: _sceneData(sceneData) {}
|
||||
|
||||
void beginRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
|
||||
const auto &sceneData = get(SceneTag{}, vertID, *rg.renderGraph);
|
||||
if (sceneData.camera && sceneData.camera->getGeometryRenderer()) {
|
||||
sceneData.camera->getGeometryRenderer()->render(rg.currentRenderPass, rg.primaryCommandBuffer, _sceneData);
|
||||
}
|
||||
}
|
||||
|
||||
void endRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
|
||||
std::ignore = vertID;
|
||||
std::ignore = rg;
|
||||
}
|
||||
|
||||
private:
|
||||
pipeline::PipelineSceneData *_sceneData{nullptr};
|
||||
};
|
||||
#endif
|
||||
|
||||
NativePipeline::NativePipeline(const allocator_type &alloc) noexcept
|
||||
: device(gfx::Device::getInstance()),
|
||||
globalDSManager(std::make_unique<pipeline::GlobalDSManager>()),
|
||||
@@ -1385,6 +1437,10 @@ bool NativePipeline::activate(gfx::Swapchain *swapchainIn) {
|
||||
pipelineSceneData->activate(device);
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
DebugRenderer::getInstance()->activate(device);
|
||||
addCustomRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND, std::make_shared<DebugRendererRenderCommand>(getPipelineSceneData()));
|
||||
#endif
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
addCustomRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND, std::make_shared<GeometryRendererRenderCommand>(getPipelineSceneData()));
|
||||
#endif
|
||||
// generate macros here rather than construct func because _clusterEnabled
|
||||
// switch may be changed in root.ts setRenderPipeline() function which is after
|
||||
|
||||
@@ -913,6 +913,13 @@ SceneBuilder *NativeRenderQueueBuilder::addScene(
|
||||
data);
|
||||
}
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
if (any(sceneFlags & SceneFlags::GEOMETRY)) {
|
||||
auto &data = get(RenderGraph::DataTag{}, *renderGraph, sceneID);
|
||||
data.custom = cc::pipeline::GEOMETRY_RENDERER_COMMAND;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (any(sceneFlags & SceneFlags::UI)) {
|
||||
CC_EXPECTS(camera);
|
||||
const auto passOrSubpassId = parent(nodeID, *renderGraph);
|
||||
@@ -1086,6 +1093,31 @@ void NativeRenderQueueBuilder::addProfiler(const scene::Camera *camera) {
|
||||
*renderGraph,
|
||||
passOrSubpassId);
|
||||
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
const auto debugId = addVertex2(
|
||||
BlitTag{},
|
||||
std::forward_as_tuple("DebugRenderer"),
|
||||
std::forward_as_tuple(),
|
||||
std::forward_as_tuple(),
|
||||
std::forward_as_tuple(),
|
||||
std::forward_as_tuple(
|
||||
IntrusivePtr<Material>{},
|
||||
RenderGraph::null_vertex(),
|
||||
SceneFlags::NONE,
|
||||
nullptr,
|
||||
BlitType::FULLSCREEN_QUAD),
|
||||
*renderGraph,
|
||||
queueId);
|
||||
auto &debugData = get(RenderGraph::DataTag{}, *renderGraph, debugId);
|
||||
debugData.custom = cc::pipeline::DEBUG_RENDERER_COMMAND;
|
||||
setCameraUBOValues(
|
||||
*camera,
|
||||
*layoutGraph,
|
||||
*pipelineRuntime->getPipelineSceneData(),
|
||||
camera->getScene() ? camera->getScene()->getMainLight() : nullptr,
|
||||
debugData);
|
||||
#endif
|
||||
|
||||
const auto sceneId = addVertex2(
|
||||
BlitTag{},
|
||||
std::forward_as_tuple("Profiler"),
|
||||
|
||||
@@ -647,8 +647,8 @@ void LightingStage::fgTransparent(scene::Camera *camera) {
|
||||
|
||||
_planarShadowQueue->recordCommandBuffer(_device, table.getRenderPass(), cmdBuff);
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
if (camera->getGeometryRenderer()) {
|
||||
camera->getGeometryRenderer()->render(table.getRenderPass(), cmdBuff, pipeline->getPipelineSceneData());
|
||||
if (auto *command = pipeline->getRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND)) {
|
||||
command->beginRenderCommand({table.getRenderPass(), cmdBuff, pipeline->getPipelineSceneData(), camera});
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -228,7 +228,9 @@ void PostProcessStage::render(scene::Camera *camera) {
|
||||
_uiPhase->render(camera, renderPass);
|
||||
renderProfiler(renderPass, cmdBuff, pipeline->getProfiler(), camera);
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
renderDebugRenderer(renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera);
|
||||
if (auto *command = pipeline->getRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND)) {
|
||||
command->beginRenderCommand({renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera});
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
|
||||
@@ -23,9 +23,6 @@
|
||||
****************************************************************************/
|
||||
|
||||
#include "ForwardStage.h"
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
#include "../GeometryRenderer.h"
|
||||
#endif
|
||||
#include "../InstancedBuffer.h"
|
||||
#include "../PipelineSceneData.h"
|
||||
#include "../PipelineUBO.h"
|
||||
@@ -262,15 +259,17 @@ void ForwardStage::render(scene::Camera *camera) {
|
||||
}
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
if (camera->getGeometryRenderer()) {
|
||||
camera->getGeometryRenderer()->render(renderPass, cmdBuff, pipeline->getPipelineSceneData());
|
||||
if (auto *command = pipeline->getRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND)) {
|
||||
command->beginRenderCommand({renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera});
|
||||
}
|
||||
#endif
|
||||
|
||||
_uiPhase->render(camera, renderPass);
|
||||
renderProfiler(renderPass, cmdBuff, _pipeline->getProfiler(), camera);
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
renderDebugRenderer(renderPass, cmdBuff, _pipeline->getPipelineSceneData(), camera);
|
||||
if (auto *command = pipeline->getRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND)) {
|
||||
command->beginRenderCommand({renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera});
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ float LODGroup::getScreenUsagePercentage(const Camera *camera) const {
|
||||
return 0;
|
||||
}
|
||||
|
||||
auto distance = 0;
|
||||
float distance = 0.0F;
|
||||
if (camera->getProjectionType() == CameraProjection::PERSPECTIVE) {
|
||||
Vec3 tmp{_localBoundaryCenter};
|
||||
tmp.transformMat4(_node->getWorldMatrix());
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
"type": "github",
|
||||
"owner": "cocos",
|
||||
"name": "cocos-engine-external",
|
||||
"checkout": "v4.0.0-7"
|
||||
"checkout": "v4.0.0-10"
|
||||
}
|
||||
}
|
||||
@@ -105,6 +105,12 @@ using namespace cc;
|
||||
%ignore cc::pipeline::GeometryRenderer::activate;
|
||||
%ignore cc::pipeline::GeometryRenderer::render;
|
||||
%ignore cc::pipeline::GeometryRenderer::destroy;
|
||||
%ignore cc::pipeline::RenderCommand;
|
||||
%ignore cc::pipeline::RenderCommandContext;
|
||||
%ignore cc::pipeline::DebugRendererRenderCommand;
|
||||
%ignore cc::pipeline::GeometryRendererRenderCommand;
|
||||
%ignore cc::pipeline::RenderPipeline::addRenderCommand;
|
||||
%ignore cc::pipeline::RenderPipeline::getRenderCommand;
|
||||
|
||||
// ----- Rename Section ------
|
||||
// Brief: Classes, methods or attributes needs to be renamed
|
||||
|
||||
+18
-9
@@ -185,8 +185,9 @@ void GoogleBillingHelper::onBillingServiceDisconnected(JNIEnv* env, jclass clazz
|
||||
if (billingClient) {
|
||||
auto it = billingClient->_listeners.find(callbackId);
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
cc::callJSfunc(it->second.get(), "onBillingServiceDisconnected");
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onBillingServiceDisconnected");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -203,8 +204,9 @@ void GoogleBillingHelper::onProductDetailsResponse(JNIEnv* env, jclass clazz,
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj);
|
||||
std::vector<cc::ProductDetails*> productDetailsList = cc::JniBilling::toProductDetailList(env, productDetailsListObj, tag, startID);
|
||||
cc::callJSfunc(it->second.get(), "onProductDetailsResponse", billingResult, productDetailsList);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onProductDetailsResponse", billingResult, productDetailsList);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,8 +241,9 @@ void GoogleBillingHelper::onConsumeResponse(JNIEnv* env, jclass clazz, jint tag,
|
||||
auto it = billingClient->_listeners.find(callbackId);
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj);
|
||||
cc::callJSfunc(it->second.get(), "onConsumeResponse", billingResult, cc::StringUtils::getStringUTFCharsJNI(env, static_cast<jstring>(purchaseToken)));
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onConsumeResponse", billingResult, cc::StringUtils::getStringUTFCharsJNI(env, static_cast<jstring>(purchaseToken)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,8 +259,9 @@ void GoogleBillingHelper::onQueryPurchasesResponse(JNIEnv* env, jclass clazz, ji
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj);
|
||||
std::vector<cc::Purchase*> purchasesList = cc::JniBilling::toPurchaseList(env, purchasesListObj, tag, startID);
|
||||
cc::callJSfunc(it->second.get(), "onQueryPurchasesResponse", billingResult, purchasesList);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onQueryPurchasesResponse", billingResult, purchasesList);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -272,8 +276,9 @@ void GoogleBillingHelper::onBillingConfigResponse(JNIEnv* env, jclass clazz, jin
|
||||
if (billingConfigObj) {
|
||||
billingConfig = cc::JniBilling::toBillingConfig(env, billingConfigObj);
|
||||
}
|
||||
cc::callJSfunc(it->second.get(), "onBillingConfigResponse", billingResult, billingConfig);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onBillingConfigResponse", billingResult, billingConfig);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -288,8 +293,9 @@ void GoogleBillingHelper::onAlternativeBillingOnlyTokenResponse(JNIEnv* env, jcl
|
||||
if (alternativeBillingOnlyReportingDetailsObj) {
|
||||
toAlternativeBillingOnlyReporting = cc::JniBilling::toAlternativeBillingOnlyReportingDetails(env, alternativeBillingOnlyReportingDetailsObj);
|
||||
}
|
||||
cc::callJSfunc(it->second.get(), "onAlternativeBillingOnlyTokenResponse", billingResult, toAlternativeBillingOnlyReporting);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onAlternativeBillingOnlyTokenResponse", billingResult, toAlternativeBillingOnlyReporting);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -304,8 +310,9 @@ void GoogleBillingHelper::onExternalOfferReportingDetailsResponse(JNIEnv* env, j
|
||||
if (externalOfferReportingDetailsObj) {
|
||||
externalOfferReportingDetails = cc::JniBilling::toExternalOfferReportingDetails(env, externalOfferReportingDetailsObj);
|
||||
}
|
||||
cc::callJSfunc(it->second.get(), "onExternalOfferReportingDetailsResponse", billingResult, externalOfferReportingDetails);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onExternalOfferReportingDetailsResponse", billingResult, externalOfferReportingDetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -332,8 +339,9 @@ void GoogleBillingHelper::onInAppMessageResponse(JNIEnv* env, jclass clazz, jint
|
||||
auto it = billingClient->_listeners.find(callbackId);
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* inAppMessageResult = cc::JniBilling::toInAppMessageResult(env, inAppMessageResultObj);
|
||||
cc::callJSfunc(it->second.get(), "onInAppMessageResponse", inAppMessageResult);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onInAppMessageResponse", inAppMessageResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -344,8 +352,9 @@ void GoogleBillingHelper::responseOnlyWithBillingResult(const std::string& funct
|
||||
auto it = billingClient->_listeners.find(callbackId);
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj);
|
||||
cc::callJSfunc(it->second.get(), functionName.c_str(), billingResult);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), functionName.c_str(), billingResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -178,7 +178,7 @@ void PlayTask::onTaskSuccess(int listerId, void* obj) {
|
||||
// Therefore, it should be removed first.
|
||||
scopedListener listener(it->second.get());
|
||||
_listeners.erase(it);
|
||||
callJSfuncWithJObject(it->second.get(), "onSuccess", obj);
|
||||
callJSfuncWithJObject(listener.get(), "onSuccess", obj);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.31",
|
||||
"version": "4.0.0-alpha.36",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.31",
|
||||
"version": "4.0.0-alpha.36",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.31",
|
||||
"version": "4.0.0-alpha.36",
|
||||
"description": "Cocos Creator is a cross-platform 2D & 3D game engine written in C++ and TypeScript, licensed under MIT.",
|
||||
"homepage": "http://www.cocos.com",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { execSync, spawn } from 'child_process';
|
||||
import { execSync } from 'child_process';
|
||||
import * as fs from 'fs-extra';
|
||||
import * as ps from 'path';
|
||||
import * as os from 'os';
|
||||
import { CocosParams } from '../base/default';
|
||||
import { cchelper, toolHelper, Paths } from "../utils";
|
||||
import { cchelper, toolHelper } from "../utils";
|
||||
import { MacOSPackTool } from "./mac-os";
|
||||
|
||||
export interface IOrientation {
|
||||
@@ -115,13 +115,8 @@ export class IOSPackTool extends MacOSPackTool {
|
||||
throw new Error("Error: Try to build iphoneos application but no developer team id was given!");
|
||||
}
|
||||
const nativePrjDir = this.paths.nativePrjDir;
|
||||
|
||||
const simulatorArch = this.getIosSimulatorArch();
|
||||
const projName = this.params.projectName;
|
||||
const os = require('os');
|
||||
const cpus = os.cpus();
|
||||
const model = (cpus && cpus[0] && cpus[0].model) ? cpus[0].model : '';
|
||||
// check mac architecture
|
||||
// const platform = /Apple/.test(model) ? `-arch arm64` : `-arch x86_64`;
|
||||
// get xcode workspace
|
||||
const regex = new RegExp(projName + '.xcworkspace$');
|
||||
const files = fs.readdirSync(nativePrjDir);
|
||||
@@ -145,7 +140,7 @@ export class IOSPackTool extends MacOSPackTool {
|
||||
await toolHelper.runCmake([projCompileParams, '-sdk', 'iphoneos', `-arch arm64`]);
|
||||
}
|
||||
if (options.simulator) {
|
||||
await toolHelper.runCmake([projCompileParams, '-sdk', 'iphonesimulator', `-arch x86_64`]); //force compile x86_64 app for iPhone simulator on Mac
|
||||
await toolHelper.runCmake([projCompileParams, '-sdk', 'iphonesimulator', `-arch ${simulatorArch}`]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -51,10 +51,36 @@ export abstract class MacOSPackTool extends NativePackTool {
|
||||
return /Apple/.test(model) && process.platform === 'darwin';
|
||||
}
|
||||
|
||||
protected getXcodeMajorVerion(): number {
|
||||
protected compareVersion(a: string, b: string): number {
|
||||
const aParts = a.split('.').map((part) => Number.parseInt(part, 10) || 0);
|
||||
const bParts = b.split('.').map((part) => Number.parseInt(part, 10) || 0);
|
||||
const maxLength = Math.max(aParts.length, bParts.length);
|
||||
|
||||
for (let i = 0; i < maxLength; i++) {
|
||||
const aValue = aParts[i] ?? 0;
|
||||
const bValue = bParts[i] ?? 0;
|
||||
if (aValue !== bValue) {
|
||||
return aValue - bValue;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected getXcodeVersion(): string {
|
||||
try {
|
||||
const output = execSync('xcrun xcodebuild -version').toString('utf8');
|
||||
return Number.parseInt(output.match(/Xcode\s(\d+)\.\d+/)![1]);
|
||||
const match = output.match(/Xcode\s+(\d+(?:\.\d+)+)/);
|
||||
return match?.[1] || '0.0';
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return '0.0';
|
||||
}
|
||||
}
|
||||
|
||||
protected getXcodeMajorVerion(): number {
|
||||
try {
|
||||
return Number.parseInt(this.getXcodeVersion().split('.')[0] || '0', 10);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
// fallback to default Xcode version
|
||||
@@ -62,6 +88,14 @@ export abstract class MacOSPackTool extends NativePackTool {
|
||||
}
|
||||
}
|
||||
|
||||
protected getIosSimulatorArch(): 'arm64' | 'x86_64' {
|
||||
// Xcode 14.3+ no longer supports running iOS Simulator under Rosetta on Apple Silicon.
|
||||
if (this.isAppleSilicon() && this.compareVersion(this.getXcodeVersion(), '14.3') >= 0) {
|
||||
return 'arm64';
|
||||
}
|
||||
return 'x86_64';
|
||||
}
|
||||
|
||||
async modifyXcodeProject() {
|
||||
if (this.params.platformParams.skipUpdateXcodeProject) {
|
||||
if (this.getXcodeMajorVerion() < 12) {
|
||||
|
||||
@@ -6,7 +6,7 @@ endif()
|
||||
|
||||
if(POLICY CMP0111)
|
||||
# https://cmake.org/cmake/help/latest/policy/CMP0111.html
|
||||
cmake_policy(SET CMP0111 OLD)
|
||||
cmake_policy(SET CMP0111 NEW)
|
||||
endif()
|
||||
|
||||
# set(CC_REGISTERED_PLUGINS)
|
||||
|
||||
@@ -49,8 +49,9 @@ endmacro()
|
||||
|
||||
|
||||
macro(cc_windows_after_target _target_name)
|
||||
|
||||
source_group(TREE ${RES_DIR}/data PREFIX "Resources" FILES ${CC_ASSET_FILES})
|
||||
|
||||
get_filename_component(CC_ASSET_ROOT "${RES_DIR}/data" ABSOLUTE)
|
||||
source_group(TREE ${CC_ASSET_ROOT} PREFIX "Resources" FILES ${CC_ASSET_FILES})
|
||||
source_group(TREE ${CC_PROJECT_DIR} PREFIX "Source Files" FILES ${CC_PROJ_SOURCES})
|
||||
source_group(TREE ${CC_PROJECT_DIR}/../common PREFIX "Source Files" FILES ${CC_COMMON_SOURCES})
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
cmake_minimum_required(VERSION 3.28)
|
||||
|
||||
set(CMAKE_SYSTEM_NAME iOS)
|
||||
set(APP_NAME "CocosGame" CACHE STRING "Project Name")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
cmake_minimum_required(VERSION 3.28)
|
||||
|
||||
set(APP_NAME "CocosGame" CACHE STRING "Project Name")
|
||||
option(ENABLE_SANDBOX "enable sandbox entitlements.plist" ON)
|
||||
|
||||
@@ -1,27 +1,45 @@
|
||||
import { Texture2D } from "../../cocos/asset/assets/texture-2d";
|
||||
import { Details } from "../../cocos/serialization/deserialize";
|
||||
import { ImageAsset } from '../../cocos/asset/assets/image-asset';
|
||||
import { Texture2D } from '../../cocos/asset/assets/texture-2d';
|
||||
import { dependMap } from '../../cocos/asset/asset-manager/depend-maps';
|
||||
import dependUtil from '../../cocos/asset/asset-manager/depend-util';
|
||||
import { setProperties } from '../../cocos/asset/asset-manager/utilities';
|
||||
import { macro } from '../../cocos/core';
|
||||
|
||||
// issue: https://github.com/cocos/cocos-engine/issues/16693
|
||||
test('Texture2D serialize', function () {
|
||||
const texture = new Texture2D();
|
||||
texture._mipmaps = [{ _uuid: '09f4f3e7-268b-478c-a7af-bbdf574ec3c6@6c48a' }];
|
||||
const ctxForExporting = {
|
||||
_depends: [] as string[],
|
||||
dependsOn(propName: string, uuid: string) {
|
||||
this._depends.push(propName, uuid);
|
||||
},
|
||||
_compressUuid: this.mustCompresseUuid,
|
||||
};
|
||||
texture._serialize(ctxForExporting);
|
||||
expect(ctxForExporting._depends).toEqual(['_textureSource', '09f4f3e7-268b-478c-a7af-bbdf574ec3c6@6c48a']);
|
||||
const textureUuid = 'f41e5c8f-0e9a-4c38-bb1d-texture2d';
|
||||
|
||||
afterEach(() => {
|
||||
dependUtil.remove(textureUuid);
|
||||
});
|
||||
|
||||
test('Texture2D deserialize', function () {
|
||||
const data = { base: '2,2,2,2,0,0', mipmaps: ['09f4f3e7-268b-478c-a7af-bbdf574ec3c6'] };
|
||||
const result = new Details();
|
||||
result.init();
|
||||
const handle = { result };
|
||||
const texture = new Texture2D();
|
||||
texture._deserialize(data, handle);
|
||||
expect(handle.result.uuidList).toEqual(['09f4f3e7-268b-478c-a7af-bbdf574ec3c6']);
|
||||
});
|
||||
test('releases every Texture2D dependency edge for an uploaded image', () => {
|
||||
const cleanupImageCache = macro.CLEANUP_IMAGE_CACHE;
|
||||
macro.CLEANUP_IMAGE_CACHE = true;
|
||||
|
||||
try {
|
||||
const texture = new Texture2D();
|
||||
texture._uuid = textureUuid;
|
||||
const image = new ImageAsset({
|
||||
_data: new Uint8Array(4),
|
||||
width: 1,
|
||||
height: 1,
|
||||
});
|
||||
image._uuid = '6d35c119-b763-4295-96e7-image';
|
||||
const deps = [
|
||||
{ uuid: image._uuid, owner: texture, prop: '_textureSource' },
|
||||
{ uuid: image._uuid, owner: texture._mipmaps, prop: '0' },
|
||||
];
|
||||
const assetsMap = { [`${image._uuid}@import`]: image };
|
||||
|
||||
dependMap.set(texture, deps);
|
||||
dependUtil._depends.add(textureUuid, { deps: deps.map((dep) => dep.uuid) });
|
||||
setProperties(textureUuid, texture, assetsMap);
|
||||
expect(image.refCount).toBe(2);
|
||||
|
||||
texture.onLoaded();
|
||||
|
||||
expect(image.refCount).toBe(0);
|
||||
expect(dependUtil.getDeps(textureUuid)).toEqual([]);
|
||||
} finally {
|
||||
macro.CLEANUP_IMAGE_CACHE = cleanupImageCache;
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user