From 4ad23f219318ade6c8f189bf5fa25c8bc5f4a39a Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Fri, 23 Sep 2022 16:55:04 +0800 Subject: [PATCH] fix submeshes have different instancing options (#12786) --- cocos/3d/framework/mesh-renderer.ts | 15 +- cocos/3d/models/baked-skinning-model.ts | 39 +++-- cocos/3d/models/skinning-model.ts | 6 +- cocos/core/pipeline/custom/executor.ts | 16 +- cocos/core/pipeline/deferred/gbuffer-stage.ts | 2 +- cocos/core/pipeline/forward/forward-stage.ts | 2 +- cocos/core/pipeline/instanced-buffer.ts | 3 +- cocos/core/pipeline/planar-shadow-queue.ts | 58 ++++--- .../pipeline/render-additive-light-queue.ts | 2 +- .../render-shadow-map-batched-queue.ts | 2 +- cocos/core/renderer/deprecated.ts | 7 +- cocos/core/renderer/scene/model.ts | 103 ++---------- cocos/core/renderer/scene/submodel.ts | 115 ++++++++++++- native/cocos/3d/models/BakedSkinningModel.cpp | 42 +++-- native/cocos/3d/models/BakedSkinningModel.h | 2 +- native/cocos/3d/models/SkinningModel.cpp | 5 +- native/cocos/3d/models/SkinningModel.h | 2 +- .../bindings/manual/jsb_scene_manual.cpp | 4 +- .../renderer/pipeline/InstancedBuffer.cpp | 25 ++- .../cocos/renderer/pipeline/InstancedBuffer.h | 4 +- .../renderer/pipeline/PlanarShadowQueue.cpp | 44 ++--- .../renderer/pipeline/PlanarShadowQueue.h | 3 +- .../pipeline/RenderAdditiveLightQueue.cpp | 4 +- .../pipeline/RenderAdditiveLightQueue.h | 2 +- .../pipeline/ShadowMapBatchedQueue.cpp | 2 +- .../pipeline/deferred/GbufferStage.cpp | 7 +- .../pipeline/forward/ForwardStage.cpp | 2 +- native/cocos/scene/Model.cpp | 159 +++--------------- native/cocos/scene/Model.h | 60 +++---- native/cocos/scene/SubModel.cpp | 138 +++++++++++++++ native/cocos/scene/SubModel.h | 34 +++- native/tools/tojs/scene.ini | 5 +- 32 files changed, 507 insertions(+), 407 deletions(-) diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index b5e18333a7..c550114de8 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -42,6 +42,7 @@ import { legacyCC } from '../../core/global-exports'; import { assertIsTrue } from '../../core/data/utils/asserts'; import { CCFloat } from '../../core/data/utils/attribute'; import { property } from '../../core/data/class-decorator'; +import { IInstancedAttributeBlock, SubModel } from '../../core/renderer/scene'; /** * @en Shadow projection mode. @@ -476,11 +477,15 @@ export class MeshRenderer extends ModelRenderer { if (JSB) { (this.model as any)._setInstancedAttribute(name, value); } else { - const { attributes, views } = this.model.instancedAttributes; - for (let i = 0; i < attributes.length; i++) { - if (attributes[i].name === name) { - views[i].set(value); - break; + const subModels = this.model.subModels; + for (let i = 0; i < subModels.length; i++) { + const subModel = subModels[i]; + const { attributes, views } = subModel.instancedAttributeBlock; + for (let i = 0; i < attributes.length; i++) { + if (attributes[i].name === name) { + views[i].set(value); + break; + } } } } diff --git a/cocos/3d/models/baked-skinning-model.ts b/cocos/3d/models/baked-skinning-model.ts index 8103bbe9c6..828859d440 100644 --- a/cocos/3d/models/baked-skinning-model.ts +++ b/cocos/3d/models/baked-skinning-model.ts @@ -37,6 +37,7 @@ import { IAnimInfo, IJointTextureHandle } from '../skeletal-animation/skeletal-a import { MorphModel } from './morph-model'; import { legacyCC } from '../../core/global-exports'; import { jointTextureSamplerInfo } from '../misc/joint-texture-sampler-info'; +import { SubModel } from '../../core/renderer/scene'; interface IJointsInfo { buffer: Buffer | null; @@ -129,11 +130,19 @@ export class BakedSkinningModel extends MorphModel { super.updateUBOs(stamp); const info = this._jointsMedium.animInfo; + + let hasNonInstancingPass = false; const idx = this._instAnimInfoIdx; - if (idx >= 0) { - const view = this.instancedAttributes.views[idx]; - view[0] = info.data[0]; - } else if (info.dirty) { + for (let i = 0; i < this._subModels.length; i++) { + const subModel = this._subModels[i]; + if (idx >= 0) { + const view = subModel.instancedAttributeBlock.views[idx]; + view[0] = info.data[0]; + } else { + hasNonInstancingPass = true; + } + } + if (hasNonInstancingPass && info.dirty) { info.buffer.update(info.data); info.dirty = false; } @@ -167,7 +176,7 @@ export class BakedSkinningModel extends MorphModel { } else { texture = resMgr.jointTexturePool.getDefaultPoseTexture(this._skeleton, this._mesh, this.transform); this._jointsMedium.boundsInfo = null; - this._modelBounds = texture && texture.bounds.get(this._mesh.hash)![0]; + this._modelBounds = texture && texture.bounds.get(this._mesh.hash)![0]; } this._applyJointTexture(texture); } @@ -204,20 +213,24 @@ export class BakedSkinningModel extends MorphModel { } } - protected _updateInstancedAttributes (attributes: Attribute[], pass: Pass) { - super._updateInstancedAttributes(attributes, pass); - this._instAnimInfoIdx = this._getInstancedAttributeIndex(INST_JOINT_ANIM_INFO); + protected _updateInstancedAttributes (attributes: Attribute[], subModel: SubModel) { + super._updateInstancedAttributes(attributes, subModel); + this._instAnimInfoIdx = subModel.getInstancedAttributeIndex(INST_JOINT_ANIM_INFO); this.updateInstancedJointTextureInfo(); } private updateInstancedJointTextureInfo () { const { jointTextureInfo, animInfo } = this._jointsMedium; const idx = this._instAnimInfoIdx; - if (idx >= 0) { // update instancing data too - const view = this.instancedAttributes.views[idx]; - view[0] = animInfo.data[0]; - view[1] = jointTextureInfo[1]; - view[2] = jointTextureInfo[2]; + for (let i = 0; i < this._subModels.length; i++) { + const subModel = this._subModels[i]; + const views = subModel.instancedAttributeBlock.views; + if (idx >= 0 && views.length > 0) { // update instancing data too + const view = views[idx]; + view[0] = animInfo.data[0]; + view[1] = jointTextureInfo[1]; + view[2] = jointTextureInfo[2]; + } } } } diff --git a/cocos/3d/models/skinning-model.ts b/cocos/3d/models/skinning-model.ts index 4ff2e3e07a..245bc5f48c 100644 --- a/cocos/3d/models/skinning-model.ts +++ b/cocos/3d/models/skinning-model.ts @@ -40,6 +40,7 @@ import { IMacroPatch, BatchingSchemes, Pass } from '../../core/renderer'; import { warnID } from '../../core/platform/debug'; import { ImageAsset, Texture2D, director } from '../../core'; import { PixelFormat } from '../../core/assets/asset-enum'; +import { SubModel } from '../../core/renderer/scene'; const uniformPatches: IMacroPatch[] = [ { name: 'CC_USE_SKINNING', value: true }, @@ -263,12 +264,13 @@ export class SkinningModel extends MorphModel { } } - protected _updateInstancedAttributes (attributes: Attribute[], pass: Pass) { + protected _updateInstancedAttributes (attributes: Attribute[], subModel: SubModel) { + const pass = subModel.passes[0]; if (pass.batchingScheme !== BatchingSchemes.NONE) { // TODO(holycanvas): #9203 better to print the complete path instead of only the current node warnID(3936, this.node.getPathInHierarchy()); } - super._updateInstancedAttributes(attributes, pass); + super._updateInstancedAttributes(attributes, subModel); } private _ensureEnoughBuffers (count: number) { diff --git a/cocos/core/pipeline/custom/executor.ts b/cocos/core/pipeline/custom/executor.ts index 9d6867f1b9..9c67c5b475 100644 --- a/cocos/core/pipeline/custom/executor.ts +++ b/cocos/core/pipeline/custom/executor.ts @@ -801,8 +801,8 @@ class DevicePreSceneTask extends WebSceneTask { const sceneFlag = this._graphScene.scene!.flags; for (const ro of this.sceneData.renderObjects) { const subModels = ro.model.subModels; - for (const submodel of subModels) { - const passes = submodel.passes; + for (const subModel of subModels) { + const passes = subModel.passes; for (const p of passes) { if (p.phase !== this._currentQueue.phaseID) continue; const batchingScheme = p.batchingScheme; @@ -810,21 +810,21 @@ class DevicePreSceneTask extends WebSceneTask { if (batchingScheme === BatchingSchemes.INSTANCING && !this._submitInfo.instances.size) { const instancedBuffer = p.getInstancedBuffer(); - instancedBuffer.merge(submodel, ro.model.instancedAttributes, passes.indexOf(p)); + instancedBuffer.merge(subModel, passes.indexOf(p)); this._submitInfo.instances.add(instancedBuffer); } else if (batchingScheme === BatchingSchemes.VB_MERGING && !this._submitInfo.batches.size) { const batchedBuffer = p.getBatchedBuffer(); - batchedBuffer.merge(submodel, passes.indexOf(p), ro.model); + batchedBuffer.merge(subModel, passes.indexOf(p), ro.model); this._submitInfo.batches.add(batchedBuffer); } else if ((sceneFlag & SceneFlags.TRANSPARENT_OBJECT) && (sceneFlag & SceneFlags.OPAQUE_OBJECT || sceneFlag & SceneFlags.OPAQUE_OBJECT)) { - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); + this._insertRenderList(ro, subModels.indexOf(subModel), passes.indexOf(p)); + this._insertRenderList(ro, subModels.indexOf(subModel), passes.indexOf(p), true); } else if ((sceneFlag & SceneFlags.CUTOUT_OBJECT) || (sceneFlag & SceneFlags.OPAQUE_OBJECT)) { - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); + this._insertRenderList(ro, subModels.indexOf(subModel), passes.indexOf(p)); } else if (sceneFlag & SceneFlags.TRANSPARENT_OBJECT) { - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); + this._insertRenderList(ro, subModels.indexOf(subModel), passes.indexOf(p), true); } } } diff --git a/cocos/core/pipeline/deferred/gbuffer-stage.ts b/cocos/core/pipeline/deferred/gbuffer-stage.ts index 49a212ef5e..e9bb243c0c 100644 --- a/cocos/core/pipeline/deferred/gbuffer-stage.ts +++ b/cocos/core/pipeline/deferred/gbuffer-stage.ts @@ -131,7 +131,7 @@ export class GbufferStage extends RenderStage { const batchingScheme = pass.batchingScheme; if (batchingScheme === BatchingSchemes.INSTANCING) { const instancedBuffer = pass.getInstancedBuffer(); - instancedBuffer.merge(subModel, ro.model.instancedAttributes, p); + instancedBuffer.merge(subModel, p); this._instancedQueue.queue.add(instancedBuffer); } else if (batchingScheme === BatchingSchemes.VB_MERGING) { const batchedBuffer = pass.getBatchedBuffer(); diff --git a/cocos/core/pipeline/forward/forward-stage.ts b/cocos/core/pipeline/forward/forward-stage.ts index 95a4620f6d..269e3e7efc 100644 --- a/cocos/core/pipeline/forward/forward-stage.ts +++ b/cocos/core/pipeline/forward/forward-stage.ts @@ -149,7 +149,7 @@ export class ForwardStage extends RenderStage { const batchingScheme = pass.batchingScheme; if (batchingScheme === BatchingSchemes.INSTANCING) { const instancedBuffer = pass.getInstancedBuffer(); - instancedBuffer.merge(subModel, ro.model.instancedAttributes, p); + instancedBuffer.merge(subModel, p); this._instancedQueue.queue.add(instancedBuffer); } else if (batchingScheme === BatchingSchemes.VB_MERGING) { const batchedBuffer = pass.getBatchedBuffer(); diff --git a/cocos/core/pipeline/instanced-buffer.ts b/cocos/core/pipeline/instanced-buffer.ts index 342fbc63a1..ea0b7ae308 100644 --- a/cocos/core/pipeline/instanced-buffer.ts +++ b/cocos/core/pipeline/instanced-buffer.ts @@ -65,7 +65,8 @@ export class InstancedBuffer { this.instances.length = 0; } - public merge (subModel: SubModel, attrs: IInstancedAttributeBlock, passIdx: number, shaderImplant: Shader | null = null) { + public merge (subModel: SubModel, passIdx: number, shaderImplant: Shader | null = null) { + const attrs = subModel.instancedAttributeBlock; const stride = attrs.buffer.length; if (!stride) { return; } // we assume per-instance attributes are always present const sourceIA = subModel.inputAssembler; diff --git a/cocos/core/pipeline/planar-shadow-queue.ts b/cocos/core/pipeline/planar-shadow-queue.ts index a0049614f8..de139ae034 100644 --- a/cocos/core/pipeline/planar-shadow-queue.ts +++ b/cocos/core/pipeline/planar-shadow-queue.ts @@ -26,18 +26,18 @@ import { AABB, intersect } from '../geometry'; import { SetIndex } from './define'; import { CommandBuffer, Device, RenderPass } from '../gfx'; -import { InstancedBuffer } from './instanced-buffer'; import { PipelineStateManager } from './pipeline-state-manager'; -import { Model, Camera } from '../renderer/scene'; +import { Model, Camera, SubModel } from '../renderer/scene'; import { RenderInstancedQueue } from './render-instanced-queue'; import { ShadowType } from '../renderer/scene/shadows'; import { Layers } from '../scene-graph/layers'; import { PipelineRuntime } from './custom/pipeline'; +import { BatchingSchemes } from '../renderer/core/pass'; const _ab = new AABB(); export class PlanarShadowQueue { - private _pendingModels: Model[] = []; + private _pendingSubModels: SubModel[] = []; private _castModels:Model[] = []; private _instancedQueue = new RenderInstancedQueue(); private _pipeline: PipelineRuntime; @@ -50,7 +50,7 @@ export class PlanarShadowQueue { const pipelineSceneData = this._pipeline.pipelineSceneData; const shadows = pipelineSceneData.shadows; this._instancedQueue.clear(); - this._pendingModels.length = 0; + this._pendingSubModels.length = 0; this._castModels.length = 0; if (!shadows.enabled || shadows.type !== ShadowType.Planar || shadows.normal.length() < 0.000001) { return; } @@ -73,14 +73,21 @@ export class PlanarShadowQueue { AABB.transform(_ab, model.worldBounds, shadows.matLight); if (!intersect.aabbFrustum(_ab, frustum)) { continue; } } - if (model.isInstancingEnabled) { - const subModels = model.subModels; - for (let m = 0; m < subModels.length; m++) { - const subModel = subModels[m]; - instancedBuffer.merge(subModel, model.instancedAttributes, 0, subModel.planarInstanceShader); + + const subModels = model.subModels; + for (let j = 0; j < subModels.length; j++) { + const subModel = subModels[j]; + const passes = subModel.passes; + for (let k = 0; k < passes.length; k++) { + const pass = passes[k]; + const batchingScheme = pass.batchingScheme; + if (batchingScheme === BatchingSchemes.INSTANCING) { + instancedBuffer.merge(subModel, k, subModel.planarShader); + this._instancedQueue.queue.add(instancedBuffer); + } else { + this._pendingSubModels.push(subModel); + } } - } else { - this._pendingModels.push(model); } } this._instancedQueue.uploadBuffers(cmdBuff); @@ -92,26 +99,23 @@ export class PlanarShadowQueue { if (!shadows.enabled || shadows.type !== ShadowType.Planar) { return; } this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff); - if (!this._pendingModels.length) { return; } + if (!this._pendingSubModels.length) { return; } const pass = shadows.material.passes[0]; const descriptorSet = pass.descriptorSet; cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, descriptorSet); - const modelCount = this._pendingModels.length; - for (let i = 0; i < modelCount; i++) { - const model = this._pendingModels[i]; - for (let j = 0; j < model.subModels.length; j++) { - const subModel = model.subModels[j]; - // This is a temporary solution - // It should not be written in a fixed way, or modified by the user - const shader = subModel.planarShader; - const ia = subModel.inputAssembler; - const pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader!, renderPass, ia); - cmdBuff.bindPipelineState(pso); - cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet); - cmdBuff.bindInputAssembler(ia); - cmdBuff.draw(ia); - } + const subModels = this._pendingSubModels; + for (let j = 0; j < subModels.length; j++) { + const subModel = subModels[j]; + // This is a temporary solution + // It should not be written in a fixed way, or modified by the user + const shader = subModel.planarShader; + const ia = subModel.inputAssembler; + const pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader!, renderPass, ia); + cmdBuff.bindPipelineState(pso); + cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet); + cmdBuff.bindInputAssembler(ia); + cmdBuff.draw(ia); } } } diff --git a/cocos/core/pipeline/render-additive-light-queue.ts b/cocos/core/pipeline/render-additive-light-queue.ts index 44487057e9..78c4aa4b4f 100644 --- a/cocos/core/pipeline/render-additive-light-queue.ts +++ b/cocos/core/pipeline/render-additive-light-queue.ts @@ -301,7 +301,7 @@ export class RenderAdditiveLightQueue { const { batchingScheme } = pass; if (batchingScheme === BatchingSchemes.INSTANCING) { // instancing const buffer = pass.getInstancedBuffer(); - buffer.merge(subModel, model.instancedAttributes, lightPassIdx); + buffer.merge(subModel, lightPassIdx); buffer.dynamicOffsets[0] = this._lightBufferStride; this._instancedQueue.queue.add(buffer); } else if (batchingScheme === BatchingSchemes.VB_MERGING) { // vb-merging diff --git a/cocos/core/pipeline/render-shadow-map-batched-queue.ts b/cocos/core/pipeline/render-shadow-map-batched-queue.ts index a3e6c74aae..1094723c3c 100644 --- a/cocos/core/pipeline/render-shadow-map-batched-queue.ts +++ b/cocos/core/pipeline/render-shadow-map-batched-queue.ts @@ -143,7 +143,7 @@ export class RenderShadowMapBatchedQueue { if (batchingScheme === BatchingSchemes.INSTANCING) { // instancing const buffer = pass.getInstancedBuffer(); - buffer.merge(subModel, model.instancedAttributes, shadowPassIdx); + buffer.merge(subModel, shadowPassIdx); this._instancedQueue.queue.add(buffer); } else if (pass.batchingScheme === BatchingSchemes.VB_MERGING) { // vb-merging const buffer = pass.getBatchedBuffer(); diff --git a/cocos/core/renderer/deprecated.ts b/cocos/core/renderer/deprecated.ts index 76ff0dc3a1..f1d620e299 100644 --- a/cocos/core/renderer/deprecated.ts +++ b/cocos/core/renderer/deprecated.ts @@ -30,7 +30,7 @@ import { legacyCC } from '../global-exports'; import { Pass } from './core/pass'; import { Camera } from './scene/camera'; import { Shadows } from './scene/shadows'; -import { SpotLight } from './scene'; +import { SpotLight, Model } from './scene'; removeProperty(RenderScene.prototype, 'RenderScene.prototype', [ { name: 'raycastUI2DNode' }, @@ -48,6 +48,11 @@ removeProperty(RenderScene.prototype, 'RenderScene.prototype', [ { name: 'rayResultSingleModel' }, ]); +removeProperty(Model.prototype, 'Model.prototype', [ + { name: 'isInstancingEnabled' }, + { name: 'instancedAttributes' }, +]); + const CameraVisFlags = {}; removeProperty(CameraVisFlags, 'CameraVisFlags', [ diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index def7906764..371a022bd7 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -33,8 +33,7 @@ import { Layers } from '../../scene-graph/layers'; import { RenderScene } from '../core/render-scene'; import { Texture2D } from '../../assets/texture-2d'; import { SubModel } from './submodel'; -import { Pass, IMacroPatch, BatchingSchemes } from '../core/pass'; -import { legacyCC } from '../../global-exports'; +import { IMacroPatch, BatchingSchemes } from '../core/pass'; import { Mat4, Vec3, Vec4 } from '../../math'; import { Attribute, DescriptorSet, Device, Buffer, BufferInfo, getTypedArrayConstructor, BufferUsageBit, FormatInfos, MemoryUsageBit, Filter, Address, Feature, SamplerInfo, deviceManager } from '../../gfx'; @@ -50,12 +49,6 @@ const lightMapPatches: IMacroPatch[] = [ { name: 'CC_USE_LIGHTMAP', value: true }, ]; -export interface IInstancedAttributeBlock { - buffer: Uint8Array; - views: TypedArray[]; - attributes: Attribute[]; -} - export enum ModelType { DEFAULT, SKINNING, @@ -65,12 +58,6 @@ export enum ModelType { LINE, } -function uploadMat4AsVec4x3 (mat: Mat4, v1: ArrayBufferView, v2: ArrayBufferView, v3: ArrayBufferView) { - v1[0] = mat.m00; v1[1] = mat.m01; v1[2] = mat.m02; v1[3] = mat.m12; - v2[0] = mat.m04; v2[1] = mat.m05; v2[2] = mat.m06; v2[3] = mat.m13; - v3[0] = mat.m08; v3[1] = mat.m09; v3[2] = mat.m10; v3[3] = mat.m14; -} - const lightmapSamplerHash = new SamplerInfo( Filter.LINEAR, Filter.LINEAR, @@ -158,14 +145,6 @@ export class Model { return this._updateStamp; } - /** - * @en Whether GPU instancing is enabled for the current model - * @zh 是否开启实例化渲染 - */ - get isInstancingEnabled () { - return this._instMatWorldIdx >= 0; - } - /** * @en Model level shadow bias * @zh 阴影偏移值 @@ -296,12 +275,6 @@ export class Model { */ public isDynamicBatching = false; - /** - * @en The instance attributes - * @zh 实例化属性 - */ - public instancedAttributes: IInstancedAttributeBlock = { buffer: null!, views: [], attributes: [] }; - /** * @en The world axis-aligned bounding box * @zh 世界空间包围盒 @@ -374,11 +347,6 @@ export class Model { */ protected _localBuffer: Buffer | null = null; - /** - * @en Instance matrix id - * @zh 实例矩阵索引 - */ - private _instMatWorldIdx = -1; private _lightmap: Texture2D | null = null; private _lightmapUVParam: Vec4 = new Vec4(); @@ -558,11 +526,17 @@ export class Model { // @ts-expect-error using private members here for efficiency const worldMatrix = this.transform._mat; - const idx = this._instMatWorldIdx; - if (idx >= 0) { - const attrs = this.instancedAttributes.views; - uploadMat4AsVec4x3(worldMatrix, attrs[idx], attrs[idx + 1], attrs[idx + 2]); - } else if (this._localBuffer) { + let hasNonInstancingPass = false; + for (let i = 0; i < subModels.length; i++) { + const subModel = subModels[i]; + const idx = subModel.instancedWorldMatrixIndex; + if (idx >= 0) { + subModel.updateInstancedWorldMatrix(worldMatrix, idx); + } else { + hasNonInstancingPass = true; + } + } + if (hasNonInstancingPass && this._localBuffer) { Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET); Mat4.inverseTranspose(m4_1, worldMatrix); @@ -597,10 +571,8 @@ export class Model { public initSubModel (idx: number, subMeshData: RenderingSubMesh, mat: Material) { this.initialize(); - let isNewSubModel = false; if (this._subModels[idx] == null) { this._subModels[idx] = this._createSubModel(); - isNewSubModel = true; } else { this._subModels[idx].destroy(); } @@ -748,57 +720,14 @@ export class Model { } const shader = subModel.passes[0].getShaderVariant(subModel.patches)!; - this._updateInstancedAttributes(shader.attributes, subModel.passes[0]); - } - - protected _getInstancedAttributeIndex (name: string) { - const { attributes } = this.instancedAttributes; - for (let i = 0; i < attributes.length; i++) { - if (attributes[i].name === name) { return i; } - } - return -1; - } - - private _setInstMatWorldIdx (idx: number) { - this._instMatWorldIdx = idx; + this._updateInstancedAttributes(shader.attributes, subModel); } // sub-classes can override the following functions if needed - // for now no submodel level instancing attributes - protected _updateInstancedAttributes (attributes: Attribute[], pass: Pass) { - if (!pass.device.hasFeature(Feature.INSTANCED_ARRAYS)) { return; } - // free old data - - let size = 0; - for (let j = 0; j < attributes.length; j++) { - const attribute = attributes[j]; - if (!attribute.isInstanced) { continue; } - size += FormatInfos[attribute.format].size; - } - - const attrs = this.instancedAttributes; - attrs.buffer = new Uint8Array(size); - attrs.views.length = attrs.attributes.length = 0; - let offset = 0; - for (let j = 0; j < attributes.length; j++) { - const attribute = attributes[j]; - if (!attribute.isInstanced) { continue; } - const attr = new Attribute(); - attr.format = attribute.format; - attr.name = attribute.name; - attr.isNormalized = attribute.isNormalized; - attr.location = attribute.location; - attrs.attributes.push(attr); - - const info = FormatInfos[attribute.format]; - - const typeViewArray = new (getTypedArrayConstructor(info))(attrs.buffer.buffer, offset, info.count); - attrs.views.push(typeViewArray); - offset += info.size; - } - if (pass.batchingScheme === BatchingSchemes.INSTANCING) { pass.getInstancedBuffer().destroy(); } // instancing IA changed - this._setInstMatWorldIdx(this._getInstancedAttributeIndex(INST_MAT_WORLD)); + // for now no subModel level instancing attributes + protected _updateInstancedAttributes (attributes: Attribute[], subModel: SubModel) { + subModel.UpdateInstancedAttributes(attributes); this._localDataUpdated = true; } diff --git a/cocos/core/renderer/scene/submodel.ts b/cocos/core/renderer/scene/submodel.ts index 2513081cd1..b4ef6928f4 100644 --- a/cocos/core/renderer/scene/submodel.ts +++ b/cocos/core/renderer/scene/submodel.ts @@ -24,18 +24,25 @@ */ import { RenderingSubMesh } from '../../assets/rendering-sub-mesh'; -import { RenderPriority, UNIFORM_REFLECTION_TEXTURE_BINDING, UNIFORM_REFLECTION_STORAGE_BINDING } from '../../pipeline/define'; +import { RenderPriority, UNIFORM_REFLECTION_TEXTURE_BINDING, UNIFORM_REFLECTION_STORAGE_BINDING, INST_MAT_WORLD } from '../../pipeline/define'; import { BatchingSchemes, IMacroPatch, Pass } from '../core/pass'; import { DescriptorSet, DescriptorSetInfo, Device, InputAssembler, Texture, TextureType, TextureUsageBit, TextureInfo, - Format, Sampler, Filter, Address, Shader, SamplerInfo, deviceManager } from '../../gfx'; + Format, Sampler, Filter, Address, Shader, SamplerInfo, deviceManager, Attribute, Feature, FormatInfos, getTypedArrayConstructor } from '../../gfx'; import { legacyCC } from '../../global-exports'; import { errorID } from '../../platform/debug'; import { getPhaseID } from '../../pipeline/pass-phase'; import { Root } from '../../root'; +import { Mat4 } from '../..'; const _dsInfo = new DescriptorSetInfo(null!); const MAX_PASS_COUNT = 8; +export interface IInstancedAttributeBlock { + buffer: Uint8Array; + views: TypedArray[]; + attributes: Attribute[]; +} + /** * @en A sub part of the model, it describes how to render a specific sub mesh. * It contains geometry information in [[RenderingSubMesh]] and all sort of rendering configuration like shaders, macro patches, passes etc. @@ -56,6 +63,8 @@ export class SubModel { protected _planarShader: Shader | null = null; protected _reflectionTex: Texture | null = null; protected _reflectionSampler: Sampler | null = null; + protected _instancedAttributeBlock: IInstancedAttributeBlock = { buffer: null!, views: [], attributes: [] }; + protected _instancedWorldMatrixIndex = -1; /** * @en @@ -175,6 +184,25 @@ export class SubModel { return this._planarShader; } + /** + * @en The instance attribute block, access by sub model + * @zh 硬件实例化属性,通过子模型访问 + */ + get instancedAttributeBlock () { + return this._instancedAttributeBlock; + } + + /** + * @en Get or set instance matrix id, access by sub model + * @zh 获取或者设置硬件实例化中的矩阵索引,通过子模型访问 + */ + set instancedWorldMatrixIndex (val : number) { + this._instancedWorldMatrixIndex = val; + } + get instancedWorldMatrixIndex () { + return this._instancedWorldMatrixIndex; + } + /** * @en * init sub model @@ -375,6 +403,89 @@ export class SubModel { } } + /** + * @en + * get instanced attribute index + * @zh + * 获取硬件实例化相关索引 + */ + /** + * @internal + */ + public getInstancedAttributeIndex (name: string) { + const { attributes } = this.instancedAttributeBlock; + for (let i = 0; i < attributes.length; i++) { + if (attributes[i].name === name) { return i; } + } + return -1; + } + + /** + * @en + * update instancing related data, invoked by model + * @zh + * 更新硬件实例化相关数据,一般由model调用 + */ + /** + * @internal + */ + public updateInstancedWorldMatrix (mat: Mat4, idx: number) { + const attrs = this.instancedAttributeBlock.views; + const v1 = attrs[idx]; + const v2 = attrs[idx + 1]; + const v3 = attrs[idx + 2]; + v1[0] = mat.m00; v1[1] = mat.m01; v1[2] = mat.m02; v1[3] = mat.m12; + v2[0] = mat.m04; v2[1] = mat.m05; v2[2] = mat.m06; v2[3] = mat.m13; + v3[0] = mat.m08; v3[1] = mat.m09; v3[2] = mat.m10; v3[3] = mat.m14; + } + /** + * @en + * update instancing related data, invoked by model + * @zh + * 更新硬件实例化相关数据,一般由model调用 + */ + /** + * @internal + */ + public UpdateInstancedAttributes (attributes: Attribute[]) { + // initialize subModelWorldMatrixIndex + this.instancedWorldMatrixIndex = -1; + + const pass = this.passes[0]; + if (!pass.device.hasFeature(Feature.INSTANCED_ARRAYS)) { return; } + // free old data + + let size = 0; + for (let j = 0; j < attributes.length; j++) { + const attribute = attributes[j]; + if (!attribute.isInstanced) { continue; } + size += FormatInfos[attribute.format].size; + } + + const attrs = this.instancedAttributeBlock; + attrs.buffer = new Uint8Array(size); + attrs.views.length = attrs.attributes.length = 0; + let offset = 0; + for (let j = 0; j < attributes.length; j++) { + const attribute = attributes[j]; + if (!attribute.isInstanced) { continue; } + const attr = new Attribute(); + attr.format = attribute.format; + attr.name = attribute.name; + attr.isNormalized = attribute.isNormalized; + attr.location = attribute.location; + attrs.attributes.push(attr); + + const info = FormatInfos[attribute.format]; + + const typeViewArray = new (getTypedArrayConstructor(info))(attrs.buffer.buffer, offset, info.count); + attrs.views.push(typeViewArray); + offset += info.size; + } + if (pass.batchingScheme === BatchingSchemes.INSTANCING) { pass.getInstancedBuffer().destroy(); } // instancing IA changed + this.instancedWorldMatrixIndex = this.getInstancedAttributeIndex(INST_MAT_WORLD); + } + protected _flushPassInfo (): void { const passes = this._passes; if (!passes) { return; } diff --git a/native/cocos/3d/models/BakedSkinningModel.cpp b/native/cocos/3d/models/BakedSkinningModel.cpp index c4e099b872..e201f229f4 100644 --- a/native/cocos/3d/models/BakedSkinningModel.cpp +++ b/native/cocos/3d/models/BakedSkinningModel.cpp @@ -114,15 +114,20 @@ void BakedSkinningModel::updateUBOs(uint32_t stamp) { Super::updateUBOs(stamp); IAnimInfo &info = _jointMedium.animInfo; - int idx = _instAnimInfoIdx; + const int idx = _instAnimInfoIdx; const float *curFrame = info.curFrame; - uint32_t frameDataBytes = info.frameDataBytes; - // float curFrame = info.data[0]; - // uint32_t curFrameDataBytes = info.data.byteLength(); - if (idx >= 0) { - auto &views = getInstancedAttributeBlock().views[idx]; - setTypedArrayValue(views, 0, *curFrame); - } else if (*info.dirtyForJSB != 0) { + bool hasNonInstancingPass = false; + for (const auto &subModel : _subModels) { + if (idx >= 0) { + auto &views = subModel->getInstancedAttributeBlock().views[idx]; + setTypedArrayValue(views, 0, *curFrame); + } else { + hasNonInstancingPass = true; + } + } + + const uint32_t frameDataBytes = info.frameDataBytes; + if (hasNonInstancingPass && *info.dirtyForJSB != 0) { info.buffer->update(curFrame, frameDataBytes); *info.dirtyForJSB = 0; } @@ -177,21 +182,24 @@ void BakedSkinningModel::updateLocalDescriptors(index_t subModelIndex, gfx::Desc } } -void BakedSkinningModel::updateInstancedAttributes(const ccstd::vector &attributes, scene::Pass *pass) { - Super::updateInstancedAttributes(attributes, pass); - _instAnimInfoIdx = getInstancedAttributeIndex(INST_JOINT_ANIM_INFO); +void BakedSkinningModel::updateInstancedAttributes(const ccstd::vector &attributes, scene::SubModel *subModel) { + Super::updateInstancedAttributes(attributes, subModel); + _instAnimInfoIdx = subModel->getInstancedAttributeIndex(INST_JOINT_ANIM_INFO); updateInstancedJointTextureInfo(); } void BakedSkinningModel::updateInstancedJointTextureInfo() { const auto &jointTextureInfo = _jointMedium.jointTextureInfo; const IAnimInfo &animInfo = _jointMedium.animInfo; - index_t idx = _instAnimInfoIdx; - if (idx >= 0) { - auto &view = getInstancedAttributeBlock().views[idx]; - setTypedArrayValue(view, 0, *animInfo.curFrame); //NOTE: curFrame is only used in JSB. - setTypedArrayValue(view, 1, jointTextureInfo[1]); - setTypedArrayValue(view, 2, jointTextureInfo[2]); + const index_t idx = _instAnimInfoIdx; + for (const auto &subModel : _subModels) { + auto &views = subModel->getInstancedAttributeBlock().views; + if (idx >= 0 && !views.empty()) { + auto &view = views[idx]; + setTypedArrayValue(view, 0, *animInfo.curFrame); //NOTE: curFrame is only used in JSB. + setTypedArrayValue(view, 1, jointTextureInfo[1]); + setTypedArrayValue(view, 2, jointTextureInfo[2]); + } } } diff --git a/native/cocos/3d/models/BakedSkinningModel.h b/native/cocos/3d/models/BakedSkinningModel.h index 7930b6c9c0..94a661f670 100644 --- a/native/cocos/3d/models/BakedSkinningModel.h +++ b/native/cocos/3d/models/BakedSkinningModel.h @@ -60,7 +60,7 @@ public: void updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) override; void updateTransform(uint32_t stamp) override; void updateUBOs(uint32_t stamp) override; - void updateInstancedAttributes(const ccstd::vector &attributes, scene::Pass *pass) override; + void updateInstancedAttributes(const ccstd::vector &attributes, scene::SubModel *subModel) override; void updateInstancedJointTextureInfo(); // void uploadAnimation(AnimationClip *anim); // TODO(xwx): AnimationClip not define diff --git a/native/cocos/3d/models/SkinningModel.cpp b/native/cocos/3d/models/SkinningModel.cpp index c4838c2586..adf675ff2a 100644 --- a/native/cocos/3d/models/SkinningModel.cpp +++ b/native/cocos/3d/models/SkinningModel.cpp @@ -208,13 +208,14 @@ void SkinningModel::updateLocalDescriptors(index_t submodelIdx, gfx::DescriptorS } } -void SkinningModel::updateInstancedAttributes(const ccstd::vector &attributes, scene::Pass *pass) { +void SkinningModel::updateInstancedAttributes(const ccstd::vector &attributes, scene::SubModel *subModel) { + auto *pass = subModel->getPass(0); if (pass->getBatchingScheme() != scene::BatchingSchemes::NONE) { // TODO(holycanvas): #9203 better to print the complete path instead of only the current node debug::warnID(3936, getNode()->getName()); CC_LOG_WARNING("pass batchingScheme is none, %s", getNode()->getName().c_str()); } - Super::updateInstancedAttributes(attributes, pass); + Super::updateInstancedAttributes(attributes, subModel); } void SkinningModel::ensureEnoughBuffers(uint32_t count) { diff --git a/native/cocos/3d/models/SkinningModel.h b/native/cocos/3d/models/SkinningModel.h index 4bb039b4fe..bdead040a6 100644 --- a/native/cocos/3d/models/SkinningModel.h +++ b/native/cocos/3d/models/SkinningModel.h @@ -61,7 +61,7 @@ public: void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) override; ccstd::vector getMacroPatches(index_t subModelIndex) override; - void updateInstancedAttributes(const ccstd::vector &attributes, scene::Pass *pass) override; + void updateInstancedAttributes(const ccstd::vector &attributes, scene::SubModel *subModel) override; void bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *mesh); diff --git a/native/cocos/bindings/manual/jsb_scene_manual.cpp b/native/cocos/bindings/manual/jsb_scene_manual.cpp index 77dd585090..a0a35ea5d8 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual.cpp @@ -717,13 +717,13 @@ static bool js_Model_registerListeners(se::State &s) // NOLINT(readability-ident se::ScriptEngine::getInstance()->callFunction(thiz, "_updateLocalDescriptors", static_cast(args.size()), args.data()); }); - cobj->getEventProcessor().on(cc::EventTypesToJS::MODEL_UPDATE_INSTANCED_ATTRIBUTES, [=](const ccstd::vector &attributes, cc::scene::Pass *pass) { + cobj->getEventProcessor().on(cc::EventTypesToJS::MODEL_UPDATE_INSTANCED_ATTRIBUTES, [=](const ccstd::vector &attributes, cc::scene::SubModel *subModel) { cobj->setCalledFromJS(true); se::AutoHandleScope hs; ccstd::array args; nativevalue_to_se(attributes, args[0]); - nativevalue_to_se(pass, args[1]); + nativevalue_to_se(subModel, args[1]); se::ScriptEngine::getInstance()->callFunction(thiz, "_updateInstancedAttributes", static_cast(args.size()), args.data()); }); diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.cpp b/native/cocos/renderer/pipeline/InstancedBuffer.cpp index a3f9ac0d1d..1f7083b961 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.cpp +++ b/native/cocos/renderer/pipeline/InstancedBuffer.cpp @@ -50,15 +50,16 @@ void InstancedBuffer::destroy() { _instances.clear(); } -void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *subModel, uint32_t passIdx) { - merge(model, subModel, passIdx, nullptr); +void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx) { + merge(subModel, passIdx, nullptr); } -void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *subModel, uint32_t passIdx, gfx::Shader *shaderImplant) { - auto stride = model->getInstancedBufferSize(); - const auto *instancedBuffer = model->getInstancedBuffer(); +void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Shader *shaderImplant) { + auto &attrs = subModel->getInstancedAttributeBlock(); + const auto stride = attrs.buffer.length(); if (!stride) return; // we assume per-instance attributes are always present + auto *sourceIA = subModel->getInputAssembler(); auto *descriptorSet = subModel->getDescriptorSet(); auto *lightingMap = descriptorSet->getTexture(LIGHTMAPTEXTURE::BINDING); @@ -92,13 +93,13 @@ void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *su if (instance.descriptorSet != descriptorSet) { instance.descriptorSet = descriptorSet; } - memcpy(instance.data + instance.stride * instance.count++, instancedBuffer, stride); + memcpy(instance.data + instance.stride * instance.count++, attrs.buffer.buffer()->getData(), stride); _hasPendingModels = true; return; } // Create a new instance - auto newSize = stride * INITIAL_CAPACITY; + const auto newSize = stride * INITIAL_CAPACITY; auto *vb = _device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, @@ -106,13 +107,11 @@ void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *su static_cast(stride), }); - const auto &instancedAttributes = model->getInstanceAttributes(); auto vertexBuffers = sourceIA->getVertexBuffers(); auto attributes = sourceIA->getAttributes(); auto *indexBuffer = sourceIA->getIndexBuffer(); - attributes.reserve(instancedAttributes.size()); - for (const auto &attribute : instancedAttributes) { + for (const auto &attribute : attrs.attributes) { attributes.emplace_back(gfx::Attribute{ attribute.name, attribute.format, @@ -123,9 +122,9 @@ void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *su } auto *data = static_cast(CC_MALLOC(newSize)); - memcpy(data, instancedBuffer, stride); + memcpy(data, attrs.buffer.buffer()->getData(), stride); vertexBuffers.emplace_back(vb); - gfx::InputAssemblerInfo iaInfo = {attributes, vertexBuffers, indexBuffer}; + const gfx::InputAssemblerInfo iaInfo = {attributes, vertexBuffers, indexBuffer}; auto *ia = _device->createInputAssembler(iaInfo); InstancedItem item = {1, INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet, lightingMap}; _instances.emplace_back(item); @@ -149,7 +148,7 @@ void InstancedBuffer::clear() { } void InstancedBuffer::setDynamicOffset(uint32_t idx, uint32_t value) { - if (_dynamicOffsets.size() <= idx) _dynamicOffsets.resize(idx + 1); + if (_dynamicOffsets.size() <= idx) _dynamicOffsets.resize(1 + idx); _dynamicOffsets[idx] = value; } } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.h b/native/cocos/renderer/pipeline/InstancedBuffer.h index a1471755ca..f10404273c 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.h +++ b/native/cocos/renderer/pipeline/InstancedBuffer.h @@ -61,8 +61,8 @@ public: ~InstancedBuffer() override; void destroy(); - void merge(const scene::Model *, const scene::SubModel *, uint32_t); - void merge(const scene::Model *, const scene::SubModel *, uint32_t, gfx::Shader *); + void merge(scene::SubModel *, uint32_t); + void merge(scene::SubModel *, uint32_t, gfx::Shader *); void uploadBuffers(gfx::CommandBuffer *cmdBuff); void clear(); void setDynamicOffset(uint32_t idx, uint32_t value); diff --git a/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp b/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp index a31cd8bee1..c38779585f 100644 --- a/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp +++ b/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp @@ -88,15 +88,19 @@ void PlanarShadowQueue::gatherShadowPasses(scene::Camera *camera, gfx::CommandBu continue; } - if (!model->getInstanceAttributes().empty()) { - int i = 0; - for (const auto &subModel : model->getSubModels()) { - instancedBuffer->merge(model, subModel, i, subModel->getPlanarInstanceShader()); - _instancedQueue->add(instancedBuffer); - ++i; + const auto &subModels = model->getSubModels(); + for (const auto &subModel : subModels) { + const auto &subModelPasses = subModel->getPasses(); + for (index_t i = 0; i < static_cast(subModelPasses.size()); ++i) { + const auto subModelPass = subModelPasses[i]; + const auto batchingScheme = subModelPass->getBatchingScheme(); + if (batchingScheme == scene::BatchingSchemes::INSTANCING) { + instancedBuffer->merge(subModel, i, subModel->getPlanarInstanceShader()); + _instancedQueue->add(instancedBuffer); + } else { // standard draw + _pendingSubModels.emplace_back(subModel); + } } - } else { - _pendingModels.emplace_back(model); } } @@ -105,7 +109,7 @@ void PlanarShadowQueue::gatherShadowPasses(scene::Camera *camera, gfx::CommandBu void PlanarShadowQueue::clear() { _castModels.clear(); - _pendingModels.clear(); + _pendingSubModels.clear(); if (_instancedQueue) _instancedQueue->clear(); } @@ -118,24 +122,22 @@ void PlanarShadowQueue::recordCommandBuffer(gfx::Device *device, gfx::RenderPass _instancedQueue->recordCommandBuffer(device, renderPass, cmdBuffer); - if (_pendingModels.empty()) { + if (_pendingSubModels.empty()) { return; } const scene::Pass *pass = (*shadowInfo->getMaterial()->getPasses())[0]; cmdBuffer->bindDescriptorSet(materialSet, pass->getDescriptorSet()); - for (const auto *model : _pendingModels) { - for (const auto &subModel : model->getSubModels()) { - auto *const shader = subModel->getPlanarShader(); - auto *const ia = subModel->getInputAssembler(); - auto *const pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass, subpassID); + for (const auto *subModel : _pendingSubModels) { + auto *const shader = subModel->getPlanarShader(); + auto *const ia = subModel->getInputAssembler(); + auto *const pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass, subpassID); - cmdBuffer->bindPipelineState(pso); - cmdBuffer->bindDescriptorSet(localSet, subModel->getDescriptorSet()); - cmdBuffer->bindInputAssembler(ia); - cmdBuffer->draw(ia); - } + cmdBuffer->bindPipelineState(pso); + cmdBuffer->bindDescriptorSet(localSet, subModel->getDescriptorSet()); + cmdBuffer->bindInputAssembler(ia); + cmdBuffer->draw(ia); } } @@ -143,7 +145,7 @@ void PlanarShadowQueue::destroy() { _pipeline = nullptr; CC_SAFE_DELETE(_instancedQueue); _castModels.clear(); - _pendingModels.clear(); + _pendingSubModels.clear(); } } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/PlanarShadowQueue.h b/native/cocos/renderer/pipeline/PlanarShadowQueue.h index 48c6239c29..98dfbcd080 100644 --- a/native/cocos/renderer/pipeline/PlanarShadowQueue.h +++ b/native/cocos/renderer/pipeline/PlanarShadowQueue.h @@ -40,7 +40,6 @@ namespace pipeline { class RenderPipeline; class InstanceBuffer; class RenderInstancedQueue; -class RenderBatchedQueue; class CC_DLL PlanarShadowQueue final { public: @@ -60,7 +59,7 @@ private: // weak reference ccstd::vector _castModels; // weak reference - ccstd::vector _pendingModels; + ccstd::vector _pendingSubModels; }; } // namespace pipeline } // namespace cc diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp index 2c6b0df1d6..28d5da8974 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp @@ -216,12 +216,12 @@ bool RenderAdditiveLightQueue::isInstancedOrBatched(const scene::Model *model) { return false; } -void RenderAdditiveLightQueue::addRenderQueue(const scene::SubModel *subModel, const scene::Model *model, scene::Pass *pass, uint32_t lightPassIdx) { +void RenderAdditiveLightQueue::addRenderQueue(scene::SubModel *subModel, const scene::Model *model, scene::Pass *pass, uint32_t lightPassIdx) { const auto batchingScheme = pass->getBatchingScheme(); const auto lightCount = _lightIndices.size(); if (batchingScheme == scene::BatchingSchemes::INSTANCING) { // instancing auto *buffer = pass->getInstancedBuffer(); - buffer->merge(model, subModel, lightPassIdx); + buffer->merge(subModel, lightPassIdx); buffer->setDynamicOffset(0, _lightBufferStride); _instancedQueue->add(buffer); } else if (batchingScheme == scene::BatchingSchemes::VB_MERGING) { // vb-merging diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h index a0571b053d..d63863dc9e 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h @@ -66,7 +66,7 @@ private: static bool isInstancedOrBatched(const scene::Model *model); void clear(); - void addRenderQueue(const scene::SubModel *subModel, const scene::Model *model, scene::Pass *pass, uint32_t lightPassIdx); + void addRenderQueue(scene::SubModel *subModel, const scene::Model *model, scene::Pass *pass, uint32_t lightPassIdx); void updateUBOs(const scene::Camera *camera, gfx::CommandBuffer *cmdBuffer); void updateLightDescriptorSet(const scene::Camera *camera, gfx::CommandBuffer *cmdBuffer); bool getLightPassIndex(const scene::Model *model, ccstd::vector *lightPassIndices) const; diff --git a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp index f6c43caf01..7af8e4f307 100644 --- a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp +++ b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp @@ -134,7 +134,7 @@ void ShadowMapBatchedQueue::add(const scene::Model *model) { if (batchingScheme == scene::BatchingSchemes::INSTANCING) { auto *instancedBuffer = subModel->getPass(shadowPassIdx)->getInstancedBuffer(); - instancedBuffer->merge(model, subModel, shadowPassIdx); + instancedBuffer->merge(subModel, shadowPassIdx); _instancedQueue->add(instancedBuffer); } else if (batchingScheme == scene::BatchingSchemes::VB_MERGING) { auto *batchedBuffer = subModel->getPass(shadowPassIdx)->getBatchedBuffer(); diff --git a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp index 8e5beb5236..94b458ca86 100644 --- a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp @@ -40,6 +40,7 @@ #include "gfx-base/GFXDevice.h" #include "profiler/Profiler.h" #include "scene/Camera.h" +#include "scene/Model.h" namespace cc { namespace pipeline { @@ -99,17 +100,17 @@ void GbufferStage::dispenseRenderObject2Queues() { for (auto ro : renderObjects) { const auto *const model = ro.model; const auto &subModels = model->getSubModels(); - auto subModelCount = subModels.size(); + const auto subModelCount = subModels.size(); for (subModelIdx = 0; subModelIdx < subModelCount; ++subModelIdx) { const auto &subModel = subModels[subModelIdx]; const auto &passes = subModel->getPasses(); - auto passCount = passes.size(); + const auto passCount = passes.size(); for (passIdx = 0; passIdx < passCount; ++passIdx) { const auto &pass = passes[passIdx]; if (pass->getPhase() != _phaseID) continue; if (pass->getBatchingScheme() == scene::BatchingSchemes::INSTANCING) { auto *instancedBuffer = pass->getInstancedBuffer(); - instancedBuffer->merge(model, subModel, passIdx); + instancedBuffer->merge(subModel, passIdx); _instancedQueue->add(instancedBuffer); } else if (pass->getBatchingScheme() == scene::BatchingSchemes::VB_MERGING) { auto *batchedBuffer = pass->getBatchedBuffer(); diff --git a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp index 091f61eb00..459129d27d 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp @@ -121,7 +121,7 @@ void ForwardStage::dispenseRenderObject2Queues() { if (pass->getPhase() != _phaseID) continue; if (pass->getBatchingScheme() == scene::BatchingSchemes::INSTANCING) { auto *instancedBuffer = pass->getInstancedBuffer(); - instancedBuffer->merge(model, subModel, passIdx); + instancedBuffer->merge(subModel, passIdx); _instancedQueue->add(instancedBuffer); } else if (pass->getBatchingScheme() == scene::BatchingSchemes::VB_MERGING) { auto *batchedBuffer = pass->getBatchedBuffer(); diff --git a/native/cocos/scene/Model.cpp b/native/cocos/scene/Model.cpp index c8fdc66731..fab3914141 100644 --- a/native/cocos/scene/Model.cpp +++ b/native/cocos/scene/Model.cpp @@ -40,39 +40,6 @@ #include "scene/SubModel.h" namespace { -cc::TypedArray getTypedArrayConstructor(const cc::gfx::FormatInfo &info, cc::ArrayBuffer *buffer, uint32_t byteOffset, uint32_t length) { - const uint32_t stride = info.size / info.count; - switch (info.type) { - case cc::gfx::FormatType::UNORM: - case cc::gfx::FormatType::UINT: { - switch (stride) { - case 1: return cc::Uint8Array(buffer, byteOffset, length); - case 2: return cc::Uint16Array(buffer, byteOffset, length); - case 4: return cc::Uint32Array(buffer, byteOffset, length); - default: - break; - } - break; - } - case cc::gfx::FormatType::SNORM: - case cc::gfx::FormatType::INT: { - switch (stride) { - case 1: return cc::Int8Array(buffer, byteOffset, length); - case 2: return cc::Int16Array(buffer, byteOffset, length); - case 4: return cc::Int32Array(buffer, byteOffset, length); - default: - break; - } - break; - } - case cc::gfx::FormatType::FLOAT: { - return cc::Float32Array(buffer, byteOffset, length); - } - default: - break; - } - return cc::Float32Array(buffer, byteOffset, length); -} cc::Float32Array &vec4ToFloat32Array(const cc::Vec4 &v, cc::Float32Array &out, index_t ofs = 0) { out[ofs + 0] = v.x; @@ -106,7 +73,6 @@ const cc::gfx::SamplerInfo LIGHTMAP_SAMPLER_WITH_MIP_HASH{ }; const ccstd::vector SHADOW_MAP_PATCHES{{"CC_RECEIVE_SHADOW", true}}; -const ccstd::string INST_MAT_WORLD = "a_matWorld0"; } // namespace namespace cc { @@ -146,23 +112,6 @@ void Model::destroy() { _isDynamicBatching = false; } -void Model::uploadMat4AsVec4x3(const Mat4 &mat, Float32Array &v1, Float32Array &v2, Float32Array &v3) { - uint32_t copyBytes = sizeof(float) * 3; - auto *buffer = const_cast(v1.buffer()->getData()); - - uint8_t *dst = buffer + v1.byteOffset(); - memcpy(dst, mat.m, copyBytes); - v1[3] = mat.m[12]; - - dst = buffer + v2.byteOffset(); - memcpy(dst, mat.m + 4, copyBytes); - v2[3] = mat.m[13]; - - dst = buffer + v3.byteOffset(); - memcpy(dst, mat.m + 8, copyBytes); - v3[3] = mat.m[14]; -} - void Model::updateTransform(uint32_t stamp) { CC_PROFILE(ModelUpdateTransform); if (isModelImplementedInJS()) { @@ -233,11 +182,18 @@ void Model::updateUBOs(uint32_t stamp) { _localDataUpdated = false; getTransform()->updateWorldTransform(); const auto &worldMatrix = getTransform()->getWorldMatrix(); - int idx = _instMatWorldIdx; - if (idx >= 0) { - ccstd::vector &attrs = getInstancedAttributeBlock().views; - uploadMat4AsVec4x3(worldMatrix, ccstd::get(attrs[idx]), ccstd::get(attrs[idx + 1]), ccstd::get(attrs[idx + 2])); - } else if (_localBuffer) { + bool hasNonInstancingPass = false; + for (const auto &subModel : _subModels) { + const auto idx = subModel->getInstancedWorldMatrixIndex(); + if (idx >= 0) { + ccstd::vector &attrs = subModel->getInstancedAttributeBlock().views; + subModel->updateInstancedWorldMatrix(worldMatrix, idx); + } else { + hasNonInstancingPass = true; + } + } + + if (hasNonInstancingPass && _localBuffer) { Mat4 mat4; mat4ToFloat32Array(worldMatrix, _localData, pipeline::UBOLocal::MAT_WORLD_OFFSET); Mat4::inverseTranspose(worldMatrix, &mat4); @@ -294,14 +250,12 @@ SubModel *Model::createSubModel() { void Model::initSubModel(index_t idx, cc::RenderingSubMesh *subMeshData, Material *mat) { initialize(); - bool isNewSubModel = false; - if (idx >= _subModels.size()) { - _subModels.resize(idx + 1, nullptr); + if (idx >= static_cast(_subModels.size())) { + _subModels.resize(1 + idx, nullptr); } if (_subModels[idx] == nullptr) { _subModels[idx] = createSubModel(); - isNewSubModel = true; } else { CC_SAFE_DESTROY(_subModels[idx]); } @@ -400,63 +354,18 @@ void Model::updateAttributesAndBinding(index_t subModelIndex) { } gfx::Shader *shader = subModel->getPasses()[0]->getShaderVariant(subModel->getPatches()); - updateInstancedAttributes(shader->getAttributes(), subModel->getPasses()[0]); + updateInstancedAttributes(shader->getAttributes(), subModel); } -index_t Model::getInstancedAttributeIndex(const ccstd::string &name) const { - const auto &attributes = _instanceAttributeBlock.attributes; - for (index_t i = 0; i < attributes.size(); ++i) { - if (attributes[i].name == name) { - return i; - } - } - return CC_INVALID_INDEX; -} - -void Model::updateInstancedAttributes(const ccstd::vector &attributes, Pass *pass) { +void Model::updateInstancedAttributes(const ccstd::vector &attributes, SubModel* subModel) { if (isModelImplementedInJS()) { if (!_isCalledFromJS) { - _eventProcessor.emit(EventTypesToJS::MODEL_UPDATE_INSTANCED_ATTRIBUTES, attributes, pass); + _eventProcessor.emit(EventTypesToJS::MODEL_UPDATE_INSTANCED_ATTRIBUTES, attributes, subModel); _isCalledFromJS = false; return; } } - - if (!pass->getDevice()->hasFeature(gfx::Feature::INSTANCED_ARRAYS)) return; - // free old data - - uint32_t size = 0; - for (const gfx::Attribute &attribute : attributes) { - if (!attribute.isInstanced) continue; - size += gfx::GFX_FORMAT_INFOS[static_cast(attribute.format)].size; - } - auto &attrs = _instanceAttributeBlock; - attrs.buffer = Uint8Array(size); - attrs.views.clear(); - attrs.attributes.clear(); - attrs.views.reserve(attributes.size()); - attrs.attributes.reserve(attributes.size()); - - uint32_t offset = 0; - - for (const gfx::Attribute &attribute : attributes) { - if (!attribute.isInstanced) continue; - gfx::Attribute attr; - attr.format = attribute.format; - attr.name = attribute.name; - attr.isNormalized = attribute.isNormalized; - attr.location = attribute.location; - attrs.attributes.emplace_back(attr); - const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attribute.format)]; - auto *buffer = attrs.buffer.buffer(); - auto typeViewArray = getTypedArrayConstructor(info, buffer, offset, info.count); - attrs.views.emplace_back(typeViewArray); - offset += info.size; - } - if (pass->getBatchingScheme() == BatchingSchemes::INSTANCING) { - pass->getInstancedBuffer()->destroy(); - } - setInstMatWorldIdx(getInstancedAttributeIndex(INST_MAT_WORLD)); + subModel->updateInstancedAttributes(attributes); _localDataUpdated = true; } @@ -509,9 +418,6 @@ void Model::updateWorldBoundDescriptors(index_t subModelIndex, gfx::DescriptorSe descriptorSet->bindBuffer(pipeline::UBOLocal::BINDING, _worldBoundBuffer); } } -void Model::setInstancedAttributesViewData(index_t viewIdx, index_t arrIdx, float value) { - ccstd::get(_instanceAttributeBlock.views[viewIdx])[arrIdx] = value; -} void Model::updateLocalShadowBias() { _localData[pipeline::UBOLocal::LOCAL_SHADOW_BIAS + 0] = _shadowBias; @@ -522,33 +428,8 @@ void Model::updateLocalShadowBias() { } void Model::setInstancedAttribute(const ccstd::string &name, const float *value, uint32_t byteLength) { - const auto &attributes = getInstancedAttributeBlock().attributes; - auto &views = getInstancedAttributeBlock().views; - - for (size_t i = 0, len = attributes.size(); i < len; ++i) { - const auto &attribute = attributes[i]; - if (attribute.name == name) { - const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attribute.format)]; - switch (info.type) { - case gfx::FormatType::NONE: - case gfx::FormatType::UNORM: - case gfx::FormatType::SNORM: - case gfx::FormatType::UINT: - case gfx::FormatType::INT: { - CC_ASSERT(false); // NOLINT - } break; - case gfx::FormatType::FLOAT: - case gfx::FormatType::UFLOAT: { - CC_ASSERT(ccstd::holds_alternative(views[i])); - auto &view = ccstd::get(views[i]); - auto *dstData = reinterpret_cast(view.buffer()->getData() + view.byteOffset()); - CC_ASSERT(byteLength <= view.byteLength()); - memcpy(dstData, value, byteLength); - } break; - default: - break; - } - } + for (const auto &subModel : _subModels) { + subModel->setInstancedAttribute(name, value, byteLength); } } diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index 0bbcfc03b4..c669c8b0d2 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -55,11 +55,6 @@ class OctreeNode; class Octree; class Pass; struct IMacroPatch; -struct InstancedAttributeBlock { - Uint8Array buffer; - ccstd::vector views; - ccstd::vector attributes; -}; class Model : public RefCounted { public: @@ -79,14 +74,13 @@ public: virtual void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat); virtual ccstd::vector getMacroPatches(index_t subModelIndex); virtual void setSubModelMaterial(index_t idx, Material *mat); - virtual void updateInstancedAttributes(const ccstd::vector &attributes, Pass *pass); + virtual void updateInstancedAttributes(const ccstd::vector &attributes, SubModel *subModel); virtual void updateTransform(uint32_t stamp); virtual void updateUBOs(uint32_t stamp); virtual void updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet); virtual void updateWorldBoundDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet); void createBoundingShape(const ccstd::optional &minPos, const ccstd::optional &maxPos); - int32_t getInstancedAttributeIndex(const ccstd::string &name) const; void initialize(); void initLightingmap(Texture2D *texture, const Vec4 &uvParam); void initLocalDescriptors(index_t subModelIndex); @@ -107,11 +101,10 @@ public: inline void attachToScene(RenderScene *scene) { _scene = scene; _localDataUpdated = true; - }; + } inline void detachFromScene() { _scene = nullptr; }; inline void setCastShadow(bool value) { _castShadow = value; } inline void setEnabled(bool value) { _enabled = value; } - inline void setInstMatWorldIdx(int32_t idx) { _instMatWorldIdx = idx; } inline void setLocalBuffer(gfx::Buffer *buffer) { _localBuffer = buffer; } inline void setWorldBoundBuffer(gfx::Buffer *buffer) { _worldBoundBuffer = buffer; } @@ -129,25 +122,15 @@ public: _modelBounds->set(_worldBounds->getCenter(), _worldBounds->getHalfExtents()); _worldBoundsDirty = true; } - inline void setInstancedAttributeBlock(const InstancedAttributeBlock &val) { - _instanceAttributeBlock = val; - _localDataUpdated = true; - } inline void setOctreeNode(OctreeNode *node) { _octreeNode = node; } inline void setScene(RenderScene *scene) { _scene = scene; if (scene) _localDataUpdated = true; } - inline bool isInited() const { return _inited; }; + inline bool isInited() const { return _inited; } inline bool isCastShadow() const { return _castShadow; } inline bool isEnabled() const { return _enabled; } - inline bool isInstancingEnabled() const { return _instMatWorldIdx >= 0; }; - inline int32_t getInstMatWorldIdx() const { return _instMatWorldIdx; } - inline const ccstd::vector &getInstanceAttributes() const { return _instanceAttributeBlock.attributes; } - inline InstancedAttributeBlock &getInstancedAttributeBlock() { return _instanceAttributeBlock; } - inline const uint8_t *getInstancedBuffer() const { return _instanceAttributeBlock.buffer.buffer()->getData(); } - inline uint32_t getInstancedBufferSize() const { return _instanceAttributeBlock.buffer.length(); } inline gfx::Buffer *getLocalBuffer() const { return _localBuffer.get(); } inline gfx::Buffer *getWorldBoundBuffer() const { return _worldBoundBuffer.get(); } inline Float32Array getLocalData() const { return _localData; } @@ -174,7 +157,6 @@ public: // For JS inline void setCalledFromJS(bool v) { _isCalledFromJS = v; } inline CallbacksInvoker &getEventProcessor() { return _eventProcessor; } - void setInstancedAttributesViewData(index_t viewIdx, index_t arrIdx, float value); inline void setLocalDataUpdated(bool v) { _localDataUpdated = v; } inline void setWorldBounds(geometry::AABB *bounds) { _worldBounds = bounds; @@ -185,21 +167,16 @@ public: protected: static SubModel *createSubModel(); - static void uploadMat4AsVec4x3(const Mat4 &mat, Float32Array &v1, Float32Array &v2, Float32Array &v3); + void updateAttributesAndBinding(index_t subModelIndex); // Please declare variables in descending order of memory size occupied by variables. + Type _type{Type::DEFAULT}; + Layers::Enum _visFlags{Layers::Enum::NONE}; - InstancedAttributeBlock _instanceAttributeBlock; - Float32Array _localData; - ccstd::vector> _subModels; - - // For JS - CallbacksInvoker _eventProcessor; - - Vec4 _lightmapUVParam; - float _shadowBias{0.0F}; - float _shadowNormalBias{0.0F}; + uint32_t _descriptorSetCount{1}; + uint32_t _priority{0}; + uint32_t _updateStamp{0}; OctreeNode *_octreeNode{nullptr}; RenderScene *_scene{nullptr}; @@ -213,14 +190,6 @@ protected: IntrusivePtr _modelBounds; IntrusivePtr _lightmap; - Type _type{Type::DEFAULT}; - Layers::Enum _visFlags{Layers::Enum::NONE}; - - uint32_t _descriptorSetCount{1}; - uint32_t _priority{0}; - uint32_t _updateStamp{0}; - int32_t _instMatWorldIdx{-1}; - bool _enabled{false}; bool _castShadow{false}; bool _receiveShadow{false}; @@ -231,6 +200,17 @@ protected: // For JS bool _isCalledFromJS{false}; + float _shadowBias{0.0F}; + float _shadowNormalBias{0.0F}; + + Vec4 _lightmapUVParam; + + // For JS + CallbacksInvoker _eventProcessor; + + Float32Array _localData; + ccstd::vector> _subModels; + private: CC_DISALLOW_COPY_MOVE_ASSIGN(Model); }; diff --git a/native/cocos/scene/SubModel.cpp b/native/cocos/scene/SubModel.cpp index 2064f68a58..a01dad7e61 100644 --- a/native/cocos/scene/SubModel.cpp +++ b/native/cocos/scene/SubModel.cpp @@ -27,6 +27,7 @@ #include "core/Root.h" #include "core/platform/Debug.h" #include "pipeline/Define.h" +#include "pipeline/InstancedBuffer.h" #include "renderer/pipeline/PipelineSceneData.h" #include "renderer/pipeline/custom/RenderInterfaceTypes.h" #include "renderer/pipeline/forward/ForwardPipeline.h" @@ -37,6 +38,42 @@ namespace cc { namespace scene { +const ccstd::string INST_MAT_WORLD = "a_matWorld0"; + +cc::TypedArray getTypedArrayConstructor(const cc::gfx::FormatInfo &info, cc::ArrayBuffer *buffer, uint32_t byteOffset, uint32_t length) { + const uint32_t stride = info.size / info.count; + switch (info.type) { + case cc::gfx::FormatType::UNORM: + case cc::gfx::FormatType::UINT: { + switch (stride) { + case 1: return cc::Uint8Array(buffer, byteOffset, length); + case 2: return cc::Uint16Array(buffer, byteOffset, length); + case 4: return cc::Uint32Array(buffer, byteOffset, length); + default: + break; + } + break; + } + case cc::gfx::FormatType::SNORM: + case cc::gfx::FormatType::INT: { + switch (stride) { + case 1: return cc::Int8Array(buffer, byteOffset, length); + case 2: return cc::Int16Array(buffer, byteOffset, length); + case 4: return cc::Int32Array(buffer, byteOffset, length); + default: + break; + } + break; + } + case cc::gfx::FormatType::FLOAT: { + return cc::Float32Array(buffer, byteOffset, length); + } + default: + break; + } + return cc::Float32Array(buffer, byteOffset, length); +} + SubModel::SubModel() { _id = generateId(); } @@ -236,6 +273,67 @@ void SubModel::onGeometryChanged() { } } +void SubModel::updateInstancedAttributes(const ccstd::vector& attributes) { + auto *pass = getPass(0); + _instancedWorldMatrixIndex = -1; + if (!pass->getDevice()->hasFeature(gfx::Feature::INSTANCED_ARRAYS)) return; + // free old data + + uint32_t size = 0; + for (const gfx::Attribute &attribute : attributes) { + if (!attribute.isInstanced) continue; + size += gfx::GFX_FORMAT_INFOS[static_cast(attribute.format)].size; + } + auto &attrs = _instancedAttributeBlock; + attrs.buffer = Uint8Array(size); + attrs.views.clear(); + attrs.attributes.clear(); + attrs.views.reserve(attributes.size()); + attrs.attributes.reserve(attributes.size()); + + uint32_t offset = 0; + + for (const gfx::Attribute &attribute : attributes) { + if (!attribute.isInstanced) continue; + gfx::Attribute attr; + attr.format = attribute.format; + attr.name = attribute.name; + attr.isNormalized = attribute.isNormalized; + attr.location = attribute.location; + attrs.attributes.emplace_back(attr); + const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attribute.format)]; + auto *buffer = attrs.buffer.buffer(); + auto typeViewArray = getTypedArrayConstructor(info, buffer, offset, info.count); + attrs.views.emplace_back(typeViewArray); + offset += info.size; + } + if (pass->getBatchingScheme() == BatchingSchemes::INSTANCING) { + pass->getInstancedBuffer()->destroy(); + } + _instancedWorldMatrixIndex = getInstancedAttributeIndex(INST_MAT_WORLD); +} + +void SubModel::updateInstancedWorldMatrix(const Mat4& mat, int32_t idx) { + auto &attrs = _instancedAttributeBlock.views; + auto &v1 = ccstd::get(attrs[idx]); + auto &v2 = ccstd::get(attrs[idx + 1]); + auto &v3 = ccstd::get(attrs[idx+ + 2]); + const uint32_t copyBytes = sizeof(float) * 3; + auto *buffer = const_cast(v1.buffer()->getData()); + + uint8_t *dst = buffer + v1.byteOffset(); + memcpy(dst, mat.m, copyBytes); + v1[3] = mat.m[12]; + + dst = buffer + v2.byteOffset(); + memcpy(dst, mat.m + 4, copyBytes); + v2[3] = mat.m[13]; + + dst = buffer + v3.byteOffset(); + memcpy(dst, mat.m + 8, copyBytes); + v3[3] = mat.m[14]; +} + void SubModel::flushPassInfo() { const auto &passes = *_passes; if (passes.empty()) return; @@ -258,5 +356,45 @@ void SubModel::setSubMesh(RenderingSubMesh *subMesh) { _subMesh = subMesh; } +void SubModel::setInstancedAttribute(const ccstd::string& name, const float* value, uint32_t byteLength) { + const auto &attributes = _instancedAttributeBlock.attributes; + auto &views = _instancedAttributeBlock.views; + for (size_t i = 0, len = attributes.size(); i < len; ++i) { + const auto &attribute = attributes[i]; + if (attribute.name == name) { + const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attribute.format)]; + switch (info.type) { + case gfx::FormatType::NONE: + case gfx::FormatType::UNORM: + case gfx::FormatType::SNORM: + case gfx::FormatType::UINT: + case gfx::FormatType::INT: { + CC_ASSERT(false); // NOLINT + } break; + case gfx::FormatType::FLOAT: + case gfx::FormatType::UFLOAT: { + CC_ASSERT(ccstd::holds_alternative(views[i])); + auto &view = ccstd::get(views[i]); + auto *dstData = reinterpret_cast(view.buffer()->getData() + view.byteOffset()); + CC_ASSERT(byteLength <= view.byteLength()); + memcpy(dstData, value, byteLength); + } break; + default: + break; + } + } + } +} + +int32_t SubModel::getInstancedAttributeIndex(const ccstd::string& name) const { + const auto &attributes = _instancedAttributeBlock.attributes; + for (index_t i = 0; i < static_cast(attributes.size()); ++i) { + if (attributes[i].name == name) { + return i; + } + } + return CC_INVALID_INDEX; +} + } // namespace scene } // namespace cc diff --git a/native/cocos/scene/SubModel.h b/native/cocos/scene/SubModel.h index 6bd14306d8..bf64b1152c 100644 --- a/native/cocos/scene/SubModel.h +++ b/native/cocos/scene/SubModel.h @@ -37,6 +37,12 @@ namespace cc { namespace scene { class Pass; +struct InstancedAttributeBlock { + Uint8Array buffer; + ccstd::vector views; + ccstd::vector attributes; +}; + class SubModel : public RefCounted { public: SubModel(); @@ -57,6 +63,8 @@ public: inline void setPriority(pipeline::RenderPriority priority) { _priority = priority; } inline void setOwner(Model *model) { _owner = model; } void setSubMesh(RenderingSubMesh *subMesh); + inline void setInstancedWorldMatrixIndex(int32_t worldMatrixIndex) { _instancedWorldMatrixIndex = worldMatrixIndex; } + void setInstancedAttribute(const ccstd::string &name, const float *value, uint32_t byteLength); inline gfx::DescriptorSet *getDescriptorSet() const { return _descriptorSet; } inline gfx::DescriptorSet *getWorldBoundDescriptorSet() const { return _worldBoundDescriptorSet; } @@ -70,6 +78,9 @@ public: inline RenderingSubMesh *getSubMesh() const { return _subMesh; } inline Model *getOwner() const { return _owner; } inline uint32_t getId() const { return _id; } + inline InstancedAttributeBlock &getInstancedAttributeBlock() { return _instancedAttributeBlock; } + inline int32_t getInstancedWorldMatrixIndex() const { return _instancedWorldMatrixIndex; } + int32_t getInstancedAttributeIndex(const ccstd::string &name) const; void initialize(RenderingSubMesh *subMesh, const std::shared_ptr>> &passes, const ccstd::vector &patches); void initPlanarShadowShader(); @@ -78,26 +89,35 @@ public: void onPipelineStateChanged(); void onMacroPatchesStateChanged(const ccstd::vector &patches); void onGeometryChanged(); + void updateInstancedAttributes(const ccstd::vector &attributes); + void updateInstancedWorldMatrix(const Mat4 &mat, int32_t idx); protected: void flushPassInfo(); + pipeline::RenderPriority _priority{pipeline::RenderPriority::DEFAULT}; + + int32_t _id{-1}; + int32_t _instancedWorldMatrixIndex{-1}; + gfx::Device *_device{nullptr}; - ccstd::vector _patches; + Model *_owner{nullptr}; + gfx::Sampler *_reflectionSampler{nullptr}; + IntrusivePtr _inputAssembler; IntrusivePtr _descriptorSet; IntrusivePtr _worldBoundDescriptorSet; - IntrusivePtr _reflectionTex; - gfx::Sampler *_reflectionSampler{nullptr}; - pipeline::RenderPriority _priority{pipeline::RenderPriority::DEFAULT}; IntrusivePtr _planarShader; IntrusivePtr _planarInstanceShader; IntrusivePtr _subMesh; - std::shared_ptr>> _passes; + + InstancedAttributeBlock _instancedAttributeBlock{}; + + ccstd::vector _patches; ccstd::vector> _shaders; - Model *_owner{nullptr}; - int32_t _id{-1}; + + std::shared_ptr>> _passes; private: static inline int32_t generateId() { diff --git a/native/tools/tojs/scene.ini b/native/tools/tojs/scene.ini index f35d84f622..94f4e4ede9 100644 --- a/native/tools/tojs/scene.ini +++ b/native/tools/tojs/scene.ini @@ -70,6 +70,7 @@ classes = Light DirectionalLight SpotLight SphereLight Model SubModel Pass Rende # functions from all classes. skip = Pass::[getBlocks initPassFromTarget], AABB::[getBoundary aabbAabb aabbFrustum aabbPlan merge transform transformExtentM4 setCenter getCenter isValid setValid setHalfExtents getHalfExtents set fromPoints], + SubModel::[getInstancedAttributeBlock (g|s)etInstancedWorldMatrixIndex (g|s)etInstancedAttributeIndex updateInstancedAttributes updateInstancedWorldMatrix], Model::[getEventProcessor getOctreeNode setOctreeNode updateOctree], SkinningModel::[uploadJointData], Frustum::[update type planes], @@ -87,7 +88,7 @@ rename_functions = Root::[initialize=_initialize], Node::[resetChangedFlags=resetHasChangedFlags _parent=_parentInternal updateSiblingIndex=_updateSiblingIndex onPreDestroyBase=_onPreDestroyBase onPreDestroy=_onPreDestroy], FogInfo::[_isEnabled=_enabled], ProgramLib::[registerEffect=register], - Model::[initLocalDescriptors=_initLocalDescriptors updateLocalDescriptors=_updateLocalDescriptors updateInstancedAttributes=_updateInstancedAttributes getInstancedAttributeIndex=_getInstancedAttributeIndex], + Model::[initLocalDescriptors=_initLocalDescriptors updateLocalDescriptors=_updateLocalDescriptors], Scene::[load=_load activate=_activate], Pass::[initPassFromTarget=_initPassFromTarget updatePassHash=_updatePassHash] @@ -105,7 +106,7 @@ getter_setter = Root::[device:_device mainWindow curWindow tempWindow windows sc RenderScene::[name cameras? mainLight? sphereLights? spotLights? models], Skybox::[model enabled/isEnabled/setEnabled useHDR/isUseHDR/setUseHDR useIBL/isUseIBL/setUseIBL useDiffuseMap/isUseDiffuseMap/setUseDiffuseMap isRGBE/isRGBE/setRGBE envmap diffuseMap], Fog::[enabled/isEnabled/setEnabled accurate/isAccurate/setAccurate fogColor type fogDensity fogStart fogEnd fogAtten fogTop fogRange fogRange colorArray], - Model::[scene _subModels:subModels/getSubModels inited/isInited _localDataUpdated/isLocalDataUpdated/setLocalDataUpdated _worldBounds:worldBounds/getWorldBounds/setWorldBounds _modelBounds:modelBounds/getModelBounds/setModelBounds worldBoundBuffer localBuffer updateStamp isInstancingEnabled/isInstancingEnabled receiveShadow/isReceiveShadow/setReceiveShadow castShadow/isCastShadow/setCastShadow shadowBias shadowNormalBias node transform visFlags enabled/isEnabled/setEnabled type instancedAttributes/getInstancedAttributeBlock/setInstancedAttributeBlock isDynamicBatching/isDynamicBatching/setDynamicBatching priority], + Model::[scene _subModels:subModels/getSubModels inited/isInited _localDataUpdated/isLocalDataUpdated/setLocalDataUpdated _worldBounds:worldBounds/getWorldBounds/setWorldBounds _modelBounds:modelBounds/getModelBounds/setModelBounds worldBoundBuffer localBuffer updateStamp receiveShadow/isReceiveShadow/setReceiveShadow castShadow/isCastShadow/setCastShadow shadowBias shadowNormalBias node transform visFlags enabled/isEnabled/setEnabled type isDynamicBatching/isDynamicBatching/setDynamicBatching priority], SubModel::[passes shaders subMesh priority inputAssembler descriptorSet patches planarInstanceShader planarShader], ShadowsInfo::[enabled/isEnabled/setEnabled type planeDirection planeHeight shadowColor maxReceived shadowMapSize], Shadows::[enabled/isEnabled/setEnabled type normal distance shadowColor maxReceived size shadowMapDirty/isShadowMapDirty/setShadowMapDirty matLight material instancingMaterial],