diff --git a/.eslintignore b/.eslintignore index ff804edfa6..ba715aa1c5 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1 +1,4 @@ *.jsb.ts +**/*.ems.ts +cocos/core/gfx/webgpu/**/* +cocos/webgpu/**/* \ No newline at end of file diff --git a/@types/url.d.ts b/@types/url.d.ts new file mode 100644 index 0000000000..5c529fa545 --- /dev/null +++ b/@types/url.d.ts @@ -0,0 +1,9 @@ +declare module 'url:native/external/emscripten/webgpu/webgpu_wasm.wasm' { + const url: string; + export default url; +} + +declare module 'url:native/external/emscripten/webgpu/glslang.wasm' { + const url: string; + export default url; +} diff --git a/EngineErrorMap.md b/EngineErrorMap.md index c58ef2da16..38b97f6e37 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -3284,6 +3284,10 @@ The shadow visible distance is so small that CSM stratification is not effective The native folder may be generated from older versions, please refer https://docs.cocos.com/creator/manual/en/release-notes/ to upgrade. +### 15100 + +Camera '%s' clear flag is skybox, but skybox is disabled, may cause strange background effect, please set camera clear flag to solid color. + ### 16000 '%s' is deprecated since v%s. diff --git a/cc.config.json b/cc.config.json index f2cca0cf7f..3c88283128 100644 --- a/cc.config.json +++ b/cc.config.json @@ -244,6 +244,13 @@ "cocos/3d/misc/create-mesh.ts": "cocos/3d/misc/create-mesh.jsb.ts" } }, + { + "test": "context.buildTimeConstants && context.buildTimeConstants.WEBGPU", + "isVirtualModule": false, + "overrides": { + "cocos/core/gfx/index.ts": "cocos/core/gfx/index.ems.ts" + } + }, { "test": "context.buildTimeConstants && context.buildTimeConstants.HTML5", "isVirtualModule": true, @@ -507,6 +514,12 @@ "type": "number", "value": 0, "internal": false + }, + "WEBGPU": { + "comment": "Running with webgpu rendering backend.", + "type": "boolean", + "value": false, + "internal": true } } } diff --git a/cocos/2d/components/label.ts b/cocos/2d/components/label.ts index 4aeaeec197..a578451a0e 100644 --- a/cocos/2d/components/label.ts +++ b/cocos/2d/components/label.ts @@ -308,28 +308,6 @@ export class Label extends UIRenderer { this.markForUpdateRenderData(); } - /** - * @en - * Font family of label, only take effect when useSystemFont property is true. - * - * @zh - * 文本字体名称, 只在 useSystemFont 属性为 true 的时候生效。 - */ - @displayOrder(8) - @visible(function (this: Label) { return !this._isSystemFontUsed; }) - @tooltip('i18n:label.font_family') - get fontFamily () { - return this._fontFamily; - } - set fontFamily (value) { - if (this._fontFamily === value) { - return; - } - - this._fontFamily = value; - this.markForUpdateRenderData(); - } - /** * @en * Line Height of label. @@ -418,6 +396,63 @@ export class Label extends UIRenderer { this.markForUpdateRenderData(); } + /** + * @en + * Whether use system font name or not. + * + * @zh + * 是否使用系统字体。 + */ + @displayOrder(12) + @tooltip('i18n:label.system_font') + get useSystemFont () { + return this._isSystemFontUsed; + } + set useSystemFont (value) { + if (this._isSystemFontUsed === value) { + return; + } + + this.destroyRenderData(); + + if (EDITOR) { + if (!value && this._isSystemFontUsed && this._userDefinedFont) { + this.font = this._userDefinedFont; + this.spacingX = this._spacingX; + return; + } + } + + this._isSystemFontUsed = !!value; + if (value) { + this.font = null; + } + this._flushAssembler(); + this.markForUpdateRenderData(); + } + + /** + * @en + * Font family of label, only take effect when useSystemFont property is true. + * + * @zh + * 文本字体名称, 只在 useSystemFont 属性为 true 的时候生效。 + */ + @displayOrder(13) + @visible(function (this: Label) { return this._isSystemFontUsed; }) + @tooltip('i18n:label.font_family') + get fontFamily () { + return this._fontFamily; + } + set fontFamily (value) { + if (this._fontFamily === value) { + return; + } + + this._fontFamily = value; + this.markForUpdateRenderData(); + } + /** * @en * The font of label. @@ -426,7 +461,7 @@ export class Label extends UIRenderer { * 文本字体。 */ @type(Font) - @displayOrder(12) + @displayOrder(13) @visible(function (this: Label) { return !this._isSystemFontUsed; }) @tooltip('i18n:label.font') get font () { @@ -456,41 +491,6 @@ export class Label extends UIRenderer { this.updateRenderData(true); } - /** - * @en - * Whether use system font name or not. - * - * @zh - * 是否使用系统字体。 - */ - @displayOrder(13) - @tooltip('i18n:label.system_font') - get useSystemFont () { - return this._isSystemFontUsed; - } - set useSystemFont (value) { - if (this._isSystemFontUsed === value) { - return; - } - - this.destroyRenderData(); - - if (EDITOR) { - if (!value && this._isSystemFontUsed && this._userDefinedFont) { - this.font = this._userDefinedFont; - this.spacingX = this._spacingX; - return; - } - } - - this._isSystemFontUsed = !!value; - if (value) { - this.font = null; - } - this._flushAssembler(); - this.markForUpdateRenderData(); - } - /** * @en * The cache mode of label. This mode only supports system fonts. diff --git a/cocos/2d/renderer/batcher-2d.ts b/cocos/2d/renderer/batcher-2d.ts index 6373f932c2..4b8bbcd99e 100644 --- a/cocos/2d/renderer/batcher-2d.ts +++ b/cocos/2d/renderer/batcher-2d.ts @@ -111,6 +111,13 @@ export class Batcher2D implements IBatcher { private _currIsStatic = false; private _currHash = 0; + //for middleware + private _currIsMiddleware = false; + private _middlewareEnableBatch = false; + private _middlewareBuffer: MeshBuffer | null = null; + private _middlewareIndexStart = 0; + private _middlewareIndexCount = 0; + private _pOpacity = 1; private _opacityDirty = 0; @@ -435,6 +442,7 @@ export class Batcher2D implements IBatcher { * @param tex - The texture used * @param mat - The material used * @param [transform] - The related node transform if the render data is based on node's local coordinates + * @deprecated since v3.6.2, please use [[commitMiddleware]] instead */ public commitIA (renderComp: UIRenderer, ia: InputAssembler, tex?: TextureBase, mat?: Material, transform?: Node) { // if the last comp is spriteComp, previous comps should be batched. @@ -468,6 +476,53 @@ export class Batcher2D implements IBatcher { this._batches.push(curDrawBatch); } + /** + * @en + * Render component data submission process for middleware2d components + * @zh + * 渲染组件中针对2D中间件组件渲染数据的提交流程 + * 例如:Spine 和 DragonBones 包含动态数据和材质的组件 + * @param comp - The committed renderable component + * @param meshBuffer - The MeshBuffer used + * @param indexOffset - indices offset + * @param indexCount - indices count + * @param tex - The texture used + * @param mat - The material used + * @param enableBatch - component support multi draw batch or not + */ + public commitMiddleware (comp: UIRenderer, meshBuffer: MeshBuffer, indexOffset: number, + indexCount: number, tex: TextureBase, mat: Material, enableBatch: boolean) { + // check if need merge draw batch + const texture = tex.getGFXTexture(); + if (enableBatch && this._middlewareEnableBatch && this._middlewareBuffer === meshBuffer + && this._currTexture === texture + && this._currMaterial.hash === mat.hash + && this._middlewareIndexStart + this._middlewareIndexCount === indexOffset + && this._currLayer === comp.node.layer) { + this._middlewareIndexCount += indexCount; + } else { + this.autoMergeBatches(this._currComponent!); + this.resetRenderStates(); + + this._currComponent = comp; + this._currTexture = texture; + this._currSampler = tex.getGFXSampler(); + this._currTextureHash = tex.getHash(); + this._currLayer = comp.node.layer; + this._currSamplerHash = this._currSampler.hash; + this._currHash = 0; + this._currTransform = enableBatch ? null : comp.node; + + this._middlewareEnableBatch = enableBatch; + this._middlewareBuffer = meshBuffer; + this._currMaterial = mat; + this._middlewareIndexStart = indexOffset; + this._middlewareIndexCount = indexCount; + } + + this._currIsMiddleware = true; + } + /** * @en * Render component data submission process of UI. @@ -561,6 +616,10 @@ export class Batcher2D implements IBatcher { * 根据合批条件,结束一段渲染数据并提交。 */ public autoMergeBatches (renderComp?: UIRenderer) { + if (this._currIsMiddleware) { + this.mergeBatchesForMiddleware(renderComp!); + return; + } const mat = this._currMaterial; if (!mat) { return; @@ -623,6 +682,36 @@ export class Batcher2D implements IBatcher { this._batches.push(curDrawBatch); } + private mergeBatchesForMiddleware (renderComp: UIRenderer) { + let depthStencil; + let dssHash = 0; + renderComp.stencilStage = StencilManager.sharedManager!.stage; + if (renderComp.customMaterial !== null) { + depthStencil = StencilManager.sharedManager!.getStencilStage(renderComp.stencilStage, this._currMaterial); + } else { + depthStencil = StencilManager.sharedManager!.getStencilStage(renderComp.stencilStage); + } + dssHash = StencilManager.sharedManager!.getStencilHash(renderComp.stencilStage); + + const curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._drawBatchPool.alloc(); + curDrawBatch.visFlags = renderComp.node.layer; + const ia = this._middlewareBuffer!.requireFreeIA(this.device); + ia.firstIndex = this._middlewareIndexStart; + ia.indexCount = this._middlewareIndexCount; + + curDrawBatch.inputAssembler = ia; + curDrawBatch.useLocalData = this._currTransform; + curDrawBatch.texture = this._currTexture; + curDrawBatch.sampler = this._currSampler; + curDrawBatch.textureHash = this._currTextureHash; + curDrawBatch.samplerHash = this._currSamplerHash; + curDrawBatch.fillPasses(this._currMaterial || null, depthStencil, dssHash, null); + this._batches.push(curDrawBatch); + + this._currIsMiddleware = false; + this._middlewareBuffer = null; + } + /** * @en * Force changes to current batch data and merge diff --git a/cocos/2d/renderer/mesh-buffer.ts b/cocos/2d/renderer/mesh-buffer.ts index e3c607b6d0..c9f76463bf 100644 --- a/cocos/2d/renderer/mesh-buffer.ts +++ b/cocos/2d/renderer/mesh-buffer.ts @@ -124,17 +124,6 @@ export class MeshBuffer { } } - protected _useLinkedData = false; - get useLinkedData () { - return this._useLinkedData; - } - set useLinkedData (val:boolean) { - if (JSB && this._useLinkedData !== val) { - this._nativeObj.useLinkData = val; - } - this._useLinkedData = val; - } - private _vertexFormatBytes = 0; private _initVDataCount = 0; private _initIDataCount = 0; @@ -193,7 +182,7 @@ export class MeshBuffer { // Initialize the first ia this._iaPool.push(this.createNewIA(device)); if (JSB) { - this._nativeObj.initialize(device, attrs, vFloatCount, iCount); + this._nativeObj.initialize(attrs); } } diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index c820dd45ad..4e843f70e1 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -69,12 +69,10 @@ export declare class NativeUIMeshBuffer { set vData(val: Float32Array); get iData(): Uint16Array; set iData(val: Uint16Array); - get useLinkData(): boolean; - set useLinkData(val: boolean); syncSharedBufferToNative(data: TypedArray); - initialize(device: Device, attrs: Attribute[], vFloatCount: number, iCount: number); + initialize(attrs: Attribute[]); reset(); destroy(); setDirty(); diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts index 0f721394a1..032c78f492 100644 --- a/cocos/2d/renderer/render-draw-info.ts +++ b/cocos/2d/renderer/render-draw-info.ts @@ -32,7 +32,7 @@ export enum AttrUInt32ArrayView { export enum RenderDrawInfoType { COMP, MODEL, - IA, + MIDDLEWARE, SUB_NODE, } diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index 97c38ce681..4ba72b5985 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/lights/directional-light-component.ts b/cocos/3d/lights/directional-light-component.ts index faf7353fac..55ce22caf6 100644 --- a/cocos/3d/lights/directional-light-component.ts +++ b/cocos/3d/lights/directional-light-component.ts @@ -115,6 +115,7 @@ export class DirectionalLight extends Light { * @en Whether activate real time shadow. * @zh 是否启用实时阴影? */ + @tooltip('i18n:lights.shadowEnabled') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 1 } }) @@ -134,6 +135,7 @@ export class DirectionalLight extends Light { * @en The shadow pcf for real time shadow. * @zh 实时阴影计算中的阴影 pcf 等级。 */ + @tooltip('i18n:lights.shadowPcf') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 5 } }) @@ -153,6 +155,7 @@ export class DirectionalLight extends Light { * @en The shadow map sampler offset for real time shadow. * @zh 实时阴影计算中的阴影纹理偏移值。 */ + @tooltip('i18n:lights.shadowBias') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 6 } }) @@ -172,6 +175,7 @@ export class DirectionalLight extends Light { * @en The global normal bias for real time shadow. * @zh 实时阴影计算中的法线偏移。 */ + @tooltip('i18n:lights.shadowNormalBias') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 7 } }) @@ -191,6 +195,7 @@ export class DirectionalLight extends Light { * @en The shadow color saturation for real time shadow. * @zh 实时阴影计算中的阴影颜色饱和度。 */ + @tooltip('i18n:lights.shadowSaturation') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 8 } }) @@ -213,6 +218,7 @@ export class DirectionalLight extends Light { * @en The potential shadow distance from the camera for real time shadow. * @zh 实时阴影计算中潜在阴影产生的范围 */ + @tooltip('i18n:lights.shadowDistance') @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type @@ -240,6 +246,7 @@ export class DirectionalLight extends Light { * @en The occlusion range for real time shadow. * @zh 实时阴影计算中剔除阴影的范围 */ + @tooltip('i18n:lights.shadowInvisibleOcclusionRange') @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type @@ -286,6 +293,7 @@ export class DirectionalLight extends Light { * @en enable csm * @zh 开启或关闭 csm 模式 */ + @tooltip('i18n:lights.enableCSM') @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type @@ -354,6 +362,7 @@ export class DirectionalLight extends Light { * @en Whether to use fixed area shadow in real time shadow. * @zh 实时阴影计算中是否使用固定区域阴影。 */ + @tooltip('i18n:lights.shadowFixedArea') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 15 } }) @@ -373,6 +382,7 @@ export class DirectionalLight extends Light { * @en The near clip plane of the shadow camera for fixed area shadow * @zh 固定区域阴影设置中阴影相机近裁剪面 */ + @tooltip('i18n:lights.shadowNear') @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type @@ -395,6 +405,7 @@ export class DirectionalLight extends Light { * @en The far clip plane of the shadow camera for fixed area shadow. * @zh 固定区域阴影设置中阴影相机远裁剪面。 */ + @tooltip('i18n:lights.shadowFar') @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type @@ -417,6 +428,7 @@ export class DirectionalLight extends Light { * @en The orthogonal size of the shadow camera for fixed area shadow. * @zh 固定区域阴影设置中阴影相机的正交尺寸 */ + @tooltip('i18n:lights.shadowOrthoSize') @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.enabled && (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type diff --git a/cocos/3d/lights/spot-light-component.ts b/cocos/3d/lights/spot-light-component.ts index 88d2a4cf82..e610a204b7 100644 --- a/cocos/3d/lights/spot-light-component.ts +++ b/cocos/3d/lights/spot-light-component.ts @@ -199,6 +199,7 @@ export class SpotLight extends Light { * @en Whether activate shadow * @zh 是否启用阴影? */ + @tooltip('i18n:lights.shadowEnabled') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 1 } }) @editable @@ -217,6 +218,7 @@ export class SpotLight extends Light { * @en The pcf level of the shadow generation. * @zh 获取或者设置阴影 pcf 等级。 */ + @tooltip('i18n:lights.shadowPcf') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 2 } }) @editable @@ -235,6 +237,7 @@ export class SpotLight extends Light { * @en The depth offset of shadow to avoid moire pattern artifacts * @zh 阴影的深度偏移, 可以减弱跨像素导致的条纹状失真 */ + @tooltip('i18n:lights.shadowBias') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 3 } }) @editable @@ -253,6 +256,7 @@ export class SpotLight extends Light { * @en The normal bias of the shadow map. * @zh 设置或者获取法线偏移。 */ + @tooltip('i18n:lights.shadowNormalBias') @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 4 } }) @editable diff --git a/cocos/3d/models/baked-skinning-model.ts b/cocos/3d/models/baked-skinning-model.ts index f29f9e6df8..0675421ddf 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 b79d9910d8..8f6d7fd7a2 100644 --- a/cocos/3d/models/skinning-model.ts +++ b/cocos/3d/models/skinning-model.ts @@ -41,6 +41,7 @@ import { warnID } from '../../core/platform/debug'; import { director } from '../../game'; import { PixelFormat } from '../../asset/assets/asset-enum'; import { Texture2D, ImageAsset } from '../../asset/assets'; +import { SubModel } from '../../render-scene'; const uniformPatches: IMacroPatch[] = [ { name: 'CC_USE_SKINNING', value: true }, @@ -264,12 +265,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/asset/asset-manager/builtin-res-mgr.jsb.ts b/cocos/asset/asset-manager/builtin-res-mgr.jsb.ts index d937075809..deebba9200 100644 --- a/cocos/asset/asset-manager/builtin-res-mgr.jsb.ts +++ b/cocos/asset/asset-manager/builtin-res-mgr.jsb.ts @@ -28,7 +28,7 @@ import { SpriteFrame } from '../../2d/assets/sprite-frame'; import type { ImageSource } from '../assets/image-asset'; import assetManager from '../asset-manager/asset-manager'; import { BuiltinBundleName } from '../asset-manager/shared'; -import { TEST } from 'internal:constants'; +import { TEST, EDITOR } from 'internal:constants'; import { Settings, settings } from '../../core/settings'; import releaseManager from '../asset-manager/release-manager'; @@ -118,7 +118,8 @@ builtinResMgrProto.loadBuiltinAssets = function () { assets.forEach((asset) => { resources[asset.name] = asset; const url = asset.nativeUrl; - releaseManager.addIgnoredAsset(asset); + // In Editor, no need to ignore asset destroy, we use auto gc to handle destroy + if (!EDITOR || legacyCC.GAME_VIEW) releaseManager.addIgnoredAsset(asset); this.addAsset(asset.name, asset); if (asset instanceof legacyCC.Material) { this._materialsToBeCompiled.push(asset); diff --git a/cocos/asset/asset-manager/builtin-res-mgr.ts b/cocos/asset/asset-manager/builtin-res-mgr.ts index 0840260d3f..836d8ab1a2 100644 --- a/cocos/asset/asset-manager/builtin-res-mgr.ts +++ b/cocos/asset/asset-manager/builtin-res-mgr.ts @@ -331,7 +331,8 @@ class BuiltinResMgr { } else { assets.forEach((asset) => { resources[asset.name] = asset; - releaseManager.addIgnoredAsset(asset); + // In Editor, no need to ignore asset destroy, we use auto gc to handle destroy + if (!EDITOR || legacyCC.GAME_VIEW) { releaseManager.addIgnoredAsset(asset); } if (asset instanceof legacyCC.Material) { this._materialsToBeCompiled.push(asset as Material); } diff --git a/cocos/asset/asset-manager/url-transformer.ts b/cocos/asset/asset-manager/url-transformer.ts index 2d1f611093..d563ac2f22 100644 --- a/cocos/asset/asset-manager/url-transformer.ts +++ b/cocos/asset/asset-manager/url-transformer.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ -import { EDITOR } from 'internal:constants'; +import { EDITOR, PREVIEW } from 'internal:constants'; import { legacyCC } from '../../core/global-exports'; import { warnID } from '../../core/platform/debug'; import { js } from '../../core/utils/js'; @@ -165,7 +165,7 @@ export function replaceOverrideAsset (task: Task) { const item = input[i] as RequestItem; if (assetsOverrideMap.has(item.uuid)) { const uuid = assetsOverrideMap.get(item.uuid)!; - if (EDITOR) { + if (EDITOR || PREVIEW) { // In EDITOR, there is no bundle, so just change uuid. item.overrideUuid = uuid; item.ext = item.isNative ? item.ext : '.json'; diff --git a/cocos/audio/audio-source.ts b/cocos/audio/audio-source.ts index ca184d819c..d6927e2a94 100644 --- a/cocos/audio/audio-source.ts +++ b/cocos/audio/audio-source.ts @@ -75,6 +75,17 @@ export class AudioSource extends Component { private _isLoaded = false; private _lastSetClip: AudioClip | null = null; + + private _resetPlayer () { + if (this._player) { + audioManager.removePlaying(this._player); + this._player.offEnded(); + this._player.offInterruptionBegin(); + this._player.offInterruptionEnd(); + this._player.destroy(); + this._player = null; + } + } /** * @en * The default AudioClip to be played for this audio source. @@ -101,6 +112,7 @@ export class AudioSource extends Component { } if (!clip) { this._lastSetClip = null; + this._resetPlayer(); return; } if (!clip._nativeAsset) { @@ -121,13 +133,7 @@ export class AudioSource extends Component { } this._isLoaded = true; // clear old player - if (this._player) { - audioManager.removePlaying(this._player); - this._player.offEnded(); - this._player.offInterruptionBegin(); - this._player.offInterruptionEnd(); - this._player.destroy(); - } + this._resetPlayer(); this._player = player; player.onEnded(() => { audioManager.removePlaying(player); diff --git a/cocos/core/gfx/index.ems.ts b/cocos/core/gfx/index.ems.ts new file mode 100644 index 0000000000..099d9db83a --- /dev/null +++ b/cocos/core/gfx/index.ems.ts @@ -0,0 +1,64 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +/** + * @packageDocumentation + * @module gfx + */ + +import { legacyCC } from '../global-exports'; +import { gfx, webgpuAdapter } from '../../webgpu/instantiated'; + +import './deprecated-3.0.0'; + +export { BlendState, PipelineStateInfo, RasterizerState, DepthStencilState, BlendTarget } from './base/pipeline-state' +export * from './base/define'; +export * from './device-manager'; + + +const polyfillCC: Record = { ...gfx }; +polyfillCC.Device = gfx.CCWGPUDevice; +polyfillCC.Swapchain = gfx.CCWGPUSwapchain; +polyfillCC.Buffer = gfx.CCWGPUBuffer; +polyfillCC.Texture = gfx.CCWGPUTexture; +polyfillCC.Sampler = gfx.CCWGPUSampler; +polyfillCC.Shader = gfx.CCWGPUShader; +polyfillCC.InputAssembler = gfx.CCWGPUInputAssembler; +polyfillCC.RenderPass = gfx.CCWGPURenderPass; +polyfillCC.Framebuffer = gfx.CCWGPUFramebuffer; +polyfillCC.DescriptorSet = gfx.CCWGPUDescriptorSet; +polyfillCC.DescriptorSetLayout = gfx.CCWGPUDescriptorSetLayout; +polyfillCC.PipelineLayout = gfx.CCWGPUPipelineLayout; +polyfillCC.PipelineState = gfx.CCWGPUPipelineState; +polyfillCC.CommandBuffer = gfx.CCWGPUCommandBuffer; +polyfillCC.Queue = gfx.CCWGPUQueue; +legacyCC.gfx = polyfillCC; + +export * from './webgpu/override'; +export * from './webgpu/webgpu-define' + +export const WGPU_WASM = true; + +console.log(gfx.Device); diff --git a/cocos/core/gfx/webgpu/override.ts b/cocos/core/gfx/webgpu/override.ts new file mode 100644 index 0000000000..c5a7cd92ed --- /dev/null +++ b/cocos/core/gfx/webgpu/override.ts @@ -0,0 +1,56 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions */ +/* eslint-disable import/no-mutable-exports */ +import { WEBGPU } from 'internal:constants'; +import { gfx, promiseForWebGPUInstantiation } from '../../../webgpu/instantiated'; + +export let Device: any; +export let WebGPUDevice: any; +export let Queue: any; +export let Swapchain: any; +export let Buffer: any; +export let Texture: any; +export let Shader: any; +export let Sampler: any; +export let InputAssembler: any; +export let RenderPass: any; +export let Framebuffer: any; +export let DescriptorSet: any; +export let DescriptorSetLayout: any; +export let PipelineLayout: any; +export let PipelineState: any; +export let CommandBuffer: any; +export let GeneralBarrier: any; +export let TextureBarrier: any; +export let BufferBarrier: any; + +WEBGPU && promiseForWebGPUInstantiation.then(() => { + Device = gfx.CCWGPUDevice; + WebGPUDevice = gfx.CCWGPUDevice; + Queue = gfx.CCWGPUQueue; + Swapchain = gfx.CCWGPUSwapchain; + Buffer = gfx.CCWGPUBuffer; + Texture = gfx.CCWGPUTexture; + Shader = gfx.CCWGPUShader; + Sampler = gfx.CCWGPUSampler; + InputAssembler = gfx.CCWGPUInputAssembler; + RenderPass = gfx.CCWGPURenderPass; + Framebuffer = gfx.CCWGPUFramebuffer; + DescriptorSet = gfx.CCWGPUDescriptorSet; + DescriptorSetLayout = gfx.CCWGPUDescriptorSetLayout; + PipelineLayout = gfx.CCWGPUPipelineLayout; + PipelineState = gfx.CCWGPUPipelineState; + CommandBuffer = gfx.CCWGPUCommandBuffer; + GeneralBarrier = gfx.WGPUGeneralBarrier; + TextureBarrier = gfx.WGPUTextureBarrier; + BufferBarrier = gfx.WGPUBufferBarrier; + + // immutable excluded + [Device, Queue, Swapchain, Buffer, Texture, Shader, InputAssembler, RenderPass, Framebuffer, DescriptorSet, + DescriptorSetLayout, PipelineState, CommandBuffer].forEach((ele) => { + const oldDestroy = ele.prototype.destroy; + ele.prototype.destroy = function () { + oldDestroy.call(this); + this.delete(); + }; + }); +}); diff --git a/cocos/core/gfx/webgpu/webgpu-define.ts b/cocos/core/gfx/webgpu/webgpu-define.ts new file mode 100644 index 0000000000..1924b9caf9 --- /dev/null +++ b/cocos/core/gfx/webgpu/webgpu-define.ts @@ -0,0 +1,597 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions */ +/* eslint-disable max-len */ +/* eslint-disable @typescript-eslint/no-unsafe-return */ +/* eslint-disable func-names */ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +import { WEBGPU } from 'internal:constants'; +import { gfx, webgpuAdapter, glslalgWasmModule, promiseForWebGPUInstantiation } from '../../../webgpu/instantiated'; +import { + Texture, CommandBuffer, DescriptorSet, Device, InputAssembler, Buffer, Shader +} from './override'; +import { + DeviceInfo, BufferTextureCopy, ShaderInfo, ShaderStageFlagBit, TextureViewInfo, TextureInfo, DrawInfo, BufferViewInfo, BufferInfo, +} from '../base/define'; + +WEBGPU && promiseForWebGPUInstantiation.then(() => { + const originDeviceInitializeFunc = Device.prototype.initialize; + Device.prototype.initialize = function (info: DeviceInfo) { + const adapter = webgpuAdapter.adapter; + const device = webgpuAdapter.device; + gfx.preinitializedWebGPUDevice = device; + device.lost.then((info) => { + console.error('Device was lost.', info); + throw new Error('Something bad happened'); + }); + console.log(adapter); + + originDeviceInitializeFunc.call(this, info); + + return true; + }; + + Device.prototype.flushCommands = function () { + }; + + const oldCreateTexture = Device.prototype.createTexture; + Device.prototype.createTexture = function (info: TextureInfo | TextureViewInfo) { + if ('texture' in info) { + return this.createTextureView(info); + } else { + return oldCreateTexture.call(this, info); + } + }; + + const oldCreateBuffer = Device.prototype.createBuffer; + Device.prototype.createBuffer = function (info: BufferInfo | BufferViewInfo) { + if ('buffer' in info) { + return this.createBufferView(info); + } else { + return oldCreateBuffer.call(this, info); + } + }; + + const oldDraw = CommandBuffer.prototype.draw; + CommandBuffer.prototype.draw = function (info: DrawInfo | typeof InputAssembler) { + if ('attributesHash' in info) { + return this.draw(info.drawInfo); + } else { + return this.drawByInfo(info); + } + }; + + const oldUpdateBuffer = Buffer.prototype.update; + Buffer.prototype.update = function (data: BufferSource, size?: number) { + const updateSize = size === undefined ? data.byteLength : size; + if ('buffer' in data) { + oldUpdateBuffer.call(this, new Uint8Array(data.buffer, data.byteOffset, data.byteLength), updateSize); + } else { + oldUpdateBuffer.call(this, new Uint8Array(data), updateSize); + } + }; + + const oldCmdUpdateBuffer = CommandBuffer.prototype.updateBuffer; + CommandBuffer.prototype.updateBuffer = function (buffer: typeof Buffer, data: BufferSource, size?: number) { + const updateSize = size === undefined ? data.byteLength : size; + + if ('buffer' in data) { + oldCmdUpdateBuffer.call(this, buffer, new Uint8Array(data.buffer, data.byteOffset, data.byteLength), updateSize); + } else { + oldCmdUpdateBuffer.call(this, buffer, new Uint8Array(data), updateSize); + } + }; + + const oldBindDescriptorSet = CommandBuffer.prototype.bindDescriptorSet; + CommandBuffer.prototype.bindDescriptorSet = function (set: number, descriptorSet: typeof DescriptorSet, dynamicOffsets?: Readonly) { + if (dynamicOffsets === undefined) { + oldBindDescriptorSet.call(this, set, descriptorSet, []); + } else if ('buffer' in dynamicOffsets) { + oldBindDescriptorSet.call(this, set, descriptorSet, new Uint32Array((dynamicOffsets as any).buffer, (dynamicOffsets as any).byteOffset, (dynamicOffsets as any).byteLength)); + } else { + oldBindDescriptorSet.call(this, set, descriptorSet, new Uint32Array(dynamicOffsets)); + } + }; + + const oldCmdCopyBuffersToTexture = CommandBuffer.prototype.copyBuffersToTexture; + CommandBuffer.prototype.copyBuffersToTexture = function (buffers: Readonly, texture: typeof Texture, regions: Readonly) { + const ucharBuffers: Uint8Array[] = []; + for (let i = 0; i < buffers.length; ++i) { + const buffer = buffers[i]; + if ('buffer' in buffer) { + ucharBuffers.push(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)); + } else { + ucharBuffers.push(new Uint8Array(buffer as any)); + } + } + oldCmdCopyBuffersToTexture.call(this, ucharBuffers, texture, regions); + }; + + const oldDeviceCopyBuffersToTexture = Device.prototype.copyBuffersToTexture; + Device.prototype.copyBuffersToTexture = function (buffers: Readonly, texture: typeof Texture, regions: Readonly) { + const ucharBuffers: Uint8Array[] = []; + for (let i = 0; i < buffers.length; ++i) { + const buffer = buffers[i]; + if ('buffer' in buffer) { + ucharBuffers.push(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)); + } else { + ucharBuffers.push(new Uint8Array(buffer as any)); + } + } + oldDeviceCopyBuffersToTexture.call(this, ucharBuffers, texture, regions); + }; + + Device.prototype.copyTexImagesToTexture = function (texImages: TexImageSource[], texture: typeof Texture, regions: BufferTextureCopy[]) { + const buffers: Uint8Array[] = []; + for (let i = 0; i < regions.length; i++) { + if ('getContext' in texImages[i]) { + const canvasElem = texImages[i] as HTMLCanvasElement; + const imageData = canvasElem.getContext('2d')?.getImageData(0, 0, texImages[i].width, texImages[i].height); + const buff = imageData!.data.buffer; + let data; + let rawBuffer; + if ('buffer' in buff) { + // es-lint as any + data = new Uint8Array((buff as any).buffer, (buff as any).byteOffset, (buff as any).byteLength); + } else { + rawBuffer = buff; + data = new Uint8Array(rawBuffer); + } + buffers[i] = data; + } else if (texImages[i] instanceof HTMLImageElement) { + const img = texImages[i] as HTMLImageElement; + const canvas = document.createElement('canvas'); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext('2d'); + ctx?.drawImage(img, 0, 0); + const imageData = ctx?.getImageData(0, 0, img.width, img.height); + const buff = imageData!.data.buffer; + let data; + let rawBuffer; + if ('buffer' in buff) { + // es-lint as any + data = new Uint8Array((buff as any).buffer, (buff as any).byteOffset, (buff as any).byteLength); + } else { + rawBuffer = buff; + data = new Uint8Array(rawBuffer); + } + buffers[i] = data; + } else { + console.log('imageBmp copy not impled!'); + } + } + + oldDeviceCopyBuffersToTexture.call(this, buffers, texture, regions); + }; + + function seperateCombinedSamplerTexture (shaderSource: string) { + // sampler and texture + const samplerTexturArr = shaderSource.match(/(.*?)\(set = \d+, binding = \d+\) uniform(.*?)sampler\w* \w+;/g); + const count = samplerTexturArr?.length ? samplerTexturArr?.length : 0; + let code = shaderSource; + + const referredFuncMap = new Map(); + const samplerSet = new Set(); + samplerTexturArr?.every((str) => { + let textureName = str.match(/(?<=uniform(.*?)sampler\w* )(\w+)(?=;)/g)!.toString(); + let samplerStr = str.replace(textureName, `${textureName}Sampler`); + let samplerFunc = samplerStr.match(/(?<=uniform(.*?))sampler(\w*)/g)!.toString(); + samplerFunc = samplerFunc.replace('sampler', ''); + if (samplerFunc === '') { + textureName = textureName.replace('Sampler', ''); + } else { + samplerStr = samplerStr.replace(/(?<=uniform(.*?))(sampler\w*)/g, 'sampler'); + + // layout (set = a, binding = b) uniform sampler2D cctex; + // to: + // layout (set = a, binding = b) uniform sampler cctexSampler; + // layout (set = a, binding = b + maxTextureNum) uniform texture2D cctex; + const samplerReg = /(?<=binding = )(\d+)(?=\))/g; + const samplerBindingStr = str.match(samplerReg)!.toString(); + const samplerBinding = Number(samplerBindingStr) + 16; + samplerStr = samplerStr.replace(samplerReg, samplerBinding.toString()); + + const textureStr = str.replace(/(?<=uniform(.*?))(sampler)(?=\w*)/g, 'texture'); + code = code.replace(str, `${textureStr}\n${samplerStr}`); + } + + if (!samplerSet.has(`${textureName}Sampler`)) { + samplerSet.add(`${textureName}Sampler`); + // gathering referred func + let referredFuncStr = `([\\w]+)[\\s]*\\([0-9a-zA-Z_\\s,]*?sampler${samplerFunc}[^\\)]+\\)[\\s]*{`; + if (samplerFunc === '') { + referredFuncStr = `([\\w]+)[\\s]*\\([0-9a-zA-Z_\\s,]*?sampler([\\S]+)[^\\)]+\\)[\\s]*{`; + } + const referredFuncRe = new RegExp(referredFuncStr, 'g'); + let reArr = referredFuncRe.exec(code); + while (reArr) { + // first to see if it's wrapped by #if 0 \n ... \n #ndif + let smpFunc = samplerFunc; + if (smpFunc === '') { + smpFunc = reArr[2]; + } + const searchTarget = code.slice(0, reArr.index); + const defValQueue: { str: string, b: boolean, condition: RegExpExecArray }[] = []; + let searchIndex = 1; + + while (searchIndex > 0) { + let ifIndex = searchTarget.indexOf('#if', searchIndex); + let elseIndex = searchTarget.indexOf('#else', searchIndex); + let endIndex = searchTarget.indexOf('#endif', searchIndex); + + if (ifIndex === -1 && elseIndex === -1 && endIndex === -1) { + break; + } + + if (ifIndex === -1) ifIndex = Number.MAX_SAFE_INTEGER; + if (elseIndex === -1) elseIndex = Number.MAX_SAFE_INTEGER; + if (endIndex === -1) endIndex = Number.MAX_SAFE_INTEGER; + + // next start with '#' is #if(def) + if (ifIndex < elseIndex && ifIndex < endIndex) { + const ifdef = (new RegExp(`#if(def)?[\\s]+(!)?([\\S]+)([\\s+]?(==)?(!=)[\\s+]?([\\S]+))?`, 'gm')).exec(searchTarget.slice(ifIndex))!; + defValQueue[defValQueue.length] = { str: ifdef[3], b: true, condition: ifdef }; + searchIndex = ifIndex + 1; + continue; + } + + if (elseIndex < endIndex && elseIndex < ifIndex) { + defValQueue[defValQueue.length - 1].b = false; + searchIndex = elseIndex + 1; + continue; + } + + if (endIndex < elseIndex && endIndex < ifIndex) { + defValQueue.pop(); + searchIndex = endIndex + 1; + continue; + } + } + + let defCheck = true; + for (let i = 0; i < defValQueue.length; i++) { + const ifdef = defValQueue[i].condition; + let evalRes = false; + if (ifdef[1]) { + evalRes = !!(new RegExp(`#define[\\s]+${ifdef[3]}`, 'gm')).exec(searchTarget); + } else { + const defVal = (new RegExp(`#define[\\s]+${ifdef[3]}[\\s]+([\\S]+).*`, 'gm')).exec(searchTarget)![1]; + if (ifdef[4]) { + const conditionVal = ifdef[7]; + evalRes = ifdef[5] ? defVal === conditionVal : defVal !== conditionVal; + } else if (ifdef[3]) { + evalRes = (defVal !== '0' && !ifdef[2]); + } + } + + if (defValQueue[i].b !== evalRes) { + defCheck = false; + break; + } + } + + const key = `${reArr[1]}_${smpFunc}_${textureName}Sampler`; + if (!referredFuncMap.has(key) && defCheck) { + referredFuncMap.set(key, [reArr[1], smpFunc, `${textureName}Sampler`]); + } + reArr = referredFuncRe.exec(code); + } + } + + // cctex in main() called directly + // .*?texture\( + const regStr = `texture\\(\\b(${textureName})\\b`; + const re = new RegExp(regStr); + let reArr = re.exec(code); + while (reArr) { + code = code.replace(re, `texture(sampler${samplerFunc}(${textureName},${textureName}Sampler)`); + reArr = re.exec(code); + } + return true; + }); + + const functionTemplates = new Map(); + const functionDeps = new Map(); + let forwardDecls = ''; + // function + referredFuncMap.forEach((pair) => { + //pre: if existed, replace + //getVec3DisplacementFromTexture\(cc_TangentDisplacements[^\\n]+ + const textureStr = pair[2].slice(0, -7); + const codePieceStr = `${pair[0]}\\((.*?)${textureStr}[^\\n]+`; + const codePieceRe = new RegExp(codePieceStr); + let res = codePieceRe.exec(code); + while (res) { + let replaceStr = res[0].replace(`${pair[0]}(`, `${pair[0]}_${pair[1]}_${pair[2]}_specialized(`); + replaceStr = replaceStr.replace(`${textureStr},`, ''); + code = code.replace(codePieceRe, replaceStr); + res = codePieceRe.exec(code); + } + + // 1. fn definition + const fnDeclReStr = `[\\n|\\W][\\w]+[\\W]+${pair[0]}[\\s]*\\((.*?)sampler${pair[1]}[^{]+`; + const fnDeclRe = new RegExp(fnDeclReStr); + const fnDecl = fnDeclRe.exec(code); + + let redefFunc = ''; + if (!functionTemplates.has(`${pair[0]}_${pair[1]}`)) { + const funcBodyStart = code.slice(fnDecl!.index); + + const funcRedefine = (funcStr: string) => { + const samplerType = `sampler${pair[1]}`; + const textureRe = (new RegExp(`.*?${samplerType}[\\s]+([\\S]+)[,\\)]`)).exec(funcStr)!; + const textureName = textureRe[1]; + const paramReStr = `${samplerType}[\\s]+${textureName}`; + let funcDef = funcStr.replace(new RegExp(paramReStr), `texture${pair[1]} ${textureName}`); + funcDef = funcDef.replace(pair[0], `${pair[0]}SAMPLER_SPEC`); + // 2. texture(...) inside, builtin funcs + const textureOpArr = ['texture', 'textureSize', 'texelFetch', 'textureLod']; + for (let i = 0; i < textureOpArr.length; i++) { + const texFuncReStr = `(${textureOpArr[i]})\\(${textureName},`; + const texFuncRe = new RegExp(texFuncReStr, 'g'); + funcDef = funcDef.replace(texFuncRe, `$1(${samplerType}(${textureName}TEXTURE_HOLDER, ${textureName}SAMPLER_HOLDER),`); + } + return funcDef; + }; + + const firstIfStatement = funcBodyStart.indexOf('#if'); + const firstElseStatement = funcBodyStart.indexOf('#e'); //#endif, #else, #elif maybe? + if ((firstElseStatement !== -1 && firstIfStatement > firstElseStatement) || (firstElseStatement === -1 && firstElseStatement !== -1)) { // ooops, now func body starts in a #if statement. + let startIndex = 0; + let count = 1; // already in #if + while (count > 0 && startIndex < funcBodyStart.length) { + const nextSymbolIdx = funcBodyStart.indexOf('#', startIndex); + const startSliceIdx = startIndex === 0 ? startIndex : startIndex - 1; + if (funcBodyStart[nextSymbolIdx + 1] === 'i') { // #if + count++; + redefFunc += funcBodyStart.slice(startSliceIdx, nextSymbolIdx); + } else if (funcBodyStart[nextSymbolIdx + 1] === 'e' && funcBodyStart[nextSymbolIdx + 2] === 'l') { //#elif, #else + if (count === 1) { + const tempFuncStr = funcBodyStart.slice(startSliceIdx, nextSymbolIdx - 1); + const funcDefStr = funcRedefine(tempFuncStr); + redefFunc += `\n${funcDefStr}`; + } else { + redefFunc += `\n${funcBodyStart.slice(startSliceIdx, nextSymbolIdx)}`; + } + } else if (funcBodyStart[nextSymbolIdx + 1] === 'e' && funcBodyStart[nextSymbolIdx + 2] === 'n') { //#endif + count--; + if (count === 0) { + const tempFuncStr = funcBodyStart.slice(startSliceIdx, nextSymbolIdx - 1); + const funcDefStr = funcRedefine(tempFuncStr); + redefFunc += `\n${funcDefStr}`; + } else { + redefFunc += `\n${funcBodyStart.slice(startSliceIdx, nextSymbolIdx)}`; + } + } else { // #define, dont care + redefFunc += funcBodyStart.slice(startSliceIdx, nextSymbolIdx); + } + startIndex = nextSymbolIdx + 1; + } + + //`(?:.(?!layout))+${pair[2]};` + const searchTarget = code.slice(0, fnDecl!.index); + const res = (new RegExp(`#if.+[\\s]*$`)).exec(searchTarget); + redefFunc = `${res![0]}${redefFunc}\n#endif`; + } else { + let count = 0; + let matchBegin = false; + let startIndex = 0; + let endIndex = 0; + for (let i = 0; i < funcBodyStart.length; ++i) { + if (funcBodyStart[i] === '{') { + ++count; + if (!matchBegin) { + matchBegin = true; + startIndex = i; + } + } else if (funcBodyStart[i] === '}') { + --count; + } + + if (matchBegin && count === 0) { + endIndex = i; + break; + } + } + const rawFunc = `${fnDecl![0]}${funcBodyStart.slice(startIndex, endIndex + 1)}`; + redefFunc = funcRedefine(rawFunc); + } + + functionTemplates.set(`${pair[0]}_${pair[1]}`, redefFunc); + } else { + redefFunc = functionTemplates.get(`${pair[0]}_${pair[1]}`)!; + } + + const depsFuncs: string[] = []; + + const iterator = referredFuncMap.values(); + let val = iterator.next().value; + while (val) { + const funcDepReStr = `\\b(${val[0] as string})\\b`; + if (redefFunc.search(funcDepReStr) !== -1) { + depsFuncs[depsFuncs.length] = val[0]; + } + val = iterator.next().value; + } + // for (let i = 0; i < referredFuncMap.values.length; ++i) { + // const funcDepReStr = `\\b(${referredFuncMap.values[i].fnName as string})\\b`; + // if (redefFunc.search(funcDepReStr) !== -1) { + // depsFuncs[depsFuncs.length] = referredFuncMap.values[i].fnName; + // } + // } + functionDeps.set(`${pair[0]}_${pair[1]}`, depsFuncs); + + const specializedFuncs = new Map(); + const specialize = (funcs: string[]) => { + funcs.every((str) => { + if (!specializedFuncs.has(`${pair[0]}_${pair[2]}_specialized`)) { + const samplerReStr = `(\\w+)SAMPLER_HOLDER`; + const textureName = pair[2].slice(0, pair[2].length - 7); // xxxxSampler + const textureStr = `(\\w+)TEXTURE_HOLDER`; + let funcTemplate = functionTemplates.get(str); + funcTemplate = funcTemplate!.replace(new RegExp(samplerReStr, 'g'), pair[2]); + funcTemplate = funcTemplate.replace(new RegExp(textureStr, 'g'), textureName); + funcTemplate = funcTemplate.replace(new RegExp('SAMPLER_SPEC', 'g'), `_${pair[1]}_${pair[2]}_specialized`); + funcTemplate = funcTemplate.replace(new RegExp(`texture${pair[1]}\\s+\\w+,`, 'g'), ''); + // funcTemplate = funcTemplate.replace('SAMPLER_SPEC', `_${pair[2]}_specialized`); + + for (let i = 0; i < depsFuncs.length; ++i) { + const depFuncStr = `${depsFuncs[i]}([\\W]?)*\\([^,)]+(,)?`; + funcTemplate = funcTemplate.replace(new RegExp(depFuncStr, 'g'), `${depsFuncs[i]}_${pair[1]}_${pair[2]}_specialized(`); + } + + let declStr = fnDecl![0].replace(pair[0], `${str}_${pair[2]}_specialized`); + declStr = declStr.replace(new RegExp(`sampler${pair[1]}[^,)]+(,)?`, 'g'), ``); + declStr += `;`; + specializedFuncs.set(declStr, funcTemplate); + } else { + return specialize(functionDeps.get(str)!); + } + return true; + }); + return true; + }; + specialize([`${pair[0]}_${pair[1]}`]); + //(?:.(?!layout))+cc_PositionDisplacementsSampler; + const samplerDefReStr = `(?:.(?!layout))+${pair[2]};`; + const samplerDef = (new RegExp(samplerDefReStr)).exec(code); + + let funcImpls = ''; + for (const [key, value] of specializedFuncs) { + forwardDecls += `\n${key}\n`; + funcImpls += `\n${value}\n`; + } + + code = code.replace(samplerDef![0], `${samplerDef![0]}\n${funcImpls}`); + }); + + // some function appears before it's defined so forward declaration is needed + forwardDecls += '\nvec3 SRGBToLinear (vec3 gamma);\nfloat getDisplacementWeight(int index);\n'; + + const highpIdx = code.indexOf('precision highp'); + const mediumpIdx = code.indexOf('precision mediump'); + const lowpIdx = code.indexOf('precision lowp'); + + /////////////////////////////////////////////////////////// + // isNan, isInf has been removed in dawn:tint + + let functionDefs = ''; + const precisionKeyWord = 'highp'; + + // const getPrecision = (idx: number) => { + // if (highpIdx !== -1 && highpIdx < idx) { + // precisionKeyWord = 'highp'; + // } else if (mediumpIdx !== -1 && mediumpIdx < idx && highpIdx < mediumpIdx) { + // precisionKeyWord = 'mediump'; + // } else if (lowpIdx !== -1 && lowpIdx < idx && mediumpIdx < lowpIdx && highpIdx < lowpIdx) { + // precisionKeyWord = 'lowp'; + // } + // }; + + const isNanIndex = code.indexOf('isnan'); + if (isNanIndex !== -1) { + // getPrecision(isNanIndex); + functionDefs += `\n + bool isNan(${precisionKeyWord} float val) { + return (val < 0.0 || 0.0 < val || val == 0.0) ? false : true; + } + \n`; + code = code.replace(/isnan\(/gi, 'isNan('); + } + + const isInfIndex = code.indexOf('isinf'); + if (isInfIndex !== -1) { + // getPrecision(isInfIndex); + functionDefs += `\n + bool isInf(${precisionKeyWord} float x) { + return x == x * 2.0 && x != 0.0; + } + \n`; + code = code.replace(/isinf\(/gi, 'isInf('); + } + + /////////////////////////////////////////////////////////// + + let firstPrecisionIdx = code.indexOf('precision'); + firstPrecisionIdx = code.indexOf(';', firstPrecisionIdx); + firstPrecisionIdx += 1; + code = `${code.slice(0, firstPrecisionIdx)}\n${forwardDecls}\n${functionDefs}\n${code.slice(firstPrecisionIdx)}`; + + return code; + } + + const createShader = Device.prototype.createShader; + Device.prototype.createShader = function (shaderInfo: ShaderInfo) { + const spvDatas: any = []; + for (let i = 0; i < shaderInfo.stages.length; ++i) { + shaderInfo.stages[i].source = seperateCombinedSamplerTexture(shaderInfo.stages[i].source); + const stageStr = shaderInfo.stages[i].stage === ShaderStageFlagBit.VERTEX ? 'vertex' + : shaderInfo.stages[i].stage === ShaderStageFlagBit.FRAGMENT ? 'fragment' : 'compute'; + const sourceCode = `#version 450\n${shaderInfo.stages[i].source}`; + const spv = glslalgWasmModule.glslang.compileGLSL(sourceCode, stageStr, true, '1.3'); + spvDatas.push(spv); + } + + const shader = this.createShaderNative(shaderInfo, spvDatas); + return shader; + }; + + // if property being frequently get in TS, try cache it + // attention: invalid if got this object from a native object, + // eg. inputAssembler.indexBuffer.objectID + function cacheReadOnlyWGPUProperties (type: T, props: string[]) { + const descriptor = { writable: true }; + props.map((prop) => { + return Object.defineProperty(type['prototype'], `_${prop}`, descriptor); + }); + + // trick for emscripten object only, which contains a `name` indicates what type it is. + const typename = type['name'].replace('CCWGPU', ''); + const oldCreate = Device.prototype[`create${typename}`]; + Device.prototype[`create${typename}`] = function (info) { + const res = oldCreate.call(this, info); + for (let prop of props) { + res[`_${prop}`] = res[`${prop}`]; + Object.defineProperty(res, `${prop}`, { + get () { + return this[`_${prop}`]; + } + }); + } + return res; + } + const oldInit = type['prototype']['initialize']; + type['prototype']['initialize'] = function (info) { + oldInit.call(this, info); + for (let prop of props) { + this[`_${prop}`] = this[`${prop}`]; + } + } + }; + + cacheReadOnlyWGPUProperties(Buffer, ['objectID']); + +}); diff --git a/cocos/core/global-exports.ts b/cocos/core/global-exports.ts index 846e52c310..752121a0b3 100644 --- a/cocos/core/global-exports.ts +++ b/cocos/core/global-exports.ts @@ -47,7 +47,7 @@ if (DEV) { legacyCC._Test = {}; } -const engineVersion = '3.6.1'; +const engineVersion = '3.6.2'; /** * The current version of Cocos2d being used.
diff --git a/cocos/core/math/color.ts b/cocos/core/math/color.ts index 1a5f826ffb..81324a4f0e 100644 --- a/cocos/core/math/color.ts +++ b/cocos/core/math/color.ts @@ -29,7 +29,8 @@ import { ValueType } from '../value-types/value-type'; import { IColorLike } from './type-define'; import { clamp, EPSILON } from './utils'; import { legacyCC } from '../global-exports'; -import { mixin } from '../utils/js-typed'; +import { assertIsTrue } from '../data/utils/asserts'; +import { Vec4 } from './vec4'; const toFloat = 1 / 255; @@ -88,7 +89,41 @@ export class Color extends ValueType { out.a = a; return out; } - + /** + * @en Convert 8bit color to Vec4 + * @zh 将当前颜色转换为到 Vec4 + * @returns Vec4 as float color value + * @example + * ``` + * const color = Color.YELLOW; + * color.toVec4(); + * ``` + */ + public static toVec4 (color:Color, out?: Vec4): Vec4 { + out = out !== undefined ? out : new Vec4(); + out.x = srgb8BitToLinear(color.r); + out.y = srgb8BitToLinear(color.g); + out.z = srgb8BitToLinear(color.b); + out.w = srgb8BitToLinear(color.a); + return out; + } + /** + * @en Set 8bit Color from Vec4 + * @zh 使用 Vec4 设置 8 bit 颜色 + * @returns 8 Bit srgb value + * @example + * ``` + * color.fromVec4(new Vec4(1,1,1,1)); + * ``` + */ + public static fromVec4 (value: Vec4, out?: Color): Color { + out = out === undefined ? new Color() : out; + out.r = linearToSrgb8Bit(value.x); + out.g = linearToSrgb8Bit(value.y); + out.b = linearToSrgb8Bit(value.z); + out.a = linearToSrgb8Bit(value.w); + return out; + } /** * @en Converts the hexadecimal formal color into rgb formal and save the results to out color. * @zh 从十六进制颜色字符串中读入颜色到 out 中 @@ -382,11 +417,7 @@ export class Color extends ValueType { * @returns A string representation of the current color. */ public toString () { - return `rgba(${ - this.r.toFixed()}, ${ - this.g.toFixed()}, ${ - this.b.toFixed()}, ${ - this.a.toFixed()})`; + return `rgba(${this.r.toFixed()}, ${this.g.toFixed()}, ${this.b.toFixed()}, ${this.a.toFixed()})`; } /** @@ -406,16 +437,9 @@ export class Color extends ValueType { */ public toCSS (opt: ('rgba' | 'rgb' | '#rrggbb' | '#rrggbbaa') = 'rgba') { if (opt === 'rgba') { - return `rgba(${ - this.r},${ - this.g},${ - this.b},${ - (this.a * toFloat).toFixed(2)})`; + return `rgba(${this.r},${this.g},${this.b},${(this.a * toFloat).toFixed(2)})`; } else if (opt === 'rgb') { - return `rgb(${ - this.r},${ - this.g},${ - this.b})`; + return `rgb(${this.r},${this.g},${this.b})`; } else { return `#${this.toHEX(opt)}`; } @@ -519,6 +543,9 @@ export class Color extends ValueType { const q = v * (1 - (s * f)); const t = v * (1 - (s * (1 - f))); switch (i) { + default: + assertIsTrue(false); + // eslint-disable-next-line no-fallthrough case 0: r = v; g = t; @@ -691,3 +718,37 @@ export function color (r?: number | Color | string, g?: number, b?: number, a?: } legacyCC.color = color; + +export function srgbToLinear (x: number): number { + if (x <= 0) return 0; + else if (x >= 1) return 1; + else if (x < 0.04045) return x / 12.92; + else return ((x + 0.055) / 1.055) ** 2.4; +} + +export function srgb8BitToLinear (x: number): number { + if ((x | 0) !== x || (x >>> 8) !== 0) { throw new RangeError('Value out of 8-bit range'); } + return SRGB_8BIT_TO_LINEAR[x]; +} + +export function linearToSrgb (x: number): number { + if (x <= 0) return 0; + else if (x >= 1) return 1; + else if (x < 0.0031308) return x * 12.92; + else return x ** (1 / 2.4) * 1.055 - 0.055; +} + +export function linearToSrgb8Bit (x: number): number { + if (x <= 0) { return 0; } + const TABLE: Array = SRGB_8BIT_TO_LINEAR; + if (x >= 1) { return TABLE.length - 1; } + let y = 0; + for (let i = TABLE.length >>> 1; i !== 0; i >>>= 1) { + if (TABLE[y | i] <= x) { y |= i; } + } + if (x - TABLE[y] <= TABLE[y + 1] - x) { return y; } else { return y + 1; } +} + +// use table for more consistent conversion between uint8 and float, offline processes only. +let SRGB_8BIT_TO_LINEAR: Array = []; +for (let i = 0; i < 256; i++) { SRGB_8BIT_TO_LINEAR.push(srgbToLinear(i / 255.0)); } diff --git a/cocos/dragon-bones/ArmatureDisplay.ts b/cocos/dragon-bones/ArmatureDisplay.ts index c09be96d2b..4998dff8fa 100644 --- a/cocos/dragon-bones/ArmatureDisplay.ts +++ b/cocos/dragon-bones/ArmatureDisplay.ts @@ -44,7 +44,7 @@ import { ArmatureSystem } from './ArmatureSystem'; import { Batcher2D } from '../2d/renderer/batcher-2d'; import { RenderEntity, RenderEntityType } from '../2d/renderer/render-entity'; import { RenderDrawInfo } from '../2d/renderer/render-draw-info'; -import { Material, Texture2D } from '../asset/assets'; +import { Material, Texture2D, builtinResMgr } from '../asset/assets'; import { Node } from '../scene-graph'; enum DefaultArmaturesEnum { @@ -392,6 +392,20 @@ export class ArmatureDisplay extends UIRenderer { this._updateDebugDraw(); } + /* + * @en Enabled batch model, if mesh is complex, do not enable batch, or will lower performance. + * @zh 开启合批,如果渲染大量相同纹理,且结构简单的龙骨动画,开启合批可以降低drawcall,否则请不要开启,cpu消耗会上升。 + */ + @tooltip('i18n:COMPONENT.dragon_bones.enabled_batch') + @editable + get enableBatch () { return this._enableBatch; } + set enableBatch (value) { + if (value !== this._enableBatch) { + this._enableBatch = value; + this._updateBatch(); + } + } + /** * @en * The bone sockets this animation component maintains.
@@ -446,6 +460,10 @@ export class ArmatureDisplay extends UIRenderer { @serializable protected _debugBones = false; + + @serializable + protected _enableBatch = false; + /* protected */ _debugDraw: Graphics | null = null; // DragonBones data store key. @@ -573,20 +591,29 @@ export class ArmatureDisplay extends UIRenderer { super.destroyRenderData(); } + private getMaterialTemplate () : Material { + let material = this.customMaterial; + if (material === null) { + material = builtinResMgr.get('default-spine-material'); + } + return material; + } + public getMaterialForBlend (src: BlendFactor, dst: BlendFactor): MaterialInstance { const key = `${src}/${dst}`; let inst = this._materialCache[key]; if (inst) { return inst; } - const material = this.getMaterial(0)!; + const material = this.getMaterialTemplate(); const matInfo = { parent: material, subModelIdx: 0, owner: this, }; + inst = new MaterialInstance(matInfo); - inst.recompileShaders({ USE_LOCAL: true }, 0); // TODO: not supported by ui + inst.recompileShaders({ TWO_COLORED: false, USE_LOCAL: false }); this._materialCache[key] = inst; inst.overridePipelineStates({ blendState: { @@ -613,6 +640,7 @@ export class ArmatureDisplay extends UIRenderer { } protected _render (batcher: Batcher2D) { + let indicesCount = 0; if (this.renderData && this._drawList) { const rd = this.renderData; const chunk = rd.chunk; @@ -620,20 +648,17 @@ export class ArmatureDisplay extends UIRenderer { const meshBuffer = rd.getMeshBuffer()!; const origin = meshBuffer.indexOffset; // Fill index buffer - accessor.appendIndices(chunk.bufferId, rd.indices!); for (let i = 0; i < this._drawList.length; i++) { this._drawIdx = i; const dc = this._drawList.data[i]; if (dc.texture) { - // Construct IA - const ia = meshBuffer.requireFreeIA(batcher.device); - ia.firstIndex = origin + dc.indexOffset; - ia.indexCount = dc.indexCount; - // Commit IA - batcher.commitIA(this, ia, dc.texture, dc.material!, this.node); + batcher.commitMiddleware(this, meshBuffer, origin + dc.indexOffset, + dc.indexCount, dc.texture, dc.material!, this._enableBatch); } + indicesCount += dc.indexCount; } - // this.node._static = true; + const subIndices = rd.indices!.subarray(0, indicesCount); + accessor.appendIndices(chunk.bufferId, subIndices); } } @@ -874,6 +899,11 @@ export class ArmatureDisplay extends UIRenderer { this.markForUpdateRenderData(); } + protected _updateBatch () { + this._cleanMaterialCache(); + this.markForUpdateRenderData(); + } + _buildArmature () { if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) return; @@ -1341,7 +1371,7 @@ export class ArmatureDisplay extends UIRenderer { protected createRenderEntity () { const renderEntity = new RenderEntity(RenderEntityType.DYNAMIC); - renderEntity.setUseLocal(true); + renderEntity.setUseLocal(false); return renderEntity; } diff --git a/cocos/dragon-bones/assembler/simple.ts b/cocos/dragon-bones/assembler/simple.ts index 29b909ffb0..074bd59e50 100644 --- a/cocos/dragon-bones/assembler/simple.ts +++ b/cocos/dragon-bones/assembler/simple.ts @@ -24,7 +24,7 @@ */ import { Armature, BlendMode } from '@cocos/dragonbones-js'; -import { Color, Mat4 } from '../../core'; +import { Color, Mat4, Vec3 } from '../../core'; import { BlendFactor } from '../../gfx'; import { vfmtPosUvColor } from '../../2d/renderer/vertex-format'; import { MaterialInstance } from '../../render-scene/core/material-instance'; @@ -77,18 +77,10 @@ let _prevDrawIndexOffset = 0; const LOCAL_FLOAT_PER_VERTEX = 4; //xyuv const PER_VERTEX_SIZE = 3 + 2 + 4; //xyz-uv-rgba; -let _x: number; -let _y: number; const _c = new Float32Array(4); let _handleVal: number; -let _m00: number; -let _m04: number; -let _m12: number; -let _m01: number; -let _m05: number; -let _m13: number; +const _tempVecPos = new Vec3(0, 0, 0); const _slotMat = new Mat4(); -let _batcher: Batcher2D; let _currentMaterial: MaterialInstance | null = null; let _currentTexture: Texture2D | null = null; @@ -274,20 +266,17 @@ function realTimeTraverse (armature: Armature, parentOpacity: number, worldMat?: } } - _m00 = _slotMat.m00; - _m04 = _slotMat.m04; - _m12 = _slotMat.m12; - _m01 = _slotMat.m01; - _m05 = _slotMat.m05; - _m13 = _slotMat.m13; // vertext format: // x y z u v r g b a for (let vi = 0, vl = vertices.length, v = _vertexFloatOffset; vi < vl; v += PER_VERTEX_SIZE) { - _x = vertices[vi++]; - _y = vertices[vi++]; + _tempVecPos.x = vertices[vi++]; + _tempVecPos.y = vertices[vi++]; + _tempVecPos.z = 0; + _tempVecPos.transformMat4(_slotMat); - _vbuf[v] = _x * _m00 + _y * _m04 + _m12; // x - _vbuf[v + 1] = _x * _m01 + _y * _m05 + _m13; // y + _vbuf[v] = _tempVecPos.x; + _vbuf[v + 1] = _tempVecPos.y; + _vbuf[v + 2] = _tempVecPos.z; _vbuf[v + 3] = vertices[vi++]; // u _vbuf[v + 4] = vertices[vi++]; // v @@ -332,14 +321,6 @@ function cacheTraverse (frame: ArmatureFrame | null, parentMat?: Mat4) { let frameVFOffset = 0; let frameIndexOffset = 0; let segVFCount = 0; - if (parentMat) { - _m00 = parentMat.m00; - _m01 = parentMat.m01; - _m04 = parentMat.m04; - _m05 = parentMat.m05; - _m12 = parentMat.m12; - _m13 = parentMat.m13; - } let colorOffset = 0; const colors = frame.colors; @@ -385,10 +366,13 @@ function cacheTraverse (frame: ArmatureFrame | null, parentMat?: Mat4) { let offset = 0; if (parentMat) { for (let ii = 0, il = _vertexCount; ii < il; ii++) { - _x = vbuf[offset]; - _y = vbuf[offset + 1]; - vbuf[offset] = _x * _m00 + _y * _m04 + _m12; - vbuf[offset + 1] = _x * _m01 + _y * _m05 + _m13; + _tempVecPos.x = vbuf[offset]; + _tempVecPos.y = vbuf[offset + 1]; + _tempVecPos.z = 0; + _tempVecPos.transformMat4(parentMat); + vbuf[offset] = _tempVecPos.x; + vbuf[offset + 1] = _tempVecPos.y; + vbuf[offset + 2] = _tempVecPos.z; offset += PER_VERTEX_SIZE; } } @@ -445,7 +429,7 @@ function updateComponentRenderData (comp: ArmatureDisplay, batcher: Batcher2D) { _handleVal |= NEED_COLOR; } - let worldMat: Mat4 | undefined; + const worldMat = comp.node.getWorldMatrix(); _vertexFloatCount = 0; _vertexOffset = 0; @@ -456,7 +440,6 @@ function updateComponentRenderData (comp: ArmatureDisplay, batcher: Batcher2D) { _actualVCount = _comp.maxVertexCount; _actualICount = _comp.maxIndexCount; - _batcher = batcher; if (comp.isAnimationCached()) { // Traverse input assembler. cacheTraverse(comp._curFrame, worldMat); diff --git a/cocos/game/director.ts b/cocos/game/director.ts index 3497a11c77..8b3b7dc011 100644 --- a/cocos/game/director.ts +++ b/cocos/game/director.ts @@ -441,10 +441,6 @@ export class Director extends EventTarget { assertID(scene, 1205); assertID(scene instanceof Scene, 1216); - // ensure scene initialized - // @ts-expect-error run private method - scene._load(); - // Delay run / replace scene to the end of the frame this.once(Director.EVENT_END_FRAME, () => { this.runSceneImmediate(scene, onBeforeLoadScene, onLaunched); diff --git a/cocos/game/game.ts b/cocos/game/game.ts index 516f06fe45..a45fd05745 100644 --- a/cocos/game/game.ts +++ b/cocos/game/game.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ -import { DEBUG, EDITOR, NATIVE, PREVIEW } from 'internal:constants'; +import { DEBUG, EDITOR, NATIVE, PREVIEW, WEBGPU } from 'internal:constants'; import { systemInfo } from 'pal/system-info'; import { findCanvas, loadJsFile } from 'pal/env'; import { Pacer } from 'pal/pacer'; @@ -84,7 +84,7 @@ export interface IGameConfig { * You can pass in parameters in game.init or override them in the [game.onPostBaseInitDelegate] event callback. * Note: you need to specify this option in the application.js template or add a delegate callback. */ - overrideSettings : Partial<{ [ k in Settings.Category[keyof Settings.Category] ]: Record }> + overrideSettings: Partial<{ [k in Settings.Category[keyof Settings.Category]]: Record }> /** * @zh @@ -602,8 +602,8 @@ export class Game extends EventTarget { public on (type: string, callback: () => void, target?: any, once?: boolean): any { // Make sure EVENT_ENGINE_INITED callbacks to be invoked if ((this._engineInited && type === Game.EVENT_ENGINE_INITED) - || (this._inited && type === Game.EVENT_GAME_INITED) - || (this._rendererInitialized && type === Game.EVENT_RENDERER_INITED)) { + || (this._inited && type === Game.EVENT_GAME_INITED) + || (this._rendererInitialized && type === Game.EVENT_RENDERER_INITED)) { callback.call(target); } return this.eventTargetOn(type, callback, target, once); @@ -686,17 +686,6 @@ export class Game extends EventTarget { if (DEBUG) { console.timeEnd('Init Base'); } - - if (sys.isXR) { - // XrEntry must not be destroyed - xr.entry = xr.XrEntry.getInstance(); - - const xrMSAA = settings.querySettings(Settings.Category.RENDERING, 'msaa') ?? 1; - const xrRenderingScale = settings.querySettings(Settings.Category.RENDERING, 'renderingScale') ?? 1.0; - xr.entry.setMultisamplesRTT(xrMSAA); - xr.entry.setRenderingScale(xrRenderingScale); - } - this.emit(Game.EVENT_POST_BASE_INIT); return this.onPostBaseInitDelegate.dispatch(); }) @@ -711,6 +700,7 @@ export class Game extends EventTarget { console.time('Init Infrastructure'); } macro.init(); + this._initXR(); const adapter = findCanvas(); if (adapter) { this.canvas = adapter.canvas; @@ -785,6 +775,7 @@ export class Game extends EventTarget { return Promise.resolve([]); }) .then(() => this._loadProjectBundles()) + .then(() => this._loadCCEScripts()) .then(() => this._setupRenderPipeline()) .then(() => this._loadPreloadAssets()) .then(() => { @@ -805,6 +796,18 @@ export class Game extends EventTarget { }); } + private _initXR () { + if (sys.isXR) { + // XrEntry must not be destroyed + xr.entry = xr.XrEntry.getInstance(); + + const xrMSAA = settings.querySettings(Settings.Category.RENDERING, 'msaa') ?? 1; + const xrRenderingScale = settings.querySettings(Settings.Category.RENDERING, 'renderingScale') ?? 1.0; + xr.entry.setMultisamplesRTT(xrMSAA); + xr.entry.setRenderingScale(xrRenderingScale); + } + } + private _compatibleWithOldParams (config: IGameConfig) { const overrideSettings = config.overrideSettings = config.overrideSettings || {}; if ('showFPS' in config) { @@ -859,6 +862,21 @@ export class Game extends EventTarget { }))); } + /** + * @internal only for browser preview + */ + private _loadCCEScripts () { + return new Promise((resolve, reject) => { + // Since there is no script in the bundle during preview, we need to load the user's script in the following way + if (PREVIEW && !TEST && !EDITOR && !NATIVE) { + const bundneName = 'cce:/internal/x/prerequisite-imports'; + import(bundneName).then(() => resolve(), (reason) => reject(reason)); + } else { + resolve(); + } + }); + } + /** * @internal only for game-view */ diff --git a/cocos/gfx/device-manager.ts b/cocos/gfx/device-manager.ts index 9400786134..2d66aaf237 100644 --- a/cocos/gfx/device-manager.ts +++ b/cocos/gfx/device-manager.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-len */ /* Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. @@ -23,7 +24,7 @@ THE SOFTWARE. */ -import { JSB } from 'internal:constants'; +import { JSB, WEBGPU } from 'internal:constants'; import { legacyCC } from '../core/global-exports'; import { error, getError } from '../core/platform/debug'; import { sys } from '../core/platform/sys'; @@ -88,6 +89,7 @@ export enum RenderType { /** * @internal */ + export class DeviceManager { private initialized = false; private _gfxDevice!: Device; @@ -127,6 +129,9 @@ export class DeviceManager { } const deviceCtors: Constructor[] = []; + if (WEBGPU) { + deviceCtors.push(legacyCC.WebGPUDevice); + } if (useWebGL2 && legacyCC.WebGL2Device) { deviceCtors.push(legacyCC.WebGL2Device); } diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index 748932cddf..162f0aa3d8 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -424,7 +424,9 @@ export declare namespace native { /** * @en create a download task. The maximum size for a single download file is 4GB. * @zh 创建一个下载任务. 单个下载文件最大为4GB. - * @param requestURL @en Request download resource URL @zh 请求下载资源的URL + * @param requestURL + * @en Request download resource URL. Node: Users need to encode the URL containing special characters except spaces (such as Chinese, etc.) + * @zh 请求下载资源的URL. 注意: 当URL中包含除空格外特殊字符(如:中文等)时需要用户自行编码后传入. * @param storagePath @en Storage path for downloaded file @zh 下载文件存储路径 * @param identifier @en identifier @zh 标识符 * @return @en DownloadTask @zh 下载任务对象 @@ -487,7 +489,9 @@ export declare namespace native { * @deprecated since v3.6.0, please use `createDownloadTask` to instead. * @en create a download task. The maximum size for a single download file is 4GB. * @zh 创建一个下载任务. 单个下载文件最大为4GB. - * @param requestURL @en Request download resource URL @zh 请求下载资源的URL + * @param requestURL + * @en Request download resource URL. Node: Users need to encode the URL containing special characters except spaces (such as Chinese, etc.) + * @zh 请求下载资源的URL. 注意: 当URL中包含除空格外特殊字符(如:中文等)时需要用户自行编码后传入. * @param storagePath @en Storage path for downloaded file @zh 下载文件存储路径 * @param identifier @en identifier @zh 标识符 * @return @en DownloadTask @zh 下载任务对象 diff --git a/cocos/physics/bullet/instantiated.ts b/cocos/physics/bullet/instantiated.ts index 7b3facc183..570d791733 100644 --- a/cocos/physics/bullet/instantiated.ts +++ b/cocos/physics/bullet/instantiated.ts @@ -25,7 +25,7 @@ // eslint-disable-next-line import/no-extraneous-dependencies import bulletModule, { bulletType } from '@cocos/bullet'; -import { WECHAT } from 'internal:constants'; +import { WECHAT, RUNTIME_BASED } from 'internal:constants'; import { game } from '../../game'; import { sys } from '../../core/platform'; import { pageSize, pageCount, importFunc } from './bullet-env'; @@ -92,7 +92,7 @@ export function waitForAmmoInstantiation () { }, errorReport); } - if (WECHAT) { + if (WECHAT || RUNTIME_BASED) { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions const wasmFilePath = `cocos-js/${module}` as any; instantiateWasm(wasmFilePath); diff --git a/cocos/render-scene/core/render-window.ts b/cocos/render-scene/core/render-window.ts index 3eb83632f1..39f991f63c 100644 --- a/cocos/render-scene/core/render-window.ts +++ b/cocos/render-scene/core/render-window.ts @@ -100,6 +100,7 @@ export class RenderWindow { protected _hasOnScreenAttachments = false; protected _hasOffScreenAttachments = false; protected _framebuffer: Framebuffer | null = null; + protected _device: Device | null = null; /** * @private @@ -121,6 +122,7 @@ export class RenderWindow { this._width = info.width; this._height = info.height; + this._device = device; this._renderPass = device.createRenderPass(info.renderPassInfo); if (info.swapchain) { @@ -177,6 +179,7 @@ export class RenderWindow { } } this._colorTextures.length = 0; + this._device = null; } /** @@ -203,7 +206,7 @@ export class RenderWindow { if (this.framebuffer) { this.framebuffer.destroy(); - this.framebuffer.initialize(new FramebufferInfo( + this._framebuffer = this._device!.createFramebuffer(new FramebufferInfo( this._renderPass!, this._colorTextures, this._depthStencilTexture, diff --git a/cocos/render-scene/deprecated.ts b/cocos/render-scene/deprecated.ts index 3d23c47473..151853f4fb 100644 --- a/cocos/render-scene/deprecated.ts +++ b/cocos/render-scene/deprecated.ts @@ -30,7 +30,7 @@ import { legacyCC } from '../core/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'; import { SubModel } from './scene/submodel'; removeProperty(RenderScene.prototype, 'RenderScene.prototype', [ @@ -49,6 +49,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/render-scene/scene/model.ts b/cocos/render-scene/scene/model.ts index 2473395f9f..5717e6afa4 100644 --- a/cocos/render-scene/scene/model.ts +++ b/cocos/render-scene/scene/model.ts @@ -33,7 +33,7 @@ import { Layers } from '../../scene-graph/layers'; import { RenderScene } from '../core/render-scene'; import { Texture2D } from '../../asset/assets/texture-2d'; import { SubModel } from './submodel'; -import { Pass, IMacroPatch, BatchingSchemes } from '../core/pass'; +import { IMacroPatch, BatchingSchemes } from '../core/pass'; import { Mat4, Vec3, Vec4 } from '../../core/math'; import { Attribute, DescriptorSet, Device, Buffer, BufferInfo, getTypedArrayConstructor, BufferUsageBit, FormatInfos, MemoryUsageBit, Filter, Address, Feature, SamplerInfo, deviceManager } from '../../gfx'; @@ -49,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, @@ -64,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, @@ -157,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 阴影偏移值 @@ -295,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 世界空间包围盒 @@ -373,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(); @@ -557,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); @@ -596,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(); } @@ -747,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/render-scene/scene/submodel.ts b/cocos/render-scene/scene/submodel.ts index f1b82294aa..d8dd0a67b1 100644 --- a/cocos/render-scene/scene/submodel.ts +++ b/cocos/render-scene/scene/submodel.ts @@ -24,18 +24,25 @@ */ import { RenderingSubMesh } from '../../asset/assets/rendering-sub-mesh'; -import { RenderPriority, UNIFORM_REFLECTION_TEXTURE_BINDING, UNIFORM_REFLECTION_STORAGE_BINDING } from '../../rendering/define'; +import { RenderPriority, UNIFORM_REFLECTION_TEXTURE_BINDING, UNIFORM_REFLECTION_STORAGE_BINDING, INST_MAT_WORLD } from '../../rendering/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 '../../core/global-exports'; import { errorID } from '../../core/platform/debug'; import { getPhaseID } from '../../rendering/pass-phase'; import { Root } from '../../root'; +import { Mat4 } from '../../core'; 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 @@ -106,7 +115,7 @@ export class SubModel { */ set subMesh (subMesh) { this._inputAssembler!.destroy(); - this._inputAssembler!.initialize(subMesh.iaInfo); + this._inputAssembler = this._device!.createInputAssembler(subMesh.iaInfo); if (this._passes![0].batchingScheme === BatchingSchemes.VB_MERGING) { this.subMesh.genFlatBuffers(); } this._subMesh = subMesh; } @@ -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 @@ -371,10 +399,93 @@ export class SubModel { // update draw info const drawInfo = this._subMesh.drawInfo; if (this._inputAssembler && drawInfo) { - this._inputAssembler.drawInfo.copy(drawInfo); + Object.assign(this._inputAssembler.drawInfo, drawInfo); } } + /** + * @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/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 96965bf24d..6ac97e5f0e 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -829,22 +829,22 @@ class DevicePreSceneTask extends WebSceneTask { if (isEmpty) { 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; if (batchingScheme === BatchingSchemes.INSTANCING) { const instancedBuffer = p.getInstancedBuffer(); - instancedBuffer.merge(submodel, ro.model.instancedAttributes, passes.indexOf(p)); + instancedBuffer.merge(subModel, ro.model.instancedAttributes, passes.indexOf(p)); this._submitInfo.instances.add(instancedBuffer); } else if (batchingScheme === BatchingSchemes.VB_MERGING) { 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 { - 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); } } } diff --git a/cocos/rendering/deferred/deferred-pipeline.ts b/cocos/rendering/deferred/deferred-pipeline.ts index 8f9bc783fd..ddba0ccef8 100644 --- a/cocos/rendering/deferred/deferred-pipeline.ts +++ b/cocos/rendering/deferred/deferred-pipeline.ts @@ -316,8 +316,8 @@ export class DeferredPipeline extends RenderPipeline { // Listens when the attachment texture is scaled this.on(PipelineEventType.ATTACHMENT_SCALE_CAHNGED, (val: number) => { data.sampler = val < 1 ? this.globalDSManager.pointSampler : this.globalDSManager.linearSampler; - this.applyFramebufferRatio(data.gbufferFrameBuffer); - this.applyFramebufferRatio(data.outputFrameBuffer); + data.gbufferFrameBuffer = this.newFramebufferByRatio(data.gbufferFrameBuffer); + data.gbufferFrameBuffer = this.newFramebufferByRatio(data.outputFrameBuffer); }); } } diff --git a/cocos/rendering/deferred/gbuffer-stage.ts b/cocos/rendering/deferred/gbuffer-stage.ts index 4f98d64a6f..fd602058b4 100644 --- a/cocos/rendering/deferred/gbuffer-stage.ts +++ b/cocos/rendering/deferred/gbuffer-stage.ts @@ -129,7 +129,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/rendering/forward/forward-stage.ts b/cocos/rendering/forward/forward-stage.ts index 278adbeb3f..26c8ecfa78 100644 --- a/cocos/rendering/forward/forward-stage.ts +++ b/cocos/rendering/forward/forward-stage.ts @@ -92,6 +92,20 @@ export class ForwardStage extends RenderStage { this._uiPhase = new UIPhase(); } + public addRenderInstancedQueue (queue: RenderInstancedQueue) { + if (this.additiveInstanceQueues.includes(queue)) { + return; + } + this.additiveInstanceQueues.push(queue); + } + + public removeRenderInstancedQueue (queue: RenderInstancedQueue) { + const index = this.additiveInstanceQueues.indexOf(queue); + if (index > -1) { + this.additiveInstanceQueues.splice(index, 1); + } + } + public initialize (info: IRenderStageInfo): boolean { super.initialize(info); if (info.renderQueues) { @@ -135,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/rendering/instanced-buffer.ts b/cocos/rendering/instanced-buffer.ts index 18ecdd9629..193f02732f 100644 --- a/cocos/rendering/instanced-buffer.ts +++ b/cocos/rendering/instanced-buffer.ts @@ -65,22 +65,23 @@ 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; const lightingMap = subModel.descriptorSet.getTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING); - let shader = shaderImplant; + let shader = shaderImplant; if (!shader) { shader = subModel.shaders[passIdx]; } const descriptorSet = subModel.descriptorSet; for (let i = 0; i < this.instances.length; ++i) { const instance = this.instances[i]; - if (instance.ia.indexBuffer !== sourceIA.indexBuffer || instance.count >= MAX_CAPACITY) { continue; } + if (instance.ia.indexBuffer?.objectID !== sourceIA.indexBuffer?.objectID || instance.count >= MAX_CAPACITY) { continue; } // check same binding - if (instance.lightingMap !== lightingMap) { + if (instance.lightingMap.objectID !== lightingMap.objectID) { continue; } @@ -97,8 +98,8 @@ export class InstancedBuffer { instance.data.set(oldData); instance.vb.resize(newSize); } - if (instance.shader !== shader) { instance.shader = shader; } - if (instance.descriptorSet !== descriptorSet) { instance.descriptorSet = descriptorSet; } + instance.shader = shader; + instance.descriptorSet = descriptorSet; instance.data.set(attrs.buffer, instance.stride * instance.count++); this.hasPendingModels = true; return; diff --git a/cocos/rendering/pipeline-ubo.ts b/cocos/rendering/pipeline-ubo.ts index d637c72651..5dd790f18e 100644 --- a/cocos/rendering/pipeline-ubo.ts +++ b/cocos/rendering/pipeline-ubo.ts @@ -514,7 +514,7 @@ export class PipelineUBO { globalDS.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); globalDS.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); globalDS.update(); - globalDS.getBuffer(UBOShadow.BINDING).update(this._shadowUBO); + this._pipeline.commandBuffers[0].updateBuffer(globalDS.getBuffer(UBOShadow.BINDING), this._shadowUBO); } public updateShadowUBORange (offset: number, data: Mat4 | Color) { diff --git a/cocos/rendering/planar-shadow-queue.ts b/cocos/rendering/planar-shadow-queue.ts index 2d6723df96..3754adfbed 100644 --- a/cocos/rendering/planar-shadow-queue.ts +++ b/cocos/rendering/planar-shadow-queue.ts @@ -27,16 +27,17 @@ import { AABB, intersect } from '../core/geometry'; import { SetIndex } from './define'; import { CommandBuffer, Device, RenderPass } from '../gfx'; import { PipelineStateManager } from './pipeline-state-manager'; -import { Model, Camera } from '../render-scene/scene'; +import { Model, Camera, SubModel } from '../render-scene/scene'; import { RenderInstancedQueue } from './render-instanced-queue'; import { ShadowType } from '../render-scene/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; @@ -49,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; } @@ -72,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); @@ -91,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/rendering/render-additive-light-queue.ts b/cocos/rendering/render-additive-light-queue.ts index c171dcccf6..b68b817eda 100644 --- a/cocos/rendering/render-additive-light-queue.ts +++ b/cocos/rendering/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/rendering/render-pipeline.ts b/cocos/rendering/render-pipeline.ts index c420eff101..b486250656 100644 --- a/cocos/rendering/render-pipeline.ts +++ b/cocos/rendering/render-pipeline.ts @@ -48,6 +48,7 @@ import { OS } from '../../pal/system-info/enum-type'; import { macro } from '../core/platform/macro'; import { UBOSkinning } from './define'; import { PipelineRuntime } from './custom/pipeline'; +import { murmurhash2_32_gc } from '../utils'; /** * @en Render pipeline information descriptor @@ -94,6 +95,25 @@ export class PipelineInputAssemblerData { quadIA: InputAssembler|null = null; } +function hashFrameBuffer (fbo: Framebuffer) { + let hash = 666; + for (const color of fbo.colorTextures) { + const info = color?.info; + const hashStr = `${info!.type}_${info!.usage}_${info!.format}_${info!.width}_${info!.height}_${info!.flags}_ + ${info!.layerCount}_${info!.levelCount}_${info!.samples}_${info!.depth}_${info!.externalRes}`; + hash = murmurhash2_32_gc(hashStr, hash); + } + + if (fbo.depthStencilTexture) { + const info = fbo.depthStencilTexture.info; + const hashStr = `${info.type}_${info.usage}_${info.format}_${info.width}_${info.height}_${info.flags}_ + ${info.layerCount}_${info.levelCount}_${info.samples}_${info.depth}_${info.externalRes}`; + hash = murmurhash2_32_gc(hashStr, hash); + } + + return hash; +} + /** * @en Render pipeline describes how we handle the rendering process for all render objects in the related render scene root. * It contains some general pipeline configurations, necessary rendering resources and some [[RenderFlow]]s. @@ -256,7 +276,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi protected _geometryRenderer: GeometryRenderer | null = null; protected declare _pipelineSceneData: PipelineSceneData; protected _pipelineRenderData: PipelineRenderData | null = null; - protected _renderPasses = new Map(); + protected _renderPasses = new Map(); protected _width = 0; protected _height = 0; protected _lastUsedRenderArea: Rect = new Rect(); @@ -310,30 +330,34 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi } public getRenderPass (clearFlags: ClearFlags, fbo: Framebuffer): RenderPass { - let renderPass = this._renderPasses.get(clearFlags); + const fbHash = hashFrameBuffer(fbo); + const hash = murmurhash2_32_gc(`${fbHash}_${clearFlags}`, 666); + let renderPass = this._renderPasses.get(hash); if (renderPass) { return renderPass; } renderPass = this.createRenderPass(clearFlags, fbo.colorTextures[0]!.format, fbo.depthStencilTexture!.format); - this._renderPasses.set(clearFlags, renderPass); + this._renderPasses.set(hash, renderPass); return renderPass; } - public applyFramebufferRatio (framebuffer: Framebuffer) { + public newFramebufferByRatio (dyingFramebuffer: Framebuffer) { const sceneData = this.pipelineSceneData; const width = this._width * sceneData.shadingScale; const height = this._height * sceneData.shadingScale; - const colorTexArr: any = framebuffer.colorTextures; + const colorTexArr: any = dyingFramebuffer.colorTextures; for (let i = 0; i < colorTexArr.length; i++) { colorTexArr[i]!.resize(width, height); } - if (framebuffer.depthStencilTexture) { - framebuffer.depthStencilTexture.resize(width, height); + if (dyingFramebuffer.depthStencilTexture) { + dyingFramebuffer.depthStencilTexture.resize(width, height); } - framebuffer.destroy(); - framebuffer.initialize(new FramebufferInfo( - framebuffer.renderPass, + // move + const newFramebuffer = this._device.createFramebuffer(new FramebufferInfo( + dyingFramebuffer.renderPass, colorTexArr, - framebuffer.depthStencilTexture, + dyingFramebuffer.depthStencilTexture, )); + dyingFramebuffer.destroy(); + return newFramebuffer; } /** diff --git a/cocos/rendering/render-shadow-map-batched-queue.ts b/cocos/rendering/render-shadow-map-batched-queue.ts index 1414f4e079..9974df385d 100644 --- a/cocos/rendering/render-shadow-map-batched-queue.ts +++ b/cocos/rendering/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/rendering/scene-culling.ts b/cocos/rendering/scene-culling.ts index df2605d0ae..962c425abf 100644 --- a/cocos/rendering/scene-culling.ts +++ b/cocos/rendering/scene-culling.ts @@ -33,6 +33,7 @@ import { IRenderObject, UBOShadow } from './define'; import { ShadowType, CSMOptimizationMode } from '../render-scene/scene/shadows'; import { PipelineSceneData } from './pipeline-scene-data'; import { ShadowLayerVolume } from './shadow/csm-layers'; +import { warnID } from '../platform'; const _tempVec3 = new Vec3(); const _sphere = Sphere.create(0, 0, 0, 1); @@ -145,8 +146,12 @@ export function sceneCulling (pipeline: RenderPipeline, camera: Camera) { } } - if (skybox.enabled && skybox.model && (camera.clearFlag & SKYBOX_FLAG)) { - renderObjects.push(getRenderObject(skybox.model, camera)); + if ((camera.clearFlag & SKYBOX_FLAG)) { + if (skybox.enabled && skybox.model) { + renderObjects.push(getRenderObject(skybox.model, camera)); + } else { + warnID(15100, camera.name); + } } const models = scene.models; diff --git a/cocos/rendering/shadow/shadow-flow.ts b/cocos/rendering/shadow/shadow-flow.ts index ac365f2afd..ed641b23e8 100644 --- a/cocos/rendering/shadow/shadow-flow.ts +++ b/cocos/rendering/shadow/shadow-flow.ts @@ -298,12 +298,9 @@ export class ShadowFlow extends RenderFlow { const shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap; const format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8; - const it = shadowFrameBufferMap.values(); - let res = it.next(); - while (!res.done) { - const frameBuffer = res.value; + for (const key of shadowFrameBufferMap.keys()) { + const frameBuffer = shadowFrameBufferMap.get(key); if (!frameBuffer) { - res = it.next(); continue; } @@ -321,13 +318,12 @@ export class ShadowFlow extends RenderFlow { const shadowRenderPass = frameBuffer.renderPass; frameBuffer.destroy(); - frameBuffer.initialize(new FramebufferInfo( + const newFrameBuffer = device.createFramebuffer(new FramebufferInfo( shadowRenderPass, renderTargets, depth, )); - - res = it.next(); + shadowFrameBufferMap.set(key, newFrameBuffer); } shadows.shadowMapDirty = false; diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/scene-graph/scene-globals.ts index 77d62716af..081edd0e5f 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/scene-graph/scene-globals.ts @@ -824,6 +824,7 @@ export class ShadowsInfo { * @en The type of the shadow * @zh 阴影渲染的类型 */ + @tooltip('i18n:shadow.type') @editable @type(ShadowType) set type (val) { @@ -838,6 +839,7 @@ export class ShadowsInfo { * @en Shadow color * @zh 阴影颜色 */ + @tooltip('i18n:shadow.shadowColor') @visible(function (this: ShadowsInfo) { return this._type === ShadowType.Planar; }) set shadowColor (val: Color) { this._shadowColor.set(val); @@ -851,8 +853,8 @@ export class ShadowsInfo { * @en The normal of the plane which receives shadow * @zh 阴影接收平面的法线 */ - @visible(function (this: ShadowsInfo) { return this._type === ShadowType.Planar; }) @tooltip('i18n:shadow.planeDirection') + @visible(function (this: ShadowsInfo) { return this._type === ShadowType.Planar; }) set planeDirection (val: Vec3) { Vec3.copy(this._normal, val); if (this._resource) { this._resource.normal = val; } @@ -865,10 +867,10 @@ export class ShadowsInfo { * @en The distance from coordinate origin to the receiving plane. * @zh 阴影接收平面与原点的距离 */ + @tooltip('i18n:shadow.planeHeight') @editable @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.Planar; }) - @tooltip('i18n:shadow.planeHeight') set planeHeight (val: number) { this._distance = val; if (this._resource) { this._resource.distance = val; } @@ -881,8 +883,8 @@ export class ShadowsInfo { * @en get or set shadow max received * @zh 获取或者设置阴影接收的最大光源数量 */ - @type(CCInteger) @tooltip('i18n:shadow.maxReceived') + @type(CCInteger) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap; }) set maxReceived (val: number) { this._maxReceived = val; @@ -896,8 +898,8 @@ export class ShadowsInfo { * @en get or set shadow map size * @zh 获取或者设置阴影纹理大小 */ - @type(ShadowSize) @tooltip('i18n:shadow.shadowMapSize') + @type(ShadowSize) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap; }) set shadowMapSize (value: number) { this._size.set(value, value); diff --git a/cocos/spine/assembler/simple.ts b/cocos/spine/assembler/simple.ts index 31e1d02fbd..20ca65d00f 100644 --- a/cocos/spine/assembler/simple.ts +++ b/cocos/spine/assembler/simple.ts @@ -32,7 +32,7 @@ import { MaterialInstance } from '../../render-scene'; import { SkeletonTexture } from '../skeleton-texture'; import { getAttributeStride, vfmtPosUvColor4B, vfmtPosUvTwoColor4B } from '../../2d/renderer/vertex-format'; import { Skeleton, SpineMaterialType } from '../skeleton'; -import { Color } from '../../core'; +import { Color, Vec3 } from '../../core'; import { BlendFactor } from '../../gfx'; import { legacyCC } from '../../core/global-exports'; import { StaticVBAccessor } from '../../2d/renderer/static-vb-accessor'; @@ -81,6 +81,7 @@ let _tempg: number; let _tempb: number; let _inRange: boolean; let _mustFlush: boolean; +const _tempVecPos = new Vec3(0, 0, 0); let _r: number; let _g: number; let _b: number; @@ -274,13 +275,16 @@ function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D) { if (nodeColor._val !== 0xffffffff || _premultipliedAlpha) { _needColor = true; } - + let nodeMat: Mat4 | null = null; + if (comp.enableBatch) { + nodeMat = comp.node.worldMatrix; + } if (comp.isAnimationCached()) { // Traverse input assembler. - cacheTraverse(); + cacheTraverse(nodeMat); } else { if (_vertexEffect) _vertexEffect.begin(comp._skeleton); - realTimeTraverse(batcher); + realTimeTraverse(nodeMat); if (_vertexEffect) _vertexEffect.end(); } // Ensure mesh buffer update @@ -494,7 +498,7 @@ function fillVertices (skeletonColor: spine.Color, } } -function realTimeTraverse (batcher: Batcher2D) { +function realTimeTraverse (worldMat: Mat4 | null) { const rd = _renderData!; _vbuf = rd.chunk.vb; _vUintBuf = new Uint32Array(_vbuf.buffer, _vbuf.byteOffset, _vbuf.length); @@ -678,6 +682,17 @@ function realTimeTraverse (batcher: Batcher2D) { for (let ii = _indexOffset, nn = _indexOffset + _indexCount; ii < nn; ii++) { _ibuf[ii] += _vertexOffset + chunkOffset; } + if (worldMat) { + for (let ii = _vertexFloatOffset, nn = _vertexFloatOffset + _vertexFloatCount; ii < nn; ii += _perVertexSize) { + _tempVecPos.x = _vbuf[ii]; + _tempVecPos.y = _vbuf[ii + 1]; + _tempVecPos.z = 0; + _tempVecPos.transformMat4(worldMat); + _vbuf[ii] = _tempVecPos.x; + _vbuf[ii + 1] = _tempVecPos.y; + _vbuf[ii + 2] = _tempVecPos.z; + } + } } _vertexFloatOffset += _vertexFloatCount; _vertexOffset += _vertexCount; @@ -720,7 +735,7 @@ function realTimeTraverse (batcher: Batcher2D) { } } -function cacheTraverse () { +function cacheTraverse (worldMat: Mat4 | null) { const frame = _comp!._curFrame; if (!frame) return; @@ -782,6 +797,17 @@ function cacheTraverse () { // Fill vertices segVFCount = segInfo.vfCount; vbuf.set(vertices.subarray(frameVFOffset, frameVFOffset + segVFCount), frameVFOffset); + if (worldMat) { + for (let ii = frameVFOffset, il = frameVFOffset + segVFCount; ii < il; ii += _perVertexSize) { + _tempVecPos.x = vbuf[ii]; + _tempVecPos.y = vbuf[ii + 1]; + _tempVecPos.z = 0; + _tempVecPos.transformMat4(worldMat); + vbuf[ii] = _tempVecPos.x; + vbuf[ii + 1] = _tempVecPos.y; + vbuf[ii + 2] = _tempVecPos.z; + } + } // Update color if (_needColor) { diff --git a/cocos/spine/deprecated.ts b/cocos/spine/deprecated.ts index ab8bf92610..5309ad8a14 100644 --- a/cocos/spine/deprecated.ts +++ b/cocos/spine/deprecated.ts @@ -27,8 +27,4 @@ import { removeProperty } from '../core/utils/x-deprecated'; import { Skeleton } from './skeleton'; removeProperty(Skeleton.prototype, 'Skeleton', [ - { - name: 'enableBatch', - suggest: 'Not support batch render mode', - }, ]); diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 1879bddf5b..4dea8c01ad 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -445,6 +445,20 @@ export class Skeleton extends UIRenderer { this._updateUseTint(); } } + /* + * @en Enabled batch model, if skeleton is complex, do not enable batch, or will lower performance. + * @zh 开启合批,如果渲染大量相同纹理,且结构简单的骨骼动画,开启合批可以降低drawcall,否则请不要开启,cpu消耗会上升。 + */ + @editable + @tooltip('i18n:COMPONENT.skeleton.enabled_batch') + get enableBatch () { return this._enableBatch; } + set enableBatch (value) { + if (value !== this._enableBatch) { + this._enableBatch = value; + this._updateBatch(); + } + } + /** * @en * The bone sockets this animation component maintains.
@@ -468,6 +482,7 @@ export class Skeleton extends UIRenderer { } get socketNodes () { return this._socketNodes; } + // Frame cache /** * @internal @@ -604,6 +619,9 @@ export class Skeleton extends UIRenderer { @serializable protected defaultAnimation = ''; + @serializable + protected _enableBatch = false; + @serializable protected _sockets: SpineSocket[] = []; @@ -1337,6 +1355,14 @@ export class Skeleton extends UIRenderer { super.destroyRenderData(); } + private getMaterialTemplate () : Material { + let material = this.customMaterial; + if (material === null) { + material = builtinResMgr.get('default-spine-material'); + } + return material; + } + public getMaterialForBlendAndTint (src: BlendFactor, dst: BlendFactor, type: SpineMaterialType): MaterialInstance { const key = `${type}/${src}/${dst}`; let inst = this._materialCache[key]; @@ -1344,20 +1370,7 @@ export class Skeleton extends UIRenderer { return inst; } - let material = this.customMaterial; - if (material === null) { - material = builtinResMgr.get('default-spine-material'); - } - - let useTwoColor = false; - switch (type) { - case SpineMaterialType.TWO_COLORED: - useTwoColor = true; - break; - case SpineMaterialType.COLORED_TEXTURED: - default: - break; - } + const material = this.getMaterialTemplate(); const matInfo = { parent: material, subModelIdx: 0, @@ -1378,7 +1391,12 @@ export class Skeleton extends UIRenderer { }], }, }); - inst.recompileShaders({ TWO_COLORED: useTwoColor, USE_LOCAL: true }); + let useTwoColor = false; + if (type === SpineMaterialType.TWO_COLORED) { + useTwoColor = true; + } + const useLocal = !this._enableBatch; + inst.recompileShaders({ TWO_COLORED: useTwoColor, USE_LOCAL: useLocal }); return inst; } @@ -1416,6 +1434,7 @@ export class Skeleton extends UIRenderer { } protected _render (batcher: Batcher2D) { + let indicesCount = 0; if (this.renderData && this._drawList) { const rd = this.renderData; const chunk = rd.chunk; @@ -1423,20 +1442,17 @@ export class Skeleton extends UIRenderer { const meshBuffer = rd.getMeshBuffer()!; const origin = meshBuffer.indexOffset; // Fill index buffer - accessor.appendIndices(chunk.bufferId, rd.indices!); for (let i = 0; i < this._drawList.length; i++) { this._drawIdx = i; const dc = this._drawList.data[i]; if (dc.texture) { - // Construct IA - const ia = meshBuffer.requireFreeIA(batcher.device); - ia.firstIndex = origin + dc.indexOffset; - ia.indexCount = dc.indexCount; - // Commit IA - batcher.commitIA(this, ia, dc.texture, dc.material!, this.node); + batcher.commitMiddleware(this, meshBuffer, origin + dc.indexOffset, + dc.indexCount, dc.texture, dc.material!, this._enableBatch); } + indicesCount += dc.indexCount; } - // this.node._static = true; + const subIndices = rd.indices!.subarray(0, indicesCount); + accessor.appendIndices(chunk.bufferId, subIndices); } } @@ -1559,11 +1575,7 @@ export class Skeleton extends UIRenderer { } // if change use batch mode, just clear material cache protected _updateBatch () { - // let baseMaterial = this.getMaterial(0); - // if (baseMaterial) { - // baseMaterial.define('CC_USE_MODEL', !this.enableBatch); - // } - // this._materialCache = {}; + this._cleanMaterialCache(); this.markForUpdateRenderData(); } diff --git a/cocos/tiledmap/assembler/simple.ts b/cocos/tiledmap/assembler/simple.ts index 9a91203872..6ba7d36e5b 100644 --- a/cocos/tiledmap/assembler/simple.ts +++ b/cocos/tiledmap/assembler/simple.ts @@ -310,7 +310,7 @@ function packRenderData () { const tiledData = _curLayer.requestTiledRenderData(); if (JSB) { tiledData.renderData = RenderData.add(vfmtPosUvColor, _accessor); - tiledData.renderData.drawInfoType = RenderDrawInfoType.IA; + tiledData.renderData.drawInfoType = RenderDrawInfoType.MIDDLEWARE; } else { tiledData.renderData = RenderData.add(vfmtPosUvColor); } diff --git a/cocos/tiledmap/tiled-layer.ts b/cocos/tiledmap/tiled-layer.ts index a247bfdc35..fcb4ac15b7 100644 --- a/cocos/tiledmap/tiled-layer.ts +++ b/cocos/tiledmap/tiled-layer.ts @@ -180,7 +180,7 @@ export class TiledLayer extends UIRenderer { private requestDrawInfo (idx: number) { if (!this._drawInfoList[idx]) { this._drawInfoList[idx] = new RenderDrawInfo(); - this._drawInfoList[idx].setDrawInfoType(RenderDrawInfoType.IA); + this._drawInfoList[idx].setDrawInfoType(RenderDrawInfoType.MIDDLEWARE); } return this._drawInfoList[idx]; } diff --git a/cocos/webgpu/glslang.js b/cocos/webgpu/glslang.js new file mode 100644 index 0000000000..c5759a65e6 --- /dev/null +++ b/cocos/webgpu/glslang.js @@ -0,0 +1,137 @@ +var Module = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + + return ( + function(Module) { + Module = Module || {}; + + var c;c||(c=typeof Module !== 'undefined' ? Module : {}); + c.compileGLSLZeroCopy=function(a,b,d,e){d=!!d;switch(b){case "vertex":var g=0;break;case "fragment":g=4;break;case "compute":g=5;break;default:throw Error("shader_stage must be 'vertex', 'fragment', or 'compute'.");}switch(e||"1.0"){case "1.0":var f=65536;break;case "1.1":f=65792;break;case "1.2":f=66048;break;case "1.3":f=66304;break;case "1.4":f=66560;break;case "1.5":f=66816;break;default:throw Error("spirv_version must be '1.0' ~ '1.5'.");}e=c._malloc(4);b=c._malloc(4);var h=aa([a,g,d,f,e,b]); + d=k(e);a=k(b);c._free(e);c._free(b);if(0===h)throw Error("GLSL compilation failed");e={};d/=4;e.data=c.HEAPU32.subarray(d,d+a);e.free=function(){c._destroy_output_buffer(h)};return e};c.compileGLSL=function(a,b,d,e){a=c.compileGLSLZeroCopy(a,b,d,e);b=a.data.slice();a.free();return b};var p={},q;for(q in c)c.hasOwnProperty(q)&&(p[q]=c[q]);var r="./this.program",t=!1,u=!1;t="object"===typeof window;u="function"===typeof importScripts;var v="",w; + if(t||u)u?v=self.location.href:document.currentScript&&(v=document.currentScript.src),_scriptDir&&(v=_scriptDir),0!==v.indexOf("blob:")?v=v.substr(0,v.lastIndexOf("/")+1):v="",u&&(w=function(a){var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)});var x=c.print||console.log.bind(console),y=c.printErr||console.warn.bind(console);for(q in p)p.hasOwnProperty(q)&&(c[q]=p[q]);p=null;c.thisProgram&&(r=c.thisProgram);var A; + c.wasmBinary&&(A=c.wasmBinary);"object"!==typeof WebAssembly&&y("no native wasm support detected");function k(a){var b="i32";"*"===b.charAt(b.length-1)&&(b="i32");switch(b){case "i1":return B[a>>0];case "i8":return B[a>>0];case "i16":return ba[a>>1];case "i32":return C[a>>2];case "i64":return C[a>>2];case "float":return ca[a>>2];case "double":return da[a>>3];default:D("invalid type for getValue: "+b)}return null}var E,ea=new WebAssembly.Table({initial:859,maximum:859,element:"anyfunc"}),fa=!1; + function ha(){var a=c._convert_glsl_to_spirv;a||D("Assertion failed: Cannot call unknown function convert_glsl_to_spirv, make sure it is exported");return a} + function aa(a){var b="string number boolean number number number".split(" "),d={string:function(a){var b=0;if(null!==a&&void 0!==a&&0!==a){var d=(a.length<<2)+1;b=G(d);ia(a,H,b,d)}return b},array:function(a){var b=G(a.length);B.set(a,b);return b}},e=ha(),g=[],f=0;if(a)for(var h=0;h=e);)++d;if(16g?e+=String.fromCharCode(g):(g-=65536,e+=String.fromCharCode(55296|g>>10,56320|g&1023))}}else e+=String.fromCharCode(g)}return e} + function ia(a,b,d,e){if(0=f){var h=a.charCodeAt(++g);f=65536+((f&1023)<<10)|h&1023}if(127>=f){if(d>=e)break;b[d++]=f}else{if(2047>=f){if(d+1>=e)break;b[d++]=192|f>>6}else{if(65535>=f){if(d+2>=e)break;b[d++]=224|f>>12}else{if(d+3>=e)break;b[d++]=240|f>>18;b[d++]=128|f>>12&63}b[d++]=128|f>>6&63}b[d++]=128|f&63}}b[d]=0}}"undefined"!==typeof TextDecoder&&new TextDecoder("utf-16le");var J,B,H,ba,C,ca,da; + function ma(a){J=a;c.HEAP8=B=new Int8Array(a);c.HEAP16=ba=new Int16Array(a);c.HEAP32=C=new Int32Array(a);c.HEAPU8=H=new Uint8Array(a);c.HEAPU16=new Uint16Array(a);c.HEAPU32=new Uint32Array(a);c.HEAPF32=ca=new Float32Array(a);c.HEAPF64=da=new Float64Array(a)}var na=c.TOTAL_MEMORY||16777216;c.wasmMemory?E=c.wasmMemory:E=new WebAssembly.Memory({initial:na/65536});E&&(J=E.buffer);na=J.byteLength;ma(J);C[84916]=5582704; + function K(a){for(;0>2]}var Q={},Ba={}; + function Ca(){if(!R){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"===typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:r},b;for(b in Ba)a[b]=Ba[b];var d=[];for(b in a)d.push(b+"="+a[b]);R=d}return R}var R;function S(a){return 0===a%4&&(0!==a%100||0===a%400)}function T(a,b){for(var d=0,e=0;e<=b;d+=a[e++]);return d}var U=[31,29,31,30,31,30,31,31,30,31,30,31],W=[31,28,31,30,31,30,31,31,30,31,30,31]; + function X(a,b){for(a=new Date(a.getTime());0e-a.getDate())b-=e-a.getDate()+1,a.setDate(1),11>d?a.setMonth(d+1):(a.setMonth(0),a.setFullYear(a.getFullYear()+1));else{a.setDate(a.getDate()+b);break}}return a} + function Da(a,b,d,e){function g(a,b,d){for(a="number"===typeof a?a.toString():a||"";a.lengtha?-1:0=h(n(new Date(a.getFullYear(),0,4)),a)?0>=h(b,a)?a.getFullYear()+1:a.getFullYear():a.getFullYear()-1}var m=C[e+40>>2];e={N:C[e>>2],M:C[e+4>>2],D:C[e+8>>2],C:C[e+12>>2],B:C[e+16>>2],A:C[e+20>>2],F:C[e+24>>2],G:C[e+28>>2],X:C[e+32>>2],L:C[e+36>>2],O:m?m?I(H,m,void 0): + "":""};d=d?I(H,d,void 0):"";m={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var l in m)d=d.replace(new RegExp(l,"g"),m[l]);var F="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), + va="January February March April May June July August September October November December".split(" ");m={"%a":function(a){return F[a.F].substring(0,3)},"%A":function(a){return F[a.F]},"%b":function(a){return va[a.B].substring(0,3)},"%B":function(a){return va[a.B]},"%C":function(a){return f((a.A+1900)/100|0,2)},"%d":function(a){return f(a.C,2)},"%e":function(a){return g(a.C,2," ")},"%g":function(a){return z(a).toString().substring(2)},"%G":function(a){return z(a)},"%H":function(a){return f(a.D,2)}, + "%I":function(a){a=a.D;0==a?a=12:12a.D?"AM":"PM"},"%S":function(a){return f(a.N,2)},"%t":function(){return"\t"},"%u":function(a){return a.F||7},"%U":function(a){var b=new Date(a.A+1900,0,1),d=0===b.getDay()?b:X(b,7-b.getDay());a=new Date(a.A+1900,a.B,a.C);return 0>h(d,a)?f(Math.ceil((31- + d.getDate()+(T(S(a.getFullYear())?U:W,a.getMonth()-1)-31)+a.getDate())/7),2):0===h(d,b)?"01":"00"},"%V":function(a){var b=n(new Date(a.A+1900,0,4)),d=n(new Date(a.A+1901,0,4)),e=X(new Date(a.A+1900,0,1),a.G);return 0>h(e,b)?"53":0>=h(d,e)?"01":f(Math.ceil((b.getFullYear()h(d,a)?f(Math.ceil((31- + d.getDate()+(T(S(a.getFullYear())?U:W,a.getMonth()-1)-31)+a.getDate())/7),2):0===h(d,b)?"01":"00"},"%y":function(a){return(a.A+1900).toString().substring(2)},"%Y":function(a){return a.A+1900},"%z":function(a){a=a.L;var b=0<=a;a=Math.abs(a)/60;return(b?"+":"-")+String("0000"+(a/60*100+a%60)).slice(-4)},"%Z":function(a){return a.O},"%%":function(){return"%"}};for(l in m)0<=d.indexOf(l)&&(d=d.replace(new RegExp(l,"g"),m[l](e)));l=Ea(d);if(l.length>b)return 0;B.set(l,a);return l.length-1} + function Ea(a){for(var b=0,d=0;d=e&&(e=65536+((e&1023)<<10)|a.charCodeAt(++d)&1023);127>=e?++b:b=2047>=e?b+2:65535>=e?b+3:b+4}b=Array(b+1);ia(a,b,0,b.length);return b} + var Ga={f:function(){},c:function(){c.___errno_location&&(C[c.___errno_location()>>2]=63);return-1},n:function(a,b){P=b;try{var d=Aa();var e=Aa();if(-1===d||0===e)var g=-28;else{var f=Q.K[d];if(f&&e===f.U){var h=(void 0).T(f.S);Q.R(d,h,e,f.flags,f.offset);(void 0).W(h);Q.K[d]=null;f.P&&Fa(f.V)}g=0}return g}catch(n){return D(n),-n.I}},a:function(){},b:function(){D()},k:function(a,b,d){H.set(H.subarray(b,b+d),a)},l:function(a){var b=B.length;if(2147418112=d;d*=2){var e=b*(1+ + .2/d);e=Math.min(e,a+100663296);e=Math.max(16777216,a,e);0>16);ma(E.buffer);var g=1;break a}catch(f){}g=void 0}if(g)return!0}return!1},d:function(a,b){var d=0;Ca().forEach(function(e,g){var f=b+d;g=C[a+4*g>>2]=f;for(f=0;f>0]=e.charCodeAt(f);B[g>>0]=0;d+=e.length+1});return 0},e:function(a,b){var d=Ca();C[a>>2]=d.length;var e=0;d.forEach(function(a){e+=a.length+1});C[b>>2]=e;return 0},h:function(){return 0}, + j:function(){return 0},g:function(a,b,d,e){try{for(var g=0,f=0;f>2],n=C[b+(8*f+4)>>2],z=0;z>2]=g;return 0}catch(F){return D(F),F.I}},memory:E,o:function(){},i:function(){},m:function(a,b,d,e){return Da(a,b,d,e)},table:ea},Ha=function(){function a(a){c.asm=a.exports;L--;c.monitorRunDependencies&&c.monitorRunDependencies(L);0==L&&(null!==M&&(clearInterval(M),M=null),N&&(a=N,N=null, + a()))}function b(b){a(b.instance)}function d(a){return xa().then(function(a){return WebAssembly.instantiate(a,e)}).then(a,function(a){y("failed to asynchronously prepare wasm: "+a);D(a)})}var e={env:Ga,wasi_snapshot_preview1:Ga};L++;c.monitorRunDependencies&&c.monitorRunDependencies(L);if(c.instantiateWasm)try{return c.instantiateWasm(e,a)}catch(g){return y("Module.instantiateWasm callback failed with error: "+g),!1}(function(){if(A||"function"!==typeof WebAssembly.instantiateStreaming||ta()||"function"!== + typeof fetch)return d(b);fetch(O,{credentials:"same-origin"}).then(function(a){return WebAssembly.instantiateStreaming(a,e).then(b,function(a){y("wasm streaming compile failed: "+a);y("falling back to ArrayBuffer instantiation");d(b)})})})();return{}}();c.asm=Ha;var ya=c.___wasm_call_ctors=function(){return(ya=c.___wasm_call_ctors=c.asm.p).apply(null,arguments)};c._convert_glsl_to_spirv=function(){return(c._convert_glsl_to_spirv=c.asm.q).apply(null,arguments)}; + c._destroy_output_buffer=function(){return(c._destroy_output_buffer=c.asm.r).apply(null,arguments)};c._malloc=function(){return(c._malloc=c.asm.s).apply(null,arguments)};var Fa=c._free=function(){return(Fa=c._free=c.asm.t).apply(null,arguments)},ja=c.stackSave=function(){return(ja=c.stackSave=c.asm.u).apply(null,arguments)},G=c.stackAlloc=function(){return(G=c.stackAlloc=c.asm.v).apply(null,arguments)},ka=c.stackRestore=function(){return(ka=c.stackRestore=c.asm.w).apply(null,arguments)}; + c.dynCall_vi=function(){return(c.dynCall_vi=c.asm.x).apply(null,arguments)};c.dynCall_v=function(){return(c.dynCall_v=c.asm.y).apply(null,arguments)};c.asm=Ha;var Y;c.then=function(a){if(Y)a(c);else{var b=c.onRuntimeInitialized;c.onRuntimeInitialized=function(){b&&b();a(c)}}return c};N=function Ia(){Y||Z();Y||(N=Ia)}; + function Z(){function a(){if(!Y&&(Y=!0,!fa)){K(pa);K(qa);if(c.onRuntimeInitialized)c.onRuntimeInitialized();if(c.postRun)for("function"==typeof c.postRun&&(c.postRun=[c.postRun]);c.postRun.length;){var a=c.postRun.shift();ra.unshift(a)}K(ra)}}if(!(0 { + // const initialize = () => { + // return new Promise(resolve => { + // Module({ + // locateFile() { + // const i = import.meta.url.lastIndexOf('/') + // return import.meta.url.substring(0, i) + '/glslang.wasm'; + // }, + // onRuntimeInitialized() { + // resolve({ + // compileGLSLZeroCopy: this.compileGLSLZeroCopy, + // compileGLSL: this.compileGLSL, + // }); + // }, + // }); + // }); + // }; + + // let instance; + // return () => { + // if (!instance) { + // instance = initialize(); + // } + // return instance; + // }; + // })(); + // (function tryToExport(root, factory) { + // if (typeof exports === 'object' && typeof module === 'object') + // module.exports = factory(); + // else if (typeof define === 'function' && define.amd) + // define("glslang", [], factory); + // else if (typeof exports === 'object') + // exports["glslang"] = factory(); + // else + // root["glslang"] = factory(); + // })(typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this, () => { + // const initialize = (wasmPath) => { + // wasmPath = 'http://localhost:7456/glslang.wasm' + // return new Promise(resolve => { + // Module({ + // locateFile() { + // return wasmPath; + // }, + // onRuntimeInitialized() { + // resolve({ + // compileGLSLZeroCopy: this.compileGLSLZeroCopy, + // compileGLSL: this.compileGLSL, + // }); + // }, + // }); + // }); + // }; + + // let instance; + // return (wasmPath) => { + // if (!instance) { + // instance = initialize(wasmPath); + // } + // return instance; + // }; + // }); + + + const initialize = (wasmPath) => { + return new Promise(resolve => { + Module({ + locateFile() { + return wasmPath; + }, + onRuntimeInitialized() { + resolve({ + compileGLSLZeroCopy: this.compileGLSLZeroCopy, + compileGLSL: this.compileGLSL, + }); + }, + }); + }); + }; + + let instance; + export default (wasmPath) => { + if (!instance) { + instance = initialize(wasmPath); + } + return instance; + }; \ No newline at end of file diff --git a/cocos/webgpu/instantiated.ts b/cocos/webgpu/instantiated.ts new file mode 100644 index 0000000000..ef9a10fb09 --- /dev/null +++ b/cocos/webgpu/instantiated.ts @@ -0,0 +1,89 @@ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable no-void */ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ +import { WEBGPU } from 'internal:constants'; +import webgpuUrl from 'url:native/external/emscripten/webgpu/webgpu_wasm.wasm'; +import glslangUrl from 'url:native/external/emscripten/webgpu/glslang.wasm'; +import wasmDevice from './webgpu_wasm.js'; +import glslangLoader from './glslang.js'; +import { legacyCC } from '../core/global-exports'; + +export const glslalgWasmModule: any = { + glslang: null, +}; + +export const gfx: any = legacyCC.gfx = { + wasmBinary: null, + nativeDevice: null, +}; + +export const webgpuAdapter: any = { + adapter: null, + device: null, +}; + +export const promiseForWebGPUInstantiation = (() => { + if (WEBGPU) { + return Promise.all([ + // @ts-expect-error The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'. + glslangLoader(new URL(glslangUrl, import.meta.url).href).then((res) => { + glslalgWasmModule.glslang = res; + }), + new Promise((resolve) => { + // @ts-expect-error The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'. + fetch(new URL(webgpuUrl, import.meta.url).href).then((response) => { + response.arrayBuffer().then((buffer) => { + gfx.wasmBinary = buffer; + wasmDevice(gfx).then(() => { + legacyCC.WebGPUDevice = gfx.CCWGPUDevice; + resolve(); + }); + }); + }); + }), + new Promise((resolve) => { + (navigator as any).gpu.requestAdapter().then((adapter) => { + adapter.requestDevice().then((device) => { + webgpuAdapter.adapter = adapter; + webgpuAdapter.device = device; + console.log(gfx); + resolve(); + }); + }); + }), + ]).then(() => Promise.resolve()); + } + return Promise.resolve(); +})(); + +if (WEBGPU) { + const intervalId = setInterval(() => { + if (legacyCC.game) { + legacyCC.game.onPreInfrastructureInitDelegate.add(() => promiseForWebGPUInstantiation); + clearInterval(intervalId); + } + }, 10); +} diff --git a/cocos/webgpu/webgpu_wasm.js b/cocos/webgpu/webgpu_wasm.js new file mode 100644 index 0000000000..973bfbb9a3 --- /dev/null +++ b/cocos/webgpu/webgpu_wasm.js @@ -0,0 +1,16 @@ + +var wasmDevice = (() => { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + + return ( +function(wasmDevice) { + wasmDevice = wasmDevice || {}; + +var Module=typeof wasmDevice!="undefined"?wasmDevice:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=title=>document.title=title}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var POINTER_SIZE=4;var tempRet0=0;var setTempRet0=value=>{tempRet0=value};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heapOrArray,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){{if(Module["onAbort"]){Module["onAbort"](what)}}what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}var wasmBinaryFile;wasmBinaryFile="webgpu_wasm.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["_a"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["ab"];addOnInit(Module["asm"]["$a"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(function(instance){return instance}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(wasmBinaryFile)&&typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){callbacks.shift()(Module)}}function handleException(e){if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)}var structRegistrations={};function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAP32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return"_"+name}return name}function createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i{if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}});if(0===unregisteredTypes.length){onComplete(typeConverters)}}function __embind_finalize_value_object(structType){var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};fieldRecords.forEach((field,i)=>{var fieldName=field.fieldName;var getterReturnType=fieldTypes[i];var getter=field.getter;var getterContext=field.getterContext;var setterArgumentType=fieldTypes[i+fieldRecords.length];var setter=field.setter;var setterContext=field.setterContext;fields[fieldName]={read:ptr=>{return getterReturnType["fromWireType"](getter(getterContext,ptr))},write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,o));runDestructors(destructors)}}});return[{name:reg.name,"fromWireType":function(ptr){var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},"toWireType":function(destructors,o){for(var fieldName in fields){if(!(fieldName in o)){throw new TypeError('Missing field: "'+fieldName+'"')}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:rawDestructor}]})}function __embind_register_bigint(primitiveType,name,size,minRange,maxRange){}function getShiftFromSize(size){switch(size){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+size)}}function embind_init_charCodes(){var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes}var embind_charCodes=undefined;function readLatin1String(ptr){var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret}var BindingError=undefined;function throwBindingError(message){throw new BindingError(message)}function registerType(rawType,registeredInstance,options={}){if(!("argPackAdvance"in registeredInstance)){throw new TypeError("registerType registeredInstance requires argPackAdvance")}var name=registeredInstance.name;if(!rawType){throwBindingError('type "'+name+'" must have a positive integer typeid pointer')}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError("Cannot register type '"+name+"' twice")}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function __embind_register_bool(rawType,name,size,trueValue,falseValue){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(wt){return!!wt},"toWireType":function(destructors,o){return o?trueValue:falseValue},"argPackAdvance":8,"readValueFromPointer":function(pointer){var heap;if(size===1){heap=HEAP8}else if(size===2){heap=HEAP16}else if(size===4){heap=HEAP32}else{throw new TypeError("Unknown boolean type size: "+name)}return this["fromWireType"](heap[pointer>>shift])},destructorFunction:null})}function ClassHandle_isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right}function shallowCopyInternalPointer(o){return{count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType}}function throwInstanceAlreadyDeleted(obj){function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")}var finalizationRegistry=false;function detachFinalizer(handle){}function runDestructor($$){if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}}function releaseClassHandle($$){$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}}function downcastPointer(ptr,ptrClass,desiredClass){if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)}var registeredPointers={};function getInheritedInstanceCount(){return Object.keys(registeredInstances).length}function getLiveInheritedInstances(){var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv}var deletionQueue=[];function flushPendingDeletes(){while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}}var delayFunction=undefined;function setDelayFunction(fn){delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}}function init_embind(){Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction}var registeredInstances={};function getBasestPointer(class_,ptr){if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr}function getInheritedInstance(class_,ptr){ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]}function makeClassHandle(prototype,record){if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record}}))}function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr:ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}function attachFinalizer(handle){if("undefined"===typeof FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$:$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)}function ClassHandle_clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}}function ClassHandle_delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}}function ClassHandle_isDeleted(){return!this.$$.ptr}function ClassHandle_deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}function init_ClassHandle(){ClassHandle.prototype["isAliasOf"]=ClassHandle_isAliasOf;ClassHandle.prototype["clone"]=ClassHandle_clone;ClassHandle.prototype["delete"]=ClassHandle_delete;ClassHandle.prototype["isDeleted"]=ClassHandle_isDeleted;ClassHandle.prototype["deleteLater"]=ClassHandle_deleteLater}function ClassHandle(){}function ensureOverloadTable(proto,methodName,humanName){if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError("Function '"+humanName+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+proto[methodName].overloadTable+")!")}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}}function exposePublicSymbol(name,value,numArguments){if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError("Cannot register public name '"+name+"' twice")}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError("Cannot register multiple overloads of a function with the same number of arguments ("+numArguments+")!")}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}}function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}function upcastPointer(ptr,ptrClass,desiredClass){while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError("Expected null or instance of "+desiredClass.name+", got an instance of "+ptrClass.name)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr}function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+embindRepr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle.$$){throwBindingError('Cannot pass "'+embindRepr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(function(){clonedHandle["delete"]()}));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+embindRepr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+handle.$$.ptrType.name+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function RegisteredPointer_getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr}function RegisteredPointer_destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}}function RegisteredPointer_deleteObject(handle){if(handle!==null){handle["delete"]()}}function init_RegisteredPointer(){RegisteredPointer.prototype.getPointee=RegisteredPointer_getPointee;RegisteredPointer.prototype.destructor=RegisteredPointer_destructor;RegisteredPointer.prototype["argPackAdvance"]=8;RegisteredPointer.prototype["readValueFromPointer"]=simpleReadValueFromPointer;RegisteredPointer.prototype["deleteObject"]=RegisteredPointer_deleteObject;RegisteredPointer.prototype["fromWireType"]=RegisteredPointer_fromWireType}function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function dynCallLegacy(sig,ptr,args){var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)}var wasmTableMirror=[];function getWasmTableEntry(funcPtr){var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func}function dynCall(sig,ptr,args){if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}var rtn=getWasmTableEntry(ptr).apply(null,args);return rtn}function getDynCaller(sig,ptr){var argCache=[];return function(){argCache.length=0;Object.assign(argCache,arguments);return dynCall(sig,ptr,argCache)}}function embind__requireFunction(signature,rawFunction){signature=readLatin1String(signature);function makeDynCaller(){if(signature.includes("j")){return getDynCaller(signature,rawFunction)}return getWasmTableEntry(rawFunction)}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError("unknown function pointer with signature "+signature+": "+rawFunction)}return fp}var UnboundTypeError=undefined;function getTypeName(type){var ptr=___getTypeName(type);var rv=readLatin1String(ptr);_free(ptr);return rv}function throwUnboundTypeError(message,types){var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(message+": "+unboundTypes.map(getTypeName).join([", "]))}function __embind_register_class(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor){name=readLatin1String(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);if(upcast){upcast=embind__requireFunction(upcastSignature,upcast)}if(downcast){downcast=embind__requireFunction(downcastSignature,downcast)}rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError("Cannot construct "+name+" due to unbound types",[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],function(base){base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(legalFunctionName,function(){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError("Use 'new' to construct "+name)}if(undefined===registeredClass.constructor_body){throw new BindingError(name+" has no accessible constructor")}var body=registeredClass.constructor_body[arguments.length];if(undefined===body){throw new BindingError("Tried to invoke ctor of "+name+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(registeredClass.constructor_body).toString()+") parameters instead!")}return body.apply(this,arguments)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})}function new_(constructor,argumentList){if(!(constructor instanceof Function)){throw new TypeError("new_ called with constructor type "+typeof constructor+" which is not a function")}var dummy=createNamedFunction(constructor.name||"unknownFunctionName",function(){});dummy.prototype=constructor.prototype;var obj=new dummy;var r=constructor.apply(obj,argumentList);return r instanceof Object?r:obj}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=false;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i>2])}return array}function __embind_register_class_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,fn){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+methodName;function unboundTypesHandler(){throwUnboundTypeError("Cannot call "+humanName+" due to unbound types",rawArgTypes)}if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}var proto=classType.registeredClass.constructor;if(undefined===proto[methodName]){unboundTypesHandler.argCount=argCount-1;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-1]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));var func=craftInvokerFunction(humanName,invokerArgsArray,null,rawInvoker,fn);if(undefined===proto[methodName].overloadTable){func.argCount=argCount-1;proto[methodName]=func}else{proto[methodName].overloadTable[argCount-1]=func}return[]});return[]})}function __embind_register_class_constructor(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor){assert(argCount>0);var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName="constructor "+classType.name;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError("Cannot register multiple constructors with identical number of parameters ("+(argCount-1)+") for class '"+classType.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!")}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError("Cannot construct "+classType.name+" due to unbound types",rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})}function __embind_register_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+methodName;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError("Cannot call "+humanName+" due to unbound types",rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})}function validateThis(this_,classType,humanName){if(!(this_ instanceof Object)){throwBindingError(humanName+' with invalid "this": '+this_)}if(!(this_ instanceof classType.registeredClass.constructor)){throwBindingError(humanName+' incompatible with "this" of type '+this_.constructor.name)}if(!this_.$$.ptr){throwBindingError("cannot call emscripten binding method "+humanName+" on deleted object")}return upcastPointer(this_.$$.ptr,this_.$$.ptrType.registeredClass,classType.registeredClass)}function __embind_register_class_property(classType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){fieldName=readLatin1String(fieldName);getter=embind__requireFunction(getterSignature,getter);whenDependentTypesAreResolved([],[classType],function(classType){classType=classType[0];var humanName=classType.name+"."+fieldName;var desc={get:function(){throwUnboundTypeError("Cannot access "+humanName+" due to unbound types",[getterReturnType,setterArgumentType])},enumerable:true,configurable:true};if(setter){desc.set=()=>{throwUnboundTypeError("Cannot access "+humanName+" due to unbound types",[getterReturnType,setterArgumentType])}}else{desc.set=v=>{throwBindingError(humanName+" is a read-only property")}}Object.defineProperty(classType.registeredClass.instancePrototype,fieldName,desc);whenDependentTypesAreResolved([],setter?[getterReturnType,setterArgumentType]:[getterReturnType],function(types){var getterReturnType=types[0];var desc={get:function(){var ptr=validateThis(this,classType,humanName+" getter");return getterReturnType["fromWireType"](getter(getterContext,ptr))},enumerable:true};if(setter){setter=embind__requireFunction(setterSignature,setter);var setterArgumentType=types[1];desc.set=function(v){var ptr=validateThis(this,classType,humanName+" setter");var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,v));runDestructors(destructors)}}Object.defineProperty(classType.registeredClass.instancePrototype,fieldName,desc);return[]});return[]})}var emval_free_list=[];var emval_handle_array=[{},{value:undefined},{value:null},{value:true},{value:false}];function __emval_decref(handle){if(handle>4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i{if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value},toHandle:value=>{switch(value){case undefined:return 1;case null:return 2;case true:return 3;case false:return 4;default:{var handle=emval_free_list.length?emval_free_list.pop():emval_handle_array.length;emval_handle_array[handle]={refcount:1,value:value};return handle}}}};function __embind_register_emval(rawType,name){name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(handle){var rv=Emval.toValue(handle);__emval_decref(handle);return rv},"toWireType":function(destructors,value){return Emval.toHandle(value)},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:null})}function embindRepr(v){if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}}function floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function integerReadValueFromPointer(name,shift,signed){switch(shift){case 0:return signed?function readS8FromPointer(pointer){return HEAP8[pointer]}:function readU8FromPointer(pointer){return HEAPU8[pointer]};case 1:return signed?function readS16FromPointer(pointer){return HEAP16[pointer>>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=value=>value;if(minRange===0){var bitshift=32-8*size;fromWireType=value=>value<>>bitshift}var isUnsignedType=name.includes("unsigned");var checkAssertions=(value,toTypeName)=>{};var toWireType;if(isUnsignedType){toWireType=function(destructors,value){checkAssertions(value,this.name);return value>>>0}}else{toWireType=function(destructors,value){checkAssertions(value,this.name);return value}}registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":toWireType,"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){var decodeStartPtr=payload;for(var i=0;i<=length;++i){var currentBytePtr=payload+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}else{for(var i=0;i>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function __embind_register_std_wstring(rawType,charSize,name){name=readLatin1String(name);var decodeString,encodeString,getHeap,lengthBytesUTF,shift;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16;getHeap=()=>HEAPU16;shift=1}else if(charSize===4){decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32;getHeap=()=>HEAPU32;shift=2}registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(destructors,value){if(!(typeof value=="string")){throwBindingError("Cannot pass non-string to C++ string type "+name)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_value_object(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){structRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}}function __embind_register_value_object_field(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){structRegistrations[structType].fields.push({fieldName:readLatin1String(fieldName),getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __emval_as(handle,returnType,destructorsRef){handle=Emval.toValue(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=Emval.toHandle(destructors);HEAPU32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}var emval_symbols={};function getStringOrSymbol(address){var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}return symbol}var emval_methodCallers=[];function __emval_call_void_method(caller,handle,methodName,args){caller=emval_methodCallers[caller];handle=Emval.toValue(handle);methodName=getStringOrSymbol(methodName);caller(handle,methodName,null,args)}function emval_addMethodCaller(caller){var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id}function emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2],"parameter "+i)}return a}var emval_registeredMethods=[];function __emval_get_method_caller(argCount,argTypes){var types=emval_lookupTypes(argCount,argTypes);var retType=types[0];var signatureName=retType.name+"_$"+types.slice(1).map(function(t){return t.name}).join("_")+"$";var returnId=emval_registeredMethods[signatureName];if(returnId!==undefined){return returnId}var params=["retType"];var args=[retType];var argsList="";for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function __emval_new_array(){return Emval.toHandle([])}function __emval_new_cstring(v){return Emval.toHandle(getStringOrSymbol(v))}function __emval_run_destructors(handle){var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)}function __emval_set_property(handle,key,value){handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value}function __emval_take_value(type,arg){type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](arg);return Emval.toHandle(v)}function _abort(){abort("")}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function getHeapMax(){return 2147483648}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}let alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var WebGPU={initManagers:function(){if(WebGPU.mgrDevice)return;function Manager(){this.objects={};this.nextId=1;this.create=function(object,wrapper){wrapper=wrapper||{};var id=this.nextId++;wrapper.refcount=1;wrapper.object=object;this.objects[id]=wrapper;return id};this.get=function(id){if(!id)return undefined;var o=this.objects[id];return o.object};this.reference=function(id){var o=this.objects[id];o.refcount++};this.release=function(id){var o=this.objects[id];o.refcount--;if(o.refcount<=0){delete this.objects[id]}}}WebGPU.mgrSurface=WebGPU.mgrSurface||new Manager;WebGPU.mgrSwapChain=WebGPU.mgrSwapChain||new Manager;WebGPU.mgrAdapter=WebGPU.mgrAdapter||new Manager;WebGPU.mgrDevice=WebGPU.mgrDevice||new Manager;WebGPU.mgrQueue=WebGPU.mgrQueue||new Manager;WebGPU.mgrCommandBuffer=WebGPU.mgrCommandBuffer||new Manager;WebGPU.mgrCommandEncoder=WebGPU.mgrCommandEncoder||new Manager;WebGPU.mgrRenderPassEncoder=WebGPU.mgrRenderPassEncoder||new Manager;WebGPU.mgrComputePassEncoder=WebGPU.mgrComputePassEncoder||new Manager;WebGPU.mgrBindGroup=WebGPU.mgrBindGroup||new Manager;WebGPU.mgrBuffer=WebGPU.mgrBuffer||new Manager;WebGPU.mgrSampler=WebGPU.mgrSampler||new Manager;WebGPU.mgrTexture=WebGPU.mgrTexture||new Manager;WebGPU.mgrTextureView=WebGPU.mgrTextureView||new Manager;WebGPU.mgrQuerySet=WebGPU.mgrQuerySet||new Manager;WebGPU.mgrBindGroupLayout=WebGPU.mgrBindGroupLayout||new Manager;WebGPU.mgrPipelineLayout=WebGPU.mgrPipelineLayout||new Manager;WebGPU.mgrRenderPipeline=WebGPU.mgrRenderPipeline||new Manager;WebGPU.mgrComputePipeline=WebGPU.mgrComputePipeline||new Manager;WebGPU.mgrShaderModule=WebGPU.mgrShaderModule||new Manager;WebGPU.mgrRenderBundleEncoder=WebGPU.mgrRenderBundleEncoder||new Manager;WebGPU.mgrRenderBundle=WebGPU.mgrRenderBundle||new Manager},makeColor:function(ptr){return{"r":HEAPF64[ptr>>3],"g":HEAPF64[ptr+8>>3],"b":HEAPF64[ptr+16>>3],"a":HEAPF64[ptr+24>>3]}},makeExtent3D:function(ptr){return{"width":HEAPU32[ptr>>2],"height":HEAPU32[ptr+4>>2],"depthOrArrayLayers":HEAPU32[ptr+8>>2]}},makeOrigin3D:function(ptr){return{"x":HEAPU32[ptr>>2],"y":HEAPU32[ptr+4>>2],"z":HEAPU32[ptr+8>>2]}},makeImageCopyTexture:function(ptr){return{"texture":WebGPU.mgrTexture.get(HEAPU32[ptr+4>>2]),"mipLevel":HEAPU32[ptr+8>>2],"origin":WebGPU.makeOrigin3D(ptr+12),"aspect":WebGPU.TextureAspect[HEAPU32[ptr+24>>2]]}},makeTextureDataLayout:function(ptr){var bytesPerRow=HEAPU32[ptr+16>>2];var rowsPerImage=HEAPU32[ptr+20>>2];return{"offset":HEAPU32[ptr+4+8>>2]*4294967296+HEAPU32[ptr+8>>2],"bytesPerRow":bytesPerRow===4294967295?undefined:bytesPerRow,"rowsPerImage":rowsPerImage===4294967295?undefined:rowsPerImage}},makeImageCopyBuffer:function(ptr){var layoutPtr=ptr+8;var bufferCopyView=WebGPU.makeTextureDataLayout(layoutPtr);bufferCopyView["buffer"]=WebGPU.mgrBuffer.get(HEAPU32[ptr+32>>2]);return bufferCopyView},makePipelineConstants:function(constantCount,constantsPtr){if(!constantCount)return;var constants={};for(var i=0;i>2]);constants[key]=HEAPF64[entryPtr+8>>3]}return constants},makeProgrammableStageDescriptor:function(ptr){if(!ptr)return undefined;return{"module":WebGPU.mgrShaderModule.get(HEAPU32[ptr+4>>2]),"entryPoint":UTF8ToString(HEAPU32[ptr+8>>2]),"constants":WebGPU.makePipelineConstants(HEAPU32[ptr+12>>2],HEAPU32[ptr+16>>2])}},DeviceLostReason:{undefined:0,destroyed:1},PreferredFormat:{rgba8unorm:18,bgra8unorm:23},AddressMode:["repeat","mirror-repeat","clamp-to-edge"],BlendFactor:["zero","one","src","one-minus-src","src-alpha","one-minus-src-alpha","dst","one-minus-dst","dst-alpha","one-minus-dst-alpha","src-alpha-saturated","constant","one-minus-constant"],BlendOperation:["add","subtract","reverse-subtract","min","max"],BufferBindingType:[,"uniform","storage","read-only-storage"],CompareFunction:[,"never","less","less-equal","greater","greater-equal","equal","not-equal","always"],CompilationInfoRequestStatus:["success","error","device-lost","unknown"],ComputePassTimestampLocation:["beginning","end"],CullMode:["none","front","back"],ErrorFilter:["validation","out-of-memory"],FeatureName:{0:undefined,1:"depth-clip-control",2:"depth24unorm-stencil8",3:"depth32float-stencil8",4:"timestamp-query",5:"pipeline-statistics-query",6:"texture-compression-bc",7:"texture-compression-etc2",8:"texture-compression-astc",9:"indirect-first-instance",1e3:"depth-clamping"},FilterMode:["nearest","linear"],FrontFace:["ccw","cw"],IndexFormat:[,"uint16","uint32"],LoadOp:[,"clear","load"],PipelineStatisticName:["vertex-shader-invocations","clipper-invocations","clipper-primitives-out","fragment-shader-invocations","compute-shader-invocations"],PowerPreference:[,"low-power","high-performance"],PredefinedColorSpace:[,"srgb"],PrimitiveTopology:["point-list","line-list","line-strip","triangle-list","triangle-strip"],QueryType:["occlusion","pipeline-statistics","timestamp"],RenderPassTimestampLocation:["beginning","end"],SamplerBindingType:[,"filtering","non-filtering","comparison"],StencilOperation:["keep","zero","replace","invert","increment-clamp","decrement-clamp","increment-wrap","decrement-wrap"],StorageTextureAccess:[,"write-only"],StoreOp:[,"store","discard"],TextureAspect:["all","stencil-only","depth-only"],TextureComponentType:["float","sint","uint","depth-comparison"],TextureDimension:["1d","2d","3d"],TextureFormat:[,"r8unorm","r8snorm","r8uint","r8sint","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32float","r32uint","r32sint","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb10a2unorm","rg11b10ufloat","rgb9e5ufloat","rg32float","rg32uint","rg32sint","rgba16uint","rgba16sint","rgba16float","rgba32float","rgba32uint","rgba32sint","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth24unorm-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm","etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb","astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],TextureSampleType:[,"float","unfilterable-float","depth","sint","uint"],TextureViewDimension:[,"1d","2d","2d-array","cube","cube-array","3d"],VertexFormat:[,"uint8x2","uint8x4","sint8x2","sint8x4","unorm8x2","unorm8x4","snorm8x2","snorm8x4","uint16x2","uint16x4","sint16x2","sint16x4","unorm16x2","unorm16x4","snorm16x2","snorm16x4","float16x2","float16x4","float32","float32x2","float32x3","float32x4","uint32","uint32x2","uint32x3","uint32x4","sint32","sint32x2","sint32x3","sint32x4"],VertexStepMode:["vertex","instance"],FeatureNameString2Enum:{undefined:"0","depth-clip-control":"1","depth24unorm-stencil8":"2","depth32float-stencil8":"3","timestamp-query":"4","pipeline-statistics-query":"5","texture-compression-bc":"6","texture-compression-etc2":"7","texture-compression-astc":"8","indirect-first-instance":"9","depth-clamping":"1000"}};function _emscripten_webgpu_get_device(){var device=Module["preinitializedWebGPUDevice"];var deviceWrapper={queueId:WebGPU.mgrQueue.create(device["queue"])};return WebGPU.mgrDevice.create(device,deviceWrapper)}var ENV={};function getExecutableName(){return thisProgram||"./this.program"}function getEnvStrings(){if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(x+"="+env[x])}getEnvStrings.strings=strings}return getEnvStrings.strings}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}var SYSCALLS={varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret}};function _environ_get(__environ,environ_buf){var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;writeAsciiToMemory(string,ptr);bufSize+=string.length+1});return 0}function _environ_sizes_get(penviron_count,penviron_buf_size){var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){bufSize+=string.length+1});HEAPU32[penviron_buf_size>>2]=bufSize;return 0}var printCharBuffers=[null,[],[]];function printChar(stream,curr){var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j>2]=num;return 0}function _setTempRet0(val){setTempRet0(val)}function _wgpuAdapterGetProperties(adapterId,properties){HEAP32[properties+4>>2]=0;HEAP32[properties+8>>2]=0;HEAP32[properties+12>>2]=0;HEAP32[properties+16>>2]=0;HEAP32[properties+20>>2]=3;HEAP32[properties+24>>2]=1}function _wgpuAdapterHasFeature(adapterId,featureEnumValue){var adapter=WebGPU.mgrAdapter.get(adapterId);return adapter.features.has(WebGPU.FeatureName[featureEnumValue])}function _wgpuAdapterRelease(id){WebGPU.mgrAdapter.release(id)}function _wgpuBindGroupRelease(id){WebGPU.mgrBindGroup.release(id)}function _wgpuBufferDestroy(bufferId){WebGPU.mgrBuffer.get(bufferId)["destroy"]()}function _wgpuBufferGetMappedRange(bufferId,offset,size){var bufferWrapper=WebGPU.mgrBuffer.objects[bufferId];if(size===0)warnOnce("getMappedRange size=0 no longer means WGPU_WHOLE_MAP_SIZE");size=size>>>0;if(size===4294967295)size=undefined;if(bufferWrapper.mapMode!==2){return 0}var mapped;try{mapped=bufferWrapper.object["getMappedRange"](offset,size)}catch(ex){return 0}var data=_malloc(mapped.byteLength);HEAPU8.fill(0,data,mapped.byteLength);bufferWrapper.onUnmap.push(function(){new Uint8Array(mapped).set(HEAPU8.subarray(data,data+mapped.byteLength));_free(data)});return data}function _wgpuBufferRelease(id){WebGPU.mgrBuffer.release(id)}function _wgpuBufferUnmap(bufferId){var bufferWrapper=WebGPU.mgrBuffer.objects[bufferId];if(!bufferWrapper.onUnmap){return}for(var i=0;i>2]),"queryIndex":HEAPU32[twPtr+4>>2],"location":WebGPU.ComputePassTimestampLocation[HEAPU32[twPtr+8>>2]]}}function makeComputePassTimestampWrites(count,twPtr){var timestampWrites=[];for(var i=0;i>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var timestampWriteCount=HEAPU32[descriptor+8>>2];if(timestampWriteCount){desc["timestampWrites"]=makeComputePassTimestampWrites(timestampWriteCount,HEAPU32[descriptor+12>>2])}}var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);return WebGPU.mgrComputePassEncoder.create(commandEncoder["beginComputePass"](desc))}function _wgpuCommandEncoderBeginRenderPass(encoderId,descriptor){function makeColorAttachment(caPtr){var viewPtr=HEAPU32[caPtr>>2];if(viewPtr===0){return undefined}var loadOpInt=HEAPU32[caPtr+8>>2];var storeOpInt=HEAPU32[caPtr+12>>2];var clearValue=WebGPU.makeColor(caPtr+16);return{"view":WebGPU.mgrTextureView.get(viewPtr),"resolveTarget":WebGPU.mgrTextureView.get(HEAPU32[caPtr+4>>2]),"clearValue":clearValue,"loadOp":WebGPU.LoadOp[loadOpInt],"storeOp":WebGPU.StoreOp[storeOpInt]}}function makeColorAttachments(count,caPtr){var attachments=[];for(var i=0;i>2]),"depthClearValue":HEAPF32[dsaPtr+12>>2],"depthLoadOp":WebGPU.LoadOp[HEAPU32[dsaPtr+4>>2]],"depthStoreOp":WebGPU.StoreOp[HEAPU32[dsaPtr+8>>2]],"depthReadOnly":HEAP8[dsaPtr+16>>0]!==0,"stencilClearValue":HEAPU32[dsaPtr+28>>2],"stencilLoadOp":WebGPU.LoadOp[HEAPU32[dsaPtr+20>>2]],"stencilStoreOp":WebGPU.StoreOp[HEAPU32[dsaPtr+24>>2]],"stencilReadOnly":HEAP8[dsaPtr+32>>0]!==0}}function makeRenderPassTimestampWrite(twPtr){return{"querySet":WebGPU.mgrQuerySet.get(HEAPU32[twPtr>>2]),"queryIndex":HEAPU32[twPtr+4>>2],"location":WebGPU.RenderPassTimestampLocation[HEAPU32[twPtr+8>>2]]}}function makeRenderPassTimestampWrites(count,twPtr){var timestampWrites=[];for(var i=0;i>2],HEAPU32[descriptor+12>>2]),"depthStencilAttachment":makeDepthStencilAttachment(HEAPU32[descriptor+16>>2]),"occlusionQuerySet":WebGPU.mgrQuerySet.get(HEAPU32[descriptor+20>>2])};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var timestampWriteCount=HEAPU32[descriptor+24>>2];if(timestampWriteCount){desc["timestampWrites"]=makeRenderPassTimestampWrites(timestampWriteCount,HEAPU32[descriptor+28>>2])}return desc}var desc=makeRenderPassDescriptor(descriptor);var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);return WebGPU.mgrRenderPassEncoder.create(commandEncoder["beginRenderPass"](desc))}function _wgpuCommandEncoderCopyBufferToBuffer(encoderId,srcId,srcOffset_low,srcOffset_high,dstId,dstOffset_low,dstOffset_high,size_low,size_high){var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);var src=WebGPU.mgrBuffer.get(srcId);var dst=WebGPU.mgrBuffer.get(dstId);commandEncoder["copyBufferToBuffer"](src,srcOffset_high*4294967296+srcOffset_low,dst,dstOffset_high*4294967296+dstOffset_low,size_high*4294967296+size_low)}function _wgpuCommandEncoderCopyBufferToTexture(encoderId,srcPtr,dstPtr,copySizePtr){var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);var copySize=WebGPU.makeExtent3D(copySizePtr);commandEncoder["copyBufferToTexture"](WebGPU.makeImageCopyBuffer(srcPtr),WebGPU.makeImageCopyTexture(dstPtr),copySize)}function _wgpuCommandEncoderCopyTextureToTexture(encoderId,srcPtr,dstPtr,copySizePtr){var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);var copySize=WebGPU.makeExtent3D(copySizePtr);commandEncoder["copyTextureToTexture"](WebGPU.makeImageCopyTexture(srcPtr),WebGPU.makeImageCopyTexture(dstPtr),copySize)}function _wgpuCommandEncoderFinish(encoderId){var commandEncoder=WebGPU.mgrCommandEncoder.get(encoderId);return WebGPU.mgrCommandBuffer.create(commandEncoder["finish"]())}function _wgpuCommandEncoderRelease(id){WebGPU.mgrCommandEncoder.release(id)}function _wgpuComputePassEncoderDispatchWorkgroups(passId,x,y,z){var pass=WebGPU.mgrComputePassEncoder.get(passId);if(pass["dispatchWorkgroups"]){pass["dispatchWorkgroups"](x,y,z)}else{pass["dispatch"](x,y,z)}}function _wgpuComputePassEncoderDispatchWorkgroupsIndirect(passId,indirectBufferId,indirectOffset_low,indirectOffset_high){var indirectBuffer=WebGPU.mgrBuffer.get(indirectBufferId);var indirectOffset=indirectOffset_high*4294967296+indirectOffset_low;var pass=WebGPU.mgrComputePassEncoder.get(passId);if(pass["dispatchWorkgroupsIndirect"]){pass["dispatchWorkgroupsIndirect"](indirectBuffer,indirectOffset)}else{pass["dispatchIndirect"](indirectBuffer,indirectOffset)}}function _wgpuComputePassEncoderEnd(passId){var pass=WebGPU.mgrComputePassEncoder.get(passId);pass["end"]()}function _wgpuComputePassEncoderRelease(id){WebGPU.mgrComputePassEncoder.release(id)}function _wgpuComputePassEncoderSetBindGroup(passId,groupIndex,groupId,dynamicOffsetCount,dynamicOffsetsPtr){var pass=WebGPU.mgrComputePassEncoder.get(passId);var group=WebGPU.mgrBindGroup.get(groupId);if(dynamicOffsetCount==0){pass["setBindGroup"](groupIndex,group)}else{var offsets=[];for(var i=0;i>2])}pass["setBindGroup"](groupIndex,group,offsets)}}function _wgpuComputePassEncoderSetPipeline(passId,pipelineId){var pass=WebGPU.mgrComputePassEncoder.get(passId);var pipeline=WebGPU.mgrComputePipeline.get(pipelineId);pass["setPipeline"](pipeline)}function _wgpuComputePipelineRelease(id){WebGPU.mgrComputePipeline.release(id)}function _wgpuDeviceCreateBindGroup(deviceId,descriptor){function makeEntry(entryPtr){var bufferId=HEAPU32[entryPtr+8>>2];var samplerId=HEAPU32[entryPtr+32>>2];var textureViewId=HEAPU32[entryPtr+36>>2];var binding=HEAPU32[entryPtr+4>>2];if(bufferId){var size_low=HEAPU32[entryPtr+24>>2];var size_high=HEAPU32[entryPtr+28>>2];var size=size_high===-1&&size_low===-1?undefined:size_high*4294967296+size_low;return{"binding":binding,"resource":{"buffer":WebGPU.mgrBuffer.get(bufferId),"offset":HEAPU32[entryPtr+4+16>>2]*4294967296+HEAPU32[entryPtr+16>>2],"size":size}}}else if(samplerId){return{"binding":binding,"resource":WebGPU.mgrSampler.get(samplerId)}}else{return{"binding":binding,"resource":WebGPU.mgrTextureView.get(textureViewId)}}}function makeEntries(count,entriesPtrs){var entries=[];for(var i=0;i>2]),"entries":makeEntries(HEAPU32[descriptor+12>>2],HEAPU32[descriptor+16>>2])};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrBindGroup.create(device["createBindGroup"](desc))}function _wgpuDeviceCreateBindGroupLayout(deviceId,descriptor){function makeBufferEntry(entryPtr){var typeInt=HEAPU32[entryPtr+4>>2];if(!typeInt)return undefined;return{"type":WebGPU.BufferBindingType[typeInt],"hasDynamicOffset":HEAP8[entryPtr+8>>0]!==0,"minBindingSize":HEAPU32[entryPtr+4+16>>2]*4294967296+HEAPU32[entryPtr+16>>2]}}function makeSamplerEntry(entryPtr){var typeInt=HEAPU32[entryPtr+4>>2];if(!typeInt)return undefined;return{"type":WebGPU.SamplerBindingType[typeInt]}}function makeTextureEntry(entryPtr){var sampleTypeInt=HEAPU32[entryPtr+4>>2];if(!sampleTypeInt)return undefined;return{"sampleType":WebGPU.TextureSampleType[sampleTypeInt],"viewDimension":WebGPU.TextureViewDimension[HEAPU32[entryPtr+8>>2]],"multisampled":HEAP8[entryPtr+12>>0]!==0}}function makeStorageTextureEntry(entryPtr){var accessInt=HEAPU32[entryPtr+4>>2];if(!accessInt)return undefined;return{"access":WebGPU.StorageTextureAccess[accessInt],"format":WebGPU.TextureFormat[HEAPU32[entryPtr+8>>2]],"viewDimension":WebGPU.TextureViewDimension[HEAPU32[entryPtr+12>>2]]}}function makeEntry(entryPtr){return{"binding":HEAPU32[entryPtr+4>>2],"visibility":HEAPU32[entryPtr+8>>2],"buffer":makeBufferEntry(entryPtr+16),"sampler":makeSamplerEntry(entryPtr+40),"texture":makeTextureEntry(entryPtr+48),"storageTexture":makeStorageTextureEntry(entryPtr+64)}}function makeEntries(count,entriesPtrs){var entries=[];for(var i=0;i>2],HEAPU32[descriptor+12>>2])};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrBindGroupLayout.create(device["createBindGroupLayout"](desc))}function _wgpuDeviceCreateBuffer(deviceId,descriptor){var mappedAtCreation=HEAP8[descriptor+24>>0]!==0;var desc={"label":undefined,"usage":HEAPU32[descriptor+8>>2],"size":HEAPU32[descriptor+4+16>>2]*4294967296+HEAPU32[descriptor+16>>2],"mappedAtCreation":mappedAtCreation};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);var bufferWrapper={};var id=WebGPU.mgrBuffer.create(device["createBuffer"](desc),bufferWrapper);if(mappedAtCreation){bufferWrapper.mapMode=2;bufferWrapper.onUnmap=[]}return id}function _wgpuDeviceCreateCommandEncoder(deviceId,descriptor){var desc;if(descriptor){desc={"label":undefined};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr)}var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrCommandEncoder.create(device["createCommandEncoder"](desc))}function _wgpuDeviceCreateComputePipeline(deviceId,descriptor){var desc={"label":undefined,"layout":WebGPU.mgrPipelineLayout.get(HEAPU32[descriptor+8>>2]),"compute":WebGPU.makeProgrammableStageDescriptor(descriptor+12)};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrComputePipeline.create(device["createComputePipeline"](desc))}function _wgpuDeviceCreatePipelineLayout(deviceId,descriptor){var bglCount=HEAPU32[descriptor+8>>2];var bglPtr=HEAPU32[descriptor+12>>2];var bgls=[];for(var i=0;i>2]))}var desc={"label":undefined,"bindGroupLayouts":bgls};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrPipelineLayout.create(device["createPipelineLayout"](desc))}function _wgpuDeviceCreateRenderPipeline(deviceId,descriptor){function makePrimitiveState(rsPtr){if(!rsPtr)return undefined;return{"topology":WebGPU.PrimitiveTopology[HEAPU32[rsPtr+4>>2]],"stripIndexFormat":WebGPU.IndexFormat[HEAPU32[rsPtr+8>>2]],"frontFace":WebGPU.FrontFace[HEAPU32[rsPtr+12>>2]],"cullMode":WebGPU.CullMode[HEAPU32[rsPtr+16>>2]]}}function makeBlendComponent(bdPtr){if(!bdPtr)return undefined;return{"operation":WebGPU.BlendOperation[HEAPU32[bdPtr>>2]],"srcFactor":WebGPU.BlendFactor[HEAPU32[bdPtr+4>>2]],"dstFactor":WebGPU.BlendFactor[HEAPU32[bdPtr+8>>2]]}}function makeBlendState(bsPtr){if(!bsPtr)return undefined;return{"alpha":makeBlendComponent(bsPtr+12),"color":makeBlendComponent(bsPtr+0)}}function makeColorState(csPtr){var formatInt=HEAPU32[csPtr+4>>2];return formatInt===0?undefined:{"format":WebGPU.TextureFormat[formatInt],"blend":makeBlendState(HEAPU32[csPtr+8>>2]),"writeMask":HEAPU32[csPtr+12>>2]}}function makeColorStates(count,csArrayPtr){var states=[];for(var i=0;i>2]],"failOp":WebGPU.StencilOperation[HEAPU32[ssfPtr+4>>2]],"depthFailOp":WebGPU.StencilOperation[HEAPU32[ssfPtr+8>>2]],"passOp":WebGPU.StencilOperation[HEAPU32[ssfPtr+12>>2]]}}function makeDepthStencilState(dssPtr){if(!dssPtr)return undefined;return{"format":WebGPU.TextureFormat[HEAPU32[dssPtr+4>>2]],"depthWriteEnabled":HEAP8[dssPtr+8>>0]!==0,"depthCompare":WebGPU.CompareFunction[HEAPU32[dssPtr+12>>2]],"stencilFront":makeStencilStateFace(dssPtr+16),"stencilBack":makeStencilStateFace(dssPtr+32),"stencilReadMask":HEAPU32[dssPtr+48>>2],"stencilWriteMask":HEAPU32[dssPtr+52>>2],"depthBias":HEAPU32[dssPtr+56>>2],"depthBiasSlopeScale":HEAPF32[dssPtr+60>>2],"depthBiasClamp":HEAPF32[dssPtr+64>>2]}}function makeVertexAttribute(vaPtr){return{"format":WebGPU.VertexFormat[HEAPU32[vaPtr>>2]],"offset":HEAPU32[vaPtr+4+8>>2]*4294967296+HEAPU32[vaPtr+8>>2],"shaderLocation":HEAPU32[vaPtr+16>>2]}}function makeVertexAttributes(count,vaArrayPtr){var vas=[];for(var i=0;i>2]*4294967296+HEAPU32[vbPtr>>2],"stepMode":WebGPU.VertexStepMode[HEAPU32[vbPtr+8>>2]],"attributes":makeVertexAttributes(HEAPU32[vbPtr+12>>2],HEAPU32[vbPtr+16>>2])}}function makeVertexBuffers(count,vbArrayPtr){if(!count)return undefined;var vbs=[];for(var i=0;i>2]),"entryPoint":UTF8ToString(HEAPU32[viPtr+8>>2]),"constants":WebGPU.makePipelineConstants(HEAPU32[viPtr+12>>2],HEAPU32[viPtr+16>>2]),"buffers":makeVertexBuffers(HEAPU32[viPtr+20>>2],HEAPU32[viPtr+24>>2])}}function makeMultisampleState(msPtr){if(!msPtr)return undefined;return{"count":HEAPU32[msPtr+4>>2],"mask":HEAPU32[msPtr+8>>2],"alphaToCoverageEnabled":HEAP8[msPtr+12>>0]!==0}}function makeFragmentState(fsPtr){if(!fsPtr)return undefined;return{"module":WebGPU.mgrShaderModule.get(HEAPU32[fsPtr+4>>2]),"entryPoint":UTF8ToString(HEAPU32[fsPtr+8>>2]),"constants":WebGPU.makePipelineConstants(HEAPU32[fsPtr+12>>2],HEAPU32[fsPtr+16>>2]),"targets":makeColorStates(HEAPU32[fsPtr+20>>2],HEAPU32[fsPtr+24>>2])}}var desc={"label":undefined,"layout":WebGPU.mgrPipelineLayout.get(HEAPU32[descriptor+8>>2]),"vertex":makeVertexState(descriptor+12),"primitive":makePrimitiveState(descriptor+40),"depthStencil":makeDepthStencilState(HEAPU32[descriptor+60>>2]),"multisample":makeMultisampleState(descriptor+64),"fragment":makeFragmentState(HEAPU32[descriptor+80>>2])};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrRenderPipeline.create(device["createRenderPipeline"](desc))}function _wgpuDeviceCreateSampler(deviceId,descriptor){var desc={"label":undefined,"addressModeU":WebGPU.AddressMode[HEAPU32[descriptor+8>>2]],"addressModeV":WebGPU.AddressMode[HEAPU32[descriptor+12>>2]],"addressModeW":WebGPU.AddressMode[HEAPU32[descriptor+16>>2]],"magFilter":WebGPU.FilterMode[HEAPU32[descriptor+20>>2]],"minFilter":WebGPU.FilterMode[HEAPU32[descriptor+24>>2]],"mipmapFilter":WebGPU.FilterMode[HEAPU32[descriptor+28>>2]],"lodMinClamp":HEAPF32[descriptor+32>>2],"lodMaxClamp":HEAPF32[descriptor+36>>2],"compare":WebGPU.CompareFunction[HEAPU32[descriptor+40>>2]]};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrSampler.create(device["createSampler"](desc))}function _wgpuDeviceCreateShaderModule(deviceId,descriptor){var nextInChainPtr=HEAPU32[descriptor>>2];var sType=HEAPU32[nextInChainPtr+4>>2];var desc={"label":undefined,"code":""};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);switch(sType){case 5:{var count=HEAPU32[nextInChainPtr+8>>2];var start=HEAPU32[nextInChainPtr+12>>2];desc["code"]=HEAPU32.subarray(start>>2,(start>>2)+count);break}case 6:{var sourcePtr=HEAPU32[nextInChainPtr+8>>2];if(sourcePtr){desc["code"]=UTF8ToString(sourcePtr)}break}}var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrShaderModule.create(device["createShaderModule"](desc))}function _wgpuDeviceCreateSwapChain(deviceId,surfaceId,descriptor){var device=WebGPU.mgrDevice.get(deviceId);var context=WebGPU.mgrSurface.get(surfaceId);var canvasSize=[HEAPU32[descriptor+16>>2],HEAPU32[descriptor+20>>2]];if(canvasSize[0]!==0){context["canvas"]["width"]=canvasSize[0]}if(canvasSize[1]!==0){context["canvas"]["height"]=canvasSize[1]}var configuration={"device":device,"format":WebGPU.TextureFormat[HEAPU32[descriptor+12>>2]],"usage":HEAPU32[descriptor+8>>2],"alphaMode":"opaque"};context["configure"](configuration);return WebGPU.mgrSwapChain.create(context)}function _wgpuDeviceCreateTexture(deviceId,descriptor){var desc={"label":undefined,"size":WebGPU.makeExtent3D(descriptor+16),"mipLevelCount":HEAPU32[descriptor+32>>2],"sampleCount":HEAPU32[descriptor+36>>2],"dimension":WebGPU.TextureDimension[HEAPU32[descriptor+12>>2]],"format":WebGPU.TextureFormat[HEAPU32[descriptor+28>>2]],"usage":HEAPU32[descriptor+8>>2]};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr);var viewFormatCount=HEAPU32[descriptor+40>>2];if(viewFormatCount){var viewFormatsPtr=HEAPU32[descriptor+44>>2];desc["viewFormats"]=Array.from(HEAP32.subarray(viewFormatsPtr>>2,(viewFormatsPtr>>2)+viewFormatCount),function(format){return WebGPU.TextureFormat[format]})}var device=WebGPU.mgrDevice.get(deviceId);return WebGPU.mgrTexture.create(device["createTexture"](desc))}function _wgpuDeviceGetQueue(deviceId){var queueId=WebGPU.mgrDevice.objects[deviceId].queueId;WebGPU.mgrQueue.reference(queueId);return queueId}function _wgpuDeviceRelease(id){WebGPU.mgrDevice.release(id)}function maybeCStringToJsString(cString){return cString>2?UTF8ToString(cString):cString}var specialHTMLTargets=[0,document,window];function findEventTarget(target){target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||document.querySelector(target);return domElement}function findCanvasEventTarget(target){return findEventTarget(target)}function _wgpuInstanceCreateSurface(instanceId,descriptor){var nextInChainPtr=HEAPU32[descriptor>>2];var descriptorFromCanvasHTMLSelector=nextInChainPtr;var selectorPtr=HEAPU32[descriptorFromCanvasHTMLSelector+8>>2];var canvas=findCanvasEventTarget(selectorPtr);var context=canvas.getContext("webgpu");if(!context)return 0;var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)context.surfaceLabelWebGPU=UTF8ToString(labelPtr);return WebGPU.mgrSurface.create(context)}function _wgpuInstanceRelease(){}function callUserCallback(func){if(ABORT){return}try{func()}catch(e){handleException(e)}}function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function _wgpuInstanceRequestAdapter(instanceId,options,callback,userdata){var opts;if(options){opts={"powerPreference":WebGPU.PowerPreference[HEAPU32[options+8>>2]],"forceFallbackAdapter":HEAP8[options+12>>0]!==0}}if(!("gpu"in navigator)){var messagePtr=allocateUTF8("WebGPU not available on this browser (navigator.gpu is not available)");getWasmTableEntry(callback)(1,0,messagePtr,userdata);_free(messagePtr);return}navigator["gpu"]["requestAdapter"](opts).then(function(adapter){callUserCallback(function(){if(adapter){var adapterId=WebGPU.mgrAdapter.create(adapter);getWasmTableEntry(callback)(0,adapterId,0,userdata)}else{var messagePtr=allocateUTF8("WebGPU not available on this system (requestAdapter returned null)");getWasmTableEntry(callback)(1,0,messagePtr,userdata);_free(messagePtr)}})},function(ex){callUserCallback(function(){var messagePtr=allocateUTF8(ex.message);getWasmTableEntry(callback)(2,0,messagePtr,userdata);_free(messagePtr)})})}function _wgpuPipelineLayoutRelease(id){WebGPU.mgrPipelineLayout.release(id)}function _wgpuQuerySetDestroy(querySetId){WebGPU.mgrQuerySet.get(querySetId)["destroy"]()}function _wgpuQuerySetRelease(id){WebGPU.mgrQuerySet.release(id)}function _wgpuQueueOnSubmittedWorkDone(queueId,signalValue_low,signalValue_high,callback,userdata){var queue=WebGPU.mgrQueue.get(queueId);queue["onSubmittedWorkDone"]().then(function(){callUserCallback(function(){getWasmTableEntry(callback)(0,userdata)})},function(){callUserCallback(function(){getWasmTableEntry(callback)(1,userdata)})})}function _wgpuQueueRelease(id){WebGPU.mgrQueue.release(id)}function _wgpuQueueSubmit(queueId,commandCount,commands){var queue=WebGPU.mgrQueue.get(queueId);var cmds=Array.from(HEAP32.subarray(commands>>2,(commands>>2)+commandCount),function(id){return WebGPU.mgrCommandBuffer.get(id)});queue["submit"](cmds)}function _wgpuQueueWriteBuffer(queueId,bufferId,bufferOffset_low,bufferOffset_high,data,size){var queue=WebGPU.mgrQueue.get(queueId);var buffer=WebGPU.mgrBuffer.get(bufferId);var bufferOffset=bufferOffset_high*4294967296+bufferOffset_low;var subarray=HEAPU8.subarray(data,data+size);queue["writeBuffer"](buffer,bufferOffset,subarray,0,size)}function _wgpuQueueWriteTexture(queueId,destinationPtr,data,dataSize,dataLayoutPtr,writeSizePtr){var queue=WebGPU.mgrQueue.get(queueId);var destination=WebGPU.makeImageCopyTexture(destinationPtr);var dataLayout=WebGPU.makeTextureDataLayout(dataLayoutPtr);var writeSize=WebGPU.makeExtent3D(writeSizePtr);var subarray=HEAPU8.subarray(data,data+dataSize);queue["writeTexture"](destination,subarray,dataLayout,writeSize)}function _wgpuRenderPassEncoderDraw(passId,vertexCount,instanceCount,firstVertex,firstInstance){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["draw"](vertexCount,instanceCount,firstVertex,firstInstance)}function _wgpuRenderPassEncoderDrawIndexed(passId,indexCount,instanceCount,firstIndex,baseVertex,firstInstance){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["drawIndexed"](indexCount,instanceCount,firstIndex,baseVertex,firstInstance)}function _wgpuRenderPassEncoderDrawIndirect(passId,indirectBufferId,indirectOffset_low,indirectOffset_high){var indirectBuffer=WebGPU.mgrBuffer.get(indirectBufferId);var indirectOffset=indirectOffset_high*4294967296+indirectOffset_low;var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["drawIndirect"](indirectBuffer,indirectOffset)}function _wgpuRenderPassEncoderEnd(passId){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["end"]()}function _wgpuRenderPassEncoderRelease(id){WebGPU.mgrRenderPassEncoder.release(id)}function _wgpuRenderPassEncoderSetBindGroup(passId,groupIndex,groupId,dynamicOffsetCount,dynamicOffsetsPtr){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var group=WebGPU.mgrBindGroup.get(groupId);if(dynamicOffsetCount==0){pass["setBindGroup"](groupIndex,group)}else{var offsets=[];for(var i=0;i>2])}pass["setBindGroup"](groupIndex,group,offsets)}}function _wgpuRenderPassEncoderSetBlendConstant(passId,colorPtr){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var color=WebGPU.makeColor(colorPtr);pass["setBlendConstant"](color)}function _wgpuRenderPassEncoderSetIndexBuffer(passId,bufferId,format,offset_low,offset_high,size_low,size_high){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var buffer=WebGPU.mgrBuffer.get(bufferId);var offset=offset_high*4294967296+offset_low;var size=size_high===-1&&size_low===-1?undefined:size_high*4294967296+size_low;pass["setIndexBuffer"](buffer,WebGPU.IndexFormat[format],offset,size)}function _wgpuRenderPassEncoderSetPipeline(passId,pipelineId){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var pipeline=WebGPU.mgrRenderPipeline.get(pipelineId);pass["setPipeline"](pipeline)}function _wgpuRenderPassEncoderSetScissorRect(passId,x,y,w,h){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["setScissorRect"](x,y,w,h)}function _wgpuRenderPassEncoderSetStencilReference(passId,reference){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["setStencilReference"](reference)}function _wgpuRenderPassEncoderSetVertexBuffer(passId,slot,bufferId,offset_low,offset_high,size_low,size_high){var pass=WebGPU.mgrRenderPassEncoder.get(passId);var buffer=WebGPU.mgrBuffer.get(bufferId);var offset=offset_high*4294967296+offset_low;var size=size_high===-1&&size_low===-1?undefined:size_high*4294967296+size_low;pass["setVertexBuffer"](slot,buffer,offset,size)}function _wgpuRenderPassEncoderSetViewport(passId,x,y,w,h,minDepth,maxDepth){var pass=WebGPU.mgrRenderPassEncoder.get(passId);pass["setViewport"](x,y,w,h,minDepth,maxDepth)}function _wgpuRenderPipelineRelease(id){WebGPU.mgrRenderPipeline.release(id)}function _wgpuSamplerRelease(id){WebGPU.mgrSampler.release(id)}function _wgpuShaderModuleRelease(id){WebGPU.mgrShaderModule.release(id)}function _wgpuSurfaceRelease(id){WebGPU.mgrSurface.release(id)}function _wgpuSwapChainGetCurrentTextureView(swapChainId){var context=WebGPU.mgrSwapChain.get(swapChainId);return WebGPU.mgrTextureView.create(context["getCurrentTexture"]()["createView"]())}function _wgpuSwapChainRelease(id){WebGPU.mgrSwapChain.release(id)}function _wgpuTextureCreateView(textureId,descriptor){var desc;if(descriptor){var mipLevelCount=HEAPU32[descriptor+20>>2];var arrayLayerCount=HEAPU32[descriptor+28>>2];desc={"format":WebGPU.TextureFormat[HEAPU32[descriptor+8>>2]],"dimension":WebGPU.TextureViewDimension[HEAPU32[descriptor+12>>2]],"baseMipLevel":HEAPU32[descriptor+16>>2],"mipLevelCount":mipLevelCount===4294967295?undefined:mipLevelCount,"baseArrayLayer":HEAPU32[descriptor+24>>2],"arrayLayerCount":arrayLayerCount===4294967295?undefined:arrayLayerCount,"aspect":WebGPU.TextureAspect[HEAPU32[descriptor+32>>2]]};var labelPtr=HEAPU32[descriptor+4>>2];if(labelPtr)desc["label"]=UTF8ToString(labelPtr)}var texture=WebGPU.mgrTexture.get(textureId);return WebGPU.mgrTextureView.create(texture["createView"](desc))}function _wgpuTextureDestroy(textureId){WebGPU.mgrTexture.get(textureId)["destroy"]()}function _wgpuTextureRelease(id){WebGPU.mgrTexture.release(id)}function _wgpuTextureViewRelease(id){WebGPU.mgrTextureView.release(id)}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}InternalError=Module["InternalError"]=extendError(Error,"InternalError");embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");init_ClassHandle();init_embind();init_RegisteredPointer();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();WebGPU.initManagers();var asmLibraryArg={"h":__embind_finalize_value_object,"Ta":__embind_register_bigint,"na":__embind_register_bool,"m":__embind_register_class,"K":__embind_register_class_class_function,"q":__embind_register_class_constructor,"d":__embind_register_class_function,"c":__embind_register_class_property,"ma":__embind_register_emval,"Q":__embind_register_float,"s":__embind_register_integer,"r":__embind_register_memory_view,"R":__embind_register_std_string,"D":__embind_register_std_wstring,"i":__embind_register_value_object,"a":__embind_register_value_object_field,"oa":__embind_register_void,"k":__emval_as,"V":__emval_call_void_method,"b":__emval_decref,"W":__emval_get_method_caller,"g":__emval_get_property,"l":__emval_incref,"p":__emval_new_array,"n":__emval_new_cstring,"j":__emval_run_destructors,"o":__emval_set_property,"f":__emval_take_value,"e":_abort,"ka":_emscripten_memcpy_big,"C":_emscripten_resize_heap,"Ba":_emscripten_webgpu_get_device,"ha":_environ_get,"ia":_environ_sizes_get,"ja":_fd_write,"P":_setTempRet0,"Ga":_wgpuAdapterGetProperties,"J":_wgpuAdapterHasFeature,"Da":_wgpuAdapterRelease,"Ha":_wgpuBindGroupRelease,"ca":_wgpuBufferDestroy,"O":_wgpuBufferGetMappedRange,"ba":_wgpuBufferRelease,"B":_wgpuBufferUnmap,"N":_wgpuCommandBufferRelease,"Ja":_wgpuCommandEncoderBeginComputePass,"pa":_wgpuCommandEncoderBeginRenderPass,"Wa":_wgpuCommandEncoderCopyBufferToBuffer,"da":_wgpuCommandEncoderCopyBufferToTexture,"Ka":_wgpuCommandEncoderCopyTextureToTexture,"u":_wgpuCommandEncoderFinish,"x":_wgpuCommandEncoderRelease,"Ia":_wgpuComputePassEncoderDispatchWorkgroups,"Va":_wgpuComputePassEncoderDispatchWorkgroupsIndirect,"ya":_wgpuComputePassEncoderEnd,"wa":_wgpuComputePassEncoderRelease,"Sa":_wgpuComputePassEncoderSetBindGroup,"Ra":_wgpuComputePassEncoderSetPipeline,"S":_wgpuComputePipelineRelease,"M":_wgpuDeviceCreateBindGroup,"L":_wgpuDeviceCreateBindGroupLayout,"v":_wgpuDeviceCreateBuffer,"y":_wgpuDeviceCreateCommandEncoder,"va":_wgpuDeviceCreateComputePipeline,"xa":_wgpuDeviceCreatePipelineLayout,"ua":_wgpuDeviceCreateRenderPipeline,"ta":_wgpuDeviceCreateSampler,"G":_wgpuDeviceCreateShaderModule,"qa":_wgpuDeviceCreateSwapChain,"E":_wgpuDeviceCreateTexture,"Y":_wgpuDeviceGetQueue,"Ca":_wgpuDeviceRelease,"Aa":_wgpuInstanceCreateSurface,"Ea":_wgpuInstanceRelease,"za":_wgpuInstanceRequestAdapter,"U":_wgpuPipelineLayoutRelease,"_":_wgpuQuerySetDestroy,"Z":_wgpuQuerySetRelease,"Ua":_wgpuQueueOnSubmittedWorkDone,"I":_wgpuQueueRelease,"z":_wgpuQueueSubmit,"ga":_wgpuQueueWriteBuffer,"X":_wgpuQueueWriteTexture,"La":_wgpuRenderPassEncoderDraw,"ea":_wgpuRenderPassEncoderDrawIndexed,"Xa":_wgpuRenderPassEncoderDrawIndirect,"la":_wgpuRenderPassEncoderEnd,"Za":_wgpuRenderPassEncoderRelease,"A":_wgpuRenderPassEncoderSetBindGroup,"Pa":_wgpuRenderPassEncoderSetBlendConstant,"Ya":_wgpuRenderPassEncoderSetIndexBuffer,"Qa":_wgpuRenderPassEncoderSetPipeline,"Na":_wgpuRenderPassEncoderSetScissorRect,"Ma":_wgpuRenderPassEncoderSetStencilReference,"fa":_wgpuRenderPassEncoderSetVertexBuffer,"Oa":_wgpuRenderPassEncoderSetViewport,"T":_wgpuRenderPipelineRelease,"sa":_wgpuSamplerRelease,"H":_wgpuShaderModuleRelease,"Fa":_wgpuSurfaceRelease,"F":_wgpuSwapChainGetCurrentTextureView,"ra":_wgpuSwapChainRelease,"w":_wgpuTextureCreateView,"aa":_wgpuTextureDestroy,"$":_wgpuTextureRelease,"t":_wgpuTextureViewRelease};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["$a"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["bb"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["cb"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["db"]).apply(null,arguments)};var ___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=function(){return(___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=Module["asm"]["eb"]).apply(null,arguments)};var dynCall_jii=Module["dynCall_jii"]=function(){return(dynCall_jii=Module["dynCall_jii"]=Module["asm"]["fb"]).apply(null,arguments)};var dynCall_viij=Module["dynCall_viij"]=function(){return(dynCall_viij=Module["dynCall_viij"]=Module["asm"]["gb"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["hb"]).apply(null,arguments)};var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run(); + + + return wasmDevice.ready +} +); +})(); +export default wasmDevice; \ No newline at end of file diff --git a/editor/assets/Default-Particle.png.meta b/editor/assets/Default-Particle.png.meta index 12612b5f27..c89ebdff96 100644 --- a/editor/assets/Default-Particle.png.meta +++ b/editor/assets/Default-Particle.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "b5b27ab1-e740-4398-b407-848fc2b2c897", diff --git a/editor/assets/chunks/builtin/functionalities/fog.chunk.meta b/editor/assets/chunks/builtin/functionalities/fog.chunk.meta index 760dfe7d31..ef5edd8c19 100644 --- a/editor/assets/chunks/builtin/functionalities/fog.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/fog.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "02a04bf3-4c27-4596-81fd-dfc35224f1d1", diff --git a/editor/assets/chunks/builtin/functionalities/morph-animation.chunk b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk index 9d69842a1f..a3614bbea3 100644 --- a/editor/assets/chunks/builtin/functionalities/morph-animation.chunk +++ b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk @@ -1,4 +1,3 @@ -#include // decode32 #include /** diff --git a/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta index 3bc483a242..b1352dcdd5 100644 --- a/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "3adaa06a-e674-487c-9d49-42bc398c255b", diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta index f10cec021f..4f2989da45 100644 --- a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "d4c26490-0a2d-4b6a-9a52-55b5741f18a4", diff --git a/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta index b2af9f5561..244a414fa3 100644 --- a/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "80908463-4566-4fdf-9744-775605cd7ab7", diff --git a/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta index f0740c7d8e..512511d820 100644 --- a/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "258a17ce-6c50-4e8a-92aa-8ecec1a6af24", diff --git a/editor/assets/chunks/builtin/functionalities/world-transform.chunk b/editor/assets/chunks/builtin/functionalities/world-transform.chunk index b4a1fd0844..188cb8be77 100644 --- a/editor/assets/chunks/builtin/functionalities/world-transform.chunk +++ b/editor/assets/chunks/builtin/functionalities/world-transform.chunk @@ -9,8 +9,6 @@ void CCGetWorldMatrix(out mat4 matWorld) vec4(a_matWorld2.xyz, 0.0), vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0) ); - #elif USE_BATCHING - matWorld = cc_matWorlds[int(a_dyn_batch_id)]; #else matWorld = cc_matWorld; #endif @@ -26,9 +24,6 @@ void CCGetWorldMatrixFull(out mat4 matWorld, out mat4 matWorldIT) vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0) ); matWorldIT = matWorld; - #elif USE_BATCHING - matWorld = cc_matWorlds[int(a_dyn_batch_id)]; - matWorldIT = matWorld; #else matWorld = cc_matWorld; matWorldIT = cc_matWorldIT; diff --git a/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta b/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta index 88f1d9961d..be0816f3f1 100644 --- a/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "c2885f54-4ff2-4284-8bbc-b77bc71965b4", diff --git a/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta b/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta index bac2e2d260..9a2f1ec63a 100644 --- a/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta +++ b/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "2c3da5b6-0202-470a-a915-59f1e2968853", diff --git a/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta index fb3ba3d851..a97e6199e1 100644 --- a/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta +++ b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "ef4fb7de-9b39-4eeb-9ae8-d292ff94a452", diff --git a/editor/assets/chunks/builtin/internal/particle-common.chunk.meta b/editor/assets/chunks/builtin/internal/particle-common.chunk.meta index 452f0a8667..1d797e2fa3 100644 --- a/editor/assets/chunks/builtin/internal/particle-common.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-common.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "7a49db3a-930e-4ffc-8659-a82141dabebb", diff --git a/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta b/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta index 90b911d7c9..85935ece9f 100644 --- a/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "df7d02d8-559a-4c02-9aac-3732cfc83d7a", diff --git a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta index 07624b6cb8..a20a9c3dcd 100644 --- a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "b4b00c01-eca8-4ae4-a04d-e00bbeb6d0e0", diff --git a/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta index f2fc3d2483..23f7ef19e9 100644 --- a/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "6e1b48cb-69c8-448c-8055-69ab9793fbab", diff --git a/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta b/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta index 19ab4b6952..25636e9a64 100644 --- a/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta +++ b/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "35822e78-bb35-405f-87bd-d42af6ac9ede", diff --git a/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta b/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta index 79d2474698..a4543b8b19 100644 --- a/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta +++ b/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "4b48672e-e044-4035-9029-13afb50c1aee", diff --git a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta index 6511219a49..fd8402a68e 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "c3e3500f-370c-4da1-92f9-d0d9fd806bd8", diff --git a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta index 8a554d4208..7424cb4e76 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "17e8e047-4c5e-412c-85c8-a76a98742f2a", diff --git a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta index 9d0d0fad91..8b9bfa9361 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "cd94308c-6959-4671-9dcb-6c58342273e2", diff --git a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta index 53dd5b0098..88dc447475 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "5e0f5e6e-5008-497f-b223-4e5f1801d8fd", diff --git a/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta index 73ede74a6f..819286afcf 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "1ea907a3-a36e-432a-ae38-af712c77aaad", diff --git a/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta index 4f9e7f7efc..3cf6808d0c 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "fa1c0cd1-03c6-45dd-8294-bf7a1e21aad4", diff --git a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk index 420504ad3c..a9a65b7576 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk @@ -1,13 +1,5 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. #if !USE_INSTANCING - #if USE_BATCHING - #pragma define BATCHING_COUNT 10 - #pragma builtin(local) - layout(set = 2, binding = 0) uniform CCLocalBatched { - highp mat4 cc_matWorlds[BATCHING_COUNT]; - }; - #else - #include - #endif + #include #endif diff --git a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta index 853ddc200a..343e596699 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "21b24bc9-a158-488e-b27c-b98a461fb438", diff --git a/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta index 0686dc98f4..9b6cad2812 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "e835c2d5-a377-4197-bdb8-382037573494", diff --git a/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta index 5ea9bba5c4..a0ddeeebc5 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "94d19070-32c6-4900-a288-2258fda37f29", diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta index e20bf64968..8d300764c6 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "e8411010-e411-43ab-8f2e-4f4865dca4cf", diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta index 295624e6ff..197170e3e5 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "69f8ecd8-cdc9-4655-a6ec-d39dacdffc2f", diff --git a/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta index d657b6681b..f5669b8335 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "99488fd6-220b-4d13-9a41-8b9439cd3944", diff --git a/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta index cdb49e8e32..2f44120ee4 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "669458fe-c428-40cd-8575-51607aa8edbc", diff --git a/editor/assets/chunks/common/color/aces.chunk.meta b/editor/assets/chunks/common/color/aces.chunk.meta index faba7c9f8b..31d68c4a7f 100644 --- a/editor/assets/chunks/common/color/aces.chunk.meta +++ b/editor/assets/chunks/common/color/aces.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "7efbe295-0202-4979-8cda-6cfe35e086cf", diff --git a/editor/assets/chunks/common/color/gamma.chunk.meta b/editor/assets/chunks/common/color/gamma.chunk.meta index 09cb52dbeb..799b465ec8 100644 --- a/editor/assets/chunks/common/color/gamma.chunk.meta +++ b/editor/assets/chunks/common/color/gamma.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "bb213412-2e68-43b3-9de5-73ca332acace", diff --git a/editor/assets/chunks/common/common-define.chunk b/editor/assets/chunks/common/common-define.chunk index 4f9a0195a4..4d4acc656b 100644 --- a/editor/assets/chunks/common/common-define.chunk +++ b/editor/assets/chunks/common/common-define.chunk @@ -43,17 +43,7 @@ #pragma define CC_HANDLE_RT_SAMPLE_FLIP(uv) uv = cc_cameraPos.w > 1.0 ? vec2(uv.x, 1.0 - uv.y) : uv #pragma define CC_HANDLE_GET_CLIP_FLIP(uv) uv = cc_cameraPos.w == 0.0 ? vec2(uv.x, -uv.y) : uv -#pragma define STEP_FINT_128(v) (step(128.0, (v) + 0.5)) -#pragma define MOD_FINT_128(v) (mod(float(int((v) + 0.5)), 128.0)) - -highp float decode32 (highp vec4 rgba) { - rgba = rgba * 255.0; - highp float Sign = 1.0 - STEP_FINT_128(rgba[3]) * 2.0; - highp float Exponent = 2.0 * MOD_FINT_128(rgba[3]) + STEP_FINT_128(rgba[2]) - 127.0; - highp float Mantissa = MOD_FINT_128(rgba[2]) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0; - return Sign * exp2(Exponent - 23.0) * Mantissa; -} - -float isNan(float val) { - return (val <= 0.0 || 0.0 <= val) ? 0.0 : 1.0; -} +// CC_USE_LIGHTMAP Values +#define CC_LIGHTMAP_DISABLED 0 +#define CC_LIGHTMAP_ALL_IN_ONE 1 +#define CC_LIGHTMAP_CC_LIGHTMAP_INDIRECT_OCCLUSION 2 diff --git a/editor/assets/chunks/common/common-define.chunk.meta b/editor/assets/chunks/common/common-define.chunk.meta index bc5f8672cc..218151219b 100644 --- a/editor/assets/chunks/common/common-define.chunk.meta +++ b/editor/assets/chunks/common/common-define.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "9d86a3e4-ec06-4e51-ba68-45f2b7739fbb", diff --git a/editor/assets/chunks/common/data/packing.chunk.meta b/editor/assets/chunks/common/data/packing.chunk.meta index 8c0ac60eb4..16a40a7f99 100644 --- a/editor/assets/chunks/common/data/packing.chunk.meta +++ b/editor/assets/chunks/common/data/packing.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "73866dd2-eaf5-40af-a061-1b9d38782204", diff --git a/editor/assets/chunks/common/data/unpack.chunk b/editor/assets/chunks/common/data/unpack.chunk index 0af8a618fa..c765bca2f7 100644 --- a/editor/assets/chunks/common/data/unpack.chunk +++ b/editor/assets/chunks/common/data/unpack.chunk @@ -1,5 +1,17 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. +#pragma define STEP_FINT_128(v) (step(128.0, (v) + 0.5)) +#pragma define MOD_FINT_128(v) (mod(float(int((v) + 0.5)), 128.0)) + +highp float decode32 (highp vec4 rgba) { + rgba = rgba * 255.0; + highp float Sign = 1.0 - STEP_FINT_128(rgba[3]) * 2.0; + highp float Exponent = 2.0 * MOD_FINT_128(rgba[3]) + STEP_FINT_128(rgba[2]) - 127.0; + highp float Mantissa = MOD_FINT_128(rgba[2]) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0; + return Sign * exp2(Exponent - 23.0) * Mantissa; +} + + vec4 packRGBE (vec3 rgb) { highp float maxComp = max(max(rgb.r, rgb.g), rgb.b); highp float e = 128.0; diff --git a/editor/assets/chunks/common/data/unpack.chunk.meta b/editor/assets/chunks/common/data/unpack.chunk.meta index bcb9a88365..527e06a4fd 100644 --- a/editor/assets/chunks/common/data/unpack.chunk.meta +++ b/editor/assets/chunks/common/data/unpack.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "e3e5d086-acc9-4dd8-98e8-24ac02f547d5", diff --git a/editor/assets/chunks/common/debug/debug-view-define.chunk.meta b/editor/assets/chunks/common/debug/debug-view-define.chunk.meta index ca074c5fbf..ae3d4eb8a6 100644 --- a/editor/assets/chunks/common/debug/debug-view-define.chunk.meta +++ b/editor/assets/chunks/common/debug/debug-view-define.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "9c973ee8-952a-4ee3-a617-ba6397db6bac", diff --git a/editor/assets/chunks/common/effect/fog.chunk.meta b/editor/assets/chunks/common/effect/fog.chunk.meta index 2e3a0ef339..3f67c55697 100644 --- a/editor/assets/chunks/common/effect/fog.chunk.meta +++ b/editor/assets/chunks/common/effect/fog.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "399f5890-dde1-40de-9751-a7aa91a56b93", diff --git a/editor/assets/chunks/common/lighting/attenuation.chunk.meta b/editor/assets/chunks/common/lighting/attenuation.chunk.meta index 6e0822a887..d9c4f2c59e 100644 --- a/editor/assets/chunks/common/lighting/attenuation.chunk.meta +++ b/editor/assets/chunks/common/lighting/attenuation.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "077cca29-6f66-4aad-a3a7-4f0a7ecd523f", diff --git a/editor/assets/chunks/common/lighting/brdf.chunk.meta b/editor/assets/chunks/common/lighting/brdf.chunk.meta index 27adcff968..96ccf4ef4a 100644 --- a/editor/assets/chunks/common/lighting/brdf.chunk.meta +++ b/editor/assets/chunks/common/lighting/brdf.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "3a85eafd-0fd0-468f-8a2e-0c81493230c7", diff --git a/editor/assets/chunks/common/lighting/functions.chunk.meta b/editor/assets/chunks/common/lighting/functions.chunk.meta index 0007383998..49020d381f 100644 --- a/editor/assets/chunks/common/lighting/functions.chunk.meta +++ b/editor/assets/chunks/common/lighting/functions.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "d360c347-a546-4967-bdd3-30cae323f123", diff --git a/editor/assets/chunks/common/lighting/light-map.chunk.meta b/editor/assets/chunks/common/lighting/light-map.chunk.meta index c408be98e3..3b48f18095 100644 --- a/editor/assets/chunks/common/lighting/light-map.chunk.meta +++ b/editor/assets/chunks/common/lighting/light-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "00e591cd-469d-4611-adb9-a5ca965a0552", diff --git a/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta b/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta index 414e0f636a..02aafc60b7 100644 --- a/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta +++ b/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "a24fb7a1-f7a5-430c-a8b2-e4c516131086", diff --git a/editor/assets/chunks/common/math/coordinates.chunk.meta b/editor/assets/chunks/common/math/coordinates.chunk.meta index 356a11304d..2c94b996d5 100644 --- a/editor/assets/chunks/common/math/coordinates.chunk.meta +++ b/editor/assets/chunks/common/math/coordinates.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "e9d8b3bb-03e4-46b2-be29-ea58fac18c18", diff --git a/editor/assets/chunks/common/math/number.chunk.meta b/editor/assets/chunks/common/math/number.chunk.meta index 8327256642..c9f1993c89 100644 --- a/editor/assets/chunks/common/math/number.chunk.meta +++ b/editor/assets/chunks/common/math/number.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "9f84c121-c61b-499f-b400-81a5448d6078", diff --git a/editor/assets/chunks/common/math/octahedron-transform.chunk.meta b/editor/assets/chunks/common/math/octahedron-transform.chunk.meta index e990809fa2..aeb951c0b6 100644 --- a/editor/assets/chunks/common/math/octahedron-transform.chunk.meta +++ b/editor/assets/chunks/common/math/octahedron-transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "41f91fc1-5aec-45dd-91ca-39ab964f8054", diff --git a/editor/assets/chunks/common/math/transform.chunk.meta b/editor/assets/chunks/common/math/transform.chunk.meta index 1bd281d564..aba003c966 100644 --- a/editor/assets/chunks/common/math/transform.chunk.meta +++ b/editor/assets/chunks/common/math/transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "0de81d5f-2a3e-467e-bcf5-84f7828edab6", diff --git a/editor/assets/chunks/common/mesh/material.chunk.meta b/editor/assets/chunks/common/mesh/material.chunk.meta index 5186e23dab..8dfb974517 100644 --- a/editor/assets/chunks/common/mesh/material.chunk.meta +++ b/editor/assets/chunks/common/mesh/material.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "f992af76-5145-4f8e-beae-6d88be403e8e", diff --git a/editor/assets/chunks/common/shadow/native-pcf.chunk.meta b/editor/assets/chunks/common/shadow/native-pcf.chunk.meta index 5e1e511993..f814f434c3 100644 --- a/editor/assets/chunks/common/shadow/native-pcf.chunk.meta +++ b/editor/assets/chunks/common/shadow/native-pcf.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "cac4ba94-f412-4899-83b1-ce035b0c09e0", diff --git a/editor/assets/chunks/common/texture/cubemap.chunk.meta b/editor/assets/chunks/common/texture/cubemap.chunk.meta index a26916f2eb..e0c9b5b150 100644 --- a/editor/assets/chunks/common/texture/cubemap.chunk.meta +++ b/editor/assets/chunks/common/texture/cubemap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "3931bd87-0a7b-4d2d-a5f1-9544227343a8", diff --git a/editor/assets/chunks/common/texture/texture-lod.chunk.meta b/editor/assets/chunks/common/texture/texture-lod.chunk.meta index 794063d21a..3b9ab99136 100644 --- a/editor/assets/chunks/common/texture/texture-lod.chunk.meta +++ b/editor/assets/chunks/common/texture/texture-lod.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "d26f7be9-ac7f-4dfd-88ee-6657dfe3426e", diff --git a/editor/assets/chunks/deprecated.chunk.meta b/editor/assets/chunks/deprecated.chunk.meta index 8eab61fa91..05a3ccb782 100644 --- a/editor/assets/chunks/deprecated.chunk.meta +++ b/editor/assets/chunks/deprecated.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "355259fc-3a13-4fed-b553-a5e2caeb2e75", diff --git a/editor/assets/chunks/legacy/decode-base.chunk b/editor/assets/chunks/legacy/decode-base.chunk index 7c29282c0f..7d6db0d9ae 100644 --- a/editor/assets/chunks/legacy/decode-base.chunk +++ b/editor/assets/chunks/legacy/decode-base.chunk @@ -1,7 +1,6 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. #pragma define-meta USE_INSTANCING editor(elevated: true) -#pragma define-meta USE_BATCHING editor(elevated: true) #include @@ -43,8 +42,6 @@ layout(location = 3) in vec4 a_tangent; #if CC_RECEIVE_SHADOW in vec2 a_localShadowBias; // x:shadow bias, y:shadow normal bias. #endif -#elif USE_BATCHING - in float a_dyn_batch_id; #endif #if CC_USE_MORPH diff --git a/editor/assets/chunks/legacy/decode-base.chunk.meta b/editor/assets/chunks/legacy/decode-base.chunk.meta index 5987d28c61..e25ff43453 100644 --- a/editor/assets/chunks/legacy/decode-base.chunk.meta +++ b/editor/assets/chunks/legacy/decode-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "e05f440c-0ba5-4c83-a039-5644d248bb87", diff --git a/editor/assets/chunks/legacy/decode-standard.chunk.meta b/editor/assets/chunks/legacy/decode-standard.chunk.meta index 76fa7d87af..303c3e5e36 100644 --- a/editor/assets/chunks/legacy/decode-standard.chunk.meta +++ b/editor/assets/chunks/legacy/decode-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "8daa33da-9438-4294-aace-2a58d1b183ab", diff --git a/editor/assets/chunks/legacy/decode.chunk.meta b/editor/assets/chunks/legacy/decode.chunk.meta index 815fe18760..e521cce105 100644 --- a/editor/assets/chunks/legacy/decode.chunk.meta +++ b/editor/assets/chunks/legacy/decode.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "385a7ca1-9421-475c-aa02-38d52ef3ba7f", diff --git a/editor/assets/chunks/legacy/fog-base.chunk.meta b/editor/assets/chunks/legacy/fog-base.chunk.meta index 621bc94080..9b6684ae2f 100644 --- a/editor/assets/chunks/legacy/fog-base.chunk.meta +++ b/editor/assets/chunks/legacy/fog-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "84b6c1d8-edf3-4d07-9151-8f7ec568fd69", diff --git a/editor/assets/chunks/legacy/fog-fs.chunk.meta b/editor/assets/chunks/legacy/fog-fs.chunk.meta index c63910a58e..d00c6f81a4 100644 --- a/editor/assets/chunks/legacy/fog-fs.chunk.meta +++ b/editor/assets/chunks/legacy/fog-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "5915ee07-9b06-4383-9b98-5b292bd116e9", diff --git a/editor/assets/chunks/legacy/fog-vs.chunk.meta b/editor/assets/chunks/legacy/fog-vs.chunk.meta index cd31a3c843..cc48be0e15 100644 --- a/editor/assets/chunks/legacy/fog-vs.chunk.meta +++ b/editor/assets/chunks/legacy/fog-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "0bc1a9f5-9282-4192-a0d4-4818568f2b16", diff --git a/editor/assets/chunks/legacy/input-standard.chunk b/editor/assets/chunks/legacy/input-standard.chunk index 23a5c6a256..351ae47a8d 100644 --- a/editor/assets/chunks/legacy/input-standard.chunk +++ b/editor/assets/chunks/legacy/input-standard.chunk @@ -1,5 +1,7 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. #include +#include //decode32 + #if CC_USE_MORPH #include #endif diff --git a/editor/assets/chunks/legacy/input-standard.chunk.meta b/editor/assets/chunks/legacy/input-standard.chunk.meta index 5251175db1..c4a9187ffa 100644 --- a/editor/assets/chunks/legacy/input-standard.chunk.meta +++ b/editor/assets/chunks/legacy/input-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "f957d7e0-a3eb-480c-b3c6-43a1a5273b71", diff --git a/editor/assets/chunks/legacy/input.chunk b/editor/assets/chunks/legacy/input.chunk index 33a4ab69f1..75faa0511b 100644 --- a/editor/assets/chunks/legacy/input.chunk +++ b/editor/assets/chunks/legacy/input.chunk @@ -1,5 +1,7 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. #include +#include //decode32 + #if CC_USE_MORPH #include #endif diff --git a/editor/assets/chunks/legacy/input.chunk.meta b/editor/assets/chunks/legacy/input.chunk.meta index 27b99aeb1c..47838ade94 100644 --- a/editor/assets/chunks/legacy/input.chunk.meta +++ b/editor/assets/chunks/legacy/input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "3b9a2995-9fa1-4862-9bcf-9b6fa2c64bd4", diff --git a/editor/assets/chunks/legacy/lighting.chunk.meta b/editor/assets/chunks/legacy/lighting.chunk.meta index b7b414e28a..167e209650 100644 --- a/editor/assets/chunks/legacy/lighting.chunk.meta +++ b/editor/assets/chunks/legacy/lighting.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "4b078b9b-ae79-4653-bc9d-d70e69b49f4b", diff --git a/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta b/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta index 6e33014baa..90eb57edb2 100644 --- a/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta +++ b/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "1cd3229a-63b6-438b-88e9-98afa7f1c69e", diff --git a/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta b/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta index da17d515ec..0b33eb268e 100644 --- a/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta +++ b/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "d22a3ca1-78fe-442c-a604-0349f5c873f7", diff --git a/editor/assets/chunks/legacy/local-batch.chunk.meta b/editor/assets/chunks/legacy/local-batch.chunk.meta index 8556ca2c67..3f9e5cfd72 100644 --- a/editor/assets/chunks/legacy/local-batch.chunk.meta +++ b/editor/assets/chunks/legacy/local-batch.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "bcff50e8-1d1f-4aea-bd0c-6868a4f2a45b", diff --git a/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta b/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta index 874741a555..554e8ce5d1 100644 --- a/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "2cdcf2a6-42f3-4142-a340-eabfe530ccbf", diff --git a/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta index 5c736f4ad9..395f519579 100644 --- a/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "4864e2f6-3eb5-4f08-a87a-5c98141cdef4", diff --git a/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta index 0984a95f92..9b73f49d4c 100644 --- a/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "f71444cb-cecf-4692-a310-2a5fdb96b469", diff --git a/editor/assets/chunks/legacy/morph.chunk.meta b/editor/assets/chunks/legacy/morph.chunk.meta index 7c900ae6a5..6178544d40 100644 --- a/editor/assets/chunks/legacy/morph.chunk.meta +++ b/editor/assets/chunks/legacy/morph.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "48359533-f5f1-4346-b242-66597abd9838", diff --git a/editor/assets/chunks/legacy/output-standard.chunk.meta b/editor/assets/chunks/legacy/output-standard.chunk.meta index 4e7271e7d8..7a4e9b5eb6 100644 --- a/editor/assets/chunks/legacy/output-standard.chunk.meta +++ b/editor/assets/chunks/legacy/output-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "a3c0cc1c-64de-4e52-9698-5f73f8db488e", diff --git a/editor/assets/chunks/legacy/output.chunk.meta b/editor/assets/chunks/legacy/output.chunk.meta index 3d594a4524..8d2abdd259 100644 --- a/editor/assets/chunks/legacy/output.chunk.meta +++ b/editor/assets/chunks/legacy/output.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "713f0582-5c82-484f-81f7-5006e5a4f48f", diff --git a/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta b/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta index f40e8cf466..6fa75c7eda 100644 --- a/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta +++ b/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "b2d386c6-615b-4375-accd-574405611e35", diff --git a/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta b/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta index 73c4783751..505d436381 100644 --- a/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "a70c48b7-cf69-4c97-a857-21149cd71200", diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk b/editor/assets/chunks/legacy/shading-standard-base.chunk index f7223f3fd0..9808cddb1d 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk @@ -117,7 +117,7 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { } #endif - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD vec3 lightmap = s.lightmap.rgb; #if CC_USE_HDR // convert from standard camera exposure parameters to current exposure value diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk.meta b/editor/assets/chunks/legacy/shading-standard-base.chunk.meta index adef3c3f57..ba8e5cb769 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "9ae7cfaf-c5cc-4899-95a5-d6e1215c8964", diff --git a/editor/assets/chunks/legacy/shading-standard.chunk.meta b/editor/assets/chunks/legacy/shading-standard.chunk.meta index 2753b8f39a..5cb5b78fcb 100644 --- a/editor/assets/chunks/legacy/shading-standard.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "f9ba1729-bacf-4e62-8c97-0103d940c464", diff --git a/editor/assets/chunks/legacy/shading-toon.chunk.meta b/editor/assets/chunks/legacy/shading-toon.chunk.meta index 0a067a7499..6b932cc60e 100644 --- a/editor/assets/chunks/legacy/shading-toon.chunk.meta +++ b/editor/assets/chunks/legacy/shading-toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "bbfd1dfb-8f99-4b68-9aa6-817d5b67096d", diff --git a/editor/assets/chunks/legacy/shadow-map-base.chunk.meta b/editor/assets/chunks/legacy/shadow-map-base.chunk.meta index 48cb2d8d89..9e390c2a2d 100644 --- a/editor/assets/chunks/legacy/shadow-map-base.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "1d68b1b7-2f78-4c24-9f35-b215dc980207", diff --git a/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta b/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta index 7737ba3c7c..87c8567d2f 100644 --- a/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "5716d893-2ecc-4110-9291-88b7e939d37d", diff --git a/editor/assets/chunks/legacy/shadow-map-vs.chunk b/editor/assets/chunks/legacy/shadow-map-vs.chunk index e10bdb6b4b..fa32af28a3 100644 --- a/editor/assets/chunks/legacy/shadow-map-vs.chunk +++ b/editor/assets/chunks/legacy/shadow-map-vs.chunk @@ -13,10 +13,8 @@ vec2 CCGetShadowBias() { #if USE_INSTANCING return vec2(a_localShadowBias.x + cc_shadowWHPBInfo.w, a_localShadowBias.y + cc_shadowLPNNInfo.z); - #elif !USE_BATCHING - return vec2(cc_localShadowBias.x + cc_shadowWHPBInfo.w, cc_localShadowBias.y + cc_shadowLPNNInfo.z); #else - return vec2(cc_shadowWHPBInfo.w, cc_shadowLPNNInfo.z); + return vec2(cc_localShadowBias.x + cc_shadowWHPBInfo.w, cc_localShadowBias.y + cc_shadowLPNNInfo.z); #endif } #endif diff --git a/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta b/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta index 0564fce7dc..178f969593 100644 --- a/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "b2e7c003-9c9f-40ee-82c6-32d920a759e8", diff --git a/editor/assets/chunks/legacy/skinning.chunk b/editor/assets/chunks/legacy/skinning.chunk index 9ecae15a4c..80cd123b96 100644 --- a/editor/assets/chunks/legacy/skinning.chunk +++ b/editor/assets/chunks/legacy/skinning.chunk @@ -1,4 +1,5 @@ #include +#include //decode32 #include #include -//#include \ No newline at end of file +//#include diff --git a/editor/assets/chunks/legacy/skinning.chunk.meta b/editor/assets/chunks/legacy/skinning.chunk.meta index 7c45a21b0c..d844cc2aaf 100644 --- a/editor/assets/chunks/legacy/skinning.chunk.meta +++ b/editor/assets/chunks/legacy/skinning.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "f1e9de44-ca95-48c8-9233-d1b5406ab544", diff --git a/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta b/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta index 4952255b79..2431b87220 100644 --- a/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta +++ b/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "31d0a199-05e2-422c-a019-8139a855841c", diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta index 47c4149611..2f92047faa 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "be2dc7d9-db45-4d0b-957b-aee1cb81bde0", diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta index ec12eb8e50..b3f0737d8b 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "7646cc74-5fcc-47c4-970b-5958505c17e5", diff --git a/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta b/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta index 1c6eaafd8e..1f29cf8c7b 100644 --- a/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta +++ b/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "9ada82f2-4c4e-433f-8090-e8bfad31fcf2", diff --git a/editor/assets/chunks/lighting-models/includes/standard.chunk.meta b/editor/assets/chunks/lighting-models/includes/standard.chunk.meta index aed47b8c7d..30c9a08510 100644 --- a/editor/assets/chunks/lighting-models/includes/standard.chunk.meta +++ b/editor/assets/chunks/lighting-models/includes/standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "cc12f5ac-3dcf-4455-aea9-b9be2dd9071e", diff --git a/editor/assets/chunks/lighting-models/includes/toon.chunk.meta b/editor/assets/chunks/lighting-models/includes/toon.chunk.meta index e50c36cac6..0a540a7ee8 100644 --- a/editor/assets/chunks/lighting-models/includes/toon.chunk.meta +++ b/editor/assets/chunks/lighting-models/includes/toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "2710ad01-b6c3-4048-b5d9-b3b69cec3e94", diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index bf63ab23b0..2d95d92299 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -83,7 +83,7 @@ // CCSurfacesLightingCalculateBaked: lightingResult.lightmapColor = vec3(0.0); - #if CC_SURFACES_USE_LIGHT_MAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_SURFACES_USE_LIGHT_MAP && !CC_FORWARD_ADD vec4 lightmap = GetLightMapColor(cc_lightingMap, FSInput_lightMapUV.xy, FSInput_lightMapUV.z); lightingResult.lightmapColor = lightmap.rgb; // lightingResult.shadow/ao *= lightmap.a; diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta index 55ceff5cac..9b997feecc 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "41c84281-f2e7-43e2-88bd-6ffcaf1daf5a", diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta b/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta index 07695ab1b5..e510e7f630 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "4c24618b-1e1d-40e4-883a-cd3fd2304233", diff --git a/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta b/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta index f7999c03d4..a4314e6d96 100644 --- a/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta +++ b/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "9276cd2c-6001-4f89-b024-f53f63628527", diff --git a/editor/assets/chunks/post-process/anti-aliasing.chunk.meta b/editor/assets/chunks/post-process/anti-aliasing.chunk.meta index 52e21fdbbe..f7e4e73d9a 100644 --- a/editor/assets/chunks/post-process/anti-aliasing.chunk.meta +++ b/editor/assets/chunks/post-process/anti-aliasing.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "60bb7684-4cd7-4d19-96c4-262e12e0b025", diff --git a/editor/assets/chunks/post-process/fxaa.chunk.meta b/editor/assets/chunks/post-process/fxaa.chunk.meta index 63f3a4284f..feeddcb097 100644 --- a/editor/assets/chunks/post-process/fxaa.chunk.meta +++ b/editor/assets/chunks/post-process/fxaa.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "0afb4a28-945f-48ac-91e5-6f483345f8ab", diff --git a/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk index 2c3ee3915b..bf9bba7d5a 100644 --- a/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk +++ b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk @@ -41,7 +41,7 @@ void CCSurfacesGetFragmentInput(out SurfacesStandardFragmentInput fsInput) #define FSInput_texcoord1 vec2(0.0, 0.0) #endif -#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD +#if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #define FSInput_lightMapUV v_luv #endif diff --git a/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta index dfaf28401b..b9f00a1ad0 100644 --- a/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "ec870cfb-9c88-4f70-929a-ae540a33075b", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk index 8359e26abc..5d4e0d3c1d 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk +++ b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk @@ -15,7 +15,7 @@ CC_SURFACES_VARING_MODIFIER vec2 v_uv; CC_SURFACES_VARING_MODIFIER mediump vec2 v_uv1; #endif -#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD +#if CC_USE_LIGHTMAP && !CC_FORWARD_ADD CC_SURFACES_VARING_MODIFIER mediump vec3 v_luv; #endif diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta index ae509452e5..e6b939474e 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "f3454fd7-28d9-48dd-a761-ebc8e26834ed", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk index 65b1736054..293aa34cef 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk +++ b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk @@ -41,8 +41,6 @@ layout(location = 2) in vec2 a_texCoord; #if CC_RECEIVE_SHADOW in vec2 a_localShadowBias; // x:shadow bias, y:shadow normal bias. #endif -#elif USE_BATCHING - in float a_dyn_batch_id; #endif diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta index 1c0c4c3b8b..1ca1580a2e 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "65084d4a-ae7c-4ca9-8448-f4cd405144b7", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk index 670b219b16..c5b740c109 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk +++ b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk @@ -34,7 +34,7 @@ struct SurfacesStandardVertexIntermediate float fogFactor; #endif -#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD +#if CC_USE_LIGHTMAP && !CC_FORWARD_ADD vec3 lightmapUV; #endif }; diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta index 3429e4df33..bdb41c97ca 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "45e6b403-a354-48de-a1e1-e59238bd30b1", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk index eb4bdc7ef0..c777938ce8 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk +++ b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk @@ -26,7 +26,7 @@ #define VSOutput_texcoord1 v_uv1 #endif -#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD +#if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #define VSOutput_lightMapUV v_luv #endif diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta index bea46aabc9..ad16db2e50 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "513eb9a6-0193-4ab1-a7da-2ab087936caa", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta index ffdd36b88d..5a1dee60ac 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "1d7d5670-83c4-4dab-acf3-edb7ae758881", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta index 786eff84ec..f3da7d7a72 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "e25e8368-0f16-4322-981e-8b7eebc97afb", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta index ad13a831b1..e3f7aed3b3 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "6a27185f-415d-419c-95b0-85337e21eff9", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta index 8231fd5cdb..e6f1be2215 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "070d960d-b2b5-437c-99da-0aeb502f7273", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk.meta index 4661c2d092..599f46e819 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "ea587cc9-8792-4693-a555-0c5787ce7d89", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta index a2a0e6dd05..e7f6b12673 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "52b875e1-87c0-4dc5-a3f7-ce32cb4d93c6", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta index 2e7803fb24..f038bd1267 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "1101cf65-cc90-486b-b6a5-29ae060e01c7", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta index 2184c1ffd7..40db985267 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "349a2be0-c8d3-420c-9dd1-bf86e01a7055", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta index 8a665f9597..2c8cc3331d 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "4306c0df-b6d6-4733-8a45-c85907f94d29", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta index 2597a07791..d30036e83f 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "a734c67a-3ce2-4978-bf57-080d1dfbbb43", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta index 9817d7fc3b..111e8b37fe 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "7a668e36-d75e-488d-b47a-52591e07151d", diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta b/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta index 59fc003fdb..57ba55be92 100644 --- a/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "29b8aed8-f4da-471e-a036-4fffc28868f3", diff --git a/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta b/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta index 8c506a3bb1..32ce633361 100644 --- a/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta +++ b/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "7ac0dc35-81bc-4b7c-9701-a401747deccf", diff --git a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta index 8de04a9d76..5b27cdba1a 100644 --- a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "b3d7cc71-db0a-4f76-a2e1-c145c679180f", diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta index 406d413813..d1c6753643 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "57b9c877-9855-47c0-bb6f-da3a2c19414e", diff --git a/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta index d5675a8111..b4d53e40c6 100644 --- a/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "3804c73c-5c8d-42cf-8382-6b64ab2ea7bc", diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk index 1ca12e5104..6939253d73 100644 --- a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk @@ -1,11 +1,9 @@ // Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. #pragma define-meta USE_INSTANCING editor(elevated: true) -#pragma define-meta USE_BATCHING editor(elevated: true) -// these two macros must be non-const +// this macro must be non-const // use #pragma define to rename a macro with editor flag //#pragma define CC_SURFACES_USE_INSTANCING USE_INSTANCING -//#pragma define CC_SURFACES_USE_BATCHING USE_BATCHING diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta index 5a1200e89a..e7255edf5f 100644 --- a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "5fb14bc4-12ef-4b8f-b2d2-e0a7df233e31", diff --git a/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta index f19174c1cc..166ab85edc 100644 --- a/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "f66020b7-1a8a-424a-abf4-a8cbe80e410f", diff --git a/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta index 71dd84019e..32ddb557ec 100644 --- a/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "2f746ff4-a6d3-41ec-bcd7-52c8283f3a57", diff --git a/editor/assets/chunks/surfaces/effect-macros/sky.chunk b/editor/assets/chunks/surfaces/effect-macros/sky.chunk index 1f6d3ef76b..fbd3efdb72 100644 --- a/editor/assets/chunks/surfaces/effect-macros/sky.chunk +++ b/editor/assets/chunks/surfaces/effect-macros/sky.chunk @@ -1,7 +1,6 @@ // Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. #pragma define USE_INSTANCING 0 -#pragma define USE_BATCHING 0 // Disable unused functionality and varying data #define CC_SURFACES_USE_TANGENT_SPACE 0 diff --git a/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta index 1e06271390..7cf6ceaf5a 100644 --- a/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "dc6e17a4-b3b4-4316-8f1e-c925b6fab67c", diff --git a/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta index a49c4e71ac..fb8c2146e9 100644 --- a/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "1de87047-07ab-491a-b418-588ff145eaec", diff --git a/editor/assets/chunks/surfaces/includes/common-fs.chunk b/editor/assets/chunks/surfaces/includes/common-fs.chunk index 67497a14cf..2d967c0cec 100644 --- a/editor/assets/chunks/surfaces/includes/common-fs.chunk +++ b/editor/assets/chunks/surfaces/includes/common-fs.chunk @@ -51,7 +51,7 @@ #include // Uniform should depend on system macro, not surface macro -#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD +#if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #include #endif diff --git a/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta index 7f9cb08c46..a18e996aa7 100644 --- a/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "a6451dbc-fc4c-4a10-84f5-072c6e982fa5", diff --git a/editor/assets/chunks/surfaces/includes/common-vs.chunk b/editor/assets/chunks/surfaces/includes/common-vs.chunk index d08a6ef3b9..03c9689b45 100644 --- a/editor/assets/chunks/surfaces/includes/common-vs.chunk +++ b/editor/assets/chunks/surfaces/includes/common-vs.chunk @@ -9,7 +9,9 @@ #include #include +// Base #include +#include // Functional #include diff --git a/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta index 4507a1b1df..09fb0d36f5 100644 --- a/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "c66380b2-694f-40bd-afd8-91a2e58d904d", diff --git a/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta index 82c32350c4..89d201bf2a 100644 --- a/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "0d0afa06-80d6-45b8-9fa6-6f6ad947c00b", diff --git a/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta index abd2cec726..7e49dbbb62 100644 --- a/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "698b9da6-3f0e-4113-8b1c-5ebc82e3ab3d", diff --git a/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta index 15d9e0d196..26292b244a 100644 --- a/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "5a2c165c-7d8d-4ed5-9142-52f895dee13c", diff --git a/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta index 8df6b5aeac..a93a3a96bf 100644 --- a/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "ef0e1f2a-454f-4613-959c-3d9da0cae4f8", diff --git a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk index c1f3c01509..bf5d875629 100644 --- a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk @@ -48,7 +48,7 @@ void CCSurfacesVertexOutput(in SurfacesStandardVertexIntermediate In) VSOutput_shadowBias = In.shadowBias; #endif -#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD +#if CC_USE_LIGHTMAP && !CC_FORWARD_ADD VSOutput_lightMapUV = In.lightmapUV; #endif @@ -117,7 +117,7 @@ void CCSurfacesVertexTransferShadow(inout SurfacesStandardVertexIntermediate In) In.shadowBias = vec2(cc_shadowWHPBInfo.w, cc_shadowLPNNInfo.z); #if USE_INSTANCING In.shadowBias += a_localShadowBias.xy; - #elif !USE_BATCHING + #else In.shadowBias += cc_localShadowBias.xy; #endif #endif @@ -125,7 +125,7 @@ void CCSurfacesVertexTransferShadow(inout SurfacesStandardVertexIntermediate In) void CCSurfacesVertexTransferLightMapUV(inout SurfacesStandardVertexIntermediate In) { -#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD +#if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #if USE_INSTANCING In.lightmapUV.xy = a_lightingMapUVParam.xy + a_texCoord1 * a_lightingMapUVParam.z; In.lightmapUV.z = a_lightingMapUVParam.w; diff --git a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta index a3e2ec1a71..9fd997e6d1 100644 --- a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "e1feba3c-c7a2-4208-9c1f-732b7e46abd4", diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk index 9385e11422..1aff7c1717 100644 --- a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk @@ -68,7 +68,7 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_UVLIGHTMAP)) { - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD color = vec4(FSInput_lightMapUV.xy, 0.0, 1.0); #else color = vec4(0.0, 0.0, 0.0, 1.0); diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta index 8d793ce426..ac4a4cd8f6 100644 --- a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "30961f82-b8ef-4d3b-a9e5-944bb5e103f1", diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta index eb9b75fcb7..7a751af2be 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "6853f548-fd1c-4a96-94f3-ba6981fbefd4", diff --git a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta index 436be700d3..20deaeb315 100644 --- a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.6", + "ver": "1.0.7", "importer": "effect-header", "imported": true, "uuid": "218130cc-7167-4535-b6b8-99807138bb39", diff --git a/editor/assets/default-terrain/default-layer-texture.jpg.meta b/editor/assets/default-terrain/default-layer-texture.jpg.meta index 878ad55d3d..bf4bf8622b 100644 --- a/editor/assets/default-terrain/default-layer-texture.jpg.meta +++ b/editor/assets/default-terrain/default-layer-texture.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "52ef29ed-bd92-4e94-ab2f-0ebc91bf3a60", diff --git a/editor/assets/default_cubemap/back.jpg.meta b/editor/assets/default_cubemap/back.jpg.meta index a248822dd0..3752b1e7f5 100644 --- a/editor/assets/default_cubemap/back.jpg.meta +++ b/editor/assets/default_cubemap/back.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "03721795-84b1-4dcd-8eb3-c8e6b88ee535", diff --git a/editor/assets/default_cubemap/bottom.jpg.meta b/editor/assets/default_cubemap/bottom.jpg.meta index 9e82b36bd1..d8153214c1 100644 --- a/editor/assets/default_cubemap/bottom.jpg.meta +++ b/editor/assets/default_cubemap/bottom.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "e049bea9-db6b-463b-8502-61bf426357a1", diff --git a/editor/assets/default_cubemap/front.jpg.meta b/editor/assets/default_cubemap/front.jpg.meta index 345a535c9c..a70c110a22 100644 --- a/editor/assets/default_cubemap/front.jpg.meta +++ b/editor/assets/default_cubemap/front.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "86eb75aa-3b2f-4c7b-b59e-bdc2e3984665", diff --git a/editor/assets/default_cubemap/left.jpg.meta b/editor/assets/default_cubemap/left.jpg.meta index 5e3b661069..3401aa0d75 100644 --- a/editor/assets/default_cubemap/left.jpg.meta +++ b/editor/assets/default_cubemap/left.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "61ac0181-00bd-4c17-97f0-5fc7f4bafb3d", diff --git a/editor/assets/default_cubemap/right.jpg.meta b/editor/assets/default_cubemap/right.jpg.meta index c2323d97ee..a1abb4f6cb 100644 --- a/editor/assets/default_cubemap/right.jpg.meta +++ b/editor/assets/default_cubemap/right.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "80aabd92-9942-4765-b685-8577a1c88b4e", diff --git a/editor/assets/default_cubemap/top.jpg.meta b/editor/assets/default_cubemap/top.jpg.meta index 0063acbe5d..1d20889968 100644 --- a/editor/assets/default_cubemap/top.jpg.meta +++ b/editor/assets/default_cubemap/top.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "6c895e98-967e-4a6d-8c08-bf6b035fa2c1", diff --git a/editor/assets/default_file_content/scene b/editor/assets/default_file_content/scene index 56435e5f9e..2f66237e49 100644 --- a/editor/assets/default_file_content/scene +++ b/editor/assets/default_file_content/scene @@ -53,10 +53,10 @@ }, "_lrot": { "__type__": "cc.Quat", - "x": -0.8005972817813567, - "y": -0.1453229557254247, - "z": -0.33176781330654553, - "w": 0.4773419623260901 + "x": -0.06397656665577071, + "y": -0.44608233363525845, + "z": -0.8239028751062036, + "w": -0.3436591377065261 }, "_lscale": { "__type__": "cc.Vec3", @@ -67,9 +67,9 @@ "_layer": 1073741824, "_euler": { "__type__": "cc.Vec3", - "x": -120.254, - "y": -42.248, - "z": -4.821 + "x": -117.894, + "y": -194.909, + "z": 38.562 }, "_id": "c0y6F5f+pAvI805TdmxIjx" }, @@ -85,8 +85,8 @@ "_color": { "__type__": "cc.Color", "r": 255, - "g": 255, - "b": 255, + "g": 250, + "b": 240, "a": 255 }, "_useColorTemperature": false, @@ -209,47 +209,33 @@ "__type__": "cc.AmbientInfo", "_skyColorHDR": { "__type__": "cc.Vec4", - "x": 0.242613, - "y": 0.362617, - "z": 0.798746, - "w": 0.520833125 - }, - "_skyColor": { - "__type__": "cc.Vec4", - "x": 0.242613, - "y": 0.362617, - "z": 0.798746, + "x": 0.21465, + "y": 0.34977, + "z": 0.576641, "w": 0.520833125 }, "_skyIllumHDR": 20000, "_skyIllum": 20000, "_groundAlbedoHDR": { "__type__": "cc.Vec4", - "x": 0.241814, - "y": 0.361945, - "z": 0.798799, - "w": 0 - }, - "_groundAlbedo": { - "__type__": "cc.Vec4", - "x": 0.241814, - "y": 0.361945, - "z": 0.798799, + "x": 0.245603, + "y": 0.246646, + "z": 0.251197, "w": 0 }, "_skyColorLDR": { "__type__": "cc.Vec4", - "x": 0.519964, - "y": 0.630786, - "z": 0.905039, + "x": 0.36244, + "y": 0.486029, + "z": 0.632565, "w": 0.5208 }, "_skyIllumLDR": 0.5208, "_groundAlbedoLDR": { "__type__": "cc.Vec4", - "x": 0.519544, - "y": 0.630484, - "z": 0.905069, + "x": 0.437391, + "y": 0.436011, + "z": 0.436589, "w": 0 } }, diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta index 3e4a4764b8..37ab51c29b 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "35ac62e8-0b7a-4367-970d-dfdfbdd023c6", diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta index bed30957c3..76e6bbfee2 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "c903a495-69a9-4bb1-8266-c5d8a692ee6f", diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta index beae837a7a..d6a0d8f98d 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "1a8fc1a3-80e2-4d20-9087-426d2162ba44", diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta index c7f2bc2a58..5b35ad3340 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "744d520a-8483-4fbc-a47b-ab57d28d6203", diff --git a/editor/assets/default_materials/default-billboard-material.mtl.meta b/editor/assets/default_materials/default-billboard-material.mtl.meta index b0d7b4b01f..2f9e10255c 100644 --- a/editor/assets/default_materials/default-billboard-material.mtl.meta +++ b/editor/assets/default_materials/default-billboard-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "78e0584a-4343-4727-8f37-e14e65c2a2db", diff --git a/editor/assets/default_materials/default-clear-stencil.mtl.meta b/editor/assets/default_materials/default-clear-stencil.mtl.meta index c9a1dbaeaf..69df2017cb 100644 --- a/editor/assets/default_materials/default-clear-stencil.mtl.meta +++ b/editor/assets/default_materials/default-clear-stencil.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "8bbdbcdd-5cd4-4100-b6d5-b7c9625b6107", diff --git a/editor/assets/default_materials/default-material-transparent.mtl.meta b/editor/assets/default_materials/default-material-transparent.mtl.meta index 682a8e2d05..2064bf7a4b 100644 --- a/editor/assets/default_materials/default-material-transparent.mtl.meta +++ b/editor/assets/default_materials/default-material-transparent.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "c31a901b-671b-4c3d-9246-f9a6e5f14b90", diff --git a/editor/assets/default_materials/default-material.mtl.meta b/editor/assets/default_materials/default-material.mtl.meta index 5ee0f527bd..b3e86cf993 100644 --- a/editor/assets/default_materials/default-material.mtl.meta +++ b/editor/assets/default_materials/default-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "d3c7820c-2a98-4429-8bc7-b8453bc9ac41", diff --git a/editor/assets/default_materials/default-particle-gpu-material.mtl.meta b/editor/assets/default_materials/default-particle-gpu-material.mtl.meta index cf9f5a4ffc..c273d265ad 100644 --- a/editor/assets/default_materials/default-particle-gpu-material.mtl.meta +++ b/editor/assets/default_materials/default-particle-gpu-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "14da1725-c4c2-42b4-ab08-ee0aeb6898b3", diff --git a/editor/assets/default_materials/default-particle-material.mtl.meta b/editor/assets/default_materials/default-particle-material.mtl.meta index 9e37a9492d..3bb67cd570 100644 --- a/editor/assets/default_materials/default-particle-material.mtl.meta +++ b/editor/assets/default_materials/default-particle-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "c0143906-9aed-447e-9436-2ae8512d1b6e", diff --git a/editor/assets/default_materials/default-spine-material.mtl.meta b/editor/assets/default_materials/default-spine-material.mtl.meta index 8ce075055b..e38d156917 100644 --- a/editor/assets/default_materials/default-spine-material.mtl.meta +++ b/editor/assets/default_materials/default-spine-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "b5d6115f-0370-4d7c-aad3-c194cc71cf98", diff --git a/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta b/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta index f15f7185b0..02351b73e4 100644 --- a/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta +++ b/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "ade8a15a-dcca-4b3c-84c6-f6476ac875bb", diff --git a/editor/assets/default_materials/default-trail-material.mtl.meta b/editor/assets/default_materials/default-trail-material.mtl.meta index ad605285f6..a9c72ed1ea 100644 --- a/editor/assets/default_materials/default-trail-material.mtl.meta +++ b/editor/assets/default_materials/default-trail-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "081cab31-dccd-428e-8652-f2404cc81c47", diff --git a/editor/assets/default_materials/missing-effect-material.mtl.meta b/editor/assets/default_materials/missing-effect-material.mtl.meta index 5df39e4c85..81b5940651 100644 --- a/editor/assets/default_materials/missing-effect-material.mtl.meta +++ b/editor/assets/default_materials/missing-effect-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "bcd64cc6-2dd9-43f6-abbe-66318d332032", diff --git a/editor/assets/default_materials/missing-material.mtl.meta b/editor/assets/default_materials/missing-material.mtl.meta index 32c04d6666..7ce8228abe 100644 --- a/editor/assets/default_materials/missing-material.mtl.meta +++ b/editor/assets/default_materials/missing-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "d930590d-bb92-4cc8-8bd1-23cd027f9edf", diff --git a/editor/assets/default_materials/particle-add.mtl.meta b/editor/assets/default_materials/particle-add.mtl.meta index 0310076572..f1c732cb5c 100644 --- a/editor/assets/default_materials/particle-add.mtl.meta +++ b/editor/assets/default_materials/particle-add.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "ea7478b0-408d-4052-b703-f0d2355e095f", diff --git a/editor/assets/default_materials/standard-material.mtl.meta b/editor/assets/default_materials/standard-material.mtl.meta index 20f739f7cc..3d3c11b1b6 100644 --- a/editor/assets/default_materials/standard-material.mtl.meta +++ b/editor/assets/default_materials/standard-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "620b6bf3-0369-4560-837f-2a2c00b73c26", diff --git a/editor/assets/default_materials/ui-alpha-test-material.mtl.meta b/editor/assets/default_materials/ui-alpha-test-material.mtl.meta index 24e98c4ae6..04831cad10 100644 --- a/editor/assets/default_materials/ui-alpha-test-material.mtl.meta +++ b/editor/assets/default_materials/ui-alpha-test-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "50f4348b-c883-4e2f-8f11-ce233b859fa1", diff --git a/editor/assets/default_materials/ui-base-material.mtl.meta b/editor/assets/default_materials/ui-base-material.mtl.meta index 9161cd8ed0..baa0914269 100644 --- a/editor/assets/default_materials/ui-base-material.mtl.meta +++ b/editor/assets/default_materials/ui-base-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "e9aa9a3e-5b2b-4ac7-a2c7-073de2b2b24f", diff --git a/editor/assets/default_materials/ui-graphics-material.mtl.meta b/editor/assets/default_materials/ui-graphics-material.mtl.meta index 69289119a2..b80ffb29eb 100644 --- a/editor/assets/default_materials/ui-graphics-material.mtl.meta +++ b/editor/assets/default_materials/ui-graphics-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "f0416e68-0200-4b77-a926-4f9d16e494da", diff --git a/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta index 5943fb0914..7f8a21ff15 100644 --- a/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "f92806d7-1768-443f-afe8-12bcde84d0f0", diff --git a/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta index 76bd56caa4..f72090c94c 100644 --- a/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "dd3a144d-ab7f-41f0-82b8-2e43a090d496", diff --git a/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta b/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta index 8095ee5128..2b7ad486e6 100644 --- a/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "efe8e2a3-eace-427b-b4f1-cb8a937ec77d", diff --git a/editor/assets/default_materials/ui-sprite-material.mtl.meta b/editor/assets/default_materials/ui-sprite-material.mtl.meta index 524140c710..b08a8b2e92 100644 --- a/editor/assets/default_materials/ui-sprite-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "fda095cb-831d-4601-ad94-846013963de8", diff --git a/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta b/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta index b680c511f8..238baedfcc 100644 --- a/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta +++ b/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "016951c5-5a09-4dd0-9bb7-f4958a82d690", diff --git a/editor/assets/default_renderpipeline/post-process.mtl.meta b/editor/assets/default_renderpipeline/post-process.mtl.meta index 4102039e4d..ee2862b3d4 100644 --- a/editor/assets/default_renderpipeline/post-process.mtl.meta +++ b/editor/assets/default_renderpipeline/post-process.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "85c4d630-c264-4b18-90a4-c52d594e6099", diff --git a/editor/assets/default_renderpipeline/tonemap.mtl.meta b/editor/assets/default_renderpipeline/tonemap.mtl.meta index cdb05e0fef..fb77aca3c0 100644 --- a/editor/assets/default_renderpipeline/tonemap.mtl.meta +++ b/editor/assets/default_renderpipeline/tonemap.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "9d9704d8-08b4-4917-ba47-9d778bc77ac6", diff --git a/editor/assets/default_skybox/default_skybox.hdr b/editor/assets/default_skybox/default_skybox.hdr index b832cf876f..87457129cf 100644 Binary files a/editor/assets/default_skybox/default_skybox.hdr and b/editor/assets/default_skybox/default_skybox.hdr differ diff --git a/editor/assets/default_skybox/default_skybox.hdr.meta b/editor/assets/default_skybox/default_skybox.hdr.meta index faf7b6e215..f13fcadb14 100644 --- a/editor/assets/default_skybox/default_skybox.hdr.meta +++ b/editor/assets/default_skybox/default_skybox.hdr.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "d032ac98-05e1-4090-88bb-eb640dcb5fc1", diff --git a/editor/assets/default_skybox/default_skybox.png b/editor/assets/default_skybox/default_skybox.png index 1dd6e4d1b6..78e3311c4c 100644 Binary files a/editor/assets/default_skybox/default_skybox.png and b/editor/assets/default_skybox/default_skybox.png differ diff --git a/editor/assets/default_skybox/default_skybox.png.meta b/editor/assets/default_skybox/default_skybox.png.meta index a2ff05be73..ed28be6c3c 100644 --- a/editor/assets/default_skybox/default_skybox.png.meta +++ b/editor/assets/default_skybox/default_skybox.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "6f01cf7f-81bf-4a7e-bd5d-0afc19696480", diff --git a/editor/assets/default_ui/atom.png.meta b/editor/assets/default_ui/atom.png.meta index 5c97537beb..3c9c428ad2 100644 --- a/editor/assets/default_ui/atom.png.meta +++ b/editor/assets/default_ui/atom.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "24c419ea-63a8-4ea1-a9d0-7fc469489bbc", diff --git a/editor/assets/default_ui/default_btn_disabled.png.meta b/editor/assets/default_ui/default_btn_disabled.png.meta index fcf5c3d60e..e0ae3c8674 100644 --- a/editor/assets/default_ui/default_btn_disabled.png.meta +++ b/editor/assets/default_ui/default_btn_disabled.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "951249e0-9f16-456d-8b85-a6ca954da16b", diff --git a/editor/assets/default_ui/default_btn_normal.png.meta b/editor/assets/default_ui/default_btn_normal.png.meta index 599e2d36b2..8eb6404397 100644 --- a/editor/assets/default_ui/default_btn_normal.png.meta +++ b/editor/assets/default_ui/default_btn_normal.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "20835ba4-6145-4fbc-a58a-051ce700aa3e", diff --git a/editor/assets/default_ui/default_btn_pressed.png.meta b/editor/assets/default_ui/default_btn_pressed.png.meta index 2c839b3fa7..5c8f5eed3a 100644 --- a/editor/assets/default_ui/default_btn_pressed.png.meta +++ b/editor/assets/default_ui/default_btn_pressed.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "544e49d6-3f05-4fa8-9a9e-091f98fc2ce8", diff --git a/editor/assets/default_ui/default_editbox_bg.png.meta b/editor/assets/default_ui/default_editbox_bg.png.meta index fe7c4a1164..f6afc7b756 100644 --- a/editor/assets/default_ui/default_editbox_bg.png.meta +++ b/editor/assets/default_ui/default_editbox_bg.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "bd1bcaba-bd7d-4a71-b143-997c882383e4", diff --git a/editor/assets/default_ui/default_panel.png.meta b/editor/assets/default_ui/default_panel.png.meta index 5b14a29f14..2a88ea9b1b 100644 --- a/editor/assets/default_ui/default_panel.png.meta +++ b/editor/assets/default_ui/default_panel.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "b730527c-3233-41c2-aaf7-7cdab58f9749", diff --git a/editor/assets/default_ui/default_progressbar.png.meta b/editor/assets/default_ui/default_progressbar.png.meta index 8b66679429..e8a9deea93 100644 --- a/editor/assets/default_ui/default_progressbar.png.meta +++ b/editor/assets/default_ui/default_progressbar.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "24a704da-2867-446d-8d1a-5e920c75e09d", diff --git a/editor/assets/default_ui/default_progressbar_bg.png.meta b/editor/assets/default_ui/default_progressbar_bg.png.meta index 18bda7027f..93dafd82c1 100644 --- a/editor/assets/default_ui/default_progressbar_bg.png.meta +++ b/editor/assets/default_ui/default_progressbar_bg.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "9fd900dd-221b-4f89-8f2c-fba34243c835", diff --git a/editor/assets/default_ui/default_radio_button_off.png.meta b/editor/assets/default_ui/default_radio_button_off.png.meta index 05ec0d79c5..cf4f23e956 100644 --- a/editor/assets/default_ui/default_radio_button_off.png.meta +++ b/editor/assets/default_ui/default_radio_button_off.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "f12a23c4-b924-4322-a260-3d982428f1e8", diff --git a/editor/assets/default_ui/default_radio_button_on.png.meta b/editor/assets/default_ui/default_radio_button_on.png.meta index e384514b35..a3e8f2398e 100644 --- a/editor/assets/default_ui/default_radio_button_on.png.meta +++ b/editor/assets/default_ui/default_radio_button_on.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "45828f25-b50d-4c52-a591-e19491a62b8c", diff --git a/editor/assets/default_ui/default_scrollbar.png.meta b/editor/assets/default_ui/default_scrollbar.png.meta index b6d2022335..32730e4a39 100644 --- a/editor/assets/default_ui/default_scrollbar.png.meta +++ b/editor/assets/default_ui/default_scrollbar.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "0da256a2-21f6-481b-90b6-d3643a09179b", diff --git a/editor/assets/default_ui/default_scrollbar_bg.png.meta b/editor/assets/default_ui/default_scrollbar_bg.png.meta index 1072568b45..941e35d054 100644 --- a/editor/assets/default_ui/default_scrollbar_bg.png.meta +++ b/editor/assets/default_ui/default_scrollbar_bg.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "28765e2f-040a-4c65-8e8c-f9d0bb79d863", diff --git a/editor/assets/default_ui/default_scrollbar_vertical.png.meta b/editor/assets/default_ui/default_scrollbar_vertical.png.meta index 1c9f0ae3d6..a3e3ad9031 100644 --- a/editor/assets/default_ui/default_scrollbar_vertical.png.meta +++ b/editor/assets/default_ui/default_scrollbar_vertical.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "afc47931-f066-46b0-90be-9fe61f213428", diff --git a/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta b/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta index 376456f7d1..f77e09440b 100644 --- a/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta +++ b/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "ffb88a8f-af62-48f4-8f1d-3cb606443a43", diff --git a/editor/assets/default_ui/default_sprite.png.meta b/editor/assets/default_ui/default_sprite.png.meta index 2557d0a65e..507bdb93be 100644 --- a/editor/assets/default_ui/default_sprite.png.meta +++ b/editor/assets/default_ui/default_sprite.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "57520716-48c8-4a19-8acf-41c9f8777fb0", diff --git a/editor/assets/default_ui/default_sprite_splash.png.meta b/editor/assets/default_ui/default_sprite_splash.png.meta index bf413bbca0..8998d56e97 100644 --- a/editor/assets/default_ui/default_sprite_splash.png.meta +++ b/editor/assets/default_ui/default_sprite_splash.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "7d8f9b89-4fd1-4c9f-a3ab-38ec7cded7ca", diff --git a/editor/assets/default_ui/default_toggle_checkmark.png.meta b/editor/assets/default_ui/default_toggle_checkmark.png.meta index 26adfb7e12..a0fb717a91 100644 --- a/editor/assets/default_ui/default_toggle_checkmark.png.meta +++ b/editor/assets/default_ui/default_toggle_checkmark.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "158e7e52-3220-4cd7-9694-713e0e6e8278", diff --git a/editor/assets/default_ui/default_toggle_disabled.png.meta b/editor/assets/default_ui/default_toggle_disabled.png.meta index 4992203dd7..aab49915f2 100644 --- a/editor/assets/default_ui/default_toggle_disabled.png.meta +++ b/editor/assets/default_ui/default_toggle_disabled.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "ca7e121b-293c-4763-829a-b7a5fa81f0d2", diff --git a/editor/assets/default_ui/default_toggle_normal.png.meta b/editor/assets/default_ui/default_toggle_normal.png.meta index 0b8b872f05..eed3b858f3 100644 --- a/editor/assets/default_ui/default_toggle_normal.png.meta +++ b/editor/assets/default_ui/default_toggle_normal.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "11bdc4b0-64a8-4eb7-a2a7-9fb9e233e977", diff --git a/editor/assets/default_ui/default_toggle_pressed.png.meta b/editor/assets/default_ui/default_toggle_pressed.png.meta index 9efd242834..2ab9f40ea9 100644 --- a/editor/assets/default_ui/default_toggle_pressed.png.meta +++ b/editor/assets/default_ui/default_toggle_pressed.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "a04e994f-ee49-47b6-9d08-2f59e3773fcc", diff --git a/editor/assets/effects/builtin-billboard.effect.meta b/editor/assets/effects/builtin-billboard.effect.meta index e20264a1b4..e2f5bf0bdb 100644 --- a/editor/assets/effects/builtin-billboard.effect.meta +++ b/editor/assets/effects/builtin-billboard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "711ebe11-f673-4cd9-9a83-63c60ba54c5b", diff --git a/editor/assets/effects/builtin-camera-texture.effect.meta b/editor/assets/effects/builtin-camera-texture.effect.meta index 9fa7a4b82b..786625a535 100644 --- a/editor/assets/effects/builtin-camera-texture.effect.meta +++ b/editor/assets/effects/builtin-camera-texture.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "bf4078d6-d2d7-4073-83bb-cd6f1802e880", diff --git a/editor/assets/effects/builtin-clear-stencil.effect.meta b/editor/assets/effects/builtin-clear-stencil.effect.meta index 7e84dd0a25..262a33ae5b 100644 --- a/editor/assets/effects/builtin-clear-stencil.effect.meta +++ b/editor/assets/effects/builtin-clear-stencil.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "810e96e4-e456-4468-9b59-f4e8f39732c0", diff --git a/editor/assets/effects/builtin-debug-renderer.effect.meta b/editor/assets/effects/builtin-debug-renderer.effect.meta index c3b4e76c92..656d058e12 100644 --- a/editor/assets/effects/builtin-debug-renderer.effect.meta +++ b/editor/assets/effects/builtin-debug-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "ff9be190-20a4-4e48-b68c-76e3c7cff085", diff --git a/editor/assets/effects/builtin-geometry-renderer.effect.meta b/editor/assets/effects/builtin-geometry-renderer.effect.meta index 85f549aa9d..a45df37642 100644 --- a/editor/assets/effects/builtin-geometry-renderer.effect.meta +++ b/editor/assets/effects/builtin-geometry-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "4bb480dd-8384-4bc9-987f-de67cc53052a", diff --git a/editor/assets/effects/builtin-graphics.effect.meta b/editor/assets/effects/builtin-graphics.effect.meta index 606abf3434..d864f60ed1 100644 --- a/editor/assets/effects/builtin-graphics.effect.meta +++ b/editor/assets/effects/builtin-graphics.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "1c02ae6f-4492-4915-b8f8-7492a3b1e4cd", diff --git a/editor/assets/effects/builtin-occlusion-query.effect.meta b/editor/assets/effects/builtin-occlusion-query.effect.meta index b72166aaa6..e8417588f1 100644 --- a/editor/assets/effects/builtin-occlusion-query.effect.meta +++ b/editor/assets/effects/builtin-occlusion-query.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "d9937e59-61fe-4ec6-92ab-7ac5a19c89b0", diff --git a/editor/assets/effects/builtin-particle-gpu.effect.meta b/editor/assets/effects/builtin-particle-gpu.effect.meta index 2a00666780..879981445a 100644 --- a/editor/assets/effects/builtin-particle-gpu.effect.meta +++ b/editor/assets/effects/builtin-particle-gpu.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "971bdb23-3ff6-43eb-b422-1c30165a3663", diff --git a/editor/assets/effects/builtin-particle-trail.effect.meta b/editor/assets/effects/builtin-particle-trail.effect.meta index 2fc3662360..c7ed3d17a4 100644 --- a/editor/assets/effects/builtin-particle-trail.effect.meta +++ b/editor/assets/effects/builtin-particle-trail.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "17debcc3-0a6b-4b8a-b00b-dc58b885581e", diff --git a/editor/assets/effects/builtin-particle-xr-trail.effect.meta b/editor/assets/effects/builtin-particle-xr-trail.effect.meta index 0ef43dd47c..8d29aa52f1 100644 --- a/editor/assets/effects/builtin-particle-xr-trail.effect.meta +++ b/editor/assets/effects/builtin-particle-xr-trail.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "e38f81af-70ec-4f7a-b377-767b0ec76377", diff --git a/editor/assets/effects/builtin-particle.effect.meta b/editor/assets/effects/builtin-particle.effect.meta index 199127c767..6e7da5c8c1 100644 --- a/editor/assets/effects/builtin-particle.effect.meta +++ b/editor/assets/effects/builtin-particle.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "d1346436-ac96-4271-b863-1f4fdead95b0", diff --git a/editor/assets/effects/builtin-reflection-deferred.effect b/editor/assets/effects/builtin-reflection-deferred.effect index 97d8c3a8d1..79bb8e8695 100644 --- a/editor/assets/effects/builtin-reflection-deferred.effect +++ b/editor/assets/effects/builtin-reflection-deferred.effect @@ -20,7 +20,7 @@ CCEffect %{ mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } - occlusion: { value: 1.0, target: pbrParams.x } + occlusion: { value: 0.0, target: pbrParams.x } roughness: { value: 0.8, target: pbrParams.y } metallic: { value: 0.6, target: pbrParams.z } normalStrenth: { value: 1.0, target: pbrParams.w, editor: { parent: USE_NORMAL_MAP } } @@ -74,7 +74,7 @@ CCProgram standard-vs %{ in vec2 a_texCoord1; #endif - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #endif @@ -106,7 +106,7 @@ CCProgram standard-vs %{ CC_TRANSFER_FOG(pos); CC_TRANSFER_SHADOW(pos); - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD CCLightingMapCaclUV(); #endif @@ -121,7 +121,7 @@ CCProgram standard-fs %{ #include #include #include - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #endif @@ -184,7 +184,7 @@ CCProgram standard-fs %{ if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; #endif - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD s.lightmap = texture(cc_lightingMap, v_luv); #endif @@ -200,6 +200,7 @@ CCProgram standard-fs %{ HIGHP_VALUE_TO_STRUCT_DEFINED(v_position, s.position); vec4 pbr = pbrParams; + pbr.x = 1.0 - pbr.x; #if USE_PBR_MAP vec4 res = texture(pbrMap, PBR_UV); pbr.x *= res.OCCLUSION_CHANNEL; diff --git a/editor/assets/effects/builtin-reflection-deferred.effect.meta b/editor/assets/effects/builtin-reflection-deferred.effect.meta index 8c5fecb1b5..159e446037 100644 --- a/editor/assets/effects/builtin-reflection-deferred.effect.meta +++ b/editor/assets/effects/builtin-reflection-deferred.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "99498f84-efe6-43a6-a9a7-e6e93eb845c1", diff --git a/editor/assets/effects/builtin-spine.effect.meta b/editor/assets/effects/builtin-spine.effect.meta index 9554bc18ba..cbbda5a701 100644 --- a/editor/assets/effects/builtin-spine.effect.meta +++ b/editor/assets/effects/builtin-spine.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "c27215d8-6835-4b68-bfbb-bdeac6100c04", diff --git a/editor/assets/effects/builtin-sprite-renderer.effect.meta b/editor/assets/effects/builtin-sprite-renderer.effect.meta index 4feaac9132..c4ff4ad5eb 100644 --- a/editor/assets/effects/builtin-sprite-renderer.effect.meta +++ b/editor/assets/effects/builtin-sprite-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "6ef1defe-7997-477a-9b35-c18859ff8066", diff --git a/editor/assets/effects/builtin-sprite.effect.meta b/editor/assets/effects/builtin-sprite.effect.meta index 493b73d9b7..2feaea8bf4 100644 --- a/editor/assets/effects/builtin-sprite.effect.meta +++ b/editor/assets/effects/builtin-sprite.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", diff --git a/editor/assets/effects/builtin-standard.effect b/editor/assets/effects/builtin-standard.effect index bf63e71f8a..22f9a4ba2f 100644 --- a/editor/assets/effects/builtin-standard.effect +++ b/editor/assets/effects/builtin-standard.effect @@ -11,7 +11,7 @@ CCEffect %{ mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } - occlusion: { value: 1.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + occlusion: { value: 0.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } roughness: { value: 0.8, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } metallic: { value: 0.6, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } @@ -118,7 +118,7 @@ CCProgram standard-vs %{ in vec2 a_texCoord1; #endif - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #endif @@ -166,7 +166,7 @@ CCProgram standard-vs %{ CC_TRANSFER_FOG(pos); CC_TRANSFER_SHADOW(pos); - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD CCLightingMapCaclUV(); #endif @@ -180,7 +180,7 @@ CCProgram standard-fs %{ #include #include #include - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #endif @@ -250,7 +250,7 @@ CCProgram standard-fs %{ if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; #endif - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD vec4 lightColor = texture(cc_lightingMap, v_luv.xy); s.lightmap = lightColor.xyz * v_luv.z; s.lightmap_test = v_luv.z; /*lum*/ @@ -274,6 +274,7 @@ CCProgram standard-fs %{ HIGHP_VALUE_TO_STRUCT_DEFINED(v_position, s.position); vec4 pbr = pbrParams; + pbr.x = 1.0 - pbr.x; #if USE_PBR_MAP vec4 res = texture(pbrMap, PBR_UV); pbr.x *= res.OCCLUSION_CHANNEL; @@ -291,8 +292,8 @@ CCProgram standard-fs %{ #endif s.occlusion = pbr.x; s.roughness = pbr.y; - s.specularIntensity = 0.5; s.metallic = pbr.z; + s.specularIntensity = pbr.w; s.emissive = emissive.rgb * emissiveScaleParam.xyz; #if USE_EMISSIVE_MAP diff --git a/editor/assets/effects/builtin-standard.effect.meta b/editor/assets/effects/builtin-standard.effect.meta index 5ef7581ebd..eb92874cc1 100644 --- a/editor/assets/effects/builtin-standard.effect.meta +++ b/editor/assets/effects/builtin-standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "1baf0fc9-befa-459c-8bdd-af1a450a0319", diff --git a/editor/assets/effects/builtin-terrain.effect b/editor/assets/effects/builtin-terrain.effect index 4916a85623..6c0ce9285d 100644 --- a/editor/assets/effects/builtin-terrain.effect +++ b/editor/assets/effects/builtin-terrain.effect @@ -111,7 +111,7 @@ CCProgram terrain-fs %{ #include #include #include - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #endif #pragma define-meta LAYERS range([0, 4]) @@ -261,7 +261,7 @@ CCProgram terrain-fs %{ #endif s.emissive = vec3(0.0, 0.0, 0.0); - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD vec4 lightColor = texture(cc_lightingMap, luv.xy); s.lightmap = lightColor.xyz * luv.z; s.lightmap_test = luv.z; /*lum*/ diff --git a/editor/assets/effects/builtin-terrain.effect.meta b/editor/assets/effects/builtin-terrain.effect.meta index f4b88c274b..f6fced1f2b 100644 --- a/editor/assets/effects/builtin-terrain.effect.meta +++ b/editor/assets/effects/builtin-terrain.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "1d08ef62-a503-4ce2-8b9a-46c90873f7d3", diff --git a/editor/assets/effects/builtin-toon.effect.meta b/editor/assets/effects/builtin-toon.effect.meta index a7cbaf60ad..0be5a1524e 100644 --- a/editor/assets/effects/builtin-toon.effect.meta +++ b/editor/assets/effects/builtin-toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "a7612b54-35e3-4238-a1a9-4a7b54635839", diff --git a/editor/assets/effects/builtin-unlit.effect.meta b/editor/assets/effects/builtin-unlit.effect.meta index b5fe8b2ef9..c093a2552d 100644 --- a/editor/assets/effects/builtin-unlit.effect.meta +++ b/editor/assets/effects/builtin-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "a3cd009f-0ab0-420d-9278-b9fdab939bbc", diff --git a/editor/assets/effects/builtin-wireframe.effect.meta b/editor/assets/effects/builtin-wireframe.effect.meta index 73586b5297..e07c27a38c 100644 --- a/editor/assets/effects/builtin-wireframe.effect.meta +++ b/editor/assets/effects/builtin-wireframe.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "81127eb0-7556-453c-b147-670782dd5e53", diff --git a/editor/assets/effects/dcc/imported-metallic-roughness.effect b/editor/assets/effects/dcc/imported-metallic-roughness.effect index 57d9153dc4..c704fc96ce 100644 --- a/editor/assets/effects/dcc/imported-metallic-roughness.effect +++ b/editor/assets/effects/dcc/imported-metallic-roughness.effect @@ -16,7 +16,7 @@ CCEffect %{ roughnessMap: { value: grey } metallic: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } metallicMap: { value: grey } - occlusion: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + occlusion: { value: 0.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } occlusionMap: { value: white } emissiveScale: { value: 1.0, editor: { displayName: Emissive } } emissiveScaleMap: { value: grey, editor: { displayName: EmissiveMap } } @@ -127,7 +127,7 @@ CCProgram standard-vs %{ in vec2 a_texCoord1; #endif - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #endif @@ -175,7 +175,7 @@ CCProgram standard-vs %{ CC_TRANSFER_FOG(pos); CC_TRANSFER_SHADOW(pos); - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD CCLightingMapCaclUV(); #endif @@ -189,7 +189,7 @@ CCProgram standard-fs %{ #include #include #include - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #endif @@ -307,7 +307,7 @@ CCProgram standard-fs %{ s.roughness = max(0.02, roughnessValue); - float occlusionValue = occlusion; + float occlusionValue = 1.0 - occlusion; #if USE_OCCLUSION_MAP vec4 occlusionColor = texture(occlusionMap, TEXTURE_UV); occlusionValue = discolor(occlusionColor.rgb); @@ -337,7 +337,7 @@ CCProgram standard-fs %{ ///////////////////////////// s.albedo = baseColor; - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD vec4 lightColor = texture(cc_lightingMap, v_luv.xy); s.lightmap = lightColor.xyz * v_luv.z; s.lightmap_test = v_luv.z; /*lum*/ diff --git a/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta index ce0d8acab3..7101eae823 100644 --- a/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta +++ b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "2ec11458-f855-4978-b14d-f3ed5cf697fa", diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect b/editor/assets/effects/dcc/imported-specular-glossiness.effect index 05af1fb76c..785de584d9 100644 --- a/editor/assets/effects/dcc/imported-specular-glossiness.effect +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect @@ -127,7 +127,7 @@ CCProgram standard-vs %{ in vec2 a_texCoord1; #endif - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #endif @@ -166,7 +166,7 @@ CCProgram standard-vs %{ CC_TRANSFER_FOG(pos); CC_TRANSFER_SHADOW(pos); - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD CCLightingMapCaclUV(); #endif @@ -185,7 +185,7 @@ CCProgram standard-fs %{ #include #include #include - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD #include #endif @@ -200,12 +200,13 @@ CCProgram standard-fs %{ #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) - #pragma define-meta DCC_APP_NAME range([0, 4]) + #pragma define-meta DCC_APP_NAME range([0, 5]) #define DCC_APP_OTHERS 0 - #define DCC_APP_AUTODESK 1 + #define DCC_APP_MAX 1 #define DCC_APP_BLENDER 2 #define DCC_APP_CINEMA4D 3 #define DCC_APP_GLTF 4 + #define DCC_APP_MAYA 5 #if USE_SHININESS_MAP uniform sampler2D shininessExponentMap; @@ -230,6 +231,7 @@ CCProgram standard-fs %{ #endif #if USE_TRANSPARENCY_MAP uniform sampler2D transparencyMap; + #pragma define-meta TRANSPARENCY_MAP_CHANNEL options([a, r, g, b]) #endif #if USE_NORMAL_MAP @@ -250,7 +252,7 @@ CCProgram standard-fs %{ #if DCC_APP_NAME == DCC_APP_BLENDER // 2-100 float glossiness = clamp(sqrt(shininessExp) * 0.1/*/10.0*/, 0.0, 0.95); // glossiness=1 may leads to specular disappear - #elif DCC_APP_NAME == DCC_APP_AUTODESK + #elif DCC_APP_NAME == DCC_APP_MAX || DCC_APP_NAME == DCC_APP_MAYA // 2-1024 float l2 = clamp(log(shininessExp + EPSILON) * 0.1442695 /*/log(2.0)/10.0*/, 0.0, 1.0); float glossiness = pow(l2, 0.5); @@ -266,7 +268,7 @@ CCProgram standard-fs %{ float specularIntensityMultiplier = mix(1.0, 5.0, roughness); #elif DCC_APP_NAME == DCC_APP_CINEMA4D float specularIntensityMultiplier = mix(1.0, 50.0, roughness); - #elif DCC_APP_NAME == DCC_APP_AUTODESK + #elif DCC_APP_NAME == DCC_APP_MAX || DCC_APP_NAME == DCC_APP_MAYA float specularIntensityMultiplier = mix(1.0, 20.0, roughness); #else // DCC_APP_NAME == DCC_APP_GLTF / DCC_APP_OTHERS float specularIntensityMultiplier = 1.0; @@ -276,7 +278,8 @@ CCProgram standard-fs %{ vec4 getSpecularColorAndFactor() { - vec3 inSpecular = specularColor.rgb; + vec3 inSpecular = specularColor.rgb * specularFactor; + float inFactor = 1.0; //reserved #if USE_SPECULAR_GLOSSINESS_MAP inSpecular = SRGBToLinear(texture(specularGlossinessMap, TEXTURE_UV).rgb); #endif @@ -285,7 +288,7 @@ CCProgram standard-fs %{ specularTex.rgb = SRGBToLinear(specularTex.rgb); inSpecular = specularTex.rgb; #endif - return vec4(inSpecular, specularFactor); + return vec4(inSpecular, inFactor); } void surf (out StandardSurface s) { //diffuse @@ -305,7 +308,10 @@ CCProgram standard-fs %{ baseColor.rgb *= diffuseFactor; #if USE_TRANSPARENCY_MAP - baseColor.a = texture(transparencyMap, TEXTURE_UV).a; + baseColor.a = texture(transparencyMap, TEXTURE_UV).TRANSPARENCY_MAP_CHANNEL; + #if DCC_APP_NAME == DCC_APP_MAYA + baseColor.a = 1.0 - baseColor.a; + #endif #endif #if USE_ALPHA_TEST @@ -319,7 +325,7 @@ CCProgram standard-fs %{ vec4 specularColorAndFactor = getSpecularColorAndFactor(); //glossiness - float inGlossiness = 0.0, inSpecularIntensity = specularColorAndFactor.w; + float inGlossiness = 0.0, inSpecularIntensity = 1.0; #if HAS_EXPORTED_GLOSSINESS #if USE_SPECULAR_GLOSSINESS_MAP inGlossiness = 1.0 - texture(specularGlossinessMap, TEXTURE_UV).a; @@ -371,12 +377,12 @@ CCProgram standard-fs %{ s.roughness = 1.0 - inGlossiness; s.metallic = inMetallic; s.specularIntensity = inSpecularIntensity * 0.5; - s.emissive = vec3(0.0); + s.emissive = emissive.rgb; #if USE_EMISSIVE_MAP s.emissive = texture(emissiveMap, TEXTURE_UV).xyz; #endif - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD vec4 lightColor = texture(cc_lightingMap, v_luv.xy); s.lightmap = lightColor.xyz * v_luv.z; s.lightmap_test = v_luv.z; /*lum*/ @@ -445,6 +451,13 @@ CCProgram shadow-caster-fs %{ in highp vec2 v_clip_depth; #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) + #pragma define-meta DCC_APP_NAME range([0, 5]) + #define DCC_APP_OTHERS 0 + #define DCC_APP_MAX 1 + #define DCC_APP_BLENDER 2 + #define DCC_APP_CINEMA4D 3 + #define DCC_APP_GLTF 4 + #define DCC_APP_MAYA 5 #if USE_ALBEDO_MAP uniform sampler2D albedoMap; @@ -452,6 +465,7 @@ CCProgram shadow-caster-fs %{ #if USE_TRANSPARENCY_MAP uniform sampler2D transparencyMap; + #pragma define-meta TRANSPARENCY_MAP_CHANNEL options([a, r, g, b]) #endif #if USE_VERTEX_COLOR @@ -468,7 +482,10 @@ CCProgram shadow-caster-fs %{ alpha *= texture(albedoMap, TEXTURE_UV).a * transparencyFactor; #endif #if USE_TRANSPARENCY_MAP - alpha = texture(transparencyMap, TEXTURE_UV).a; + alpha = texture(transparencyMap, TEXTURE_UV).TRANSPARENCY_MAP_CHANNEL; + #if DCC_APP_NAME == DCC_APP_MAYA + alpha = 1.0 - alpha; + #endif #endif if (alpha < alphaThreshold) discard; #endif diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta index 65cdc0ec62..ccf6219139 100644 --- a/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "f648964e-8d32-41fc-9ac9-7a1e714dd17b", diff --git a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect index f0e0515a49..1886e628d0 100644 --- a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect +++ b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect @@ -16,7 +16,7 @@ CCEffect %{ roughnessMap: { value: grey } metallic: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } metallicMap: { value: grey } - occlusion: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + occlusion: { value: 0.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } occlusionMap: { value: white } emissiveScale: { value: 1.0, editor: { displayName: Emissive } } emissiveScaleMap: { value: grey, editor: { displayName: EmissiveMap } } @@ -291,7 +291,7 @@ CCProgram surface-fragment %{ { vec4 pbr = vec4(1.0,1.0,1.0,1.0); //ao - float occlusionValue = occlusion; + float occlusionValue = 1.0 - occlusion; #if USE_OCCLUSION_MAP vec4 occlusionColor = texture(occlusionMap, TEXTURE_UV); occlusionValue = discolor(occlusionColor.rgb); diff --git a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta index f29d286864..20280ed61c 100644 --- a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta +++ b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "994bae8e-8bfc-4bc4-a32d-ad924f9917d0", diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect index 47c620cd7f..a13dc7d509 100644 --- a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect @@ -7,26 +7,27 @@ CCEffect %{ - vert: standard-vs frag: standard-fs properties: &props - mainTexture: { value: grey, target: albedoMap, editor: { displayName: DiffuseMap } } - mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, linear: true, editor: { displayName: DiffuseColor, type: color } } - albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } - alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } - emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } - emissiveMap: { value: grey } - shininessExponentMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } - shininessExponent: { value: 100.0, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } - specularColor: { value: [0.0, 0.0, 0.0, 0.0], linear: true, editor: { displayName: SpecularColor, type: color } } - specularMap: { value: grey, editor: { parent: '!HAS_EXPORTED_METALLIC' } } - specularFactor: { value: 1.0, editor: { parent: '!HAS_EXPORTED_METALLIC' } } - transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } - transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } - normalStrength: { value: 1.0, target: normalScale, editor: { displayName: bumpFactor, parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } - normalMap: { value: normal } - glossiness: { value: 0.0, editor: { parent: HAS_EXPORTED_GLOSSINESS, slide: true, range: [0, 1.0], step: 0.001 } } - metallic: { value: 0.0, editor: { parent: HAS_EXPORTED_METALLIC, slide: true, range: [0, 1.0], step: 0.001 } } - metallicMap: { value: grey, editor: { parent: HAS_EXPORTED_METALLIC } } - occlusionMap: { value: white } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: DiffuseMap } } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, linear: true, editor: { displayName: DiffuseColor, type: color } } + albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } + alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } + emissiveMap: { value: grey } + shininessExponentMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } + shininessExponent: { value: 100.0, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } + specularGlossinessMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } + specularColor: { value: [0.0, 0.0, 0.0, 0.0], linear: true, editor: { displayName: SpecularColor, type: color } } + specularMap: { value: grey, editor: { parent: '!HAS_EXPORTED_METALLIC' } } + specularFactor: { value: 1.0, editor: { parent: '!HAS_EXPORTED_METALLIC' } } + transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } + transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + normalStrength: { value: 1.0, target: normalScale, editor: { displayName: bumpFactor, parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } + normalMap: { value: normal } + glossiness: { value: 0.0, editor: { parent: HAS_EXPORTED_GLOSSINESS, slide: true, range: [0, 1.0], step: 0.001 } } + metallic: { value: 0.0, editor: { parent: HAS_EXPORTED_METALLIC, slide: true, range: [0, 1.0], step: 0.001 } } + metallicMap: { value: grey, editor: { parent: HAS_EXPORTED_METALLIC } } + occlusionMap: { value: white } - &forward-add vert: standard-vs frag: standard-fs @@ -136,17 +137,21 @@ CCProgram surface-vertex %{ CCProgram surface-fragment %{ #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) - #pragma define-meta DCC_APP_NAME range([0, 4]) + #pragma define-meta DCC_APP_NAME range([0, 5]) #define DCC_APP_OTHERS 0 - #define DCC_APP_AUTODESK 1 + #define DCC_APP_MAX 1 #define DCC_APP_BLENDER 2 #define DCC_APP_CINEMA4D 3 #define DCC_APP_GLTF 4 + #define DCC_APP_MAYA 5 #if USE_SHININESS_MAP uniform sampler2D shininessExponentMap; #pragma define-meta GLOSSINESS_MAP_CHANNEL options([r,g,b,a]) #endif + #if USE_SPECULAR_GLOSSINESS_MAP + uniform sampler2D specularGlossinessMap; + #endif #if USE_SPECULAR_MAP uniform sampler2D specularMap; #endif @@ -159,6 +164,7 @@ CCProgram surface-fragment %{ #endif #if USE_TRANSPARENCY_MAP uniform sampler2D transparencyMap; + #pragma define-meta TRANSPARENCY_MAP_CHANNEL options([a, r, g, b]) #endif #if USE_EMISSIVE_MAP @@ -185,11 +191,11 @@ CCProgram surface-fragment %{ #if DCC_APP_NAME == DCC_APP_BLENDER // 2-100 float glossiness = clamp(sqrt(shininessExp) * 0.1/*/10.0*/, 0.0, 0.95); // glossiness=1 may leads to specular disappear - #elif DCC_APP_NAME == DCC_APP_AUTODESK + #elif DCC_APP_NAME == DCC_APP_MAX || DCC_APP_NAME == DCC_APP_MAYA // 2-1024 float l2 = clamp(log(shininessExp + EPSILON) * 0.1442695 /*/log(2.0)/10.0*/, 0.0, 1.0); float glossiness = pow(l2, 0.5); - #else // DCC_APP_NAME == DCC_APP_CINEMA4D、DCC_APP_GLTF、DCC_APP_OTHERS + #else // DCC_APP_NAME == DCC_APP_CINEMA4D / DCC_APP_GLTF / DCC_APP_OTHERS // 2-1024 float glossiness = clamp(log(shininessExp + EPSILON) * 0.1442695 /*/log(2.0)/10.0*/, 0.0, 1.0); #endif @@ -201,9 +207,9 @@ CCProgram surface-fragment %{ float specularIntensityMultiplier = mix(1.0, 5.0, roughness); #elif DCC_APP_NAME == DCC_APP_CINEMA4D float specularIntensityMultiplier = mix(1.0, 50.0, roughness); - #elif DCC_APP_NAME == DCC_APP_AUTODESK + #elif DCC_APP_NAME == DCC_APP_MAX || DCC_APP_NAME == DCC_APP_MAYA float specularIntensityMultiplier = mix(1.0, 20.0, roughness); - #else // DCC_APP_NAME == DCC_APP_GLTF、DCC_APP_OTHERS + #else // DCC_APP_NAME == DCC_APP_GLTF / DCC_APP_OTHERS float specularIntensityMultiplier = 1.0; #endif return specularIntensityMultiplier; @@ -211,13 +217,17 @@ CCProgram surface-fragment %{ vec4 getSpecularColorAndFactor() { - vec3 inSpecular = specularColor.rgb; + vec3 inSpecular = specularColor.rgb * specularFactor; + float inFactor = 1.0; //reserved + #if USE_SPECULAR_GLOSSINESS_MAP + inSpecular = SRGBToLinear(texture(specularGlossinessMap, TEXTURE_UV).rgb); + #endif #if USE_SPECULAR_MAP vec4 specularTex = texture(specularMap, TEXTURE_UV); specularTex.rgb = SRGBToLinear(specularTex.rgb); inSpecular = specularTex.rgb; #endif - return vec4(inSpecular, specularFactor); + return vec4(inSpecular, inFactor); } #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY @@ -232,7 +242,10 @@ CCProgram surface-fragment %{ alpha *= texture(albedoMap, TEXTURE_UV).a * transparencyFactor; #endif #if USE_TRANSPARENCY_MAP - alpha = texture(transparencyMap, TEXTURE_UV).a; + alpha = texture(transparencyMap, TEXTURE_UV).TRANSPARENCY_MAP_CHANNEL; + #if DCC_APP_NAME == DCC_APP_MAYA + alpha = 1.0 - alpha; + #endif #endif if (alpha < alphaThreshold) discard; #endif @@ -280,7 +293,10 @@ CCProgram surface-fragment %{ baseColor.rgb *= diffuseFactor; #if USE_TRANSPARENCY_MAP - baseColor.a = texture(transparencyMap, TEXTURE_UV).a; + baseColor.a = texture(transparencyMap, TEXTURE_UV).TRANSPARENCY_MAP_CHANNEL; + #if DCC_APP_NAME == DCC_APP_MAYA + baseColor.a = 1.0 - baseColor.a; + #endif #endif #if USE_ALPHA_TEST @@ -289,9 +305,13 @@ CCProgram surface-fragment %{ vec4 specularColorAndFactor = getSpecularColorAndFactor(); //glossiness - float inGlossiness = 0.0, inSpecularIntensity = specularColorAndFactor.w; + float inGlossiness = 0.0, inSpecularIntensity = 1.0; #if HAS_EXPORTED_GLOSSINESS - inGlossiness = glossiness; + #if USE_SPECULAR_GLOSSINESS_MAP + inGlossiness = 1.0 - texture(specularGlossinessMap, TEXTURE_UV).a; + #else + inGlossiness = glossiness; + #endif #else #if USE_SHININESS_MAP #if GLOSSINESS_MAP_USE_SINGLE_CHANNEL diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta index 110a000176..7312d3f819 100644 --- a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "5b7d6814-90a6-4d9f-b7fd-410dca9de957", diff --git a/editor/assets/effects/editor/gizmo.effect.meta b/editor/assets/effects/editor/gizmo.effect.meta index 0afaef47ed..0e59e7f2b2 100644 --- a/editor/assets/effects/editor/gizmo.effect.meta +++ b/editor/assets/effects/editor/gizmo.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "9d6c6bde-2fe2-44ee-883b-909608948b04", diff --git a/editor/assets/effects/editor/grid-2d.effect.meta b/editor/assets/effects/editor/grid-2d.effect.meta index 8490f31350..1f4b776d6e 100644 --- a/editor/assets/effects/editor/grid-2d.effect.meta +++ b/editor/assets/effects/editor/grid-2d.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "cb2c332a-fa5e-4235-a129-f011634bb7ad", diff --git a/editor/assets/effects/editor/grid-stroke.effect.meta b/editor/assets/effects/editor/grid-stroke.effect.meta index 2d786d73a1..8f3614a270 100644 --- a/editor/assets/effects/editor/grid-stroke.effect.meta +++ b/editor/assets/effects/editor/grid-stroke.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "4736e978-c8fa-449f-9cf6-fe0158ded9d7", diff --git a/editor/assets/effects/editor/grid.effect.meta b/editor/assets/effects/editor/grid.effect.meta index a2b07395c1..5927bf6fec 100644 --- a/editor/assets/effects/editor/grid.effect.meta +++ b/editor/assets/effects/editor/grid.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "ba35f02e-a81c-464c-bfc5-c788328da667", diff --git a/editor/assets/effects/editor/light.effect.meta b/editor/assets/effects/editor/light.effect.meta index 75bd610c46..a20a6e0612 100644 --- a/editor/assets/effects/editor/light.effect.meta +++ b/editor/assets/effects/editor/light.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "e4e4cb19-8dd2-450d-ad20-1a818263b8d3", diff --git a/editor/assets/effects/editor/terrain-circle-brush.effect.meta b/editor/assets/effects/editor/terrain-circle-brush.effect.meta index c3dac65d38..8313ee6308 100644 --- a/editor/assets/effects/editor/terrain-circle-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-circle-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "a3e72674-c38f-4336-a285-1826b1799cd7", diff --git a/editor/assets/effects/editor/terrain-image-brush.effect.meta b/editor/assets/effects/editor/terrain-image-brush.effect.meta index c99fcfbba0..089e42d2d1 100644 --- a/editor/assets/effects/editor/terrain-image-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-image-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "7a115de7-2d94-4620-8b89-766d7f8cbff9", diff --git a/editor/assets/effects/editor/terrain-select-brush.effect.meta b/editor/assets/effects/editor/terrain-select-brush.effect.meta index f07ce0350f..92a953e711 100644 --- a/editor/assets/effects/editor/terrain-select-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-select-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "9b4d3fa5-89bf-4715-b69a-dbbd1efaf6a5", diff --git a/editor/assets/effects/pipeline/bloom.effect.meta b/editor/assets/effects/pipeline/bloom.effect.meta index 0dd3ccc25b..a486e68931 100644 --- a/editor/assets/effects/pipeline/bloom.effect.meta +++ b/editor/assets/effects/pipeline/bloom.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "28d6d6b8-3f66-4a73-9795-17a0852ba2d4", diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect.meta b/editor/assets/effects/pipeline/deferred-lighting.effect.meta index b16f8f6e0a..cf13a3ebfd 100644 --- a/editor/assets/effects/pipeline/deferred-lighting.effect.meta +++ b/editor/assets/effects/pipeline/deferred-lighting.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "5d45aa00-e064-4938-b314-4265f0c2258c", diff --git a/editor/assets/effects/pipeline/planar-shadow.effect.meta b/editor/assets/effects/pipeline/planar-shadow.effect.meta index 13c12b217c..d53a4a8701 100644 --- a/editor/assets/effects/pipeline/planar-shadow.effect.meta +++ b/editor/assets/effects/pipeline/planar-shadow.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "9361fd90-ba52-4f84-aa93-6e878fd576ca", diff --git a/editor/assets/effects/pipeline/post-process.effect.meta b/editor/assets/effects/pipeline/post-process.effect.meta index 3146f233da..b51c1b1055 100644 --- a/editor/assets/effects/pipeline/post-process.effect.meta +++ b/editor/assets/effects/pipeline/post-process.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "ec8106fe-05bf-4e94-943c-e0d3b7bb5e45", diff --git a/editor/assets/effects/pipeline/skybox.effect.meta b/editor/assets/effects/pipeline/skybox.effect.meta index 77302e9090..ed157e898f 100644 --- a/editor/assets/effects/pipeline/skybox.effect.meta +++ b/editor/assets/effects/pipeline/skybox.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "511d2633-09a7-4bdd-ac42-f778032124b3", diff --git a/editor/assets/effects/pipeline/smaa.effect.meta b/editor/assets/effects/pipeline/smaa.effect.meta index c14844616e..94fbbf8e61 100644 --- a/editor/assets/effects/pipeline/smaa.effect.meta +++ b/editor/assets/effects/pipeline/smaa.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "6624c63c-0e3d-4d5f-bd15-a7805b71c521", diff --git a/editor/assets/effects/pipeline/tonemap.effect.meta b/editor/assets/effects/pipeline/tonemap.effect.meta index 026e08f574..5423bf56cb 100644 --- a/editor/assets/effects/pipeline/tonemap.effect.meta +++ b/editor/assets/effects/pipeline/tonemap.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "31b152ff-f689-4082-a292-3eb5a0b33014", diff --git a/editor/assets/effects/surfaces/sky.effect.meta b/editor/assets/effects/surfaces/sky.effect.meta index eb8789005a..2fdf69ce74 100644 --- a/editor/assets/effects/surfaces/sky.effect.meta +++ b/editor/assets/effects/surfaces/sky.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "6308c013-7d49-4160-9516-562dd205b480", diff --git a/editor/assets/effects/surfaces/standard.effect b/editor/assets/effects/surfaces/standard.effect index cb06da9d49..4d8c94aac5 100644 --- a/editor/assets/effects/surfaces/standard.effect +++ b/editor/assets/effects/surfaces/standard.effect @@ -11,7 +11,7 @@ CCEffect %{ mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } - occlusion: { value: 1.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + occlusion: { value: 0.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } roughness: { value: 0.8, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } metallic: { value: 0.6, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } @@ -276,6 +276,7 @@ CCProgram surface-fragment %{ vec4 SurfacesFragmentModifyPBRParams() { vec4 pbr = pbrParams; + pbr.x = 1.0 - pbr.x; #if USE_PBR_MAP vec4 res = texture(pbrMap, DEFAULT_UV); pbr.x *= res.OCCLUSION_CHANNEL; diff --git a/editor/assets/effects/surfaces/standard.effect.meta b/editor/assets/effects/surfaces/standard.effect.meta index 6af96b1627..1bdb51d35b 100644 --- a/editor/assets/effects/surfaces/standard.effect.meta +++ b/editor/assets/effects/surfaces/standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "c8f66d17-351a-48da-a12c-0212d28575c4", diff --git a/editor/assets/effects/surfaces/terrain.effect.meta b/editor/assets/effects/surfaces/terrain.effect.meta index 08dc88cba5..8ccca297a4 100644 --- a/editor/assets/effects/surfaces/terrain.effect.meta +++ b/editor/assets/effects/surfaces/terrain.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "a0fd9f76-74fe-423c-92d9-298906c189ba", diff --git a/editor/assets/effects/surfaces/toon.effect.meta b/editor/assets/effects/surfaces/toon.effect.meta index 18b6d782a7..17d7bf405a 100644 --- a/editor/assets/effects/surfaces/toon.effect.meta +++ b/editor/assets/effects/surfaces/toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "9b20a514-6cc3-49de-b216-b6b863046249", diff --git a/editor/assets/effects/util/batched-unlit.effect.meta b/editor/assets/effects/util/batched-unlit.effect.meta index 74f7b84313..76fdeeba7b 100644 --- a/editor/assets/effects/util/batched-unlit.effect.meta +++ b/editor/assets/effects/util/batched-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "f1556893-88b6-4c65-8c16-a5256ef3ad25", diff --git a/editor/assets/effects/util/profiler.effect.meta b/editor/assets/effects/util/profiler.effect.meta index 50bd98cf46..c8d6d15a87 100644 --- a/editor/assets/effects/util/profiler.effect.meta +++ b/editor/assets/effects/util/profiler.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "871c3b6c-7379-419d-bda3-794b239ab90d", diff --git a/editor/assets/effects/util/sequence-anim.effect.meta b/editor/assets/effects/util/sequence-anim.effect.meta index bdbc5ce866..ce3684f058 100644 --- a/editor/assets/effects/util/sequence-anim.effect.meta +++ b/editor/assets/effects/util/sequence-anim.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "27cc5a0b-ec0b-4a67-98cf-b42d4fa971de", diff --git a/editor/assets/effects/util/splash-screen.effect.meta b/editor/assets/effects/util/splash-screen.effect.meta index a1007e16dd..6ef217d3d8 100644 --- a/editor/assets/effects/util/splash-screen.effect.meta +++ b/editor/assets/effects/util/splash-screen.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.9", + "ver": "1.6.0", "importer": "effect", "imported": true, "uuid": "970b0598-bcb0-4714-91fb-2e81440dccd8", diff --git a/editor/assets/gizmo/camera.png.meta b/editor/assets/gizmo/camera.png.meta index 2ecace6893..a70e701521 100644 --- a/editor/assets/gizmo/camera.png.meta +++ b/editor/assets/gizmo/camera.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "bd373594-df84-486d-a34a-19d09ddaa973", diff --git a/editor/assets/gizmo/directional-light.png.meta b/editor/assets/gizmo/directional-light.png.meta index 5729c79fb6..82816162a4 100644 --- a/editor/assets/gizmo/directional-light.png.meta +++ b/editor/assets/gizmo/directional-light.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "9cb543ba-d152-4809-8a44-8e7bd5712123", diff --git a/editor/assets/gizmo/particle-system.png.meta b/editor/assets/gizmo/particle-system.png.meta index 75d075c168..a68eeecacd 100644 --- a/editor/assets/gizmo/particle-system.png.meta +++ b/editor/assets/gizmo/particle-system.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "55052bc6-9909-43c1-b2fc-8818060fb069", diff --git a/editor/assets/gizmo/scene-gizmo.mtl.meta b/editor/assets/gizmo/scene-gizmo.mtl.meta index 1cd949f6c7..b6cfafcc3d 100644 --- a/editor/assets/gizmo/scene-gizmo.mtl.meta +++ b/editor/assets/gizmo/scene-gizmo.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.13", + "ver": "1.0.15", "importer": "material", "imported": true, "uuid": "6d3bfb1f-604a-4fb3-9fd8-789862cc55e7", diff --git a/editor/assets/gizmo/sphere-light.png.meta b/editor/assets/gizmo/sphere-light.png.meta index eb08ffa1c0..e842725b23 100644 --- a/editor/assets/gizmo/sphere-light.png.meta +++ b/editor/assets/gizmo/sphere-light.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "c78f78a5-3553-4d1f-ad3b-177fe55af68b", diff --git a/editor/assets/gizmo/spot-light.png.meta b/editor/assets/gizmo/spot-light.png.meta index 2b98ec6ab7..2ab0f62b75 100644 --- a/editor/assets/gizmo/spot-light.png.meta +++ b/editor/assets/gizmo/spot-light.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "191b676f-175b-41fa-8283-ac539875bfd8", diff --git a/editor/assets/gizmo/webview.png.meta b/editor/assets/gizmo/webview.png.meta index 459c27f9b1..5b2d3f3d03 100644 --- a/editor/assets/gizmo/webview.png.meta +++ b/editor/assets/gizmo/webview.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "b9f47df4-b2f0-4270-bd8a-07bb344a8253", diff --git a/editor/assets/gizmo/x.png.meta b/editor/assets/gizmo/x.png.meta index f7d69d7edb..8f873956b3 100644 --- a/editor/assets/gizmo/x.png.meta +++ b/editor/assets/gizmo/x.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "ac74fa2b-1f5b-4ff5-a3f0-f127f4483e91", diff --git a/editor/assets/gizmo/y.png.meta b/editor/assets/gizmo/y.png.meta index f4ce95fa46..69cb031934 100644 --- a/editor/assets/gizmo/y.png.meta +++ b/editor/assets/gizmo/y.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "7b5313d0-f1aa-4b1b-a3c8-59d523c35301", diff --git a/editor/assets/gizmo/z.png.meta b/editor/assets/gizmo/z.png.meta index b11ad7b240..687f727a8b 100644 --- a/editor/assets/gizmo/z.png.meta +++ b/editor/assets/gizmo/z.png.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.24", + "ver": "1.0.25", "importer": "image", "imported": true, "uuid": "389d5fee-e29c-4221-b397-a4934a0a5694", diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index 7d2c9fb079..8082af61f5 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -12,7 +12,7 @@ "label": "i18n:ENGINE.features.graphics.label", "multi": true, "description": "i18n:ENGINE.features.graphics.description", - "default": ["gfx-webgl", "gfx-webgl2"], + "default": ["gfx-webgl", "gfx-webgl2", "gfx-webgpu"], "options": { "gfx-webgl": { "required": true, diff --git a/editor/engine-features/schema.json b/editor/engine-features/schema.json index 060d10e5ac..8f79449fbc 100644 --- a/editor/engine-features/schema.json +++ b/editor/engine-features/schema.json @@ -76,6 +76,9 @@ "gfx-webgl2": { "$ref": "#/definitions/Item" }, + "gfx-webgpu": { + "$ref": "#/definitions/Item" + }, "graphcis": { "$ref": "#/definitions/Item" }, @@ -217,6 +220,9 @@ "gfx-webgl2": { "$ref": "#/definitions/BaseItem" }, + "gfx-webgpu": { + "$ref": "#/definitions/BaseItem" + }, "graphcis": { "$ref": "#/definitions/BaseItem" }, @@ -311,5 +317,4 @@ } }, "type": "object" -} - +} \ No newline at end of file diff --git a/editor/engine-features/types.ts b/editor/engine-features/types.ts index 467f787c0e..2ff6a5f7cd 100644 --- a/editor/engine-features/types.ts +++ b/editor/engine-features/types.ts @@ -3,6 +3,7 @@ export type EngineFeature = | 'gfx-webgl' | 'gfx-webgl2' + | 'gfx-webgpu' | 'base' | 'graphcis' | '3d' diff --git a/editor/exports/color-utils.ts b/editor/exports/color-utils.ts new file mode 100644 index 0000000000..e7a8a33c36 --- /dev/null +++ b/editor/exports/color-utils.ts @@ -0,0 +1,9 @@ +import { + linearToSrgb8Bit, + srgbToLinear, +} from '../../cocos/core/math/color'; + +export { + linearToSrgb8Bit, + srgbToLinear, +}; diff --git a/editor/i18n/en/assets.js b/editor/i18n/en/assets.js index a415a3a25a..498e80b769 100644 --- a/editor/i18n/en/assets.js +++ b/editor/i18n/en/assets.js @@ -242,7 +242,7 @@ module.exports = { }, materialDumpDir: { name: 'Material Dump Directory', - title: 'The directory to dump the materials.\nDefault to a direct sub-folder named `Materials_${model-file-base-name}` under current path.', + title: 'The directory to dump the materials.
Default to a direct sub-folder named `Materials_${model-file-base-name}` under current path.', }, useVertexColors: { name: 'Use Vertex Colors', diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 4d9f944665..7f44e5812d 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -77,19 +77,20 @@ module.exports = { skyIllum: 'Ambient lighting intensity.', }, skybox: { - applyDiffuseMap: 'When checking, scene objects will use accurate diffusion map instead of hemisphere lighting.', + EnvironmentLightingType: 'Choose environment lighting types:
Custom hemisphere diffuse, no reflections.
Autogen hemisphere diffuse, with reflections.
More accuracy diffuse map, with reflections.', enabled: 'Enable or disable skybox rendering with Envmap cube texture settings.', - useIBL: 'When checking, scene objects will calculate image based lighting from Envmap settings with diffuse and specular-reflections. Otherwise objects only calculate hemisphere diffuse lighting.', - useHDR: 'Toggle HDR or LDR mode. Each mode has seperate light source settings, HDR mode uses physical luminosity unit with camera exposure attributes, and LDR mode uses none-unit without exposure calculations.', - envmap: 'Set skybox texture and environment light source. Support cross / longitude and latitude / 6-separated cube textures. Support hdr / tga / png file type.', + useHDR: 'Toggle HDR or LDR mode.
Each mode has seperate light source settings,
HDR mode uses physical luminosity unit with camera exposure attributes,
and LDR mode uses none-unit without exposure calculations.', + envmap: 'Set skybox texture and environment light source.
Support cross / longitude and latitude / 6-separated cube textures.
Support hdr / tga / png file type.', + rotationAngle: 'Adjust Y-axis rotation for skybox and sky lighting.', + material: 'Set custom skybox material, see skybox.effect.', }, fog: { enabled: 'Enable or disable global fog effect.', - accurate: 'Toggle vertex fog and pixel fog. Pixel fog has more accurate visual effect with low vertex count objects, but vertex fog has better performance.', + accurate: 'Toggle vertex fog and pixel fog.
Pixel fog has more accurate visual effect with low vertex count objects,
but vertex fog has better performance.', fogColor: 'Fog In-Scattering Color.', type: 'Different calculation models.', fogDensity: 'The larger the value, the more foggy it looks.', - fogStart: 'Fog will start with this value (world space unit). Increase this value if you want more clarity nearby.', + fogStart: 'Fog will start with this value (world space unit).
Increase this value if you want more clarity nearby.', fogEnd: 'Further than this value (world space unit), will receive maximum fog effect.', fogAtten: 'The smaller the value, the more foggy it looks.', fogTop: 'Objects above this height value (world space unit) are not affected by fog.', @@ -97,19 +98,11 @@ module.exports = { }, shadow: { enabled: 'Enable or disable real time shadows.', + type: 'Shadow effect type', + shadowColor: 'The planar shadow color', planeDirection: 'The normal vector of the plane which receives shadow.', planeHeight: 'The height from the origin of the plane which receives shadow.', - saturation: 'Shadow saturation. This value should be 1.0, we recommend that you\'d rather increase ambient lighting than modify this value. ', - pcf: 'Enable soft shadows.', - bias: 'Bias value (world space unit) that can avoid moire artifacts with shadows. The more the value, the more the light leakage.', - normalBias: 'Bias value (world space unit) that can avoid moire artifacts with surfaces that parallel to the directional light.', shadowMapSize: 'Shadowmap resolutions.', - fixedArea: 'Toggle CSM and fixed area shadows. When checking, shadow will not follow camera, it distributes around directional light position. It is a legacy mode that we do not recommend.', - near: 'Fix area start.', - far: 'Fix area end.', - orthoSize: 'Fix area size, the larger value, the lower precision of shadows.', - invisibleOcclusionRange: 'If some shadow near the camera is missing, increase this value (world space unit) to fix it.', - shadowDistance: 'Shadows do not appear beyond this distance (world space unit).', maxReceived: 'Number of the effective light sources that produce shadows.', }, animation: { @@ -117,9 +110,9 @@ module.exports = { clips: 'You can access and play animation clips via a script', play_on_load: 'Automatically play animation clip with the scene is loaded', use_baked_animation: - 'Whether to bake animations. Default to true,\nwhich substantially increases performance while making all animations completely fixed', + 'Whether to bake animations.
Default to true, which substantially increases performance while making all animations completely fixed', sockets: - 'The joint sockets this animation component maintains.\nSockets have to be registered before attaching custom nodes to animated joints', + 'The joint sockets this animation component maintains.
Sockets have to be registered before attaching custom nodes to animated joints', }, audio: { clip: 'The default AudioClip to be played for this audio source', @@ -130,13 +123,13 @@ module.exports = { batched_skinning_model: { atlas_size: 'Size of the generated texture atlas', batchable_texture_names: - "Texture properties that will be actually using the generated atlas.\nThe first unit's texture will be used if not specified", - units: 'Source skinning model components, containing all the data to be batched', + "Texture properties that will be actually using the generated atlas.
The first unit's texture will be used if not specified", + units: 'Source skinning model components,
containing all the data to be batched', }, camera: { priority: 'Render priority of the camera, in ascending-order', visibility: 'Visibility mask, declaring a set of node layers that will be visible to this camera', - clear_flags: 'Clearing flags of the camera, specifies which part of the framebuffer will be actually cleared every frame', + clear_flags: 'Clearing flags of the camera,
specifies which part of the framebuffer will be actually cleared every frame', color: 'Clearing color of the camera', depth: 'Clearing depth of the camera', stencil: 'Clearing stencil of the camera', @@ -144,12 +137,12 @@ module.exports = { fov_axis: 'The axis on which the FOV would be fixed regardless of screen aspect changes', fov: 'Field of view of the camera', ortho_height: 'Viewport height in orthographic mode', - near: 'Near clipping distance of the camera, should be as large as possible within acceptable range', - far: 'Far clipping distance of the camera, should be as small as possible within acceptable range', + near: 'Near clipping distance of the camera,
should be as large as possible within acceptable range', + far: 'Far clipping distance of the camera,
should be as small as possible within acceptable range', aperture: 'Camera aperture, controls the exposure parameter', shutter: 'Camera shutter, controls the exposure parameter', ISO: 'Camera ISO, controls the exposure parameter', - rect: 'Screen viewport of the camera wrt. the sceen size', + rect: 'The size of the viewport that this camera will eventually render to the screen.', target_texture: 'Output render texture of the camera. Default to null, which outputs directly to screen', }, lights: { @@ -162,21 +155,36 @@ module.exports = { term: 'The photometric term currently being used', size: 'Size of the light', range: 'Range of the light', + shadowEnabled: 'Enable or disable real time shadows', + shadowPcf: 'Enable soft shadows', + shadowBias: 'Bias value (world space unit) that can avoid moire artifacts with shadows.
The more the value, the more the light leakage', + shadowNormalBias: 'Bias value (world space unit) that can avoid moire artifacts with surfaces that parallel to the directional light', + shadowSaturation: 'Shadow saturation. This value should be 1.0.
We recommend that you\'d rather increase ambient lighting than modify this value', + shadowDistance: 'Shadows do not appear beyond this distance (world space unit)', + shadowInvisibleOcclusionRange: 'If some shadow near the camera is missing,
increase this value (world space unit) to fix it', + enableCSM: 'Enable CSM', + shadowFixedArea: 'Toggle CSM and fixed area shadows.
When checking, shadow will not follow camera, it distributes around directional light position.
It is a legacy mode that we do not recommend', + shadowNear: 'Fix area start', + shadowFar: 'Fix area end', + shadowOrthoSize: 'Fix area size, the larger value, the lower precision of shadows', }, model: { + shadow_receiving_model: 'Shadow receive mode', shadow_casting_model: 'Shadow projection mode', mesh: 'The mesh of the model', skinning_root: 'The skinning root, where the controlling Animation is located', + shadow_bias: 'Bias value (world space unit) that can avoid moire artifacts with shadows for model.
The more the value, the more the light leakage', + shadow_normal_bias: 'Bias value (world space unit) that can avoid moire artifacts with surfaces that parallel to the directional light', }, sprite: { gray_scale: 'Whether turn on grayscale rendering mode', sprite_frame: 'Sprite Frame image to use', atlas: 'Atlas that the image belongs to', type: - 'Rendering mode:\n - Simple: Modifying the size will stretch the image as a whole, which is suitable for sequence frame animation and normal images. \n' + - '- Sliced: When changing the size, the four corners will not stretch, which is suitable for UI buttons and panel backgrounds. \n' + - '- Tiled : When changing the size, the original size image will continue to be tiled. \n' + - '- Filled : set a certain starting position and direction of filling, and the picture can be cropped and displayed at a certain ratio.', + 'Rendering mode:
- Simple: Modifying the size will stretch the image as a whole, which is suitable for sequence frame animation and normal images.
' + + '- Sliced: When changing the size, the four corners will not stretch, which is suitable for UI buttons and panel backgrounds.
' + + '- Tiled : When changing the size, the original size image will continue to be tiled.
' + + '- Filled : set a certain starting position and direction of filling, and the picture can be cropped and displayed at a certain ratio.', original_size: "Use the Image's original size as the Node size?", edit_button: 'Edit', select_button: 'Select In Atlas', @@ -189,9 +197,9 @@ module.exports = { src_blend_factor: 'The source image blend mode', dst_blend_factor: 'The destination image blend mode', size_mode: - 'Set the size of the node on which the Sprite component is on. CUSTOM for setting width and height manually;TRIMMED to use image size with transparent pixels trimmed; RAW to use image size without trimming.', + 'Set the size of the node on which the Sprite component is on.
CUSTOM for setting width and height manually;
TRIMMED to use image size with transparent pixels trimmed;
RAW to use image size without trimming.', trim: - "Whether to render transparent pixels around image in node's bounding box. If you check this option the bounding box will not include transparent pixels around the image.", + "Whether to render transparent pixels around image in node's bounding box.
If you check this option the bounding box will not include transparent pixels around the image.", }, UIOpacity: { opacity: 'The value between 0 to 255 showing the transparency of the object', @@ -207,9 +215,9 @@ module.exports = { target: 'Node that receives click events', component: 'Component that receive click events', handler: 'Component method to respond to click events', - customEventData: "The extra event data passed to the event handler, it's passed in as the last argument in the event handler. ", + customEventData: "The extra event data passed to the event handler,
it's passed in as the last argument in the event handler. ", }, - interactable: 'Interactable state of the button, when this item is unchecked, the button is disabled', + interactable: 'Interactable state of the button,
when this item is unchecked, the button is disabled', transition: 'Transition type when the button state changes', normal_color: 'Button color', pressed_color: 'Button color when pressed', @@ -217,22 +225,22 @@ module.exports = { disabled_color: 'Button color when disabled', duration: 'Transition time for button color change or zoom change', zoom_scale: - 'When the user clicks the button, the button is scaled to a value equal to the original scale of the Button * zoomScale, zoomScale can be a negative number', - auto_gray_effect: 'When this flag is true, Button target sprite will turn gray when interactable is false.', + 'When the user clicks the button,
the button is scaled to a value equal to the original scale of the Button * zoomScale,
zoomScale can be a negative number', + auto_gray_effect: 'When this flag is true,
Button target sprite will turn gray when interactable is false.', normal_sprite: 'The sprite frame used when the button is in a normal sate.', pressed_sprite: 'The sprite frame used when the button is in a pressed sate.', hover_sprite: 'The sprite frame used when the button is in hovered over.', disabled_sprite: 'The sprite frame used when the button is in a disabled sate.', target: - "reference to the Sprite as target's background. When the state of the target changes the sprite's color or sprite frame will be updated.", - click_events: 'By changing the number to 1 or more, you can set the receiver and the handler for each click event', + "reference to the Sprite as target's background.
When the state of the target changes the sprite's color or sprite frame will be updated.", + click_events: 'By changing the number to 1 or more,
you can set the receiver and the handler for each click event', }, canvas: { camera: '2D rendering camera', align: 'Automatically calculate parameters for the camera.', design_resolution: 'The resolution of the assets used in the game, in pixels.', - fit_height: 'Canvas allows designers to automatically scale the resolution to the full height of devices screen', - fit_width: 'Canvas allows designers to automatically scale the resolution to the full width of devices screen', + fit_height: 'Canvas allows designers to automatically scale the resolution to the full height of devices screen', + fit_width: 'Canvas allows designers to automatically scale the resolution to the full width of devices screen', }, forceOvertimeModule: { x: 'Acceleration component along X-axis', @@ -254,12 +262,12 @@ module.exports = { font_family: 'Font family name', line_height: 'Line height, in points', overflow: - 'Text layout modes: \n 1. CLAMP: Text nodes outside the bounding box will be truncated. \n 2. SHRINK: Automatically shrink text box according to the constraint node. \n 3. RESIZE: Automatically updates the Node based on heightof the text.', + 'Text layout modes:
1. CLAMP: Text nodes outside the bounding box will be truncated.
2. SHRINK: Automatically shrink text box according to the constraint node.
3. RESIZE: Automatically updates the Node based on heightof the text.', wrap: 'Wrap text?', font: 'What font to use', system_font: 'Whether to use the system default font', cache_mode: - 'Text cache modes:\n 1. NONE: No cache,draw once. \n 2. BITMAP: Text is added as a static image to the dynamic atlas for batch merging, but its content cannot be dynamically modified frequently. \n 3. CHAR: Split the text into characters and cache the character texture into a character atlas for reuse, which is suitable for text content with repeated character content and frequently updated.', + 'Text cache modes:
1. NONE: No cache,draw once.
2. BITMAP: Text is added as a static image to the dynamic atlas for batch merging, but its content cannot be dynamically modified frequently.
3. CHAR: Split the text into characters and cache the character texture into a character atlas for reuse, which is suitable for text content with repeated character content and frequently updated.', font_bold: 'Font bold', font_italic: 'Font italic', font_underline: 'Font underlined', @@ -286,7 +294,7 @@ module.exports = { }, line: { texture: 'Line texture', - wordSpace: 'Which coordinate the point in line belongs to. Check if in world space, otherwise local space', + wordSpace: 'Which coordinate the point in line belongs to.
Check if in world space, otherwise local space', positions: 'Position of control point', width: 'Fixed line width if constant input, or line width gradually changes according to the value if curve input', tile: 'Number of texture tiles', @@ -295,7 +303,7 @@ module.exports = { }, progress: { bar_sprite: 'A progress bar is displayed with the Sprite node that can dynamically change the size', - mode: 'Progress bar display modes, including: \n 1. HORIZONTAL: horizontal mode \n 2. VERTICAL: vertical mode \n 3. FILLED: fan-fill mode', + mode: 'Progress bar display modes, including:
1. HORIZONTAL: horizontal mode
2. VERTICAL: vertical mode
3. FILLED: fan-fill mode', total_length: 'Length of progress bar. The maximum length of 100', progress: 'Current progress indicator, ranging from 0-1', reverse: 'Can the progress bar update negatively (i.e go backwards)', @@ -304,33 +312,33 @@ module.exports = { handle: 'reference to the interactive bar sprite', direction: 'Scroll direction', auto_hide: 'Automatically hide', - auto_hide_time: 'How long will the scroll bar to be hidden after no scrolling action.\nNote: Only valid if "enableAutoHide" is true', + auto_hide_time: 'How long will the scroll bar to be hidden after no scrolling action.
Note: Only valid if "enableAutoHide" is true', }, scrollview: { content: 'A scrollable display of the Nodes content', horizontal: 'Horizontal scroll', vertical: 'Vertical scroll', inertia: 'When inertia is set, the content will continue to move when touch ended', - brake: 'It determines how quickly the content stop moving\nA value of 1 will stop the movement immediately\nA value of 0 will never stop the movement until it reaches to the boundary of scrollview', + brake: 'It determines how quickly the content stop moving.
A value of 1 will stop the movement immediately.
A value of 0 will never stop the movement until it reaches to the boundary of scrollview.', elastic: "If elastic is set, the content will bounce back when it's moved out of scroll boundary.", horizontal_bar: 'Horizontal scrollbar', vertical_bar: 'Vertical scrollbar', - bounceDuration: 'The elapse time for bouncing. A value of 0 means the content will bounce back immediately.', + bounceDuration: 'The elapse time for bouncing.
A value of 0 means the content will bounce back immediately.', scrollEvents: 'Scrollview events callback', - cancelInnerEvents: 'If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes', + cancelInnerEvents: 'If cancelInnerEvents is set to true,
the scroll behavior will cancel touch events on inner content nodes', }, pageview: { sizeMode: 'Specify the size type of each page in PageView', direction: 'The page view direction', scrollThreshold: - 'The scroll threshold value, when drag exceeds this value, release the next page will automatically scroll, less than the restore', + 'The scroll threshold value, when drag exceeds this value,
release the next page will automatically scroll, less than the restore', pageTurningEventTiming: - "Change the AutoScroll stop epsilon value of PageView, change this value could adjust the PageView's event triggering timing.", + "Change the AutoScroll stop epsilon value of PageView,
change this value could adjust the PageView's event triggering timing.", indicator: 'The Page View Indicator', pageTurningSpeed: 'The time required to turn over a page. unit: second', pageEvents: 'PageView events callback', autoPageTurningThreshold: - 'The turning velocity threshold for page turning\nWhen user swipes the PageView quickly, a velocity is calculated based on the swipe distance and time.\nIf the velocity is larger than the threshold, the page will be flipped', + 'The turning velocity threshold for page turning.
When user swipes the PageView quickly,
a velocity is calculated based on the swipe distance and time.
If the velocity is larger than the threshold, the page will be flipped', }, pageview_indicator: { spriteFrame: 'The sprite frame for each element', @@ -374,8 +382,8 @@ module.exports = { frameOverTime: 'How frame speed changes over time in a cycle', startFrame: 'Which frame start to play during the lifetime of particle system', cycleCount: 'Playing cycle count of whole lifetime', - randomRow: 'Generate animation by a row of texture random selected,\nonly valid in SingleRow', - rowIndex: 'Generate animation by a row of texture at [rowIndex],\nonly valid in SingleRow and randomRow is disabled', + randomRow: 'Generate animation by a row of texture random selected,
only valid in SingleRow', + rowIndex: 'Generate animation by a row of texture at [rowIndex],
only valid in SingleRow and randomRow is disabled', }, toggle: { interactable: 'Interactive Toggle? When this one is not selected, the Toggle is in a disabled state', @@ -386,24 +394,24 @@ module.exports = { disabled_color: 'Toggle color when disabled', duration: 'How long until the Toggle color/scale transitions to a new color?', zoom_scale: - 'When user press the Toggle, the Toggle will zoom to a scale.The final scale of the Toggle equals (Toggle original scale * zoomScale), zoomScale could be negative value.', - auto_gray_effect: 'When this flag is true, Toggle target sprite will turn gray when interactable is false.', + 'When user press the Toggle, the Toggle will zoom to a scale.
The final scale of the Toggle equals (Toggle original scale * zoomScale), zoomScale could be negative value.', + auto_gray_effect: 'When this flag is true,
the Toggle target sprite will turn gray when interactable is false.', normal_sprite: 'The Sprite that is used when the Toggle is in a normal sate.', pressed_sprite: 'The Sprite that is used when the Toggle is in a pressed sate.', hover_sprite: 'The Sprite that is used when the Toggle is hovered over.', disabled_sprite: 'The Sprite that is used when the Toggle is in a disabled sate.', target: - "reference to the Sprite as Toggle's background. When the state of the button changes the sprite's color or sprite frame will be updated.", + "reference to the Sprite as Toggle's background.
When the state of the button changes the sprite's color or sprite frame will be updated.", isChecked: - 'If this flag is true, the associated checkMark sprite component will be enabled, otherwise the checkMark will be disabled.', + 'If this flag is true, the associated checkMark sprite component will be enabled,
otherwise the checkMark will be disabled.', checkMark: 'The Sprite component displayed when Toggle is checked.', toggleGroup: - 'The toggle group which the toggle belongs to. When it is null, the toggle is a CheckBox. Otherwise, the toggle is a RadioButton.', + 'The toggle group which the toggle belongs to. When it is null, the toggle is a CheckBox.
Otherwise, the toggle is a RadioButton.', check_events: 'The events triggered while toggle item is checked', }, toggle_group: { allowSwitchOff: - "If this setting is true, a toggle could be switched off and on when pressed.If it is false, it will make sure there is always only one toggle could be switched on and the already switched on toggle can't be switched off.", + "If this setting is true, a toggle could be switched off and on when pressed.
If it is false, it will make sure there is always only one toggle could be switched on and the already switched on toggle can't be switched off.", check_events: "If Toggle is clicked, it will trigger event's handler.", }, shapeModule: { @@ -419,7 +427,7 @@ module.exports = { sphericalDirectionAmount: 'Lerp value between current emit direction and current move direction', randomPositionAmount: 'Random setting of particle move position(particle will appear beyond emit range)', radius: 'Radius of particle emitter', - radiusThickness: 'Radius thickness of particle emitter (invalid when emitter type is Box):\n - 0 emit from surface;\n - 1 emit from center;\n - 0 ~ 1 emit between center and surface', + radiusThickness: 'Radius thickness of particle emitter (invalid when emitter type is Box):
- 0 emit from surface;
- 1 emit from center;
- 0 ~ 1 emit between center and surface', arcMode: 'Emit mode in the sector range', arcSpread: 'Space margin along arc', arcSpeed: 'Emit speed along arc', @@ -453,41 +461,41 @@ module.exports = { }, widget: { target: - 'Specifies an alignment target that can only be one of the parent nodes of the current node. The default value is null, and when null, indicates the current parent', + 'Specifies an alignment target that can only be one of the parent nodes of the current node.
The default value is null, and when null, indicates the current parent', align_top: 'Top edge alignment of the target Node', align_bottom: 'Bottom edge alignment of the target Node', align_left: 'Left edge alignment of the target Node', align_right: 'Right edge alignment of the target Node', align_h_center: 'Align to the horizontal midpoint of the target Node', align_v_center: 'Align to the vertical midpoint of the target Node', - align_mode: 'Specifies the alignment mode of the Widget, which determines when the widget should refresh at runtime.', + align_mode: 'Specifies the alignment mode of the Widget,
which determines when the widget should refresh at runtime.', top: 'Top edge position in pixels. This can be a percentage and a positive or negative value', - bottom: 'Bottom edge position in pixels. This can be a percentage and a positive or negative value', - left: 'Left edge position in pixels. This can be a percentage and a positive or negative value', - right: 'Right edge position in pixels. This can be a percentage and a positive or negative value', - horizontal_center: 'Horizontal midpoint offset in pixels, This can be a percentage and a positive or negative value', - vertical_center: 'Vertical midpoint offset in pixels, This can be a percentage and a positive or negative value', + bottom: 'Bottom edge position in pixels.
This can be a percentage and a positive or negative value', + left: 'Left edge position in pixels.
This can be a percentage and a positive or negative value', + right: 'Right edge position in pixels.
This can be a percentage and a positive or negative value', + horizontal_center: 'Horizontal midpoint offset in pixels.
This can be a percentage and a positive or negative value', + vertical_center: 'Vertical midpoint offset in pixels.
This can be a percentage and a positive or negative value', }, layout: { layout_type: - 'Automatic layout mode: \n 1. NONE, no automatic arrangement of child Nodes \n 2. HORIZONTAL, automatic horizontal arrangement of child Nodes \n 3. VERTICAL, automatic vertical arrangement of child Nodes\n 4. GRID, automatic grid arrangement of child Nodes', + 'Automatic layout mode:
1. NONE, no automatic arrangement of child Nodes.
2. HORIZONTAL, automatic horizontal arrangement of child Nodes.
3. VERTICAL, automatic vertical arrangement of child Nodes.
4. GRID, automatic grid arrangement of child Nodes.', resize_mode: - 'Automatic resize mode: \n 1. NONE, no resize of both child Nodes and container. \n 2. CONTAINER, resize container Node. \n 3. CHILDREN, resize child Nodes.', + 'Automatic resize mode:
1. NONE, no resize of both child Nodes and container.
2. CONTAINER, resize container Node.
3. CHILDREN, resize child Nodes.', padding_left: 'Use a padding between left sides of the Node', padding_right: 'Use a padding between right sides of the Node', padding_top: 'Use a padding between top sides of the Node', padding_bottom: 'Use a padding between bottom sides of the Node', space_x: 'The horizontal distance between adjacent child Nodes', space_y: 'The vertical distance between adjacent child Nodes', - vertical_direction: 'Vertically align in the direction of the child Nodes: \n 1. TOP_TO_BOTTOM, \n 2. BOTTOM_TO_TOP', - horizontal_direction: 'Horizontally align in the direction of the child Nodes: \n 1. LEFT_TO_RIGHT \n 2. RIGHT_TO_LEFT', + vertical_direction: 'Vertically align in the direction of the child Nodes:
1. TOP_TO_BOTTOM,
2. BOTTOM_TO_TOP', + horizontal_direction: 'Horizontally align in the direction of the child Nodes:
1. LEFT_TO_RIGHT
2. RIGHT_TO_LEFT', cell_size: 'In Grid layout, the size of each child element.', start_axis: 'In Grid layout, the arrangement direction of children elements.', - constraint: 'In Grid layout, content layout constraints, including: \n 1.NONE, no constraints \n 2.FIXED_ROW, fixed number of rows \n 3.FIXED_COL, fixed number of columns', + constraint: 'In Grid layout, content layout constraints, including:
1.NONE, no constraints
2.FIXED_ROW, fixed number of rows
3.FIXED_COL, fixed number of columns', constraint_number: 'In Grid layout, number of rows or columns for content layout constraints', affected_scale: 'Child node scaling affects layout', - align_horizontal: 'Align content horizontally\nFixed starting position in the same direction when Type is Horizontal.', - align_vertical: 'Align content vertically\nFixed starting position in the same direction when Type is Vertical.', + align_horizontal: 'Align content horizontally
Fixed starting position in the same direction when Type is Horizontal.', + align_vertical: 'Align content vertically
Fixed starting position in the same direction when Type is Vertical.', }, particle: { export_title: 'Export custom particle data to plist file.', @@ -515,11 +523,11 @@ module.exports = { placeholder_label: "The Label component attached to the node for EditBox's placeholder text label", editing_began: 'The event handler to be triggered when user begin to edit text', text_changed: 'The event handler to be triggered when the text content changes', - editing_ended: 'The event handler to be triggered when user stop editing\nIn single line mode, the function is usually called when the user presses enter or clicks outside the input box on the screen \n In case of multiline input, the function is usually called when the user clicks outside the input box on the screen', - editing_return: 'The event handler to be called when return key is pressed\nIn single line mode, pressing the Enter key also causes the input box to lose focus', + editing_ended: 'The event handler to be triggered when user stop editing.
In single line mode, the function is usually called when the user presses enter or clicks outside the input box on the screen.
In case of multiline input, the function is usually called when the user clicks outside the input box on the screen', + editing_return: 'The event handler to be called when return key is pressed.
In single line mode, pressing the Enter key also causes the input box to lose focus.', }, videoplayer: { - resourceType: 'The resource type of video player, REMOTE for remote url and LOCAL for local file path.', + resourceType: 'The resource type of video player,
REMOTE for remote url and LOCAL for local file path.', remoteURL: 'The remote URL of video.', clip: 'The local video clip', playOnAwake: 'Whether the video start playing automatically after loaded?', @@ -530,13 +538,13 @@ module.exports = { keepAspectRatio: 'Whether keep the aspect ration of the original video.', fullScreenOnAwake: 'Whether play video in fullscreen mode?', stayOnBottom: - 'Always below the game view (only useful on Web. Note: The specific effects are not guaranteed to be consistent, depending on whether each browser supports or restricts).', + 'Always below the game view (only useful on Web.
Note: The specific effects are not guaranteed to be consistent, depending on whether each browser supports or restricts).', videoPlayerEvent: - "The video player's callback, it will be triggered when certain event occurs, like: playing, paused, stopped and completed.", + "The video player's callback, it will be triggered when certain event occurs,
like: playing, paused, stopped and completed.", }, webview: { - url: 'A given URL to be loaded by the Webview, it should have a http or https prefix.', - webviewEvents: "The Webview's event callback , it will be triggered when certain Webview event occurs.", + url: 'A given URL to be loaded by the Webview,
it should have a http or https prefix.', + webviewEvents: "The Webview's event callback ,
it will be triggered when certain Webview event occurs.", }, richtext: { string: 'Text of the RichText, you could use BBcode in the string', @@ -544,29 +552,29 @@ module.exports = { vertical_align: 'Vertical alignment', font_size: 'Font size, in points', font: 'Custom TTF font of Rich Text', - font_family:'Custom System font of Rich Text', + font_family: 'Custom System font of Rich Text', use_system_font: 'Using system font', cache_mode: 'The cache mode of label. This mode only supports system fonts.', max_width: 'The maximize width of RichText, pass 0 means not limit the maximize width.', line_height: 'Line height, in points', image_atlas: - 'The image atlas for the img tag. For each src value in the img tag, there should be a valid sprite frame in the image atlas.', + 'The image atlas for the img tag. For each src value in the img tag,
there should be a valid sprite frame in the image atlas.', handleTouchEvent: - 'Once checked, the Rich Text will block all input events (mouse and touch) within the bounding box of the node, preventing the input from penetrating into the underlying node.', + 'Once checked, the Rich Text will block all input events (mouse and touch) within the bounding box of the node,
preventing the input from penetrating into the underlying node.', }, UICoordinateTracker: { target: 'Target node', camera: 'The 3D camera representing the original coordinate system.', use_scale: "Whether to scale the converted 2d node's size according to the distance between the camera and the 3d node.", distance: 'The distance from the camera for displaying the 2d node in normal size', - sync_events: 'Event callback after coordinates synchronization.\nThe first parameter of the callback is the mapped local coordinate in UI camera.\nThe second parameter is the distance scale of the 3d node from the 3d camera viewport.', + sync_events: 'Event callback after coordinates synchronization.
The first parameter of the callback is the mapped local coordinate in UI camera.
The second parameter is the distance scale of the 3d node from the 3d camera viewport.', }, subContextView: { design_size: 'Design resolution of the SubContextView, dynamic updates at runtime is not possible', fps: 'Update frame rate for the SubContextView', }, skeleton: { - skeleton_data: 'The skeleton data contains the skeleton information, drag the json file exported from Spine to get started.', + skeleton_data: 'The skeleton data contains the skeleton information,
drag the json file exported from Spine to get started.', default_skin: 'Choose the default skin.', animation: 'The name of current playing animation.', loop: 'Whether loop current animation', @@ -577,14 +585,14 @@ module.exports = { }, dragon_bones: { dragon_bones_asset: - 'The json data contains the DragonBones information, drag the json file exported from DragonBones to get started.', + 'The json data contains the DragonBones information,
drag the json file exported from DragonBones to get started.', dragon_bones_atlas_asset: - 'The json data contains the Texture information, drag the json file exported from DragonBones to get started.', + 'The json data contains the Texture information,
drag the json file exported from DragonBones to get started.', armature_name: 'The name of current armature.', animation_name: 'The name of current playing animation.', time_scale: 'The time scale of this armature.', play_times: - 'The play times of the default animation.\n-1 means using the value of config file\n0 means repeat for ever\n>0 means repeat times', + 'The play times of the default animation.
-1 means using the value of config file.
0 means repeat for ever
>0 means repeat times.', debug_bones: 'Indicates whether open debug bones', }, motionStreak: { @@ -597,9 +605,9 @@ module.exports = { }, missing_scirpt: { error_compiled: - 'Error on executing script, or the script reference is missing. Please check error log carefully and correct/recover your script. The component will be restored once scripting error is gone. If you no long need the missing script, please remove this component manually.', + 'Error on executing script, or the script reference is missing.
Please check error log carefully and correct/recover your script. The component will be restored once scripting error is gone. If you no long need the missing script, please remove this component manually.', error_not_compiled: - 'Error on compiling script. Please check error log carefully and correct your script. This component will be restored once compiling error is gone.', + 'Error on compiling script. Please check error log carefully and correct your script.
This component will be restored once compiling error is gone.', }, collider: { editing: 'Edit this collider component', @@ -635,12 +643,12 @@ module.exports = { emitterMode: 'Particles emitter modes', gravity: 'Gravity of the emitter', speed: 'Speed and variation of the emitter', - tangentialAccel: 'Tangential acceleration and variation of each particle. Only available in Gravity mode ', - radialAccel: 'Acceleration and variation of each particle. Only available in Gravity mode', - rotationIsDir: 'Indicate whether the rotation of each particle equals to its direction. Only available in Gravity mode', - startRadius: 'Starting radius and variation of the particles. Only available in Radius mode', - endRadius: 'Ending radius and variation of the particles. Only available in Radius mode', - rotatePerS: 'Number of degrees to rotate a particle around the source pos per second and variation. Only available in Radius mode', + tangentialAccel: 'Tangential acceleration and variation of each particle.
Only available in Gravity mode ', + radialAccel: 'Acceleration and variation of each particle.
Only available in Gravity mode', + rotationIsDir: 'Indicate whether the rotation of each particle equals to its direction.
Only available in Gravity mode', + startRadius: 'Starting radius and variation of the particles.
Only available in Radius mode', + endRadius: 'Ending radius and variation of the particles.
Only available in Radius mode', + rotatePerS: 'Number of degrees to rotate a particle around the source pos per second and variation.
Only available in Radius mode', capacity: 'Maximum particle amount that the system can generate', scaleSpace: 'Scale space', startSize3D: 'Set start size of X, Y and Z respectively if true', @@ -674,9 +682,9 @@ module.exports = { textureAnimationModule: 'Texture animation module', trailModule: 'Trail module (only support on CPU)', renderer: 'Particle render module', - renderCulling: 'Whether to enable the particle culling feature. \nIf enabled, a particle emitter bounding box will be generated, \nand the particle emitter will be culled if the bounding box is not in the visible range of the camera. \nPlease refer to the cullingMode option below for the behavior settings after particle culling.', - cullingMode: 'Sets the behavior of the particle emitter after it has been culled. \nThe available options include Pause, Pause and Catchup, and Always Simulate.\nWhen the Pause is selected, the particle will pause the simulation if the particle emitter bounding box is not in the camera\'s visible range. \nIf it resumes visibility, the particle will continue simulating at the time of last pause.\nWhen the Pause and Catchup is selected, if the particle emitter bounding box is not in the camera\'s visible range, the particle will pause the simulation. If visible again, the particle will start simulating at the current time.\nWhen the Always Simulate is selected, the particle will keep simulating regardless of whether the particle emitter bounding box is in the camera\'s visible range, but will not render when it is not in the camera\'s visible range.', - alignSpace: 'Particle alignment space, the available options include View Space. \nWorld Space and Local Space.\nWhen the View Space is selected, the rotation direction of the particle mesh will follow the camera\'s view direction.\nWhen the World Space is selected, the direction of the particle mesh will use the world space rotation direction of the node where the particle emitter is located.\nWhen the Local Space is selected, the particle mesh will use the local space rotation direction of the node where the particle emitter is located.', + renderCulling: 'Whether to enable the particle culling feature.
If enabled, a particle emitter bounding box will be generated,
and the particle emitter will be culled if the bounding box is not in the visible range of the camera.
Please refer to the cullingMode option below for the behavior settings after particle culling.', + cullingMode: 'Sets the behavior of the particle emitter after it has been culled.
The available options include Pause, Pause and Catchup, and Always Simulate.
When the Pause is selected, the particle will pause the simulation if the particle emitter bounding box is not in the camera\'s visible range.
If it resumes visibility, the particle will continue simulating at the time of last pause.
When the Pause and Catchup is selected, if the particle emitter bounding box is not in the camera\'s visible range, the particle will pause the simulation. If visible again, the particle will start simulating at the current time.
When the Always Simulate is selected, the particle will keep simulating regardless of whether the particle emitter bounding box is in the camera\'s visible range, but will not render when it is not in the camera\'s visible range.', + alignSpace: 'Particle alignment space, the available options include View Space.
World Space and Local Space.
When the View Space is selected, the rotation direction of the particle mesh will follow the camera\'s view direction.
When the World Space is selected, the direction of the particle mesh will use the world space rotation direction of the node where the particle emitter is located.
When the Local Space is selected, the particle mesh will use the local space rotation direction of the node where the particle emitter is located.', aabbHalfX: 'Half width of the emitter bounding box', aabbHalfY: 'Half height of the emitter bounding box', aabbHalfZ: 'Half length of the emitter bounding box', @@ -687,21 +695,21 @@ module.exports = { spriteFrame: 'The mask image', inverted: 'The Reverse mask (Not supported Canvas Mode)', alphaThreshold: - 'The alpha threshold, The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold (Not supported Canvas Mode)', + 'The alpha threshold.
The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
(Not supported Canvas Mode)', segements: 'The segements for ellipse mask', }, physics: { rigidbody: { enabledContactListener: - 'Should enabled contact listener. When a collision is trigger, the collision callback will only be called when enabled contact listener.', + 'Should enabled contact listener. When a collision is trigger,
the collision callback will only be called when enabled contact listener.', bullet: 'Is this a fast moving body that should be prevented from tunneling through other moving bodies?', type: 'Rigid body type : Static, Kinematic, Dynamic or Animated.', allowSleep: 'Set this flag to false if this body should never fall asleep. Note that this increases CPU usage.', gravityScale: 'Scale the gravity applied to this body.', linearDamping: - 'Linear damping is use to reduce the linear velocity.\nThe damping parameter can be larger than 1, but the damping effect becomes sensitive to the time step when the damping parameter is large.', + 'Linear damping is use to reduce the linear velocity.
The damping parameter can be larger than 1, but the damping effect becomes sensitive to the time step when the damping parameter is large.', angularDamping: - 'Angular damping is use to reduce the angular velocity.\nThe damping parameter can be larger than 1 but the damping effect becomes sensitive to the time step when the damping parameter is large.', + 'Angular damping is use to reduce the angular velocity.
The damping parameter can be larger than 1 but the damping effect becomes sensitive to the time step when the damping parameter is large.', linearVelocity: "The linear velocity of the body's origin in world co-ordinates", angularVelocity: 'The angular velocity of the body.', fixedRotation: 'Should this body be prevented from rotating?', @@ -724,8 +732,8 @@ module.exports = { maxForce: 'The maximum force can be applied to rigid body.', maxTorque: 'The maximum torque can be applied to rigid body.', correctionFactor: 'The position correction factor in the range [0,1].', - mouseRegion: "The node used to register touch event. If this is null, it will be the joint's node.", - target: 'The target point. The mouse joint will move chosen rigid body to target point.', + mouseRegion: "The node used to register touch event.
If this is null, it will be the joint's node.", + target: 'The target point.
The mouse joint will move chosen rigid body to target point.', localAxisA: 'The local joint axis relative to rigid body.', enableLimit: 'Enable joint distance limit?', enableMotor: 'Enable joint motor?', @@ -733,7 +741,7 @@ module.exports = { upperLimit: 'The upper joint limit.', maxMotorForce: 'The maximum force can be applied to rigid body to reach the target motor speed.', motorSpeed: 'The expected motor speed.', - referenceAngle: 'The reference angle. An angle between bodies considered to be zero for the joint angle.', + referenceAngle: 'The reference angle.
An angle between bodies considered to be zero for the joint angle.', lowerAngle: 'The lower angle.', upperAngle: 'The upper angle.', maxMotorTorque: 'The maximum torque can be applied to rigid body to reach the target motor speed.', @@ -741,17 +749,17 @@ module.exports = { offset: 'Position offset', size: 'Box size', radius: 'Circle radius', - tag: 'Tag. If a node has several collider components, you can judge which type of collider is collided according to the tag.', + tag: 'Tag. If a node has several collider components,
you can judge which type of collider is collided according to the tag.', points: 'Polygon points', }, }, block_input_events: { brief_help: - 'This component will block all input events, \npreventing the input from penetrating to other nodes below the screen, \ntypically for the background of the top-level UI of the screen.', + 'This component will block all input events,
preventing the input from penetrating to other nodes below the screen,
typically for the background of the top-level UI of the screen.', }, tiledtile: { - row: 'Specify the TiledTile horizontal coordinate, use map tile as the unit.', - column: 'Specify the TiledTile vertical coordinate, use map tile as the unit.', + row: 'Specify the TiledTile horizontal coordinate,
use map tile as the unit.', + column: 'Specify the TiledTile vertical coordinate,
use map tile as the unit.', gid: 'Specify the TiledTile gid.', layer: 'Specify which TiledLayer the TiledTile belong to.', }, @@ -793,7 +801,11 @@ module.exports = { }, gfx_webgl2: { label: "WebGL 2.0", - description: "Include support for WebGL 2.0 graphics API.\n If WebGL 2.0 is not available on target platform, the one will fallback as WebGL 1.0.", + description: "Include support for WebGL 2.0 graphics API.
If WebGL 2.0 is not available on target platform, the one will fallback as WebGL 1.0.", + }, + gfx_webgpu: { + label: "WebGPU", + description: "Include support for WebGPU graphics API.", }, ui: { label: "User Interface", @@ -937,14 +949,14 @@ module.exports = { }, }, renderable_2d: { - srcBlendFactor: 'Specifies the source blend mode, it will clone a new material object.', + srcBlendFactor: 'Specifies the source blend mode,
it will clone a new material object.', dstBlendFactor: 'Specifies the destination blend mode.', color: 'Main color for rendering, it normally multiplies with texture color.', }, ui_transform: { - content_size:'Size of the UI node.', - anchor_point:'Anchor point of the UI node.', - priority:'Priority of rendering ordering.', + content_size: 'Size of the UI node.', + anchor_point: 'Anchor point of the UI node.', + priority: 'Priority of rendering ordering.', }, graphics: { lineWidth: 'The width of edges', @@ -960,8 +972,8 @@ module.exports = { type: 'Type of this rigid body', mass: 'The mass of this rigid body, which needs to be greater than 0', allowSleep: 'Whether to allow automatic hibernation', - linearDamping: 'Used to decay the linear velocity, the larger it is, the faster the decay will be', - angularDamping: 'Used to decay the angular velocity, the larger it is, the faster the decay will be', + linearDamping: 'Used to decay the linear velocity,
the larger it is, the faster the decay will be', + angularDamping: 'Used to decay the angular velocity,
the larger it is, the faster the decay will be', useGravity: 'Whether to use gravity', linearFactor: 'For scaling physical values (velocity or force) in each axis direction', angularFactor: 'Angular factor to scale physical values (velocity or force) in each axis direction', @@ -985,7 +997,7 @@ module.exports = { plane_normal: 'The normal to the plane in the local coordinate system', plane_constant: 'The distance of the plane moving along the normal from the origin in the local coordinate system', mesh_mesh: 'Mesh resources used by collider', - mesh_convex: 'Whether to use convex hull approximation instead, \nthe number of vertices should be less than 255, \nand the dynamics can be supported after turning on', + mesh_convex: 'Whether to use convex hull approximation instead,
the number of vertices should be less than 255,
and the dynamics can be supported after turning on', terrain_terrain: 'Terrain resources used by collider', simplex_shapeType: 'Simplex type, point, line, triangle, tetrahedron', simplex_vertex0: 'Vertex 0 of the shape', @@ -993,7 +1005,7 @@ module.exports = { simplex_vertex2: 'Vertex 2 of the shape', simplex_vertex3: 'Vertex 3 of the shape', }, - constant_force:{ + constant_force: { force: 'The force apply on a rigid body in the world coordinate system', localForce: 'The force apply on a rigid body in the local coordinate system', torque: 'The torque applied to the rigid body in the world coordinate system', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index d992fc3347..54ddbe026a 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -77,11 +77,12 @@ module.exports = { skyIllum: '环境光强度', }, skybox: { - applyDiffuseMap: '勾选后,场景物体将使用更精确的漫反射图来取代默认的半球光照。', + EnvironmentLightingType: '选择三种环境光照类型:
手调半球漫反射,无环境反射;
自动生成半球漫反射,带环境反射;
更精确的漫反射图,带环境反射;', enabled: '勾选后即可开启天空盒,使用设置的立方体贴图进行渲染', - useIBL: '勾选后,场景物体将使用设置的立方体贴图来进行环境光漫反射及镜面反射计算.', - useHDR: '切换高/低动态范围模式,每种模式都有自己独立的光源设定。\n高动态(HDR)模式会使用光度学灯光单位,配合相机镜头属性进行曝光计算,\n低动态(LDR)模式使用无单位光源和无曝光的镜头,更便于保留原图颜色', - envmap: '设置一个立方体贴图作为环境光源和天空盒,贴图类型包括十字型 HDR 贴图、经纬度图、手动创建的 CubeMap 等。目前支持 HDR/TGA/PNG 等文件格式。', + useHDR: '切换高/低动态范围模式,每种模式都有自己独立的光源设定。
高动态(HDR)模式会使用光度学灯光单位,配合相机镜头属性进行曝光计算,
低动态(LDR)模式使用无单位光源和无曝光的镜头,更便于保留原图颜色', + envmap: '设置一个立方体贴图作为环境光源和天空盒,
贴图类型包括十字型 HDR 贴图、经纬度图、手动创建的 CubeMap 等。
目前支持 HDR/TGA/PNG 等文件格式。', + rotationAngle: '调节天空盒与环境照明绕Y轴旋转的角度.', + material: '可使用自定义的天空盒材质,参考 skybox.effect.', }, fog: { enabled: '雾开关', @@ -97,26 +98,18 @@ module.exports = { }, shadow: { enabled: '是否开启实时阴影', + type: '阴影效果类型, 目前包括 ShadowMap(阴影贴图)、Planar(平面阴影)', + shadowColor: '平面阴影颜色', planeDirection: '阴影接收平面的法线,垂直于阴影,用于调整阴影的倾斜度', planeHeight: '阴影接收平面距离原点的高度', - saturation: '阴影饱和度,建议设置为 1.0。若需要减小方向光阴影的饱和程度,推荐通过增加环境光来实现,而不是调节该值。', - pcf: '开启软阴影,目前支持 HARD(硬采样)、SOFT(4 倍采样)、SOFT_2X(9 倍采样)类型', - bias: '增加深度偏移值(世界空间单位)可以有效消除阴影摩尔纹,但是过大的值可能造成漏光现象', - normalBias: '法线深度偏移值(世界空间单位),可以消除物体表面朝向平行于阳光方向的阴影摩尔纹,\n防止曲面出现锯齿状;但是过大的值可能会造成阴影位置偏差', shadowMapSize: '阴影贴图分辨率,目前支持 Low_256x256、Medium_512x512、High_1024x1024、Ultra_2048x2048 四种精度的纹理', - fixedArea: '切换固定区域和 CSM 模式。固定区域是一种旧模式,我们并不推荐使用。勾选该项则开启 CSM 模式,该模式下阴影会跟随方向光节点的位置,在方向光包围盒附近分布,而非跟随相机。', - near: '固定区域开始值', - far: '固定区域结束值', - orthoSize: '固定区域大小,该值越大则阴影精度越低', - invisibleOcclusionRange: '如果有背后的潜在投射物阴影丢失,请增大该值(世界空间单位)', - shadowDistance: '阴影有效距离(世界空间单位),该值越大则阴影精度越低', maxReceived: '产生阴影的有效光源数量', }, animation: { default_clip: '在勾选自动播放或调用 play() 时默认播放的动画 clip。', clips: '通过脚本可以访问并播放的 AnimationClip 列表', play_on_load: '是否在运行游戏后自动播放默认动画 clip。', - use_baked_animation: '是否使用预烘焙动画,默认启用,可以大幅提高运行效时率,\n但所有动画效果会被彻底固定,不支持任何形式的编辑', + use_baked_animation: '是否使用预烘焙动画,默认启用,可以大幅提高运行效时率,
但所有动画效果会被彻底固定,不支持任何形式的编辑', sockets: '当前动画组件维护的挂点数组。要挂载自定义节点到受动画驱动的骨骼上,必须先在此注册挂点', }, audio: { @@ -159,20 +152,35 @@ module.exports = { term: '当前使用的光度学计量单位', size: '光源大小', range: '光源范围', + shadowEnabled: '是否开启实时阴影', + shadowPcf: '开启软阴影,目前支持 HARD(硬采样)、SOFT(4 倍采样)、SOFT_2X(9 倍采样)、SOFT_4X(16 倍采样)类型', + shadowBias: '增加深度偏移值(世界空间单位)可以有效消除阴影摩尔纹,但是过大的值可能造成漏光现象', + shadowNormalBias: '法线深度偏移值(世界空间单位),可以消除物体表面朝向平行于阳光方向的阴影摩尔纹,
防止曲面出现锯齿状;但是过大的值可能会造成阴影位置偏差', + shadowSaturation: '阴影饱和度,建议设置为 1.0。
若需要减小方向光阴影的饱和程度,推荐通过增加环境光来实现,而不是调节该值。', + shadowDistance: '阴影有效距离(世界空间单位),该值越大则阴影精度越低', + shadowInvisibleOcclusionRange: '如果有背后的潜在投射物阴影丢失,请增大该值(世界空间单位)', + enableCSM: '开启 CSM 模式', + shadowFixedArea: '切换固定区域和 CSM 模式。固定区域是一种旧模式,我们并不推荐使用。
勾选该项则开启 CSM 模式,该模式下阴影会跟随方向光节点的位置,在方向光包围盒附近分布,而非跟随相机。', + shadowNear: '固定区域开始值', + shadowFar: '固定区域结束值', + shadowOrthoSize: '固定区域大小,该值越大则阴影精度越低', }, model: { + shadow_receiving_model: '阴影接受方式', shadow_casting_model: '阴影投射方式', mesh: '模型的网格数据', skinning_root: '骨骼根节点的引用,对应控制此模型的动画组件所在节点', + shadow_bias: '模型额外增加深度偏移值(世界空间单位)可以有效消除阴影摩尔纹,但是过大的值可能造成漏光现象', + shadow_normal_bias: '模型额外增加法线深度偏移值(世界空间单位),可以消除物体表面朝向平行于阳光方向的阴影摩尔纹,
防止曲面出现锯齿状;但是过大的值可能会造成阴影位置偏差', }, sprite: { gray_scale: '是否开启灰度渲染模式', atlas: '图片资源所属的 Atlas 图集资源', sprite_frame: '渲染 Sprite 使用的 Sprite Frame 图片资源', type: - '渲染模式:\n - 普通(Simple):修改尺寸会整体拉伸图像,适用于序列帧动画和普通图像 \n' + - '- 九宫格 Sliced 修改尺寸时四个角的区域不会拉伸,适用于 UI 按钮和面板背景 \n' + - '- 平铺 Tiled 修改尺寸时会不断平铺原始大小的图片 \n' + + '渲染模式:
- 普通(Simple):修改尺寸会整体拉伸图像,适用于序列帧动画和普通图像
' + + '- 九宫格 Sliced 修改尺寸时四个角的区域不会拉伸,适用于 UI 按钮和面板背景
' + + '- 平铺 Tiled 修改尺寸时会不断平铺原始大小的图片
' + '- 填充 Filled 设置一定的填充起始位置和方向,能够以一定比率剪裁显示图片', original_size: '是否使用图片资源的原始尺寸作为 Sprite 节点的 size', edit_button: '编辑', @@ -186,7 +194,7 @@ module.exports = { src_blend_factor: '混合显示两张图片时,源图片的取值模式', dst_blend_factor: '混合显示两张图片时,目标图片的取值模式', size_mode: - '指定 Sprite 所在节点的尺寸\nCUSTOM 表示自定义尺寸\nTRIMMED 表示取原始图片剪裁透明像素后的尺寸\nRAW 表示取原始图片未剪裁的尺寸', + '指定 Sprite 所在节点的尺寸
CUSTOM 表示自定义尺寸
TRIMMED 表示取原始图片剪裁透明像素后的尺寸
RAW 表示取原始图片未剪裁的尺寸', trim: '节点约束框内是否包括透明像素区域,勾选此项会去除节点约束框内的透明区域', }, UIOpacity: { @@ -214,7 +222,7 @@ module.exports = { duration: '按钮颜色变化或者缩放变化的过渡时间', zoom_scale: '当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale, zoomScale 可以为负数', auto_gray_effect: - '如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,\n会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰', + '如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,
会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰', normal_sprite: '普通状态的按钮背景图资源', pressed_sprite: '按下状态的按钮背景图资源', hover_sprite: '悬停状态的按钮背景图资源', @@ -226,7 +234,7 @@ module.exports = { camera: '2D 渲染相机', align: '自动为 camera 计算参数', design_resolution: - '设计分辨率是游戏在设计时使用的分辨率参考,以像素为单位,通过下面的适配策略,\n可以在不同分辨率的设备上按照一定的方式对 Canvas 进行整体缩放来适配。', + '设计分辨率是游戏在设计时使用的分辨率参考,以像素为单位,通过下面的适配策略,
可以在不同分辨率的设备上按照一定的方式对 Canvas 进行整体缩放来适配。', fit_height: '自动缩放 Canvas 使设计分辨率的高度充满设备屏幕的高度', fit_width: '自动缩放 Canvas 使设计分辨率的宽度充满设备屏幕的宽度', }, @@ -250,12 +258,12 @@ module.exports = { font_family: '文字字体名字', line_height: '文字行高,以 point 为单位', overflow: - '文字排版模式,包括以下三种:\n 1. CLAMP: 节点约束框之外的文字会被截断 \n 2. SHRINK: 自动根据节点约束框缩小文字\n 3. RESIZE: 根据文本内容自动更新节点的 height 属性.', + '文字排版模式,包括以下三种:
1. CLAMP: 节点约束框之外的文字会被截断
2. SHRINK: 自动根据节点约束框缩小文字
3. RESIZE: 根据文本内容自动更新节点的 height 属性.', wrap: '是否允许自动换行', font: 'Label 使用的字体资源', system_font: '是否使用系统默认字体,选中此项会将 file 属性置空', cache_mode: - '文本缓存模式,包括以下三种:\n 1. NONE: 不做任何缓存,文本内容进行一次绘制 \n 2. BITMAP: 将文本作为静态图像加入动态图集进行批次合并,但是不能频繁动态修改文本内容 \n 3. CHAR: 将文本拆分为字符并且把字符纹理缓存到一张字符图集中进行复用,适用于字符内容重复并且频繁更新的文本内容', + '文本缓存模式,包括以下三种:
1. NONE: 不做任何缓存,文本内容进行一次绘制
2. BITMAP: 将文本作为静态图像加入动态图集进行批次合并,但是不能频繁动态修改文本内容
3. CHAR: 将文本拆分为字符并且把字符纹理缓存到一张字符图集中进行复用,适用于字符内容重复并且频繁更新的文本内容', font_bold: '字体加粗', font_italic: '字体倾斜', font_underline: '字体加下划线', @@ -291,7 +299,7 @@ module.exports = { }, progress: { bar_sprite: '进度条显示用的 Sprite 节点,可以动态改变尺寸', - mode: '进度条显示模式, 包括以下三种:\n 1. HORIZONTAL: 水平方向模式 \n 2. VERTICAL: 垂直方向模式 \n 3. FILLED: 扇形填充模式', + mode: '进度条显示模式, 包括以下三种:
1. HORIZONTAL: 水平方向模式
2. VERTICAL: 垂直方向模式
3. FILLED: 扇形填充模式', total_length: '进度条在 progress 为 1 时的最大长度', progress: '当前进度指示,范围从0到1', reverse: '是否反向驱动进度条', @@ -300,7 +308,7 @@ module.exports = { handle: '作为当前滚动区域位置显示的滑块 Sprite', direction: 'ScrollBar的滚动方向', auto_hide: '是否在没有滚动动作时自动隐藏 Scroll Bar', - auto_hide_time: '没有滚动动作后经过多久会自动隐藏\n注意:只有当 Enable Auto Hide 为 true 时才有效', + auto_hide_time: '没有滚动动作后经过多久会自动隐藏
注意:只有当 Enable Auto Hide 为 true 时才有效', }, scrollview: { content: '包含可滚动展示内容的节点引用', @@ -319,12 +327,12 @@ module.exports = { sizeMode: '页面视图中每个页面大小类型', direction: '页面视图滚动方向', scrollThreshold: '滚动临界值,默认单位百分比,当拖拽超出该数值时,松开会自动滚动下一页,小于时则还原', - pageTurningEventTiming: '设置 Page View 页面自动滚动动画结束的阈值,\n修改此值可以调整 Page View 事件的发送时机。', + pageTurningEventTiming: '设置 Page View 页面自动滚动动画结束的阈值,
修改此值可以调整 Page View 事件的发送时机。', indicator: '页面视图指示器组件', pageTurningSpeed: '每个页面翻页时所需时间。单位:秒', pageEvents: '页面视图的事件回调函数', autoPageTurningThreshold: - '快速滑动翻页临界值\n当用户快速滑动时,会根据滑动开始和结束的距离与时间计算出一个速度值\n该值与此临界值相比较,如果大于临界值,则进行自动翻页', + '快速滑动翻页临界值
当用户快速滑动时,会根据滑动开始和结束的距离与时间计算出一个速度值
该值与此临界值相比较,如果大于临界值,则进行自动翻页', }, pageview_indicator: { spriteFrame: '每个页面标记显示的图片', @@ -368,8 +376,8 @@ module.exports = { frameOverTime: '一个周期内动画播放的帧与时间变化曲线', startFrame: '从第几帧开始播放,时间为整个粒子系统的生命周期', cycleCount: '一个生命周期内播放循环的次数', - randomRow: '随机从动画贴图中选择一行以生成动画,\n此选项仅在动画播放方式为 Single Row 时生效', - rowIndex: '从动画贴图中选择特定行以生成动画,\n此选项仅在动画播放方式为 Single Row 时且禁用 Random Row 时可用', + randomRow: '随机从动画贴图中选择一行以生成动画,
此选项仅在动画播放方式为 Single Row 时生效', + rowIndex: '从动画贴图中选择特定行以生成动画,
此选项仅在动画播放方式为 Single Row 时且禁用 Random Row 时可用', }, toggle: { interactable: 'Toggle 是否可交互,这一项未选中时,Toggle 处在禁用状态', @@ -380,9 +388,9 @@ module.exports = { hover_color: '悬停状态的 Toggle 背景颜色', disabled_color: '禁用状态的 Toggle 背景颜色', duration: 'Toggle 颜色变化或者缩放变化的过渡时间', - zoom_scale: '当用户点击 Toggle 后,Toggle 会缩放到一个值,\n这个值等于 Toggle 原始 scale * zoomScale, zoomScale 可以为负数', + zoom_scale: '当用户点击 Toggle 后,Toggle 会缩放到一个值,
这个值等于 Toggle 原始 scale * zoomScale, zoomScale 可以为负数', auto_gray_effect: - '如果这个标记为 true,当 toggle 的 interactable 属性为 false 的时候,\n会使用内置 shader 让 toggle 的 target 节点的 sprite 组件变灰', + '如果这个标记为 true,当 toggle 的 interactable 属性为 false 的时候,
会使用内置 shader 让 toggle 的 target 节点的 sprite 组件变灰', normal_sprite: '普通状态的 Toggle 背景图资源', pressed_sprite: '按下状态的 Toggle 背景图资源', hover_sprite: '悬停状态的 Toggle 背景图资源', @@ -391,7 +399,7 @@ module.exports = { isChecked: '如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。', checkMark: 'Toggle 处于选中状态时显示的精灵图片', toggleGroup: - 'Toggle 所属的 Toggle Group,这个属性是可选的。\n如果这个属性为 null,则 Toggle 是一个 CheckBox,否则,Toggle 是一个 Radio Button。', + 'Toggle 所属的 Toggle Group,这个属性是可选的。
如果这个属性为 null,则 Toggle 是一个 CheckBox,否则,Toggle 是一个 Radio Button。', check_events: 'Toggle 按钮的点击事件列表', }, toggle_group: { @@ -403,7 +411,7 @@ module.exports = { rotation: '粒子发射器旋转角度', scale: '粒子发射器缩放比例', arc: '粒子发射器在一个扇形范围内发射', - angle: '圆锥的轴与母线的夹角\n决定圆锥发射器的开合程度', + angle: '圆锥的轴与母线的夹角
决定圆锥发射器的开合程度', shapeType: '粒子发射器类型', emitFrom: '粒子从发射器哪个部位发射', alignToDirection: '根据粒子的初始方向决定粒子的移动方向', @@ -411,11 +419,11 @@ module.exports = { sphericalDirectionAmount: '表示当前发射方向与当前位置到结点中心连线方向的插值', randomPositionAmount: '粒子生成位置随机设定(设定此值为非 0 会使粒子生成位置超出生成器大小范围)', radius: '粒子发射器半径', - radiusThickness: '粒子发射器发射位置(对 Box 类型的发射器无效):\n - 0 表示从表面发射;\n - 1 表示从中心发射;\n - 0 ~ 1 之间表示在中心到表面之间发射。', + radiusThickness: '粒子发射器发射位置(对 Box 类型的发射器无效):
- 0 表示从表面发射;
- 1 表示从中心发射;
- 0 ~ 1 之间表示在中心到表面之间发射。', arcMode: '粒子在扇形范围内的发射方式', arcSpread: '控制可能产生粒子的弧周围的离散间隔', arcSpeed: '粒子沿圆周发射的速度', - length: '圆锥顶部截面距离底部的轴长\n决定圆锥发射器的高度', + length: '圆锥顶部截面距离底部的轴长
决定圆锥发射器的高度', boxThickness: '粒子发射器发射位置(针对 Box 类型的粒子发射器)', }, slider: { @@ -428,8 +436,8 @@ module.exports = { mode: 'Particle在每个粒子的运动轨迹上形成拖尾效果', lifeTime: '拖尾的生命周期', minParticleDistance: '粒子每生成一个拖尾节点所运行的最短距离', - space: '拖尾所在的坐标系,\nWorld 在世界坐标系中运行,\nLocal 在本地坐标系中运行', - textureMode: '贴图在拖尾上的展开形式,\nStretch 贴图覆盖在整条拖尾上,\nRepeat 贴图覆盖在一段拖尾上', + space: '拖尾所在的坐标系,
World 在世界坐标系中运行,
Local 在本地坐标系中运行', + textureMode: '贴图在拖尾上的展开形式,
Stretch 贴图覆盖在整条拖尾上,
Repeat 贴图覆盖在一段拖尾上', widthFromParticle: '拖尾宽度继承自粒子大小', widthRatio: '拖尾宽度,如果继承自粒子则是粒子大小的比例', colorFromParticle: '拖尾颜色是否继承自粒子', @@ -462,20 +470,20 @@ module.exports = { }, layout: { layout_type: - '自动布局模式,包括:\n 1. NONE,不会对子节点进行自动布局 \n 2. HORIZONTAL,横向自动排布子物体 \n 3. VERTICAL,垂直自动排布子物体\n 4. GRID, 采用网格方式对子物体自动进行布局', + '自动布局模式,包括:
1. NONE,不会对子节点进行自动布局
2. HORIZONTAL,横向自动排布子物体
3. VERTICAL,垂直自动排布子物体
4. GRID, 采用网格方式对子物体自动进行布局', resize_mode: - '缩放模式,包括:\n 1. NONE,不会对子节点和容器进行大小缩放 \n 2. CONTAINER, 对容器的大小进行缩放 \n 3. CHILD, 对子节点的大小进行缩放', + '缩放模式,包括:
1. NONE,不会对子节点和容器进行大小缩放
2. CONTAINER, 对容器的大小进行缩放
3. CHILD, 对子节点的大小进行缩放', padding_left: 'Layout 节点左边界和子节点的内边距', padding_right: 'Layout 节点右边界和子节点的内边距', padding_top: 'Layout 节点上边界和子节点的内边距', padding_bottom: 'Layout 节点下边界和子节点的内边距', space_x: '相邻子节点之间的水平距离', space_y: '相邻子节点之间的垂直距离', - vertical_direction: '垂直排列子节点的方向,包括:\n 1. TOP_TO_BOTTOM, 从上到下排列 \n 2. BOTTOM_TO_TOP, 从下到上排列', - horizontal_direction: '水平排列子节点的方向,包括:\n 1. LEFT_TO_RIGHT, 从左到右排列 \n 2. RIGHT_TO_LEFT, 从右到左排列', + vertical_direction: '垂直排列子节点的方向,包括:
1. TOP_TO_BOTTOM, 从上到下排列
2. BOTTOM_TO_TOP, 从下到上排列', + horizontal_direction: '水平排列子节点的方向,包括:
1. LEFT_TO_RIGHT, 从左到右排列
2. RIGHT_TO_LEFT, 从右到左排列', cell_size: '网格布局中,规定每一个网格的大小', start_axis: '网格布局中,子物体排版时的起始方向轴,支持水平和垂直两个方向。', - constraint: '网格布局中,内容布局约束,包括:\n 1.NONE,无约束 \n 2.FIXED_ROW,行数固定 \n 3.FIXED_COL,列数固定', + constraint: '网格布局中,内容布局约束,包括:
1.NONE,无约束
2.FIXED_ROW,行数固定
3.FIXED_COL,列数固定', constraint_number: '网格布局中,内容布局约束的行或列数量', affected_scale: '子节点缩放比例是否影响布局', align_horizontal: '自动对齐。在 Type 为 Horizontal 时自动对齐纵坐标', @@ -507,8 +515,8 @@ module.exports = { placeholder_label: '输入框占位符节点上挂载的 Label 组件对象', editing_began: '开始编辑文本输入框触发的事件回调', text_changed: '编辑文本输入框时触发的事件回调', - editing_ended: '结束编辑文本输入框时触发的事件回调\n在单行模式下面,一般是在用户按下回车或者点击屏幕输入框以外的地方调用该函数\n如果是多行输入,一般是在用户点击屏幕输入框以外的地方调用该函数', - editing_return: '当用户按下回车按键时的事件回调\n如果是单行输入框,按回车键还会使输入框失去焦点', + editing_ended: '结束编辑文本输入框时触发的事件回调
在单行模式下面,一般是在用户按下回车或者点击屏幕输入框以外的地方调用该函数
如果是多行输入,一般是在用户点击屏幕输入框以外的地方调用该函数', + editing_return: '当用户按下回车按键时的事件回调
如果是单行输入框,按回车键还会使输入框失去焦点', }, videoplayer: { resourceType: '视频来源:REMOTE 表示远程视频 URL,LOCAL 表示本地视频地址。', @@ -547,7 +555,7 @@ module.exports = { camera: '照射相机', use_scale: '是否是缩放映射', distance: '距相机多少距离为正常显示计算大小', - sync_events: '映射数据事件\n回调的第一个参数是映射后的本地坐标,第二个是距相机距离', + sync_events: '映射数据事件
回调的第一个参数是映射后的本地坐标,第二个是距相机距离', }, subContextView: { design_size: '开放数据域的设计分辨率,禁止在运行时动态更新', @@ -569,7 +577,7 @@ module.exports = { armature_name: '当前的 Armature 名称', animation_name: '当前播放的动画名称', time_scale: '当前骨骼中所有动画的时间缩放率', - play_times: '播放默认动画的循环次数\n - 1 表示使用配置文件中的默认值\n0 表示无限循环\n > 0 表示循环次数', + play_times: '播放默认动画的循环次数
- 1 表示使用配置文件中的默认值
0 表示无限循环
> 0 表示循环次数', debug_bones: '是否显示 bone 的 debug 信息', }, motionStreak: { @@ -658,9 +666,9 @@ module.exports = { textureAnimationModule: '贴图动画模块', trailModule: '粒子轨迹模块(只支持 CPU 粒子)', renderer: '粒子渲染模块', - renderCulling: '是否开启粒子剔除功能。\n开启该项将会生成一个粒子发射器包围盒,若包围盒不在摄像机的可见范围内,该粒子发射器便会被剔除。\n粒子发射器被剔除后的行为请参考下面的 Culling Mode。', - cullingMode: '粒子发射器被剔除之后的行为,可设置的选项包括 Pause, Pause and Catchup, Always Simulate。\n选择 Pause 时,若粒子发射器包围盒不在摄像机的可见范围内,粒子暂停模拟。若恢复可见,则粒子会接着上次暂停的时间继续模拟;\n选择 Pause and Catchup 时,若粒子发射器包围盒不在摄像机的可见范围内,粒子暂停模拟。若恢复可见,则粒子会以当前的时间开始模拟;\n选择 Always Simulate 时,无论粒子发射器包围盒是否在摄像机的可见范围内,粒子都会一直模拟,只是不在摄像机的可见范围内时不进行渲染。', - alignSpace: '粒子对齐方向空间,可设置的选项包括:视角空间、世界空间和局部空间。\n选择视角空间时,粒子网格的旋转方向将会跟随摄像机的视角方向;\n选择世界空间时,粒子网格的方向将会使用发射器节点的世界空间旋转方向;\n选择局部空间时,粒子网格使用发射器节点的局部空间旋转方向。', + renderCulling: '是否开启粒子剔除功能。
开启该项将会生成一个粒子发射器包围盒,若包围盒不在摄像机的可见范围内,该粒子发射器便会被剔除。
粒子发射器被剔除后的行为请参考下面的 Culling Mode。', + cullingMode: '粒子发射器被剔除之后的行为,可设置的选项包括 Pause, Pause and Catchup, Always Simulate。
选择 Pause 时,若粒子发射器包围盒不在摄像机的可见范围内,粒子暂停模拟。若恢复可见,则粒子会接着上次暂停的时间继续模拟;
选择 Pause and Catchup 时,若粒子发射器包围盒不在摄像机的可见范围内,粒子暂停模拟。若恢复可见,则粒子会以当前的时间开始模拟;
选择 Always Simulate 时,无论粒子发射器包围盒是否在摄像机的可见范围内,粒子都会一直模拟,只是不在摄像机的可见范围内时不进行渲染。', + alignSpace: '粒子对齐方向空间,可设置的选项包括:视角空间、世界空间和局部空间。
选择视角空间时,粒子网格的旋转方向将会跟随摄像机的视角方向;
选择世界空间时,粒子网格的方向将会使用发射器节点的世界空间旋转方向;
选择局部空间时,粒子网格使用发射器节点的局部空间旋转方向。', aabbHalfX: '设置发射器包围盒半宽', aabbHalfY: '设置发射器包围盒半高', aabbHalfZ: '设置发射器包围盒半长', @@ -677,7 +685,7 @@ module.exports = { rigidbody: { enabledContactListener: '是否启用接触接听器。当 Collider 产生碰撞时,只有开启了接触接听器才会调用相应的回调函数', bullet: '这个刚体是否是一个快速移动的刚体,并且需要禁止穿过其他快速移动的刚体', - type: '刚体类型:\nStatic(静态), \nKinematic(不受外力), \nDynamic(动态)和 Animated(通过设置线性速度和角速度驱动)', + type: '刚体类型:
Static(静态),
Kinematic(不受外力),
Dynamic(动态)和 Animated(通过设置线性速度和角速度驱动)', allowSleep: '如果此刚体永远都不应该进入睡眠,那么设置这个属性为 False。需要注意这将使 CPU 占用率提高', gravityScale: '缩放应用在此刚体上的重力值', linearDamping: @@ -774,7 +782,11 @@ module.exports = { }, gfx_webgl2: { label: "WebGL 2.0", - description: "包含对 WebGL 2.0 图形 API 的支持。\n当 WebGL 2.0 在目标平台上不可用时会自动回退至 WebGL 1.0。", + description: "包含对 WebGL 2.0 图形 API 的支持。
当 WebGL 2.0 在目标平台上不可用时会自动回退至 WebGL 1.0。", + }, + gfx_webgpu: { + label: "WebGPU", + description: "包含对 WebGPU 图形 API 的支持。", }, ui: { label: "用户界面", @@ -923,9 +935,9 @@ module.exports = { color: '渲染颜色,一般情况下会和贴图颜色相乘', }, ui_transform: { - content_size:'内容尺寸', - anchor_point:'锚点位置', - priority:'渲染排序优先级', + content_size: '内容尺寸', + anchor_point: '锚点位置', + priority: '渲染排序优先级', }, graphics: { lineWidth: '线条宽度', @@ -938,7 +950,7 @@ module.exports = { physics3d: { rigidbody: { group: '刚体分组', - type: '刚体类型:\nStatic为静态, \nKinematic 为运动学(通过变换信息操控), \nDynamic 为动力学(通过物理数值操控)', + type: '刚体类型:
Static为静态,
Kinematic 为运动学(通过变换信息操控),
Dynamic 为动力学(通过物理数值操控)', mass: '刚体质量,需大于 0', allowSleep: '是否允许自动休眠', linearDamping: '线性阻尼,用于衰减线性速度,值越大,衰减越快', @@ -974,7 +986,7 @@ module.exports = { simplex_vertex2: '形状的顶点 2', simplex_vertex3: '形状的顶点 3', }, - constant_force:{ + constant_force: { force: '在世界坐标系中,对刚体施加的力', localForce: '在本地坐标系中,对刚体施加的力', torque: '在世界坐标系中,对刚体施加的扭转力', diff --git a/editor/inspector/assets/material.js b/editor/inspector/assets/material.js index d33c21cf88..480297b155 100644 --- a/editor/inspector/assets/material.js +++ b/editor/inspector/assets/material.js @@ -35,7 +35,6 @@ exports.template = /* html */ `
-
@@ -49,7 +48,6 @@ exports.$ = { location: '.location', technique: '.technique', useInstancing: '.useInstancing', - useBatching: '.useBatching', materialDump: '.material-dump', custom: '.custom', @@ -289,11 +287,6 @@ exports.methods = { if (firstPass.childMap.USE_INSTANCING) { technique.useInstancing.value = firstPass.childMap.USE_INSTANCING.value; - if (firstPass.childMap.USE_BATCHING) { - technique.useBatching.value = firstPass.childMap.USE_BATCHING.value; - technique.useBatching.visible = !technique.useInstancing.value; - } - this.changeInstancing(technique.useInstancing.value); } @@ -302,12 +295,6 @@ exports.methods = { setHidden(technique.useInstancing && !technique.useInstancing.visible, this.$.useInstancing); setReadonly(this.asset.readonly, this.$.useInstancing); } - - if (technique.useBatching) { - this.$.useBatching.render(technique.useBatching); - setHidden(technique.useInstancing.value || (technique.useBatching && !technique.useBatching.visible), this.$.useBatching); - setReadonly(this.asset.readonly, this.$.useBatching); - } }, async updatePreview(emit) { @@ -322,21 +309,6 @@ exports.methods = { pass.childMap.USE_INSTANCING.value = checked; } }); - - // if Instancing show, Batching hidden - setHidden(checked, this.$.useBatching); - if (checked) { - this.changeBatching(false); - this.$.useBatching.render(this.technique.useBatching); - } - }, - - changeBatching(checked) { - this.technique.passes.forEach((pass) => { - if (pass.childMap.USE_BATCHING) { - pass.childMap.USE_BATCHING.value = checked; - } - }); }, initCache() { @@ -542,13 +514,6 @@ exports.ready = function() { this.change(); }); - // The event is triggered when the useBatching is modified - this.$.useBatching.addEventListener('change-dump', (event) => { - this.changeBatching(event.target.dump.value); - this.storeCache(event.target.dump); - this.change(); - }); - // The event triggered when the content of material is modified this.$.materialDump.addEventListener('change-dump', async (event) => { const dump = event.target.dump; diff --git a/editor/inspector/components/label.js b/editor/inspector/components/label.js index a5f04ced3e..2d3aa5eadd 100644 --- a/editor/inspector/components/label.js +++ b/editor/inspector/components/label.js @@ -1,4 +1,4 @@ -const { getName, setHidden, isMultipleInvalid, setTooltip, setLabel } = require('../utils/prop'); +const { getName, setHidden, isMultipleInvalid } = require('../utils/prop'); const { template, $, update } = require('./base'); const fontStyles = ['isBold', 'isItalic', 'isUnderline']; exports.template = template; @@ -57,7 +57,7 @@ exports.ready = function() { prop.dump = dump; const label = document.createElement('ui-label'); label.setAttribute('slot', 'label'); - setLabel(label, dump); + label.value = getName(dump); const content = document.createElement('ui-tab'); content.setAttribute('slot', 'content'); content.addEventListener('change', (event) => { @@ -80,9 +80,10 @@ exports.ready = function() { } else { image.setAttribute('value', `align-${iconName}`); } - setTooltip(image, { tooltip: `${dump.tooltip}_${iconName}` }); - image.setAttribute('readonly', true); + button.appendChild(image); + button.setAttribute('tooltip', `${dump.tooltip}_${iconName}`); + content.appendChild(button); } prop.appendChild(label); @@ -104,7 +105,7 @@ exports.ready = function() { prop.dump = dump; const label = document.createElement('ui-label'); label.setAttribute('slot', 'label'); - setLabel(label, dump); + label.value = getName(dump); const content = document.createElement('ui-tab'); content.setAttribute('slot', 'content'); content.addEventListener('change', (event) => { @@ -127,8 +128,10 @@ exports.ready = function() { } else { image.setAttribute('value', `align-${iconName}`); } - setTooltip(image, { tooltip: `${dump.tooltip}_${iconName}` }); + button.appendChild(image); + button.setAttribute('tooltip', `${dump.tooltip}_${iconName}`); + content.appendChild(button); } prop.appendChild(label); @@ -150,7 +153,7 @@ exports.ready = function() { const label = document.createElement('ui-label'); label.setAttribute('slot', 'label'); label.value = 'FontStyle'; - label.setAttribute('tooltip', Editor.I18n.t('ENGINE.components.label.font_style_tooltip')); + label.setAttribute('tooltip', 'i18n:ENGINE.components.label.font_style_tooltip'); prop.appendChild(label); const content = document.createElement('div'); content.setAttribute('slot', 'content'); @@ -161,8 +164,8 @@ exports.ready = function() { const style = fontStyles[index]; const label = document.createElement('ui-label'); label.innerHTML = styleDisplayNames[index]; - setTooltip(label, this.dump.value[style]); label.setAttribute('key', style); + label.setAttribute('tooltip', this.dump.value[style].tooltip); label.classList.add('fontStyle', styleClassNames[index]); label.addEventListener('mouseup', () => { prop.dump = this.dump.value[style]; diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index c33b0adcb8..d67a3c8576 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -181,7 +181,7 @@ exports.listeners = { * So stop preview some properties. */ const stopPreviewOnTheseTooltips = [ - 'i18n:animation.default_clip', + 'i18n:ENGINE.animation.default_clip', ]; if (stopPreviewOnTheseTooltips.includes(dump.tooltip)) { return; diff --git a/editor/inspector/utils/material.js b/editor/inspector/utils/material.js index 47adb2607c..ae37c74d1b 100644 --- a/editor/inspector/utils/material.js +++ b/editor/inspector/utils/material.js @@ -15,13 +15,13 @@ exports.buildEffect = function(index, passData) { childMap: {}, }; - const hideAttrs = ['USE_INSTANCING', 'USE_BATCHING']; + const hideAttrs = ['USE_INSTANCING']; function encode(item) { let current = tree; /** - * USE_INSTANCING and USE_BATCHING are common to every child in passes + * USE_INSTANCING is common to every child in passes * To make editing easier, they are referred to the outside of the passes * At this point, you need to set each of the passes to be non-editable and invisible */ @@ -172,7 +172,6 @@ exports.buildEffect = function(index, passData) { exports.materialTechniquePolyfill = function(origin) { let useInstancing; - let useBatching; const passes = origin.passes.map((data, index) => { // Merge data.defines and data.props const pass = exports.buildEffect(index, data); @@ -183,17 +182,11 @@ exports.materialTechniquePolyfill = function(origin) { useInstancing = JSON.parse(JSON.stringify(pass.childMap.USE_INSTANCING)); useInstancing.visible = true; } - - if (!useBatching && pass.childMap.USE_BATCHING) { - useBatching = JSON.parse(JSON.stringify(pass.childMap.USE_BATCHING)); - useBatching.visible = true; - } - return pass; }); /** - * USE_INSTANCING and USE_BATCHING are common to every child in passes + * USE_INSTANCING is common to every child in passes * For ease of editing, they are referred to outside of the passes * Two external variables useInstancing, useBatching are provided to dock * The value of the first pass takes precedence @@ -202,7 +195,6 @@ exports.materialTechniquePolyfill = function(origin) { name: origin.name, passes, useInstancing, - useBatching, }; return technique; diff --git a/editor/inspector/utils/prop.js b/editor/inspector/utils/prop.js index bb059198c0..636d4ad2ec 100644 --- a/editor/inspector/utils/prop.js +++ b/editor/inspector/utils/prop.js @@ -331,39 +331,6 @@ exports.getName = function(dump) { return name.trim(); }; -exports.setTooltip = function(element, dump) { - if (dump.tooltip) { - let tooltip = dump.tooltip; - if (tooltip.startsWith('i18n:')) { - tooltip = Editor.I18n.t('ENGINE.' + tooltip.substr(5)); - // If ENGINE doesn't translate, use extension's translation data and try to translate directly - if (!tooltip || tooltip === dump.tooltip) { - tooltip = Editor.I18n.t(dump.tooltip.substr(5)) || dump.tooltip; - } - } - element.setAttribute('tooltip', tooltip); - } else { - element.removeAttribute('tooltip'); - } -}; - -/** - * Sets the generic property Label in prop - * name and tooltip - */ -exports.setLabel = function($label, dump) { - if (!dump) { - dump = this.dump; - } - - if (!$label || !dump) { - return; - } - - $label.innerHTML = exports.getName(dump); - exports.setTooltip($label, dump); -}; - exports.createTabGroup = function(dump, panel) { const $group = document.createElement('div'); $group.setAttribute('class', 'tab-group'); diff --git a/gulp/util/api-docs-build.js b/gulp/util/api-docs-build.js index 28835bd83f..712893fc62 100644 --- a/gulp/util/api-docs-build.js +++ b/gulp/util/api-docs-build.js @@ -11,7 +11,7 @@ program const mode = 'commonjs'; const docsName = 'Cocos-Creator-API'; -const exclude = '"**/cocos/**/+(webgl|webgl2|utils|builtin|renderer|scene|models|misc|ammo|shapes|constraint|cannon|graphics|profiler|shader-sources|physx|spec|box2d)/*.ts"'; +const exclude = '"**/cocos/**/+(webgl|webgl2|webgpu|utils|builtin|renderer|scene|models|misc|ammo|shapes|constraint|cannon|graphics|profiler|shader-sources|physx|spec|box2d)/*.ts"'; const readme = 'none'; //const exclude = '"**/cocos/**/index.ts"'; @@ -108,7 +108,7 @@ exports.generateHTMLWithLocalization = function () { removeLanguage != "en" && this.generateAPIEN(index, jsonFiles, `${output}/en`); } -function checkJsonFileExists (jsonFils) { +function checkJsonFileExists(jsonFils) { let existsSync = fs.accessSync || fs.existsSync; try { existsSync(jsonFils) @@ -120,7 +120,7 @@ function checkJsonFileExists (jsonFils) { return true; } -function outputDebug (child) { +function outputDebug(child) { // spawnSync if (child.output && child.output.length > 0) { for (let i = 0; i < child.output.length; i++) { diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index a7241af001..bca18a34dd 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -239,6 +239,9 @@ endfunction() if(NOT DEFINED NODE_EXECUTABLE) if(DEFINED EDITOR_NODEJS) set(NODE_EXECUTABLE ${EDITOR_NODEJS}) + elseif(DEFINED ENV{NODE_EXECUTABLE}) + set(NODE_EXECUTABLE $ENV{NODE_EXECUTABLE}) + message(STATUS "set NODE_EXECUTABLE by env") else() find_program(NODE_EXECUTABLE NAMES node) endif() @@ -263,6 +266,7 @@ elseif(ANDROID) elseif(OHOS) include(${CMAKE_CURRENT_LIST_DIR}/../../templates/cmake/ohos.cmake) elseif(QNX) +elseif(EMSCRIPTEN) else() message(FATAL_ERROR "Unhandled platform specified cmake utils!") endif() diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index d4edec7abf..0ee8bc517e 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -32,6 +32,7 @@ #include "scene/Pass.h" namespace cc { + Batcher2d::Batcher2d() : Batcher2d(nullptr) { } @@ -255,52 +256,32 @@ CC_FORCE_INLINE void Batcher2d::handleModelDraw(RenderEntity* entity, RenderDraw } } -CC_FORCE_INLINE void Batcher2d::handleIADraw(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node) { - generateBatch(_currEntity, _currDrawInfo); - uint32_t dataHash = drawInfo->getDataHash(); - entity->setEnumStencilStage(_stencilManager->getStencilStage()); - auto tempStage = static_cast(entity->getStencilStage()); - _currHash = dataHash; - _currMaterial = drawInfo->getMaterial(); - _currStencilStage = tempStage; - _currLayer = entity->getNode()->getLayer(); +CC_FORCE_INLINE void Batcher2d::handleMiddlewareDraw(RenderEntity* entity, RenderDrawInfo* drawInfo) { + auto layer = entity->getNode()->getLayer(); + Material* material = drawInfo->getMaterial(); + auto* texture = drawInfo->getTexture(); + auto* sampler = drawInfo->getSampler(); + auto* meshBuffer = drawInfo->getMeshBuffer(); - // make sure next generateBatch return. - _currEntity = nullptr; - _currDrawInfo = nullptr; - _currMeshBuffer = nullptr; - - // if(frame) - _currTexture = drawInfo->getTexture(); - _currSampler = drawInfo->getSampler(); - _currSamplerHash = _currSampler->getHash(); - setIndexRange(drawInfo); - - UIMeshBuffer* currMeshBuffer = drawInfo->getMeshBuffer(); - currMeshBuffer->setDirty(true); - gfx::InputAssembler* ia = currMeshBuffer->requireFreeIA(getDevice()); - ia->setFirstIndex(drawInfo->getIndexOffset()); - ia->setIndexCount(drawInfo->getIbCount()); - - // stencilstage - gfx::DepthStencilState* depthStencil = nullptr; - ccstd::hash_t dssHash = 0; - StencilStage entityStage = entity->getEnumStencilStage(); - depthStencil = _stencilManager->getDepthStencilState(entityStage, drawInfo->getMaterial()); - dssHash = _stencilManager->getStencilHash(entityStage); - - auto* curdrawBatch = _drawBatchPool.alloc(); - curdrawBatch->setVisFlags(_currLayer); - curdrawBatch->setInputAssembler(ia); - curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash); - const auto& pass = curdrawBatch->getPasses().at(0); - if (entity->getUseLocal()) { - drawInfo->updateLocalDescriptorSet(node, pass->getLocalSetLayout()); - curdrawBatch->setDescriptorSet(drawInfo->getLocalDes()); + // check for merge draw + auto enableBatch = !entity->getUseLocal(); + if (enableBatch && _currTexture == texture && _currMeshBuffer == meshBuffer + && !_currEntity->getUseLocal() + && material->getHash() == _currMaterial->getHash() + && drawInfo->getIndexOffset() == _currDrawInfo->getIndexOffset() + _currDrawInfo->getIbCount() + && layer == _currLayer) { + auto ibCount = _currDrawInfo->getIbCount(); + _currDrawInfo->setIbCount(ibCount + drawInfo->getIbCount()); } else { - curdrawBatch->setDescriptorSet(getDescriptorSet(_currTexture, _currSampler, pass->getLocalSetLayout())); + generateBatch(_currEntity, _currDrawInfo); + _currLayer = layer; + _currMaterial = material; + _currTexture = texture; + _currMeshBuffer = meshBuffer; + _currEntity = entity; + _currDrawInfo = drawInfo; + _currHash = 0; } - _batches.push_back(curdrawBatch); } CC_FORCE_INLINE void Batcher2d::handleSubNode(RenderEntity* entity, RenderDrawInfo* drawInfo) { // NOLINT @@ -321,8 +302,8 @@ CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawI case RenderDrawInfoType::MODEL: handleModelDraw(entity, drawInfo); break; - case RenderDrawInfoType::IA: - handleIADraw(entity, drawInfo, node); + case RenderDrawInfoType::MIDDLEWARE: + handleMiddlewareDraw(entity, drawInfo); break; case RenderDrawInfoType::SUB_NODE: handleSubNode(entity, drawInfo); @@ -333,7 +314,14 @@ CC_FORCE_INLINE void Batcher2d::handleDrawInfo(RenderEntity* entity, RenderDrawI } void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) { - if (drawInfo == nullptr || _currMaterial == nullptr) { + if (drawInfo == nullptr) { + return; + } + if (drawInfo->getEnumDrawInfoType() == RenderDrawInfoType::MIDDLEWARE) { + generateBatchForMiddleware(entity, drawInfo); + return; + } + if (_currMaterial == nullptr) { return; } gfx::InputAssembler* ia = nullptr; @@ -381,6 +369,47 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) { _batches.push_back(curdrawBatch); } +void Batcher2d::generateBatchForMiddleware(RenderEntity* entity, RenderDrawInfo* drawInfo) { + auto layer = entity->getNode()->getLayer(); + auto* material = drawInfo->getMaterial(); + auto* texture = drawInfo->getTexture(); + auto* sampler = drawInfo->getSampler(); + auto* meshBuffer = drawInfo->getMeshBuffer(); + //set meshbuffer offset + auto indexOffset = drawInfo->getIndexOffset(); + auto indexCount = drawInfo->getIbCount(); + indexOffset += indexCount; + if (meshBuffer->getIndexOffset() < indexOffset) { + meshBuffer->setIndexOffset(indexOffset); + } + + meshBuffer->setDirty(true); + gfx::InputAssembler* ia = meshBuffer->requireFreeIA(getDevice()); + ia->setFirstIndex(drawInfo->getIndexOffset()); + ia->setIndexCount(drawInfo->getIbCount()); + + // stencilstage + auto stencilStage = _stencilManager->getStencilStage(); + gfx::DepthStencilState* depthStencil = _stencilManager->getDepthStencilState(stencilStage, material); + ccstd::hash_t dssHash = _stencilManager->getStencilHash(stencilStage); + + auto* curdrawBatch = _drawBatchPool.alloc(); + curdrawBatch->setVisFlags(_currLayer); + curdrawBatch->setInputAssembler(ia); + curdrawBatch->fillPass(material, depthStencil, dssHash); + const auto& pass = curdrawBatch->getPasses().at(0); + if (entity->getUseLocal()) { + drawInfo->updateLocalDescriptorSet(entity->getNode(), pass->getLocalSetLayout()); + curdrawBatch->setDescriptorSet(drawInfo->getLocalDes()); + } else { + curdrawBatch->setDescriptorSet(getDescriptorSet(texture, sampler, pass->getLocalSetLayout())); + } + _batches.push_back(curdrawBatch); + // make sure next generateBatch return. + resetRenderStates(); + _currMeshBuffer = nullptr; +} + void Batcher2d::resetRenderStates() { _currMaterial = nullptr; _currTexture = nullptr; @@ -465,30 +494,8 @@ void Batcher2d::uploadBuffers() { meshRenderData->uploadBuffers(); } - size_t i = 0; - size_t ii = 0; for (auto& map : _meshBuffersMap) { for (auto& buffer : map.second) { -#if CC_USE_MIDDLEWARE - // set vData and iData With Middleware buffer. - if (buffer->getUseLinkData()) { - int nativeFormat = 6; - size_t index = i; - if (buffer->getAttributes().size() == 3) { - i++; - } else { - nativeFormat = 7; - index = ii; - ii++; - } - auto* middleWare = middleware::MiddlewareManager::getInstance(); - auto* middleBuffer = middleWare->getMeshBuffer(nativeFormat); - auto* srcIBuf = middleBuffer->getIBFromBufferArray(index); - auto* srcVBuf = middleBuffer->getVBFromBufferArray(index); - buffer->setVData(reinterpret_cast(srcVBuf)); - buffer->setIData(reinterpret_cast(srcIBuf)); - } -#endif buffer->uploadBuffers(); buffer->reset(); } diff --git a/native/cocos/2d/renderer/Batcher2d.h b/native/cocos/2d/renderer/Batcher2d.h index 8298ddbcff..b49e955b82 100644 --- a/native/cocos/2d/renderer/Batcher2d.h +++ b/native/cocos/2d/renderer/Batcher2d.h @@ -69,9 +69,10 @@ public: void handleDrawInfo(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node); void handleComponentDraw(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node); void handleModelDraw(RenderEntity* entity, RenderDrawInfo* drawInfo); - void handleIADraw(RenderEntity* entity, RenderDrawInfo* drawInfo, Node* node); + void handleMiddlewareDraw(RenderEntity* entity, RenderDrawInfo* drawInfo); void handleSubNode(RenderEntity* entity, RenderDrawInfo* drawInfo); void generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo); + void generateBatchForMiddleware(RenderEntity* entity, RenderDrawInfo* drawInfo); void resetRenderStates(); private: diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index ae9b120bdf..e08c4fbbe5 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -48,7 +48,7 @@ struct Render2dLayout { enum class RenderDrawInfoType : uint8_t { COMP, MODEL, - IA, + MIDDLEWARE, SUB_NODE, }; @@ -124,6 +124,9 @@ public: _material = material; } + inline void setMeshBuffer(UIMeshBuffer* meshBuffer) { + _meshBuffer = meshBuffer; + } inline UIMeshBuffer* getMeshBuffer() const { return _meshBuffer; } diff --git a/native/cocos/2d/renderer/UIMeshBuffer.cpp b/native/cocos/2d/renderer/UIMeshBuffer.cpp index 93f9dfa757..2bf6dc4901 100644 --- a/native/cocos/2d/renderer/UIMeshBuffer.cpp +++ b/native/cocos/2d/renderer/UIMeshBuffer.cpp @@ -49,9 +49,13 @@ void UIMeshBuffer::setIData(uint16_t* iData) { _iData = iData; } -void UIMeshBuffer::initialize(gfx::Device* /*device*/, ccstd::vector&& attrs, uint32_t /*vFloatCount*/, uint32_t /*iCount*/) { +void UIMeshBuffer::initialize(ccstd::vector &&attrs, bool needCreateLayout) { _attributes = attrs; _vertexFormatBytes = getAttributesStride(attrs); + if (needCreateLayout) { + _meshBufferLayout = new MeshBufferLayout(); + } + _needDeleteLayout = needCreateLayout; } void UIMeshBuffer::reset() { @@ -87,6 +91,9 @@ void UIMeshBuffer::destroy() { delete ia; } _iaPool.clear(); + if (_needDeleteLayout) { + CC_SAFE_DELETE(_meshBufferLayout); + } } void UIMeshBuffer::setDirty() { diff --git a/native/cocos/2d/renderer/UIMeshBuffer.h b/native/cocos/2d/renderer/UIMeshBuffer.h index 32fd8c071e..52e3a04570 100644 --- a/native/cocos/2d/renderer/UIMeshBuffer.h +++ b/native/cocos/2d/renderer/UIMeshBuffer.h @@ -47,7 +47,7 @@ public: inline uint16_t* getIData() const { return _iData; } void setIData(uint16_t* iData); - void initialize(gfx::Device* device, ccstd::vector&& attrs, uint32_t vFloatCount, uint32_t iCount); + void initialize(ccstd::vector&& attrs, bool needCreateLayout = false); void reset(); void destroy(); void setDirty(); @@ -68,8 +68,6 @@ public: void setIndexOffset(uint32_t indexOffset); inline bool getDirty() const { return _meshBufferLayout->dirtyMark != 0; } void setDirty(bool dirty) const; - inline bool getUseLinkData() const { return _useLinkData; } - inline void setUseLinkData(bool val) { _useLinkData = val; } inline const ccstd::vector& getAttributes() const { return _attributes; } @@ -83,16 +81,18 @@ private: MeshBufferLayout* _meshBufferLayout{nullptr}; uint32_t* _sharedBuffer{nullptr}; - bool _dirty{false}; + uint32_t _vertexFormatBytes{0}; uint32_t _initVDataCount{0}; uint32_t _initIDataCount{0}; - ccstd::vector _attributes; + uint32_t _nextFreeIAHandle{0}; + ccstd::vector _attributes; ccstd::vector _iaPool{}; gfx::InputAssemblerInfo _iaInfo; - uint32_t _nextFreeIAHandle{0}; + + bool _dirty{false}; bool _needDeleteVData{false}; - bool _useLinkData{false}; + bool _needDeleteLayout{false}; }; } // namespace cc 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/base/LogRemote.cpp b/native/cocos/base/LogRemote.cpp index 02e29697c5..a1f42a8731 100644 --- a/native/cocos/base/LogRemote.cpp +++ b/native/cocos/base/LogRemote.cpp @@ -51,12 +51,21 @@ namespace { - #define AUTO_TEST_CONFIG_FILE "auto-test-config.json" - #define ATC_KEY_CONFIG "ServerConfig" - #define ATC_KEY_IP "IP" - #define ATC_KEY_PORT "PORT" - #define ATC_KEY_PLANID "planId" - #define ATC_KEY_FLAGID "flagId" + // #define AUTO_TEST_CONFIG_FILE "auto-test-config.json" // v1 + #define AUTO_TEST_CONFIG_FILE "testConfig.json" // v2 + + #define OLD_ATC_KEY_CONFIG "ServerConfig" + #define OLD_ATC_KEY_IP "IP" + #define OLD_ATC_KEY_PORT "PORT" + #define OLD_ATC_KEY_PLANID "planId" + #define OLD_ATC_KEY_FLAGID "flagId" + + #define ATC_KEY_CONFIG "localServer" + #define ATC_KEY_IP "ip" + #define ATC_KEY_PORT "port" + #define ATC_KEY_JOBID "jobId" + #define ATC_KEY_PLATFORMS "platforms" + #define ATC_KEY_PLATFORM_INDEX "platformIndex" enum class UdpLogClientState { UNINITIALIZED, @@ -155,26 +164,53 @@ private: return; } - if (!doc.HasMember(ATC_KEY_CONFIG)) { - _status = UdpLogClientState::DONE; - return; - } - { + if (doc.HasMember(OLD_ATC_KEY_CONFIG)) { // parse clientID & testID - if (doc.HasMember(ATC_KEY_FLAGID)) { - _clientID = doc[ATC_KEY_FLAGID].GetString(); + if (doc.HasMember(OLD_ATC_KEY_FLAGID)) { + _clientID = doc[OLD_ATC_KEY_FLAGID].GetString(); } else { _clientID = "flagId is not set!"; } - if (doc.HasMember(ATC_KEY_PLANID)) { - _testID = doc[ATC_KEY_PLANID].GetString(); + if (doc.HasMember(OLD_ATC_KEY_PLANID)) { + _testID = doc[OLD_ATC_KEY_PLANID].GetString(); } else { _testID = "planId is not set!"; } - } - { + // parse ip & port + rapidjson::Value &cfg = doc[OLD_ATC_KEY_CONFIG]; + if (!cfg.HasMember(OLD_ATC_KEY_IP) || !cfg.HasMember(OLD_ATC_KEY_PORT)) { + _status = UdpLogClientState::DONE; + return; + } + const char *remoteIp = cfg[OLD_ATC_KEY_IP].GetString(); + // The `PORT` property is used by other service and the next port is for log collection. + int remotePort = cfg[OLD_ATC_KEY_PORT].GetInt() + 1; + setServerAddr(remoteIp, remotePort); + } else if (doc.HasMember(ATC_KEY_CONFIG)) { + if (doc.HasMember(ATC_KEY_JOBID)) { + _testID = doc[ATC_KEY_JOBID].GetString(); + } else { + _testID = "jobId is not set!"; + } + if (doc.HasMember(ATC_KEY_PLATFORMS)) { + rapidjson::Value &platforms = doc[ATC_KEY_PLATFORMS]; + if (!platforms.IsArray() || platforms.Size() < 1) { + _clientID = "array platforms is empty"; + } else { + rapidjson::Value &plt = platforms[0]; + if (!plt.HasMember(ATC_KEY_PLATFORM_INDEX)) { + _clientID = "platforms[0] not key platformIndex"; + } else { + rapidjson::Value &index = plt[ATC_KEY_PLATFORM_INDEX]; + _clientID = index.IsInt() ? std::to_string(index.GetInt()) : index.GetString(); + } + } + } else { + _clientID = "platforms not set!"; + } + // parse ip & port rapidjson::Value &cfg = doc[ATC_KEY_CONFIG]; if (!cfg.HasMember(ATC_KEY_IP) || !cfg.HasMember(ATC_KEY_PORT)) { @@ -185,7 +221,11 @@ private: // The `PORT` property is used by other service and the next port is for log collection. int remotePort = cfg[ATC_KEY_PORT].GetInt() + 1; setServerAddr(remoteIp, remotePort); + } else { + _status = UdpLogClientState::DONE; + return; } + _bootID = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()) .count(); diff --git a/native/cocos/base/StringUtil.cpp b/native/cocos/base/StringUtil.cpp index 58168ed96b..fd324f9a44 100644 --- a/native/cocos/base/StringUtil.cpp +++ b/native/cocos/base/StringUtil.cpp @@ -28,7 +28,9 @@ #include #include #include -#include "base/ZipUtils.h" +#ifndef CC_WGPU_WASM + #include "base/ZipUtils.h" +#endif #include "base/base64.h" #include "base/std/container/string.h" #include "memory/Memory.h" @@ -163,6 +165,7 @@ ccstd::string &StringUtil::toupper(ccstd::string &str) { } ccstd::string GzipedString::value() const { // NOLINT(readability-convert-member-functions-to-static) +#ifndef CC_WGPU_WASM uint8_t *outGzip{nullptr}; uint8_t *outBase64{nullptr}; auto *input = reinterpret_cast(const_cast(_str.c_str())); @@ -172,6 +175,9 @@ ccstd::string GzipedString::value() const { // NOLINT(readability-convert-member free(outGzip); free(outBase64); return ret; +#else + return ""; +#endif } } // namespace cc diff --git a/native/cocos/base/TypeDef.h b/native/cocos/base/TypeDef.h index 7ac43b46c2..e1cd48eed1 100644 --- a/native/cocos/base/TypeDef.h +++ b/native/cocos/base/TypeDef.h @@ -32,7 +32,7 @@ using uint = std::uint32_t; using ushort = std::uint16_t; -#if (CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX) // linux has typedef ulong +#if (CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX && CC_PLATFORM != CC_PLATFORM_EMSCRIPTEN) // linux has typedef ulong using ulong = std::uint32_t; #endif using FlagBits = std::uint32_t; diff --git a/native/cocos/base/threading/MessageQueue.cpp b/native/cocos/base/threading/MessageQueue.cpp index 652aa639e9..ee5b6c9f69 100644 --- a/native/cocos/base/threading/MessageQueue.cpp +++ b/native/cocos/base/threading/MessageQueue.cpp @@ -76,6 +76,18 @@ void MessageQueue::MemoryAllocator::freeByUser(MessageQueue *const mainMessageQu mainMessageQueue->kick(); } +MessageQueue::MemoryAllocator::~MemoryAllocator() noexcept { + destroy(); +} + +void MessageQueue::MemoryAllocator::destroy() noexcept { + uint8_t *chunk = nullptr; + if(_chunkPool.try_dequeue(chunk)) { + ::free(chunk); + _chunkCount.fetch_sub(1, std::memory_order_acq_rel); + } +} + void MessageQueue::MemoryAllocator::free(uint8_t *const chunk) noexcept { if (_chunkCount.load(std::memory_order_acquire) >= MEMORY_CHUNK_POOL_CAPACITY) { memoryFreeForMultiThread(chunk); diff --git a/native/cocos/base/threading/MessageQueue.h b/native/cocos/base/threading/MessageQueue.h index aba64308c2..bf9bad1916 100644 --- a/native/cocos/base/threading/MessageQueue.h +++ b/native/cocos/base/threading/MessageQueue.h @@ -138,7 +138,7 @@ private: class ALIGNAS(64) MemoryAllocator final { public: MemoryAllocator() = default; - ~MemoryAllocator() = default; + ~MemoryAllocator() noexcept; MemoryAllocator(MemoryAllocator const &) = delete; MemoryAllocator(MemoryAllocator &&) = delete; MemoryAllocator &operator=(MemoryAllocator const &) = delete; @@ -148,6 +148,7 @@ private: uint8_t *request() noexcept; void recycle(uint8_t *chunk, bool freeByUser) noexcept; void freeByUser(MessageQueue *mainMessageQueue) noexcept; + void destroy() noexcept; private: using ChunkQueue = moodycamel::ConcurrentQueue; diff --git a/native/cocos/bindings/auto/jsb_2d_auto.h b/native/cocos/bindings/auto/jsb_2d_auto.h index e491b077a1..eda45319ff 100644 --- a/native/cocos/bindings/auto/jsb_2d_auto.h +++ b/native/cocos/bindings/auto/jsb_2d_auto.h @@ -62,6 +62,9 @@ JSB_REGISTER_OBJECT_TYPE(cc::UIMeshBuffer); extern se::Object *__jsb_cc_UIMeshBuffer_proto; // NOLINT extern se::Class * __jsb_cc_UIMeshBuffer_class; // NOLINT +JSB_REGISTER_OBJECT_TYPE(cc::Batcher2d); +extern se::Object *__jsb_cc_Batcher2d_proto; // NOLINT +extern se::Class * __jsb_cc_Batcher2d_class; // NOLINT JSB_REGISTER_OBJECT_TYPE(cc::Render2dLayout); extern se::Object *__jsb_cc_Render2dLayout_proto; // NOLINT diff --git a/native/cocos/bindings/auto/jsb_dragonbones_auto.h b/native/cocos/bindings/auto/jsb_dragonbones_auto.h index 162b64e835..dae1d5356c 100644 --- a/native/cocos/bindings/auto/jsb_dragonbones_auto.h +++ b/native/cocos/bindings/auto/jsb_dragonbones_auto.h @@ -49,6 +49,9 @@ JSB_REGISTER_OBJECT_TYPE(dragonBones::Rectangle); extern se::Object *__jsb_dragonBones_Rectangle_proto; // NOLINT extern se::Class * __jsb_dragonBones_Rectangle_class; // NOLINT +JSB_REGISTER_OBJECT_TYPE(dragonBones::BlendState); +extern se::Object *__jsb_dragonBones_BlendState_proto; // NOLINT +extern se::Class * __jsb_dragonBones_BlendState_class; // NOLINT JSB_REGISTER_OBJECT_TYPE(dragonBones::Transform); extern se::Object *__jsb_dragonBones_Transform_proto; // NOLINT diff --git a/native/cocos/bindings/auto/jsb_editor_support_auto.h b/native/cocos/bindings/auto/jsb_editor_support_auto.h index 173b4c7c5d..49db03e567 100644 --- a/native/cocos/bindings/auto/jsb_editor_support_auto.h +++ b/native/cocos/bindings/auto/jsb_editor_support_auto.h @@ -124,6 +124,9 @@ JSB_REGISTER_OBJECT_TYPE(cc::middleware::Texture2D); extern se::Object *__jsb_cc_middleware_Texture2D_proto; // NOLINT extern se::Class * __jsb_cc_middleware_Texture2D_class; // NOLINT +JSB_REGISTER_OBJECT_TYPE(cc::middleware::V3F_T2F_C4B); +extern se::Object *__jsb_cc_middleware_V3F_T2F_C4B_proto; // NOLINT +extern se::Class * __jsb_cc_middleware_V3F_T2F_C4B_class; // NOLINT JSB_REGISTER_OBJECT_TYPE(cc::middleware::SpriteFrame); extern se::Object *__jsb_cc_middleware_SpriteFrame_proto; // NOLINT diff --git a/native/cocos/bindings/auto/jsb_scene_auto.h b/native/cocos/bindings/auto/jsb_scene_auto.h index 8927146378..e7502d153d 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.h +++ b/native/cocos/bindings/auto/jsb_scene_auto.h @@ -144,6 +144,14 @@ extern se::Object *__jsb_cc_scene_Shadows_proto; // NOLINT extern se::Class * __jsb_cc_scene_Shadows_class; // NOLINT +extern se::Object *__jsb_cc_scene_InstancedAttributeBlock_proto; // NOLINT +extern se::Class *__jsb_cc_scene_InstancedAttributeBlock_class; // NOLINT + +bool js_register_cc_scene_InstancedAttributeBlock(se::Object *obj); // NOLINT + +template <> +bool sevalue_to_native(const se::Value &, cc::scene::InstancedAttributeBlock *, se::Object *ctx); //NOLINT + JSB_REGISTER_OBJECT_TYPE(cc::scene::SkyboxInfo); extern se::Object *__jsb_cc_scene_SkyboxInfo_proto; // NOLINT extern se::Class * __jsb_cc_scene_SkyboxInfo_class; // NOLINT diff --git a/native/cocos/bindings/event/EventDispatcher.cpp b/native/cocos/bindings/event/EventDispatcher.cpp index 307b8b7ee5..7760db338e 100644 --- a/native/cocos/bindings/event/EventDispatcher.cpp +++ b/native/cocos/bindings/event/EventDispatcher.cpp @@ -26,6 +26,7 @@ #include #include "cocos/application/ApplicationManager.h" #include "cocos/bindings/event/CustomEventTypes.h" +#include "cocos/bindings/jswrapper/HandleObject.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global_init.h" #include "cocos/platform/interfaces/modules/ISystemWindow.h" @@ -40,8 +41,17 @@ se::Object *jsMouseEventObj = nullptr; se::Object *jsKeyboardEventObj = nullptr; se::Object *jsControllerEventArray = nullptr; se::Object *jsResizeEventObj = nullptr; -se::Object *jsOrientationEventObj = nullptr; bool inited = false; + +// attach the argument object to the function +void accessCacheArgObj(se::Object *func, se::Value *argObj, const char *cacheKey = "__reusedArgumentObject") { + func->getProperty(cacheKey, argObj); + if (argObj->isUndefined()) { + se::HandleObject argumentObj(se::Object::createPlainObject()); + argObj->setObject(argumentObj); + } +} + } // namespace namespace cc { @@ -98,11 +108,6 @@ void EventDispatcher::destroy() { jsResizeEventObj = nullptr; } - if (jsOrientationEventObj != nullptr) { - jsOrientationEventObj->unroot(); - jsOrientationEventObj->decRef(); - jsOrientationEventObj = nullptr; - } inited = false; tickVal.setUndefined(); } @@ -362,18 +367,15 @@ void EventDispatcher::dispatchOrientationChangeEvent(int orientation) { se::AutoHandleScope scope; CC_ASSERT(inited); - if (jsOrientationEventObj == nullptr) { - jsOrientationEventObj = se::Object::createPlainObject(); - jsOrientationEventObj->root(); - } - se::Value func; __jsbObj->getProperty("onOrientationChanged", &func); if (func.isObject() && func.toObject()->isFunction()) { - jsOrientationEventObj->setProperty("orientation", se::Value(orientation)); + se::Value evtObj; + accessCacheArgObj(func.toObject(), &evtObj); + evtObj.toObject()->setProperty("orientation", se::Value(orientation)); se::ValueArray args; - args.emplace_back(se::Value(jsOrientationEventObj)); + args.emplace_back(evtObj); func.toObject()->call(args, nullptr); } } @@ -529,7 +531,7 @@ void EventDispatcher::removeAllEventListeners() { delete node.second; } listeners.clear(); - //start from 1 cuz 0 represents pause and resume + // start from 1 cuz 0 represents pause and resume hashListenerId = 1; } diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 583eff579b..3a47aa1b50 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -1109,7 +1109,12 @@ bool nativevalue_to_se(const ccstd::variant &from, se::Value &to, se::O template bool nativevalue_to_se(const ccstd::variant *from, se::Value &to, se::Object *ctx) { // NOLINT - return nativevalue_to_se(*from, to, ctx); + if (from) { + return nativevalue_to_se(*from, to, ctx); + } + + to.setNull(); + return true; } template diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.cpp b/native/cocos/bindings/manual/jsb_conversions_spec.cpp index 5657efc43b..ba8c2ecb50 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.cpp +++ b/native/cocos/bindings/manual/jsb_conversions_spec.cpp @@ -1469,6 +1469,26 @@ bool nativevalue_to_se(const cc::gfx::Rect &from, se::Value &to, se::Object * /* return true; } +// NOLINTNEXTLINE(readability-identifier-naming) +bool nativevalue_to_se(const cc::gfx::FormatInfo *from, se::Value &to, se::Object * /*unused*/) { + se::HandleObject obj(se::Object::createPlainObject()); + if (from) { + obj->setProperty("name", se::Value(from->name)); + obj->setProperty("size", se::Value(from->size)); + obj->setProperty("count", se::Value(from->count)); + obj->setProperty("type", se::Value(static_cast(from->type))); + obj->setProperty("hasAlpha", se::Value(from->hasAlpha)); + obj->setProperty("hasDepth", se::Value(from->hasDepth)); + obj->setProperty("hasStencil", se::Value(from->hasStencil)); + obj->setProperty("isCompressed", se::Value(from->isCompressed)); + to.setObject(obj); + } else { + to.setNull(); + } + return true; +} + + // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::ArrayBuffer &arrayBuffer, se::Value &to, se::Object * /*ctx*/) { to.setObject(arrayBuffer.getJSArrayBuffer()); diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.h b/native/cocos/bindings/manual/jsb_conversions_spec.h index 09cd381d28..6fd854ac7e 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.h +++ b/native/cocos/bindings/manual/jsb_conversions_spec.h @@ -575,6 +575,8 @@ bool nativevalue_to_se(const cc::Rect &from, se::Value &to, se::Object *ctx); // bool nativevalue_to_se(const cc::gfx::Rect &from, se::Value &to, se::Object *ctx); // NOLINT(readability-identifier-naming) +bool nativevalue_to_se(const cc::gfx::FormatInfo *from, se::Value &to, se::Object *ctx); // NOLINT(readability-identifier-naming + bool nativevalue_to_se(const cc::network::DownloadTask &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) inline bool nativevalue_to_se(const ccstd::monostate & /*from*/, se::Value &to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) diff --git a/native/cocos/bindings/manual/jsb_scene_manual.cpp b/native/cocos/bindings/manual/jsb_scene_manual.cpp index 79e743eb68..f1bcb6df55 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual.cpp @@ -718,13 +718,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/editor-support/MeshBuffer.cpp b/native/cocos/editor-support/MeshBuffer.cpp index f2ce1b1ebb..1669238bc2 100644 --- a/native/cocos/editor-support/MeshBuffer.cpp +++ b/native/cocos/editor-support/MeshBuffer.cpp @@ -24,9 +24,23 @@ ****************************************************************************/ #include "MeshBuffer.h" +#include "2d/renderer/UIMeshBuffer.h" MIDDLEWARE_BEGIN +static const ccstd::vector ATTRIBUTES_V3F_T2F_C4B{ + gfx::Attribute{gfx::ATTR_NAME_POSITION, gfx::Format::RGB32F}, + gfx::Attribute{gfx::ATTR_NAME_TEX_COORD, gfx::Format::RG32F}, + gfx::Attribute{gfx::ATTR_NAME_COLOR, gfx::Format::RGBA8, true}, +}; + +static const ccstd::vector ATTRIBUTES_V3F_T2F_C4B_C4B{ + gfx::Attribute{gfx::ATTR_NAME_POSITION, gfx::Format::RGB32F}, + gfx::Attribute{gfx::ATTR_NAME_TEX_COORD, gfx::Format::RG32F}, + gfx::Attribute{gfx::ATTR_NAME_COLOR, gfx::Format::RGBA8, true}, + gfx::Attribute{gfx::ATTR_NAME_COLOR2, gfx::Format::RGBA8, true}, +}; + MeshBuffer::MeshBuffer(int vertexFormat) : MeshBuffer(vertexFormat, INIT_INDEX_BUFFER_SIZE, MAX_VERTEX_BUFFER_SIZE) { } @@ -58,6 +72,7 @@ void MeshBuffer::clear() { } _ibArr.clear(); _vbArr.clear(); + cleanUIMeshBuffer(); } void MeshBuffer::init() { @@ -66,6 +81,8 @@ void MeshBuffer::init() { auto *rVB = new IOTypedArray(se::Object::TypedArrayType::FLOAT32, _vb.getCapacity()); _vbArr.push_back(rVB); + cleanUIMeshBuffer(); + addUIMeshBuffer(); } void MeshBuffer::uploadVB() { @@ -75,6 +92,9 @@ void MeshBuffer::uploadVB() { auto *rVB = _vbArr[_bufferPos]; rVB->reset(); rVB->writeBytes(reinterpret_cast(_vb.getBuffer()), _vb.length()); + auto *uiMeshBuffer = _uiMeshBufferArr[_bufferPos]; + uiMeshBuffer->setVData(reinterpret_cast(rVB->getBuffer())); + uiMeshBuffer->setByteOffset(static_cast(_vb.length())); } void MeshBuffer::uploadIB() { @@ -84,6 +104,8 @@ void MeshBuffer::uploadIB() { auto *rIB = _ibArr[_bufferPos]; rIB->reset(); rIB->writeBytes(reinterpret_cast(_ib.getBuffer()), _ib.length()); + auto *uiMeshBuffer = _uiMeshBufferArr[_bufferPos]; + uiMeshBuffer->setIData(reinterpret_cast(rIB->getBuffer())); } void MeshBuffer::next() { @@ -97,6 +119,10 @@ void MeshBuffer::next() { auto *rVB = new IOTypedArray(se::Object::TypedArrayType::FLOAT32, _vb.getCapacity()); _vbArr.push_back(rVB); } + + if (_uiMeshBufferArr.size() <= _bufferPos) { + addUIMeshBuffer(); + } } void MeshBuffer::reset() { @@ -105,4 +131,31 @@ void MeshBuffer::reset() { _ib.reset(); } +void MeshBuffer::addUIMeshBuffer() { + UIMeshBuffer* uiMeshBuffer = new UIMeshBuffer(); + ccstd::vector attrs; + if (_vertexFormat == VF_XYZUVC) { + attrs = ATTRIBUTES_V3F_T2F_C4B; + } else { + attrs = ATTRIBUTES_V3F_T2F_C4B_C4B; + } + uiMeshBuffer->initialize(std::move(attrs), true); + _uiMeshBufferArr.push_back(uiMeshBuffer); +} + +void MeshBuffer::cleanUIMeshBuffer() { + for(auto *buf : _uiMeshBufferArr) { + delete buf; + } + _uiMeshBufferArr.clear(); +} + +cc::UIMeshBuffer *MeshBuffer::getUIMeshBuffer() const { + return _uiMeshBufferArr[_bufferPos]; +} + +const ccstd::vector& MeshBuffer::uiMeshBuffers() const { + return _uiMeshBufferArr; +} + MIDDLEWARE_END diff --git a/native/cocos/editor-support/MeshBuffer.h b/native/cocos/editor-support/MeshBuffer.h index 2023dacd4f..2dcc5c3a69 100644 --- a/native/cocos/editor-support/MeshBuffer.h +++ b/native/cocos/editor-support/MeshBuffer.h @@ -29,6 +29,10 @@ #include "IOTypedArray.h" #include "base/std/container/vector.h" +namespace cc { + class UIMeshBuffer; +}; + MIDDLEWARE_BEGIN class MeshBuffer { @@ -72,7 +76,7 @@ public: return _bufferPos + 1; } - std::size_t getBufferPos() const { + uint16_t getBufferPos() const { return _bufferPos; } @@ -84,6 +88,10 @@ public: return _ib; } + cc::UIMeshBuffer *getUIMeshBuffer() const; + + const ccstd::vector &uiMeshBuffers() const; + void uploadVB(); void uploadIB(); void reset(); @@ -93,10 +101,13 @@ private: void clear(); void init(); void afterCleanupHandle(); + void addUIMeshBuffer(); + void cleanUIMeshBuffer(); ccstd::vector _ibArr; ccstd::vector _vbArr; - std::size_t _bufferPos = 0; + ccstd::vector _uiMeshBufferArr; + uint16_t _bufferPos = 0; IOBuffer _vb; IOBuffer _ib; int _vertexFormat = 0; diff --git a/native/cocos/editor-support/MiddlewareManager.cpp b/native/cocos/editor-support/MiddlewareManager.cpp index bffb126bd9..4de5f4b446 100644 --- a/native/cocos/editor-support/MiddlewareManager.cpp +++ b/native/cocos/editor-support/MiddlewareManager.cpp @@ -26,6 +26,8 @@ #include "MiddlewareManager.h" #include #include "SeApi.h" +#include "2d/renderer/Batcher2d.h" +#include "core/Root.h" MIDDLEWARE_BEGIN @@ -67,49 +69,26 @@ void MiddlewareManager::clearRemoveList() { void MiddlewareManager::update(float dt) { isUpdating = true; - _renderInfo.reset(); - auto *renderBuffer = _renderInfo.getBuffer(); - if (renderBuffer) { - renderBuffer->writeUint32(0); - } - _attachInfo.reset(); auto *attachBuffer = _attachInfo.getBuffer(); if (attachBuffer) { attachBuffer->writeUint32(0); } - auto isOrderDirty = false; - uint32_t maxRenderOrder = 0; for (auto *editor : _updateList) { - uint32_t renderOrder = maxRenderOrder; if (!_removeList.empty()) { auto removeIt = std::find(_removeList.begin(), _removeList.end(), editor); if (removeIt == _removeList.end()) { editor->update(dt); - renderOrder = editor->getRenderOrder(); } } else { editor->update(dt); - renderOrder = editor->getRenderOrder(); - } - - if (maxRenderOrder > renderOrder) { - isOrderDirty = true; - } else { - maxRenderOrder = renderOrder; } } isUpdating = false; clearRemoveList(); - - if (isOrderDirty) { - std::sort(_updateList.begin(), _updateList.end(), [](IMiddleware *it1, IMiddleware *it2) { - return it1->getRenderOrder() < it2->getRenderOrder(); - }); - } } void MiddlewareManager::render(float dt) { @@ -141,6 +120,18 @@ void MiddlewareManager::render(float dt) { buffer->uploadIB(); buffer->uploadVB(); } + + uint16_t accID = 65534; + auto* batch2d = Root::getInstance()->getBatcher2D(); + if (it.first == VF_XYZUVCC) { + accID = 65535; + } + ccstd::vector uiMeshArray; + auto &uiBufArray = buffer->uiMeshBuffers(); + for (auto &item : uiBufArray) { + uiMeshArray.push_back((UIMeshBuffer *)item); + } + batch2d->syncMeshBuffersToNative(accID, std::move(uiMeshArray)); } clearRemoveList(); diff --git a/native/cocos/editor-support/MiddlewareManager.h b/native/cocos/editor-support/MiddlewareManager.h index 65a3b2c515..6b0ca79d24 100644 --- a/native/cocos/editor-support/MiddlewareManager.h +++ b/native/cocos/editor-support/MiddlewareManager.h @@ -43,7 +43,6 @@ public: virtual ~IMiddleware() = default; virtual void update(float dt) = 0; virtual void render(float dt) = 0; - virtual uint32_t getRenderOrder() const = 0; }; /** diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.cpp b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.cpp index 8c9314cb5e..7526735983 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.cpp +++ b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.cpp @@ -30,6 +30,9 @@ #include "base/memory/Memory.h" #include "gfx-base/GFXDef.h" #include "math/Math.h" +#include "2d/renderer/RenderDrawInfo.h" +#include "2d/renderer/RenderEntity.h" +#include "renderer/core/MaterialInstance.h" using namespace cc; // NOLINT(google-build-using-namespace) using namespace cc::gfx; // NOLINT(google-build-using-namespace) @@ -56,13 +59,6 @@ CCArmatureCacheDisplay::CCArmatureCacheDisplay(const std::string &armatureName, // store global TypedArray begin and end offset _sharedBufferOffset = new IOTypedArray(se::Object::TypedArrayType::UINT32, sizeof(uint32_t) * 2); - // store render order(1), world matrix(16) - _paramsBuffer = new IOTypedArray(se::Object::TypedArrayType::FLOAT32, sizeof(float) * 17); - // set render order to 0 - _paramsBuffer->writeFloat32(0); - // set world transform to identity - _paramsBuffer->writeBytes(reinterpret_cast(&cc::Mat4::IDENTITY), sizeof(float) * 16); - beginSchedule(); } @@ -73,10 +69,12 @@ CCArmatureCacheDisplay::~CCArmatureCacheDisplay() { delete _sharedBufferOffset; _sharedBufferOffset = nullptr; } + for (auto* draw : _drawInfoArray) { + CC_SAFE_DELETE(draw); + } - if (_paramsBuffer) { - delete _paramsBuffer; - _paramsBuffer = nullptr; + for (auto& item : _materialCaches) { + CC_SAFE_DELETE(item.second); } } @@ -143,6 +141,8 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { auto *mgr = MiddlewareManager::getInstance(); if (!mgr->isRendering) return; + auto *entity = _entity; + entity->clearDynamicRenderDrawInfos(); const auto &segments = frameData->getSegments(); const auto &colors = frameData->getColors(); @@ -150,27 +150,13 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { _sharedBufferOffset->reset(); _sharedBufferOffset->clear(); - auto *renderMgr = mgr->getRenderInfoMgr(); - auto *renderInfo = renderMgr->getBuffer(); - if (!renderInfo) return; - auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); if (!attachInfo) return; - // store render info offset - _sharedBufferOffset->writeUint32(static_cast(renderInfo->getCurPos()) / sizeof(uint32_t)); // store attach info offset _sharedBufferOffset->writeUint32(static_cast(attachInfo->getCurPos()) / sizeof(uint32_t)); - // check enough space - renderInfo->checkSpace(sizeof(uint32_t) * 2, true); - // write border - renderInfo->writeUint32(0xffffffff); - - // matieral len - renderInfo->writeUint32(segments.size()); - if (segments.empty() || colors.empty()) return; middleware::MeshBuffer *mb = mgr->getMeshBuffer(VF_XYZUVC); @@ -178,8 +164,7 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { middleware::IOBuffer &ib = mb->getIB(); const auto &srcVB = frameData->vb; const auto &srcIB = frameData->ib; - - auto *paramsBuffer = _paramsBuffer->getBuffer(); + auto &nodeWorldMat = entity->getNode()->getWorldMatrix(); int colorOffset = 0; ArmatureCache::ColorData *nowColor = colors[colorOffset++]; @@ -196,7 +181,6 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { std::size_t srcIndexBytesOffset = 0; std::size_t vertexBytes = 0; std::size_t indexBytes = 0; - int curTextureIndex = 0; BlendMode blendMode = BlendMode::Normal; std::size_t dstVertexOffset = 0; std::size_t dstIndexOffset = 0; @@ -206,6 +190,8 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { bool needColor = false; int curBlendSrc = -1; int curBlendDst = -1; + cc::Texture2D* curTexture = nullptr; + RenderDrawInfo* curDrawInfo = nullptr; if (abs(_nodeColor.r - 1.0F) > 0.0001F || abs(_nodeColor.g - 1.0F) > 0.0001F || @@ -229,16 +215,17 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { }; handleColor(nowColor); - + int segmentCount = 0; for (auto *segment : segments) { vertexBytes = segment->vertexFloatCount * sizeof(float); - - // check enough space - renderInfo->checkSpace(sizeof(uint32_t) * 6, true); - + curDrawInfo = requestDrawInfo(segmentCount++); + entity->addDynamicRenderDrawInfo(curDrawInfo); // fill new texture index - curTextureIndex = segment->getTexture()->getRealTextureIndex(); - renderInfo->writeUint32(curTextureIndex); + curTexture = static_cast(segment->getTexture()->getRealTexture()); + gfx::Texture *texture = curTexture->getGFXTexture(); + gfx::Sampler *sampler = curTexture->getGFXSampler(); + curDrawInfo->setTexture(texture); + curDrawInfo->setSampler(sampler); blendMode = static_cast(segment->blendMode); switch (blendMode) { @@ -260,8 +247,8 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { break; } // fill new blend src and dst - renderInfo->writeUint32(curBlendSrc); - renderInfo->writeUint32(curBlendDst); + auto *material = requestMaterial(curBlendSrc, curBlendDst); + curDrawInfo->setMaterial(material); // fill vertex buffer vb.checkSpace(vertexBytes, true); @@ -269,7 +256,14 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { dstVertexBuffer = reinterpret_cast(vb.getCurBuffer()); dstColorBuffer = reinterpret_cast(vb.getCurBuffer()); vb.writeBytes(reinterpret_cast(srcVB.getBuffer()) + srcVertexBytesOffset, vertexBytes); + // batch handle + cc::Vec3 *point = nullptr; + for (auto posIndex = 0; posIndex < segment->vertexFloatCount; posIndex += VF_XYZUVC) { + point = reinterpret_cast(dstVertexBuffer + posIndex); + point->z = 0; + point->transformMat4(*point, nodeWorldMat); + } // handle vertex color if (needColor) { auto frameFloatOffset = srcVertexBytesOffset / sizeof(float); @@ -298,13 +292,13 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { srcIndexBytesOffset += indexBytes; // fill new index and vertex buffer id - auto bufferIndex = mb->getBufferPos(); - renderInfo->writeUint32(bufferIndex); + UIMeshBuffer* uiMeshBuffer = mb->getUIMeshBuffer(); + curDrawInfo->setMeshBuffer(uiMeshBuffer); // fill new index offset - renderInfo->writeUint32(dstIndexOffset); + curDrawInfo->setIndexOffset(dstIndexOffset); // fill new indice segamentation count - renderInfo->writeUint32(segment->indexCount); + curDrawInfo->setIbCount(segment->indexCount); } if (_useAttach) { @@ -400,6 +394,16 @@ void CCArmatureCacheDisplay::setAttachEnabled(bool enabled) { _useAttach = enabled; } +void CCArmatureCacheDisplay::setBatchEnabled(bool enabled) { + if (enabled != _enableBatch) { + for (auto& item : _materialCaches) { + CC_SAFE_DELETE(item.second); + } + _materialCaches.clear(); + _enableBatch = enabled; + } +} + se_object_ptr CCArmatureCacheDisplay::getSharedBufferOffset() const { if (_sharedBufferOffset) { return _sharedBufferOffset->getTypeArray(); @@ -407,19 +411,51 @@ se_object_ptr CCArmatureCacheDisplay::getSharedBufferOffset() const { return nullptr; } -se_object_ptr CCArmatureCacheDisplay::getParamsBuffer() const { - if (_paramsBuffer) { - return _paramsBuffer->getTypeArray(); - } - return nullptr; +void CCArmatureCacheDisplay::setRenderEntity(cc::RenderEntity* entity) { + _entity = entity; } -uint32_t CCArmatureCacheDisplay::getRenderOrder() const { - if (_paramsBuffer) { - auto *buffer = _paramsBuffer->getBuffer(); - return static_cast(buffer[0]); +void CCArmatureCacheDisplay::setMaterial(cc::Material *material) { + _material = material; +} + + +cc::RenderDrawInfo* CCArmatureCacheDisplay::requestDrawInfo(int idx) { + if (_drawInfoArray.size() < idx + 1) { + cc::RenderDrawInfo *draw = new cc::RenderDrawInfo(); + draw->setDrawInfoType(static_cast(RenderDrawInfoType::MIDDLEWARE)); + _drawInfoArray.push_back(draw); } - return 0; + return _drawInfoArray[idx]; +} + +cc::Material *CCArmatureCacheDisplay::requestMaterial(uint16_t blendSrc, uint16_t blendDst) { + uint32_t key = static_cast(blendSrc) << 16 | static_cast(blendDst); + if (_materialCaches.find(key) == _materialCaches.end()) { + const IMaterialInstanceInfo info { + (Material*)_material, + 0 + }; + MaterialInstance* materialInstance = new MaterialInstance(info); + PassOverrides overrides; + BlendStateInfo stateInfo; + stateInfo.blendColor = gfx::Color{1.0F, 1.0F, 1.0F, 1.0F}; + BlendTargetInfo targetInfo; + targetInfo.blendEq = gfx::BlendOp::ADD; + targetInfo.blendAlphaEq = gfx::BlendOp::ADD; + targetInfo.blendSrc = (gfx::BlendFactor)blendSrc; + targetInfo.blendDst = (gfx::BlendFactor)blendDst; + targetInfo.blendSrcAlpha = (gfx::BlendFactor)blendSrc; + targetInfo.blendDstAlpha = (gfx::BlendFactor)blendDst; + BlendTargetInfoList targetList {targetInfo}; + stateInfo.targets = targetList; + overrides.blendState = stateInfo; + materialInstance->overridePipelineStates(overrides); + const MacroRecord macros {{"USE_LOCAL", false}}; + materialInstance->recompileShaders(macros); + _materialCaches[key] = materialInstance; + } + return _materialCaches[key]; } DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.h b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.h index 1886ac5b6f..45470bd680 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.h +++ b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.h @@ -30,6 +30,12 @@ #include "base/RefCounted.h" #include "dragonbones/DragonBonesHeaders.h" +namespace cc { +class RenderEntity; +class RenderDrawInfo; +class Material; +}; + DRAGONBONES_NAMESPACE_BEGIN class CCArmatureCacheDisplay : public cc::RefCounted, public cc::middleware::IMiddleware { @@ -40,7 +46,6 @@ public: void update(float dt) override; void render(float dt) override; - uint32_t getRenderOrder() const override; void setTimeScale(float scale) { _timeScale = scale; @@ -59,10 +64,7 @@ public: Animation *getAnimation() const; void setColor(float r, float g, float b, float a); - void setBatchEnabled(bool enabled) { - // disable switch batch mode, force to enable batch, it may be changed in future version - // _batch = enabled; - } + void setBatchEnabled(bool enabled); void setAttachEnabled(bool enabled); void setOpacityModifyRGB(bool value) { @@ -86,11 +88,11 @@ public: * format |render info offset|attach info offset| */ se_object_ptr getSharedBufferOffset() const; - /** - * @return js send to cpp parameters, it's a Uint32Array - * format |render order|world matrix| - */ - se_object_ptr getParamsBuffer() const; + + cc::RenderDrawInfo *requestDrawInfo(int idx); + cc::Material *requestMaterial(uint16_t blendSrc, uint16_t blendDst); + void setMaterial(cc::Material *material); + void setRenderEntity(cc::RenderEntity* entity); private: float _timeScale = 1; @@ -106,7 +108,7 @@ private: std::map _listenerIDMap; bool _useAttach = false; - bool _batch = true; + bool _enableBatch = true; cc::middleware::Color4F _nodeColor = cc::middleware::Color4F::WHITE; bool _premultipliedAlpha = false; @@ -115,8 +117,11 @@ private: EventObject *_eventObject; cc::middleware::IOTypedArray *_sharedBufferOffset = nullptr; - // Js fill this buffer to send parameter to cpp, avoid to call jsb function. - cc::middleware::IOTypedArray *_paramsBuffer = nullptr; + + cc::RenderEntity *_entity = nullptr; + cc::Material *_material = nullptr; + ccstd::vector _drawInfoArray; + ccstd::unordered_map _materialCaches; }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.cpp b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.cpp index 00c7b196e2..bdddc56294 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.cpp +++ b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.cpp @@ -31,6 +31,9 @@ #include "gfx-base/GFXDef.h" #include "math/Math.h" #include "math/Vec3.h" +#include "2d/renderer/RenderDrawInfo.h" +#include "2d/renderer/RenderEntity.h" +#include "renderer/core/MaterialInstance.h" USING_NS_MW; // NOLINT(google-build-using-namespace) using namespace cc; // NOLINT(google-build-using-namespace) @@ -48,13 +51,6 @@ CCArmatureDisplay *CCArmatureDisplay::create() { CCArmatureDisplay::CCArmatureDisplay() { _sharedBufferOffset = new IOTypedArray(se::Object::TypedArrayType::UINT32, sizeof(uint32_t) * 2); - - // store render order(1), world matrix(16) - _paramsBuffer = new IOTypedArray(se::Object::TypedArrayType::FLOAT32, sizeof(float) * 17); - // set render order to 0 - _paramsBuffer->writeFloat32(0); - // set world transform to identity - _paramsBuffer->writeBytes(reinterpret_cast(&cc::Mat4::IDENTITY), sizeof(float) * 16); } CCArmatureDisplay::~CCArmatureDisplay() { @@ -69,10 +65,12 @@ CCArmatureDisplay::~CCArmatureDisplay() { delete _sharedBufferOffset; _sharedBufferOffset = nullptr; } + for (auto* draw : _drawInfoArray) { + CC_SAFE_DELETE(draw); + } - if (_paramsBuffer) { - delete _paramsBuffer; - _paramsBuffer = nullptr; + for (auto& item : _materialCaches) { + CC_SAFE_DELETE(item.second); } } @@ -101,55 +99,37 @@ void CCArmatureDisplay::dbRender() { if (this->_armature->getParent()) { return; } + if (!_entity) { + return; + } + auto *entity = _entity; + entity->clearDynamicRenderDrawInfos(); auto *mgr = MiddlewareManager::getInstance(); if (!mgr->isRendering) return; - auto *renderMgr = mgr->getRenderInfoMgr(); - auto *renderInfo = renderMgr->getBuffer(); - if (!renderInfo) return; - auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); if (!attachInfo) return; - // store render info offset - _sharedBufferOffset->writeUint32(static_cast(renderInfo->getCurPos()) / sizeof(uint32_t)); // store attach info offset _sharedBufferOffset->writeUint32(static_cast(attachInfo->getCurPos()) / sizeof(uint32_t)); - // check enough space - renderInfo->checkSpace(sizeof(uint32_t) * 2, true); - // write border - renderInfo->writeUint32(0xffffffff); - - std::size_t materialLenOffset = renderInfo->getCurPos(); - //reserved space to save material len - renderInfo->writeUint32(0); - - // render not ready - auto *paramsBuffer = _paramsBuffer->getBuffer(); - float renderOrder = *reinterpret_cast(paramsBuffer); - if (renderOrder < 0) { - return; - } - _preBlendMode = -1; - _preTextureIndex = -1; - _curTextureIndex = -1; _preISegWritePos = -1; _curISegLen = 0; _debugSlotsLen = 0; _materialLen = 0; + _preTexture = nullptr; + _curTexture = nullptr; + _curDrawInfo = nullptr; + // Traverse all aramture to fill vertex and index buffer. traverseArmature(_armature); - renderInfo->writeUint32(materialLenOffset, _materialLen); - if (_preISegWritePos != -1) { - renderInfo->writeUint32(_preISegWritePos, _curISegLen); - } + if (_curDrawInfo) _curDrawInfo->setIbCount(_curISegLen); if (_useAttach || _debugDraw) { const auto &bones = _armature->getBones(); @@ -233,8 +213,8 @@ CCArmatureDisplay *CCArmatureDisplay::getRootDisplay() { void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity) { static cc::Mat4 matrixTemp; + auto &nodeWorldMat = _entity->getNode()->getWorldMatrix(); - auto *paramsBuffer = _paramsBuffer->getBuffer(); // data store in buffer which 0 to 3 is render order, left data is node world matrix const auto &slots = armature->getSlots(); auto *mgr = MiddlewareManager::getInstance(); @@ -244,9 +224,6 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity IOBuffer &ib = mb->getIB(); float realOpacity = _nodeColor.a; - auto *renderMgr = mgr->getRenderInfoMgr(); - auto *renderInfo = renderMgr->getBuffer(); - if (!renderInfo) return; auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); @@ -255,16 +232,14 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity // range [0.0, 255.0] Color4B color(0, 0, 0, 0); CCSlot *slot = nullptr; - middleware::Texture2D *texture = nullptr; int isFull = 0; auto flush = [&]() { // fill pre segment count field - if (_preISegWritePos != -1) { - // _assembler->updateIARange(_materialLen - 1, _preISegWritePos, _curISegLen); - renderInfo->writeUint32(_preISegWritePos, _curISegLen); - } + if (_curDrawInfo) _curDrawInfo->setIbCount(_curISegLen); + _curDrawInfo = requestDrawInfo(_materialLen); + _entity->addDynamicRenderDrawInfo(_curDrawInfo); // prepare to fill new segment field switch (slot->_blendMode) { case BlendMode::Add: @@ -285,31 +260,20 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity break; } - // check enough space - renderInfo->checkSpace(sizeof(uint32_t) * 6, true); - - // fill new texture index - renderInfo->writeUint32(_curTextureIndex); - // fill new blend src and dst - renderInfo->writeUint32(_curBlendSrc); - renderInfo->writeUint32(_curBlendDst); - // fill new index and vertex buffer id - auto bufferIndex = mb->getBufferPos(); - renderInfo->writeUint32(bufferIndex); - - // fill new index offset - renderInfo->writeUint32(static_cast(ib.getCurPos()) / sizeof(uint16_t)); - - // save new segment indices count pos field - _preISegWritePos = static_cast(renderInfo->getCurPos()); - - // reserve indice segamentation count - renderInfo->writeUint32(0); + auto *material = requestMaterial(_curBlendSrc, _curBlendDst); + _curDrawInfo->setMaterial(material); + gfx::Texture *texture = _curTexture->getGFXTexture(); + gfx::Sampler *sampler = _curTexture->getGFXSampler(); + _curDrawInfo->setTexture(texture); + _curDrawInfo->setSampler(sampler); + UIMeshBuffer *uiMeshBuffer = mb->getUIMeshBuffer(); + _curDrawInfo->setMeshBuffer(uiMeshBuffer); + _curDrawInfo->setIndexOffset(static_cast(ib.getCurPos()) / sizeof(uint16_t)); // reset pre blend mode to current _preBlendMode = static_cast(slot->_blendMode); // reset pre texture index to current - _preTextureIndex = _curTextureIndex; + _preTexture = _curTexture; // reset index segmentation count _curISegLen = 0; @@ -336,14 +300,13 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity continue; } - texture = slot->getTexture(); - if (!texture) continue; - _curTextureIndex = texture->getRealTextureIndex(); + if (!slot->getTexture()) continue; + _curTexture = static_cast(slot->getTexture()->getRealTexture()); auto vbSize = slot->triangles.vertCount * sizeof(middleware::V3F_T2F_C4B); isFull |= vb.checkSpace(vbSize, true); // If texture or blendMode change,will change material. - if (_preTextureIndex != _curTextureIndex || _preBlendMode != static_cast(slot->_blendMode) || isFull) { + if (_preTexture != _curTexture || _preBlendMode != static_cast(slot->_blendMode) || isFull) { flush(); } @@ -357,6 +320,8 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity // Transform component matrix to global matrix middleware::Triangles &triangles = slot->triangles; cc::Mat4 *worldMatrix = &slot->worldMatrix; + cc::Mat4::multiply(nodeWorldMat, *worldMatrix, &matrixTemp); + worldMatrix = &matrixTemp; middleware::V3F_T2F_C4B *worldTriangles = slot->worldVerts; @@ -438,19 +403,61 @@ se_object_ptr CCArmatureDisplay::getSharedBufferOffset() const { return nullptr; } -se_object_ptr CCArmatureDisplay::getParamsBuffer() const { - if (_paramsBuffer) { - return _paramsBuffer->getTypeArray(); +void CCArmatureDisplay::setBatchEnabled(bool enabled) { + if (enabled != _enableBatch) { + for (auto& item : _materialCaches) { + CC_SAFE_DELETE(item.second); + } + _materialCaches.clear(); + _enableBatch = enabled; } - return nullptr; } -uint32_t CCArmatureDisplay::getRenderOrder() const { - if (_paramsBuffer) { - auto *buffer = _paramsBuffer->getBuffer(); - return static_cast(buffer[0]); +void CCArmatureDisplay::setRenderEntity(cc::RenderEntity* entity) { + _entity = entity; +} + +void CCArmatureDisplay::setMaterial(cc::Material *material) { + _material = material; +} + + +cc::RenderDrawInfo* CCArmatureDisplay::requestDrawInfo(int idx) { + if (_drawInfoArray.size() < idx + 1) { + cc::RenderDrawInfo *draw = new cc::RenderDrawInfo(); + draw->setDrawInfoType(static_cast(RenderDrawInfoType::MIDDLEWARE)); + _drawInfoArray.push_back(draw); } - return 0; + return _drawInfoArray[idx]; +} + +cc::Material *CCArmatureDisplay::requestMaterial(uint16_t blendSrc, uint16_t blendDst) { + uint32_t key = static_cast(blendSrc) << 16 | static_cast(blendDst); + if (_materialCaches.find(key) == _materialCaches.end()) { + const IMaterialInstanceInfo info { + (Material*)_material, + 0 + }; + MaterialInstance* materialInstance = new MaterialInstance(info); + PassOverrides overrides; + BlendStateInfo stateInfo; + stateInfo.blendColor = gfx::Color{1.0F, 1.0F, 1.0F, 1.0F}; + BlendTargetInfo targetInfo; + targetInfo.blendEq = gfx::BlendOp::ADD; + targetInfo.blendAlphaEq = gfx::BlendOp::ADD; + targetInfo.blendSrc = (gfx::BlendFactor)blendSrc; + targetInfo.blendDst = (gfx::BlendFactor)blendDst; + targetInfo.blendSrcAlpha = (gfx::BlendFactor)blendSrc; + targetInfo.blendDstAlpha = (gfx::BlendFactor)blendDst; + BlendTargetInfoList targetList {targetInfo}; + stateInfo.targets = targetList; + overrides.blendState = stateInfo; + materialInstance->overridePipelineStates(overrides); + const MacroRecord macros {{"USE_LOCAL", false}}; + materialInstance->recompileShaders(macros); + _materialCaches[key] = materialInstance; + } + return _materialCaches[key]; } DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.h b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.h index 8f9f5faf0e..ab10e0cd12 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.h +++ b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.h @@ -36,6 +36,13 @@ #include "dragonbones/DragonBonesHeaders.h" #include "middleware-adapter.h" +namespace cc { +class RenderEntity; +class RenderDrawInfo; +class Material; +class Texture2D; +}; + DRAGONBONES_NAMESPACE_BEGIN /** @@ -99,10 +106,6 @@ public: * @inheritDoc */ void removeDBEventListener(const std::string &type, const std::function &listener) override; - /** - * @inheritDoc - */ - uint32_t getRenderOrder() const override; using dbEventCallback = std::function; void setDBEventCallback(dbEventCallback callback) { @@ -132,11 +135,6 @@ public: * format |render info offset|attach info offset| */ se_object_ptr getSharedBufferOffset() const; - /** - * @return js send to cpp parameters, it's a Uint32Array - * format |render order|world matrix| - */ - se_object_ptr getParamsBuffer() const; void setColor(float r, float g, float b, float a); @@ -144,10 +142,7 @@ public: _debugDraw = enabled; } - void setBatchEnabled(bool enabled) { - // disable switch batch mode, force to enable batch, it may be changed in future version - // _batch = enabled; - } + void setBatchEnabled(bool enabled); void setAttachEnabled(bool enabled) { _useAttach = enabled; @@ -169,13 +164,18 @@ public: */ CCArmatureDisplay *getRootDisplay(); + cc::RenderDrawInfo *requestDrawInfo(int idx); + cc::Material *requestMaterial(uint16_t blendSrc, uint16_t blendDst); + void setMaterial(cc::Material *material); + void setRenderEntity(cc::RenderEntity* entity); private: std::map _listenerIDMap; int _preBlendMode = -1; - int _preTextureIndex = -1; - int _curTextureIndex = -1; int _curBlendSrc = -1; int _curBlendDst = -1; + cc::Texture2D *_preTexture = nullptr; + cc::Texture2D *_curTexture = nullptr; + cc::RenderDrawInfo *_curDrawInfo = nullptr; int _preISegWritePos = -1; int _curISegLen = 0; @@ -185,6 +185,7 @@ private: bool _useAttach = false; bool _premultipliedAlpha = false; + bool _enableBatch = false; // NOTE: We bind Vec2 to make JS deserialization works, we need to return const reference in convertToRootSpace method, // because returning Vec2 JSB object on stack to JS will let JS get mess data. @@ -195,8 +196,11 @@ private: cc::middleware::IOTypedArray *_sharedBufferOffset = nullptr; cc::middleware::IOTypedArray *_debugBuffer = nullptr; - // Js fill this buffer to send parameter to cpp, avoid to call jsb function. - cc::middleware::IOTypedArray *_paramsBuffer = nullptr; + + cc::RenderEntity *_entity = nullptr; + cc::Material *_material = nullptr; + ccstd::vector _drawInfoArray; + ccstd::unordered_map _materialCaches; }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCFactory.h b/native/cocos/editor-support/dragonbones-creator-support/CCFactory.h index 07e098f7ad..9d8c133b3a 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCFactory.h +++ b/native/cocos/editor-support/dragonbones-creator-support/CCFactory.h @@ -112,8 +112,6 @@ public: _dragonBonesInstance->render(); } - virtual uint32_t getRenderOrder() const override { return 0; } - /** * @note When script engine clean up is trigger,will stop dragonbones timer. */ diff --git a/native/cocos/editor-support/dragonbones/animation/IAnimatable.h b/native/cocos/editor-support/dragonbones/animation/IAnimatable.h index bbe1b7ae6f..cdfc005dac 100644 --- a/native/cocos/editor-support/dragonbones/animation/IAnimatable.h +++ b/native/cocos/editor-support/dragonbones/animation/IAnimatable.h @@ -95,18 +95,6 @@ public: */ virtual WorldClock* getClock() const = 0; virtual void setClock(WorldClock* value) = 0; - - /** - * - Gets render order. - * @version Cocos creator 2.3 - * @language en_US - */ - /** - * - 获得渲染顺序。 - * @version Cocos creator 2.3 - * @language zh_CN - */ - virtual uint32_t getRenderOrder() const { return 0; } }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones/animation/WorldClock.cpp b/native/cocos/editor-support/dragonbones/animation/WorldClock.cpp index 8bfc227c68..d825a63631 100644 --- a/native/cocos/editor-support/dragonbones/animation/WorldClock.cpp +++ b/native/cocos/editor-support/dragonbones/animation/WorldClock.cpp @@ -91,26 +91,11 @@ void WorldClock::remove(IAnimatable* value) { } void WorldClock::render() { - auto isOrderDirty = false; - uint32_t maxRenderOrder = 0; for (const auto animatable : _animatebles) { if (animatable != nullptr) { animatable->render(); - auto renderOrder = animatable->getRenderOrder(); - if (maxRenderOrder > renderOrder) { - isOrderDirty = true; - } else { - maxRenderOrder = renderOrder; - } } } - - if (isOrderDirty) { - std::sort(_animatebles.begin(), _animatebles.end(), [](IAnimatable* it1, IAnimatable* it2) { - if (!it1 || !it2) return false; - return it1->getRenderOrder() < it2->getRenderOrder(); - }); - } } void WorldClock::clear() { diff --git a/native/cocos/editor-support/dragonbones/armature/Armature.cpp b/native/cocos/editor-support/dragonbones/armature/Armature.cpp index 443f1e01c9..da4d2dc63a 100644 --- a/native/cocos/editor-support/dragonbones/armature/Armature.cpp +++ b/native/cocos/editor-support/dragonbones/armature/Armature.cpp @@ -228,13 +228,6 @@ void Armature::render() { } } -uint32_t Armature::getRenderOrder() const { - if (_proxy) { - return _proxy->getRenderOrder(); - } - return 0; -} - void Armature::invalidUpdate(const std::string& boneName, bool updateSlot) { if (!boneName.empty()) { const auto bone = getBone(boneName); diff --git a/native/cocos/editor-support/dragonbones/armature/Armature.h b/native/cocos/editor-support/dragonbones/armature/Armature.h index db4c4de8a8..23f6269bba 100644 --- a/native/cocos/editor-support/dragonbones/armature/Armature.h +++ b/native/cocos/editor-support/dragonbones/armature/Armature.h @@ -189,10 +189,6 @@ public: * @inheritDoc */ void render() override; - /** - * @inheritDoc - */ - uint32_t getRenderOrder() const override; /** * - Forces a specific bone or its owning slot to update the transform or display property in the next frame. * @param boneName - The bone name. (If not set, all bones will be update) diff --git a/native/cocos/editor-support/dragonbones/armature/IArmatureProxy.h b/native/cocos/editor-support/dragonbones/armature/IArmatureProxy.h index 07c97b2585..7d4a36bcb0 100644 --- a/native/cocos/editor-support/dragonbones/armature/IArmatureProxy.h +++ b/native/cocos/editor-support/dragonbones/armature/IArmatureProxy.h @@ -105,18 +105,6 @@ public: * @language zh_CN */ virtual Animation* getAnimation() const = 0; - - /** - * - Gets render order - * @version Cocos Creator 2.3 - * @language en_US - */ - /** - * - 获得渲染顺序。 - * @version Cocos Creator 2.3 - * @language zh_CN - */ - virtual uint32_t getRenderOrder() const = 0; }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/middleware-adapter.cpp b/native/cocos/editor-support/middleware-adapter.cpp index ff62c9a796..82345f239c 100644 --- a/native/cocos/editor-support/middleware-adapter.cpp +++ b/native/cocos/editor-support/middleware-adapter.cpp @@ -106,6 +106,14 @@ void Texture2D::setTexParameters(const TexParams &texParams) { } } +void Texture2D::setRealTexture(void* texturePtr) { + _texturePtr = texturePtr; +} + +void *Texture2D::getRealTexture() const { + return _texturePtr; +} + SpriteFrame *SpriteFrame::createWithTexture(Texture2D *texture, const cc::Rect &rect) { auto *spriteFrame = new (std::nothrow) SpriteFrame(); spriteFrame->initWithTexture(texture, rect); diff --git a/native/cocos/editor-support/middleware-adapter.h b/native/cocos/editor-support/middleware-adapter.h index 164724cf58..3c1a2bc6c7 100644 --- a/native/cocos/editor-support/middleware-adapter.h +++ b/native/cocos/editor-support/middleware-adapter.h @@ -181,6 +181,8 @@ public: /** Sets texture param callback*/ void setTexParamCallback(const texParamCallback &callback); + void setRealTexture(void* texturePtr); + void *getRealTexture() const; private: /** width in pixels */ int _pixelsWide = 0; @@ -192,6 +194,7 @@ private: int _realTextureIndex = 0; texParamCallback _texParamCallback = nullptr; + void* _texturePtr = nullptr; }; /////////////////////////////////////////////////////////////////////// diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.cpp index 842a3b6164..1b1a5970c1 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.cpp @@ -35,6 +35,9 @@ #include "base/memory/Memory.h" #include "gfx-base/GFXDef.h" #include "math/Math.h" +#include "2d/renderer/RenderDrawInfo.h" +#include "2d/renderer/RenderEntity.h" +#include "renderer/core/MaterialInstance.h" USING_NS_MW; // NOLINT(google-build-using-namespace) @@ -57,13 +60,6 @@ SkeletonCacheAnimation::SkeletonCacheAnimation(const std::string &uuid, bool isS // store global TypedArray begin and end offset _sharedBufferOffset = new IOTypedArray(se::Object::TypedArrayType::UINT32, sizeof(uint32_t) * 2); - // store render order(1), world matrix(16) - _paramsBuffer = new IOTypedArray(se::Object::TypedArrayType::FLOAT32, sizeof(float) * 17); - // set render order to 0 - _paramsBuffer->writeFloat32(0); - // set world transform to identity - _paramsBuffer->writeBytes(reinterpret_cast(&cc::Mat4::IDENTITY), sizeof(float) * 16); - beginSchedule(); } @@ -73,11 +69,6 @@ SkeletonCacheAnimation::~SkeletonCacheAnimation() { _sharedBufferOffset = nullptr; } - if (_paramsBuffer) { - delete _paramsBuffer; - _paramsBuffer = nullptr; - } - if (_skeletonCache) { _skeletonCache->release(); _skeletonCache = nullptr; @@ -87,6 +78,13 @@ SkeletonCacheAnimation::~SkeletonCacheAnimation() { _animationQueue.pop(); delete ani; } + for (auto* draw : _drawInfoArray) { + CC_SAFE_DELETE(draw); + } + + for (auto& item : _materialCaches) { + CC_SAFE_DELETE(item.second); + } stopSchedule(); } @@ -160,6 +158,8 @@ void SkeletonCacheAnimation::render(float /*dt*/) { if (!_animationData) return; SkeletonCache::FrameData *frameData = _animationData->getFrameData(_curFrameIndex); if (!frameData) return; + auto *entity = _entity; + entity->clearDynamicRenderDrawInfos(); const auto &segments = frameData->getSegments(); const auto &colors = frameData->getColors(); @@ -171,27 +171,13 @@ void SkeletonCacheAnimation::render(float /*dt*/) { _sharedBufferOffset->reset(); _sharedBufferOffset->clear(); - auto *renderMgr = mgr->getRenderInfoMgr(); - auto *renderInfo = renderMgr->getBuffer(); - if (!renderInfo) return; - auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); if (!attachInfo) return; - // store render info offset - _sharedBufferOffset->writeUint32(static_cast(renderInfo->getCurPos()) / sizeof(uint32_t)); // store attach info offset _sharedBufferOffset->writeUint32(static_cast(attachInfo->getCurPos()) / sizeof(uint32_t)); - // check enough space - renderInfo->checkSpace(sizeof(uint32_t) * 2, true); - // write border - renderInfo->writeUint32(0xffffffff); - - // material len - renderInfo->writeUint32(segments.size()); - auto vertexFormat = _useTint ? VF_XYZUVCC : VF_XYZUVC; middleware::MeshBuffer *mb = mgr->getMeshBuffer(vertexFormat); middleware::IOBuffer &vb = mb->getVB(); @@ -211,8 +197,7 @@ void SkeletonCacheAnimation::render(float /*dt*/) { int vs = _useTint ? vs2 : vs1; int vbs = _useTint ? vbs2 : vbs1; - auto *paramsBuffer = _paramsBuffer->getBuffer(); - const cc::Mat4 &nodeWorldMat = *reinterpret_cast(¶msBuffer[4]); + auto &nodeWorldMat = entity->getNode()->getWorldMatrix(); int colorOffset = 0; SkeletonCache::ColorData *nowColor = colors[colorOffset++]; @@ -232,7 +217,6 @@ void SkeletonCacheAnimation::render(float /*dt*/) { int tintBytes = 0; int srcIndexBytesOffset = 0; int indexBytes = 0; - int curTextureIndex = 0; double effectHash = 0; int blendMode = 0; int dstVertexOffset = 0; @@ -243,6 +227,8 @@ void SkeletonCacheAnimation::render(float /*dt*/) { bool needColor = false; int curBlendSrc = -1; int curBlendDst = -1; + cc::Texture2D* curTexture = nullptr; + RenderDrawInfo* curDrawInfo = nullptr; if (abs(_nodeColor.r - 1.0F) > 0.0001F || abs(_nodeColor.g - 1.0F) > 0.0001F || @@ -271,7 +257,7 @@ void SkeletonCacheAnimation::render(float /*dt*/) { }; handleColor(nowColor); - + int segmentCount = 0; for (auto *segment : segments) { srcVertexBytes = static_cast(segment->vertexFloatCount * sizeof(float)); if (!_useTint) { @@ -282,13 +268,14 @@ void SkeletonCacheAnimation::render(float /*dt*/) { vertexBytes = srcVertexBytes; vertexFloats = segment->vertexFloatCount; } - - // check enough space - renderInfo->checkSpace(sizeof(uint32_t) * 6, true); - + curDrawInfo = requestDrawInfo(segmentCount++); + entity->addDynamicRenderDrawInfo(curDrawInfo); // fill new texture index - curTextureIndex = segment->getTexture()->getRealTextureIndex(); - renderInfo->writeUint32(curTextureIndex); + curTexture = static_cast(segment->getTexture()->getRealTexture()); + gfx::Texture *texture = curTexture->getGFXTexture(); + gfx::Sampler *sampler = curTexture->getGFXSampler(); + curDrawInfo->setTexture(texture); + curDrawInfo->setSampler(sampler); blendMode = segment->blendMode; switch (blendMode) { @@ -309,8 +296,8 @@ void SkeletonCacheAnimation::render(float /*dt*/) { curBlendDst = static_cast(BlendFactor::ONE_MINUS_SRC_ALPHA); } // fill new blend src and dst - renderInfo->writeUint32(curBlendSrc); - renderInfo->writeUint32(curBlendDst); + auto *material = requestMaterial(curBlendSrc, curBlendDst); + curDrawInfo->setMaterial(material); // fill vertex buffer vb.checkSpace(vertexBytes, true); @@ -325,7 +312,15 @@ void SkeletonCacheAnimation::render(float /*dt*/) { } else { vb.writeBytes(reinterpret_cast(srcVB.getBuffer()) + srcVertexBytesOffset, vertexBytes); } - + // batch handle + if (_enableBatch) { + cc::Vec3 *point = nullptr; + for (auto posIndex = 0; posIndex < vertexFloats; posIndex += vs) { + point = reinterpret_cast(dstVertexBuffer + posIndex); + point->z = 0; + point->transformMat4(*point, nodeWorldMat); + } + } // handle vertex color if (needColor) { int srcVertexFloatOffset = static_cast(srcVertexBytesOffset / sizeof(float)); @@ -366,13 +361,13 @@ void SkeletonCacheAnimation::render(float /*dt*/) { srcIndexBytesOffset += indexBytes; // fill new index and vertex buffer id - auto bufferIndex = mb->getBufferPos(); - renderInfo->writeUint32(bufferIndex); + UIMeshBuffer* uiMeshBuffer = mb->getUIMeshBuffer(); + curDrawInfo->setMeshBuffer(uiMeshBuffer); // fill new index offset - renderInfo->writeUint32(dstIndexOffset); + curDrawInfo->setIndexOffset(dstIndexOffset); // fill new indice segamentation count - renderInfo->writeUint32(segment->indexCount); + curDrawInfo->setIbCount(segment->indexCount); } if (_useAttach) { @@ -445,8 +440,13 @@ void SkeletonCacheAnimation::setColor(float r, float g, float b, float a) { } void SkeletonCacheAnimation::setBatchEnabled(bool enabled) { - // disable switch batch mode, force to enable batch, it may be changed in future version - // _batch = enabled; + if (_enableBatch != enabled) { + for (auto& item : _materialCaches) { + CC_SAFE_DELETE(item.second); + } + _materialCaches.clear(); + _enableBatch = enabled; + } } void SkeletonCacheAnimation::setOpacityModifyRGB(bool value) { @@ -536,21 +536,6 @@ se_object_ptr SkeletonCacheAnimation::getSharedBufferOffset() const { return nullptr; } -se_object_ptr SkeletonCacheAnimation::getParamsBuffer() const { - if (_paramsBuffer) { - return _paramsBuffer->getTypeArray(); - } - return nullptr; -} - -uint32_t SkeletonCacheAnimation::getRenderOrder() const { - if (_paramsBuffer) { - auto *buffer = _paramsBuffer->getBuffer(); - return static_cast(buffer[0]); - } - return 0; -} - void SkeletonCacheAnimation::setToSetupPose() { if (_skeletonCache) { _skeletonCache->setToSetupPose(); @@ -568,4 +553,50 @@ void SkeletonCacheAnimation::setSlotsToSetupPose() { _skeletonCache->setSlotsToSetupPose(); } } +void SkeletonCacheAnimation::setRenderEntity(cc::RenderEntity* entity) { + _entity = entity; +} + +void SkeletonCacheAnimation::setMaterial(cc::Material *material) { + _material = material; +} + +cc::RenderDrawInfo* SkeletonCacheAnimation::requestDrawInfo(int idx) { + if (_drawInfoArray.size() < idx + 1) { + cc::RenderDrawInfo *draw = new cc::RenderDrawInfo(); + draw->setDrawInfoType(static_cast(RenderDrawInfoType::MIDDLEWARE)); + _drawInfoArray.push_back(draw); + } + return _drawInfoArray[idx]; +} + +cc::Material *SkeletonCacheAnimation::requestMaterial(uint16_t blendSrc, uint16_t blendDst) { + uint32_t key = static_cast(blendSrc) << 16 | static_cast(blendDst); + if (_materialCaches.find(key) == _materialCaches.end()) { + const IMaterialInstanceInfo info { + (Material*)_material, + 0 + }; + MaterialInstance* materialInstance = new MaterialInstance(info); + PassOverrides overrides; + BlendStateInfo stateInfo; + stateInfo.blendColor = gfx::Color{1.0F, 1.0F, 1.0F, 1.0F}; + BlendTargetInfo targetInfo; + targetInfo.blendEq = gfx::BlendOp::ADD; + targetInfo.blendAlphaEq = gfx::BlendOp::ADD; + targetInfo.blendSrc = (gfx::BlendFactor)blendSrc; + targetInfo.blendDst = (gfx::BlendFactor)blendDst; + targetInfo.blendSrcAlpha = (gfx::BlendFactor)blendSrc; + targetInfo.blendDstAlpha = (gfx::BlendFactor)blendDst; + BlendTargetInfoList targetList {targetInfo}; + stateInfo.targets = targetList; + overrides.blendState = stateInfo; + materialInstance->overridePipelineStates(overrides); + const MacroRecord macros {{"TWO_COLORED", _useTint}, {"USE_LOCAL", !_enableBatch}}; + materialInstance->recompileShaders(macros); + _materialCaches[key] = materialInstance; + } + return _materialCaches[key]; +} + } // namespace spine diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h index cbba98c5f3..cbeaa2acac 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h @@ -35,6 +35,12 @@ #include "middleware-adapter.h" #include "spine/spine.h" +namespace cc { +class RenderEntity; +class RenderDrawInfo; +class Material; +}; + namespace spine { class SkeletonCacheAnimation : public cc::RefCounted, public cc::middleware::IMiddleware { @@ -44,7 +50,6 @@ public: void update(float dt) override; void render(float dt) override; - uint32_t getRenderOrder() const override; Skeleton *getSkeleton() const; @@ -95,12 +100,11 @@ public: * format |render info offset|attach info offset| */ se_object_ptr getSharedBufferOffset() const; - /** - * @return js send to cpp parameters, it's a Uint32Array - * format |render order|world matrix| - */ - se_object_ptr getParamsBuffer() const; + cc::RenderDrawInfo *requestDrawInfo(int idx); + cc::Material *requestMaterial(uint16_t blendSrc, uint16_t blendDst); + void setMaterial(cc::Material *material); + void setRenderEntity(cc::RenderEntity* entity); private: float _timeScale = 1; bool _paused = false; @@ -122,6 +126,7 @@ private: bool _isAniComplete = true; std::string _animationName; bool _useTint = true; + bool _enableBatch = false; struct AniQueueData { std::string animationName; @@ -132,7 +137,9 @@ private: AniQueueData *_headAnimation = nullptr; cc::middleware::IOTypedArray *_sharedBufferOffset = nullptr; - // Js fill this buffer to send parameter to cpp, avoid to call jsb function. - cc::middleware::IOTypedArray *_paramsBuffer = nullptr; + cc::RenderEntity *_entity = nullptr; + cc::Material *_material = nullptr; + ccstd::vector _drawInfoArray; + ccstd::unordered_map _materialCaches; }; } // namespace spine diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp index b559ff27b4..2f94434161 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp @@ -40,6 +40,9 @@ #include "math/Vec3.h" #include "spine-creator-support/AttachmentVertices.h" #include "spine-creator-support/spine-cocos2dx.h" +#include "2d/renderer/RenderDrawInfo.h" +#include "2d/renderer/RenderEntity.h" +#include "renderer/core/MaterialInstance.h" USING_NS_MW; // NOLINT(google-build-using-namespace) using namespace spine; // NOLINT(google-build-using-namespace) @@ -86,15 +89,6 @@ void SkeletonRenderer::initialize() { _sharedBufferOffset = new cc::middleware::IOTypedArray(se::Object::TypedArrayType::UINT32, sizeof(uint32_t) * 2); } - if (_paramsBuffer == nullptr) { - // store render order(1), world matrix(16) - _paramsBuffer = new cc::middleware::IOTypedArray(se::Object::TypedArrayType::FLOAT32, sizeof(float) * 17); - // set render order to 0 - _paramsBuffer->writeFloat32(0); - // set world transform to identity - _paramsBuffer->writeBytes(reinterpret_cast(&cc::Mat4::IDENTITY), sizeof(float) * 16); - } - _skeleton->setToSetupPose(); _skeleton->updateWorldTransform(); beginSchedule(); @@ -161,9 +155,12 @@ SkeletonRenderer::~SkeletonRenderer() { _sharedBufferOffset = nullptr; } - if (_paramsBuffer) { - delete _paramsBuffer; - _paramsBuffer = nullptr; + for (auto* draw : _drawInfoArray) { + CC_SAFE_DELETE(draw); + } + + for (auto& item : _materialCaches) { + CC_SAFE_DELETE(item.second); } stopSchedule(); @@ -262,7 +259,8 @@ void SkeletonRenderer::initWithBinaryFile(const std::string &skeletonDataFile, c void SkeletonRenderer::render(float /*deltaTime*/) { if (!_skeleton) return; - + auto *entity = _entity; + entity->clearDynamicRenderDrawInfos(); _sharedBufferOffset->reset(); _sharedBufferOffset->clear(); @@ -270,33 +268,17 @@ void SkeletonRenderer::render(float /*deltaTime*/) { auto *mgr = MiddlewareManager::getInstance(); if (!mgr->isRendering) return; - auto *renderMgr = mgr->getRenderInfoMgr(); - auto *renderInfo = renderMgr->getBuffer(); - if (!renderInfo) return; - auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); if (!attachInfo) return; - - // store render info offset - _sharedBufferOffset->writeUint32(static_cast(renderInfo->getCurPos()) / sizeof(uint32_t)); // store attach info offset _sharedBufferOffset->writeUint32(static_cast(attachInfo->getCurPos()) / sizeof(uint32_t)); - // check enough space - renderInfo->checkSpace(sizeof(uint32_t) * 2, true); - // write border - renderInfo->writeUint32(0xffffffff); - - std::size_t materialLenOffset = renderInfo->getCurPos(); - //reserved space to save material len - renderInfo->writeUint32(0); - // If opacity is 0,then return. if (_skeleton->getColor().a == 0) { return; } - + auto& nodeWorldMat = entity->getNode()->getWorldMatrix(); // color range is [0.0, 1.0] cc::middleware::Color4F color; cc::middleware::Color4F darkColor; @@ -321,10 +303,6 @@ void SkeletonRenderer::render(float /*deltaTime*/) { vbs = vbs2; } - auto *paramsBuffer = _paramsBuffer->getBuffer(); - // data store in buffer which 0 to 3 is render order, left data is node world matrix - const cc::Mat4 &nodeWorldMat = *reinterpret_cast(¶msBuffer[4]); - unsigned int vbSize = 0; unsigned int ibSize = 0; @@ -332,11 +310,10 @@ void SkeletonRenderer::render(float /*deltaTime*/) { int curBlendDst = -1; int curBlendMode = -1; int preBlendMode = -1; - int preTextureIndex = -1; - int curTextureIndex = -1; - - int preISegWritePos = -1; uint32_t curISegLen = 0; + cc::Texture2D* preTexture = nullptr; + cc::Texture2D* curTexture = nullptr; + RenderDrawInfo* curDrawInfo = nullptr; int materialLen = 0; Slot *slot = nullptr; @@ -352,9 +329,11 @@ void SkeletonRenderer::render(float /*deltaTime*/) { auto flush = [&]() { // fill pre segment indices count field - if (preISegWritePos != -1) { - renderInfo->writeUint32(preISegWritePos, curISegLen); + if (curDrawInfo) { + curDrawInfo->setIbCount(curISegLen); } + curDrawInfo = requestDrawInfo(materialLen); + entity->addDynamicRenderDrawInfo(curDrawInfo); // prepare to fill new segment field curBlendMode = slot->getData().getBlendMode(); switch (curBlendMode) { @@ -374,30 +353,19 @@ void SkeletonRenderer::render(float /*deltaTime*/) { curBlendSrc = static_cast(_premultipliedAlpha ? BlendFactor::ONE : BlendFactor::SRC_ALPHA); curBlendDst = static_cast(BlendFactor::ONE_MINUS_SRC_ALPHA); } - - // check enough space - renderInfo->checkSpace(sizeof(uint32_t) * 6, true); - - // fill new texture index - renderInfo->writeUint32(curTextureIndex); - // fill new blend src and dst - renderInfo->writeUint32(curBlendSrc); - renderInfo->writeUint32(curBlendDst); - // fill new index and vertex buffer id - auto bufferIndex = mb->getBufferPos(); - renderInfo->writeUint32(bufferIndex); - - // fill new index offset - renderInfo->writeUint32(static_cast(ib.getCurPos()) / sizeof(uint16_t)); - // save new segment indices count pos field - preISegWritePos = static_cast(renderInfo->getCurPos()); - // reserve indice segamentation count - renderInfo->writeUint32(0); - + auto *material = requestMaterial(curBlendSrc, curBlendDst); + curDrawInfo->setMaterial(material); + gfx::Texture *texture = curTexture->getGFXTexture(); + gfx::Sampler *sampler = curTexture->getGFXSampler(); + curDrawInfo->setTexture(texture); + curDrawInfo->setSampler(sampler); + auto* uiMeshBuffer = mb->getUIMeshBuffer(); + curDrawInfo->setMeshBuffer(uiMeshBuffer); + curDrawInfo->setIndexOffset(static_cast(ib.getCurPos()) / sizeof(uint16_t)); // reset pre blend mode to current preBlendMode = static_cast(slot->getData().getBlendMode()); // reset pre texture index to current - preTextureIndex = curTextureIndex; + preTexture = curTexture; // reset index segmentation count curISegLen = 0; // material length increased @@ -747,12 +715,20 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } } - curTextureIndex = attachmentVertices->_texture->getRealTextureIndex(); + curTexture = (cc::Texture2D*)attachmentVertices->_texture->getRealTexture(); // If texture or blendMode change,will change material. - if (preTextureIndex != curTextureIndex || preBlendMode != slot->getData().getBlendMode() || isFull) { + if (preTexture != curTexture || preBlendMode != slot->getData().getBlendMode() || isFull) { flush(); } - + if (_enableBatch) { + uint8_t *vbBuffer = vb.getCurBuffer(); + cc::Vec3 *point = nullptr; + for (unsigned int ii = 0, nn = vbSize; ii < nn; ii += vbs) { + point = reinterpret_cast(vbBuffer + ii); + point->z = 0; + point->transformMat4(*point, nodeWorldMat); + } + } auto vertexOffset = vb.getCurPos() / vbs; if (vbSize > 0 && ibSize > 0) { if (vertexOffset > 0) { @@ -775,10 +751,7 @@ void SkeletonRenderer::render(float /*deltaTime*/) { if (effect) effect->end(); - renderInfo->writeUint32(materialLenOffset, materialLen); - if (preISegWritePos != -1) { - renderInfo->writeUint32(preISegWritePos, curISegLen); - } + if (curDrawInfo) curDrawInfo->setIbCount(curISegLen); if (_useAttach || _debugBones) { auto &bones = _skeleton->getBones(); @@ -984,8 +957,13 @@ void SkeletonRenderer::setColor(float r, float g, float b, float a) { } void SkeletonRenderer::setBatchEnabled(bool enabled) { - // disable switch batch mode, force to enable batch, it may be changed in future version - // _batch = enabled; + if (enabled != _enableBatch) { + for (auto& item : _materialCaches) { + CC_SAFE_DELETE(item.second); + } + _materialCaches.clear(); + _enableBatch = enabled; + } } void SkeletonRenderer::setDebugBonesEnabled(bool enabled) { @@ -1022,17 +1000,48 @@ se_object_ptr SkeletonRenderer::getSharedBufferOffset() const { return nullptr; } -se_object_ptr SkeletonRenderer::getParamsBuffer() const { - if (_paramsBuffer) { - return _paramsBuffer->getTypeArray(); - } - return nullptr; +void SkeletonRenderer::setRenderEntity(cc::RenderEntity* entity) { + _entity = entity; } -uint32_t SkeletonRenderer::getRenderOrder() const { - if (_paramsBuffer) { - auto *buffer = _paramsBuffer->getBuffer(); - return static_cast(buffer[0]); - } - return 0; +void SkeletonRenderer::setMaterial(cc::Material *material) { + _material = material; +} + +cc::RenderDrawInfo* SkeletonRenderer::requestDrawInfo(int idx) { + if (_drawInfoArray.size() < idx + 1) { + cc::RenderDrawInfo *draw = new cc::RenderDrawInfo(); + draw->setDrawInfoType(static_cast(RenderDrawInfoType::MIDDLEWARE)); + _drawInfoArray.push_back(draw); + } + return _drawInfoArray[idx]; +} + +cc::Material *SkeletonRenderer::requestMaterial(uint16_t blendSrc, uint16_t blendDst) { + uint32_t key = static_cast(blendSrc) << 16 | static_cast(blendDst); + if (_materialCaches.find(key) == _materialCaches.end()) { + const IMaterialInstanceInfo info { + (Material*)_material, + 0 + }; + MaterialInstance* materialInstance = new MaterialInstance(info); + PassOverrides overrides; + BlendStateInfo stateInfo; + stateInfo.blendColor = gfx::Color{1.0F, 1.0F, 1.0F, 1.0F}; + BlendTargetInfo targetInfo; + targetInfo.blendEq = gfx::BlendOp::ADD; + targetInfo.blendAlphaEq = gfx::BlendOp::ADD; + targetInfo.blendSrc = (gfx::BlendFactor)blendSrc; + targetInfo.blendDst = (gfx::BlendFactor)blendDst; + targetInfo.blendSrcAlpha = (gfx::BlendFactor)blendSrc; + targetInfo.blendDstAlpha = (gfx::BlendFactor)blendDst; + BlendTargetInfoList targetList {targetInfo}; + stateInfo.targets = targetList; + overrides.blendState = stateInfo; + materialInstance->overridePipelineStates(overrides); + const MacroRecord macros {{"TWO_COLORED", _useTint}, {"USE_LOCAL", !_enableBatch}}; + materialInstance->recompileShaders(macros); + _materialCaches[key] = materialInstance; + } + return _materialCaches[key]; } diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h index b3667d048d..99853e9cbd 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h @@ -40,6 +40,12 @@ #include "spine-creator-support/VertexEffectDelegate.h" #include "spine/spine.h" +namespace cc { +class RenderEntity; +class RenderDrawInfo; +class Material; +}; + namespace spine { class AttachmentVertices; @@ -56,7 +62,6 @@ public: void update(float deltaTime) override {} void render(float deltaTime) override; virtual cc::Rect getBoundingBox() const; - uint32_t getRenderOrder() const override; Skeleton *getSkeleton() const; @@ -108,11 +113,6 @@ public: * format |render info offset|attach info offset| */ se_object_ptr getSharedBufferOffset() const; - /** - * @return js send to cpp parameters, it's a Uint32Array - * format |render order|world matrix| - */ - se_object_ptr getParamsBuffer() const; void setColor(float r, float g, float b, float a); void setBatchEnabled(bool enabled); @@ -145,6 +145,11 @@ public: void initWithBinaryFile(const std::string &skeletonDataFile, const std::string &atlasFile, float scale = 1); virtual void initialize(); + + cc::RenderDrawInfo *requestDrawInfo(int idx); + cc::Material *requestMaterial(uint16_t blendSrc, uint16_t blendDst); + void setMaterial(cc::Material *material); + void setRenderEntity(cc::RenderEntity* entity); protected: void setSkeletonData(SkeletonData *skeletonData, bool ownsSkeletonData); @@ -167,6 +172,7 @@ protected: bool _premultipliedAlpha = false; SkeletonClipping *_clipper = nullptr; bool _useTint = false; + bool _enableBatch = false; std::string _uuid; int _startSlotIndex = -1; @@ -174,8 +180,11 @@ protected: cc::middleware::IOTypedArray *_sharedBufferOffset = nullptr; cc::middleware::IOTypedArray *_debugBuffer = nullptr; - // Js fill this buffer to send parameter to cpp, avoid to call jsb function. - cc::middleware::IOTypedArray *_paramsBuffer = nullptr; + + cc::RenderEntity *_entity = nullptr; + cc::Material *_material = nullptr; + ccstd::vector _drawInfoArray; + ccstd::unordered_map _materialCaches; }; } // namespace spine diff --git a/native/cocos/editor-support/spine/SkeletonBinary.cpp b/native/cocos/editor-support/spine/SkeletonBinary.cpp index f0814a24c0..c3742e2d33 100644 --- a/native/cocos/editor-support/spine/SkeletonBinary.cpp +++ b/native/cocos/editor-support/spine/SkeletonBinary.cpp @@ -525,12 +525,17 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo return box; } case AttachmentType_Mesh: { + bool needDelete = false; int vertexCount; MeshAttachment *mesh; String path(readStringRef(input, skeletonData)); if (path.isEmpty()) path = name; mesh = _attachmentLoader->newMeshAttachment(*skin, String(name), String(path)); + if (!mesh) { + mesh = new MeshAttachment(name); + needDelete = true; + } mesh->_path = path; readColor(input, mesh->getColor()); vertexCount = readVarint(input, true); @@ -547,6 +552,13 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo mesh->_width = 0; mesh->_height = 0; } + // mesh should not be added to skin, just delete it. While it still needs to read + // all bytes to make sure next readAttachment read back right data. + if (needDelete) { + delete mesh; + mesh = nullptr; + return nullptr; + } _attachmentLoader->configureAttachment(mesh); return mesh; } diff --git a/native/cocos/network/Downloader-curl.cpp b/native/cocos/network/Downloader-curl.cpp index 7cb72c7218..9e5e6016a9 100644 --- a/native/cocos/network/Downloader-curl.cpp +++ b/native/cocos/network/Downloader-curl.cpp @@ -32,12 +32,12 @@ #include "application/ApplicationManager.h" #include "base/Scheduler.h" +#include "base/StringUtil.h" #include "base/memory/Memory.h" #include "base/std/container/deque.h" #include "base/std/container/set.h" #include "base/std/container/vector.h" #include "platform/FileUtils.h" - #include "network/Downloader.h" // **NOTE** @@ -309,7 +309,8 @@ private: const DownloadTaskCURL *coTask = wrapper.second; // set url - curl_easy_setopt(handle, CURLOPT_URL, task.requestURL.c_str()); + ccstd::string url(task.requestURL); + curl_easy_setopt(handle, CURLOPT_URL, StringUtil::replaceAll(url, " ", "%20").c_str()); // set write func if (forContent) { diff --git a/native/cocos/network/Downloader-java.cpp b/native/cocos/network/Downloader-java.cpp index e399f9e803..a03d28ae9d 100644 --- a/native/cocos/network/Downloader-java.cpp +++ b/native/cocos/network/Downloader-java.cpp @@ -32,6 +32,7 @@ #include "network/Downloader.h" #include "platform/java/jni/JniHelper.h" #include "platform/java/jni/JniImp.h" +#include "base/StringUtil.h" #ifndef JCLS_DOWNLOADER #define JCLS_DOWNLOADER "com/cocos/lib/CocosDownloader" @@ -147,7 +148,8 @@ IDownloadTask *DownloaderJava::createCoTask(std::shared_ptr "createTask", "(" JARG_DOWNLOADER "I" JARG_STR JARG_STR "[" JARG_STR ")V")) { jclass jclassString = methodInfo.env->FindClass("java/lang/String"); - jstring jstrURL = methodInfo.env->NewStringUTF(task->requestURL.c_str()); + ccstd::string url(task->requestURL); + jstring jstrURL = methodInfo.env->NewStringUTF(StringUtil::replaceAll(url, " ", "%20").c_str()); jstring jstrPath = methodInfo.env->NewStringUTF(task->storagePath.c_str()); jobjectArray jarrayHeader = methodInfo.env->NewObjectArray(task->header.size() * 2, jclassString, nullptr); const ccstd::unordered_map &headMap = task->header; diff --git a/native/cocos/network/DownloaderImpl-apple.mm b/native/cocos/network/DownloaderImpl-apple.mm index 857168c0f7..8e7fbd458f 100644 --- a/native/cocos/network/DownloaderImpl-apple.mm +++ b/native/cocos/network/DownloaderImpl-apple.mm @@ -274,7 +274,9 @@ void DownloaderApple::abort(const std::unique_ptr &task) { - (NSURLSessionDownloadTask *)createDownloadTask:(std::shared_ptr &)task { const char *urlStr = task->requestURL.c_str(); DLLOG("DownloaderAppleImpl createDownloadTask: %s", urlStr); - NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:urlStr]]; + NSString *resourcePath = [NSString stringWithUTF8String:urlStr]; + NSString *encodePath = [resourcePath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet]; + NSURL *url = [NSURL URLWithString:encodePath]; NSMutableURLRequest *request = nil; if (_hints.timeoutInSeconds > 0) { request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:(NSTimeInterval)_hints.timeoutInSeconds]; diff --git a/native/cocos/network/WebSocketServer.cpp b/native/cocos/network/WebSocketServer.cpp index 4ff7dbc352..9e391438de 100644 --- a/native/cocos/network/WebSocketServer.cpp +++ b/native/cocos/network/WebSocketServer.cpp @@ -94,11 +94,13 @@ void schedule_task_into_server_thread_task_queue(uv_async_t *async, std::functio namespace cc { namespace network { -#define RUN_IN_GAMETHREAD(task) \ - do { \ - CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([=]() { \ - task; \ - }); \ +#define RUN_IN_GAMETHREAD(task) \ + do { \ + if (CC_CURRENT_APPLICATION()) { \ + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([=]() { \ + task; \ + }); \ + } \ } while (0) #define DISPATCH_CALLBACK_IN_GAMETHREAD() \ @@ -386,7 +388,10 @@ WebSocketServerConnection::~WebSocketServerConnection() { bool WebSocketServerConnection::send(std::shared_ptr data) { _sendQueue.emplace_back(data); - onDrainMessage(); + if (!_wsi || _closed || _readyState == ReadyState::CLOSING) { + return false; + } + lws_callback_on_writable(_wsi); return true; } diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/websocket/CocosWebSocket.java b/native/cocos/platform/android/java/src/com/cocos/lib/websocket/CocosWebSocket.java index 55de6d3af8..8afefb1469 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/websocket/CocosWebSocket.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/websocket/CocosWebSocket.java @@ -295,6 +295,9 @@ public class CocosWebSocket extends WebSocketListener { public void onClosing(org.cocos2dx.okhttp3.WebSocket _webSocket, int code, String reason) { output("Closing : " + code + " / " + reason); + if (_webSocket != null) { + _webSocket.close(code, reason); + } } @Override diff --git a/native/cocos/plugins/bus/EventBus.cpp b/native/cocos/plugins/bus/EventBus.cpp index 0a1ff4b9f1..f417d45f4d 100644 --- a/native/cocos/plugins/bus/EventBus.cpp +++ b/native/cocos/plugins/bus/EventBus.cpp @@ -29,7 +29,6 @@ namespace cc { namespace plugin { -using ListenerEntry = ListEntry; Listener::Listener(BusType type) : Listener(EventBus::acquire(type)) {} @@ -52,40 +51,25 @@ EventBus *EventBus::acquire(BusType type) { return &cache[type]; } -EventBus::EventBus() { - _list.first = _list.last = &_entry; -} - void EventBus::addListener(Listener *listener) { - assert(listener->nextEntry == nullptr && listener->prevEntry == nullptr); - listener->prevEntry = _list.last; - listener->nextEntry = &_entry; - _list.first = _list.first == _list.last ? listener : _list.first; - _list.last = listener; + assert(std::find(_listeners.begin(), _listeners.end(), listener) != _listeners.end()); + _listeners.emplace_back(listener); } void EventBus::removeListener(Listener *listener) { - if (listener->nextEntry == nullptr || listener->prevEntry == nullptr) { - return; + auto tgt = std::find(_listeners.begin(), _listeners.end(), listener); + if (tgt != _listeners.end()) { + _listeners.erase(tgt); } - _list.first = listener->prevEntry; - _list.last = listener->nextEntry; - listener->nextEntry = listener->prevEntry = nullptr; } void EventBus::dispatch(EventBase *event) { - static_assert(offsetof(Listener, prevEntry) == 0, "Listener should inherit ListEntry"); - static_assert(offsetof(EventBus, _list) == 0, "EventBus should contains ListEntry"); - static_assert(sizeof(_list) == sizeof(_entry), "ListEntry size should match"); - auto *curr = _list.first; - while (curr != &_entry) { - auto *listener = reinterpret_cast(curr); + for (auto *listener : _listeners) { for (auto &handle : listener->_handles) { if (strcmp(handle->signature(), event->signature()) == 0) { handle->invoke(event); } } - curr = curr->nextEntry; } } diff --git a/native/cocos/plugins/bus/EventBus.h b/native/cocos/plugins/bus/EventBus.h index 21c1b50af7..287c6cac94 100644 --- a/native/cocos/plugins/bus/EventBus.h +++ b/native/cocos/plugins/bus/EventBus.h @@ -126,18 +126,10 @@ constexpr void validateParameterTypes(const std::tuple * /*unused*/) { validateParameterType()...}; } -template -struct ListEntry { - ListEntry *prevEntry{nullptr}; - ListEntry *nextEntry{nullptr}; - T *prev() { return static_cast(prevEntry); } - T *next() { return static_cast(nextEntry); } -}; - class EventBus; struct EventCallbackBase; -class Listener : public ListEntry { +class Listener { public: explicit Listener(BusType type); Listener(BusType type, const char *name); @@ -165,7 +157,7 @@ class EventBus { public: static EventBus *acquire(BusType type); - EventBus(); + EventBus() = default; template void send(ARGS &&...args); @@ -174,14 +166,7 @@ private: void dispatch(EventBase *event); void addListener(Listener *); void removeListener(Listener *); - - union { - ListEntry _entry; - struct { - ListEntry *first{nullptr}; - ListEntry *last{nullptr}; - } _list; - }; + std::vector _listeners; friend class Listener; }; diff --git a/native/cocos/renderer/core/PassUtils.cpp b/native/cocos/renderer/core/PassUtils.cpp index 7c40f13240..b047ed5b82 100644 --- a/native/cocos/renderer/core/PassUtils.cpp +++ b/native/cocos/renderer/core/PassUtils.cpp @@ -179,6 +179,12 @@ const ccstd::unordered_map type2writer = { a[idx] = vec3.x; a[idx + 1] = vec3.y; a[idx + 2] = 0; + } else if (ccstd::holds_alternative(v)) { + const auto &color = ccstd::get(v); + Vec4 colorFloat{color.toVec4()}; + a[idx] = colorFloat.x; + a[idx + 1] = colorFloat.y; + a[idx + 2] = colorFloat.z; } else { CC_ASSERT(false); } diff --git a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h index 775010dab4..fd41ef9446 100644 --- a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h +++ b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h @@ -55,7 +55,7 @@ public: Texture *getTexture(uint32_t binding, uint32_t index) const; Sampler *getSampler(uint32_t binding, uint32_t index) const; - inline DescriptorSetLayout *getLayout() { return _layout; } + inline DescriptorSetLayout *getLayout() const { return _layout; } inline void bindBuffer(uint32_t binding, Buffer *buffer) { bindBuffer(binding, buffer, 0U); } inline void bindTexture(uint32_t binding, Texture *texture) { bindTexture(binding, texture, 0U); } diff --git a/native/cocos/renderer/gfx-wgpu/CMakeLists.txt b/native/cocos/renderer/gfx-wgpu/CMakeLists.txt index 1f0b450045..8083028fb4 100644 --- a/native/cocos/renderer/gfx-wgpu/CMakeLists.txt +++ b/native/cocos/renderer/gfx-wgpu/CMakeLists.txt @@ -11,15 +11,25 @@ set(ENGINE_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../../..) include(${ENGINE_ROOT_DIR}/cmake/predefine.cmake) -include (${ENGINE_ROOT_DIR}/external/CMakeLists.txt) +# include (${ENGINE_ROOT_DIR}/external/CMakeLists.txt) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wno-nonportable-include-path -fno-exceptions -v") -set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g3 -D_DEBUG=1 -Wno-unused -O0") -set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -g0 -DNDEBUG=1 -O3") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -Wextra -Wno-nonportable-include-path -fno-exceptions -v") +set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -g3 -D_DEBUG=1 -Wno-unused -O0 -std=c++17") +set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -w -DNDEBUG=1 -O3 -std=c++17") + +AUX_SOURCE_DIRECTORY( + ./states + WGPU_STATES_SRC +) AUX_SOURCE_DIRECTORY( . - WGPU_SRC + WGPU_IMPL_SRC +) + +set(WGPU_SRC + ${WGPU_STATES_SRC} + ${WGPU_IMPL_SRC} ) AUX_SOURCE_DIRECTORY( @@ -32,6 +42,7 @@ AUX_SOURCE_DIRECTORY( ../../../cocos/base COCOS_BASE ) +list(FILTER COCOS_BASE EXCLUDE REGEX "ZipUtils.*") AUX_SOURCE_DIRECTORY( ../../../cocos/renderer/gfx-base @@ -101,13 +112,14 @@ target_include_directories( ${CC_EXTERNAL_PRIVATE_INCLUDES} ) +# message(${WGPU_EMS_EXTERNAL_LIBS}) target_link_libraries( ${APP_NAME}_wasm PRIVATE PUBLIC - ${CC_EXTERNAL_LIBS} + # ${WGPU_EMS_EXTERNAL_LIBS} ) set(EMS_LINK_FLAGS -"--bind --no-entry -O3 -s USE_ES6_IMPORT_META=0 -s EXPORT_ES6=1 -s MODULARIZE=1 -s EXPORT_NAME='wasmDevice' -s ENVIRONMENT=web -s WASM=1 -s USE_WEBGPU=1 -s NO_EXIT_RUNTIME=1 -s LLD_REPORT_UNDEFINED -s ALLOW_MEMORY_GROWTH=1 -s ASSERTIONS=1 -s SAFE_HEAP -s WARN_UNALIGNED=1" +"-flto --bind --no-entry -O3 -s USE_ES6_IMPORT_META=0 -s EXPORT_ES6=1 -s MODULARIZE=1 -s EXPORT_NAME='wasmDevice' -s ENVIRONMENT=web -s WASM=1 -s USE_WEBGPU=1 -s NO_EXIT_RUNTIME=1 -s LLD_REPORT_UNDEFINED -s ALLOW_MEMORY_GROWTH=1" ) -set_target_properties(${APP_NAME}_wasm PROPERTIES LINK_FLAGS ${EMS_LINK_FLAGS}) \ No newline at end of file +set_target_properties(${APP_NAME}_wasm PROPERTIES CXX_STANDARD 17 LINK_FLAGS ${EMS_LINK_FLAGS}) diff --git a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp index 4a7ec4c0cf..5a6d5f4d1e 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp @@ -32,14 +32,18 @@ namespace cc { namespace gfx { -namespace anoymous { -CCWGPUBuffer *defaultUniformBuffer = nullptr; -CCWGPUBuffer *defaultStorageBuffer = nullptr; -} // namespace anoymous +namespace { +CCWGPUBuffer *dftUniformBuffer = nullptr; +CCWGPUBuffer *dftStorageBuffer = nullptr; +} // namespace using namespace emscripten; -CCWGPUBuffer::CCWGPUBuffer() : wrapper(val::object()) { +CCWGPUBuffer::CCWGPUBuffer() : Buffer() { +} + +CCWGPUBuffer::~CCWGPUBuffer() { + doDestroy(); } void CCWGPUBuffer::doInit(const BufferInfo &info) { @@ -58,7 +62,7 @@ void CCWGPUBuffer::doInit(const BufferInfo &info) { .label = nullptr, .usage = toWGPUBufferUsage(info.usage), .size = _size, - .mappedAtCreation = false, //hasFlag(info.memUsage, MemoryUsageBit::DEVICE), + .mappedAtCreation = false, // hasFlag(info.memUsage, MemoryUsageBit::DEVICE), }; _gpuBufferObject->mapped = descriptor.mappedAtCreation; @@ -72,6 +76,7 @@ void CCWGPUBuffer::doInit(const BufferInfo &info) { } _gpuBufferObject->wgpuBuffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + CCWGPUDevice::getInstance()->getMemoryStatus().bufferSize += _size; _internalChanged = true; } // namespace gfx @@ -83,10 +88,12 @@ void CCWGPUBuffer::doInit(const BufferViewInfo &info) { void CCWGPUBuffer::doDestroy() { if (_gpuBufferObject) { - if (_gpuBufferObject->wgpuBuffer) { - wgpuBufferDestroy(_gpuBufferObject->wgpuBuffer); + if (_gpuBufferObject->wgpuBuffer && !_isBufferView) { + CCWGPUDevice::getInstance()->moveToTrash(_gpuBufferObject->wgpuBuffer); + CCWGPUDevice::getInstance()->getMemoryStatus().bufferSize -= _size; } delete _gpuBufferObject; + _gpuBufferObject = nullptr; } _internalChanged = true; } @@ -97,8 +104,9 @@ void CCWGPUBuffer::doResize(uint32_t size, uint32_t count) { return; } if (_gpuBufferObject->wgpuBuffer) { - wgpuBufferDestroy(_gpuBufferObject->wgpuBuffer); + CCWGPUDevice::getInstance()->moveToTrash(_gpuBufferObject->wgpuBuffer); } + CCWGPUDevice::getInstance()->getMemoryStatus().bufferSize -= _size; if (hasFlag(_usage, BufferUsageBit::INDIRECT)) { const size_t drawInfoCount = _size / sizeof(DrawInfo); @@ -113,9 +121,10 @@ void CCWGPUBuffer::doResize(uint32_t size, uint32_t count) { .label = nullptr, .usage = toWGPUBufferUsage(_usage), .size = _size, - .mappedAtCreation = false, //hasFlag(_memUsage, MemoryUsageBit::DEVICE), + .mappedAtCreation = false, // hasFlag(_memUsage, MemoryUsageBit::DEVICE), }; _gpuBufferObject->wgpuBuffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + CCWGPUDevice::getInstance()->getMemoryStatus().bufferSize += _size; _internalChanged = true; } // namespace gfx @@ -161,7 +170,7 @@ void CCWGPUBuffer::update(const void *buffer, uint32_t size) { uint32_t alignedSize = ceil(size / 4.0) * 4; size_t buffSize = alignedSize; wgpuQueueWriteBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, _gpuBufferObject->wgpuBuffer, offset, buffer, buffSize); - //wgpuBufferUnmap(_gpuBufferObject->wgpuBuffer); + // wgpuBufferUnmap(_gpuBufferObject->wgpuBuffer); } void CCWGPUBuffer::update(const DrawInfoList &drawInfos) { @@ -170,7 +179,7 @@ void CCWGPUBuffer::update(const DrawInfoList &drawInfos) { void const *data = nullptr; size_t offset = _isBufferView ? _offset : 0; size_t buffSize = 0; - //if (hasFlag(_usage, BufferUsageBit::INDIRECT)) + // if (hasFlag(_usage, BufferUsageBit::INDIRECT)) if (drawInfos[0].indexCount) { auto &indexedIndirectObjs = _gpuBufferObject->indexedIndirectObjs; for (size_t i = 0; i < drawInfoCount; i++) { @@ -178,7 +187,7 @@ void CCWGPUBuffer::update(const DrawInfoList &drawInfos) { indexedIndirectObjs[i].instanceCount = drawInfos[i].instanceCount /* ? drawInfos[i]->instanceCoun : 1 */; indexedIndirectObjs[i].firstIndex = drawInfos[i].firstIndex; indexedIndirectObjs[i].baseVertex = drawInfos[i].vertexOffset; - indexedIndirectObjs[i].firstInstance = 0; //check definition of indexedIndirectObj; + indexedIndirectObjs[i].firstInstance = 0; // check definition of indexedIndirectObj; } data = indexedIndirectObjs.data(); buffSize = indexedIndirectObjs.size() * sizeof(CCWGPUDrawIndexedIndirectObject); @@ -209,31 +218,31 @@ void CCWGPUBuffer::stamp() { } CCWGPUBuffer *CCWGPUBuffer::defaultUniformBuffer() { - if (!anoymous::defaultUniformBuffer) { + if (!dftUniformBuffer) { BufferInfo info = { .usage = BufferUsageBit::UNIFORM, .memUsage = MemoryUsageBit::DEVICE, - .size = 4, + .size = 256, .flags = BufferFlagBit::NONE, }; - anoymous::defaultUniformBuffer = ccnew CCWGPUBuffer; - anoymous::defaultUniformBuffer->initialize(info); + dftUniformBuffer = ccnew CCWGPUBuffer; + dftUniformBuffer->initialize(info); } - return anoymous::defaultUniformBuffer; + return dftUniformBuffer; } CCWGPUBuffer *CCWGPUBuffer::defaultStorageBuffer() { - if (!anoymous::defaultStorageBuffer) { + if (!dftStorageBuffer) { BufferInfo info = { .usage = BufferUsageBit::STORAGE, .memUsage = MemoryUsageBit::DEVICE, - .size = 4, + .size = 256, .flags = BufferFlagBit::NONE, }; - anoymous::defaultStorageBuffer = ccnew CCWGPUBuffer; - anoymous::defaultStorageBuffer->initialize(info); + dftStorageBuffer = ccnew CCWGPUBuffer; + dftStorageBuffer->initialize(info); } - return anoymous::defaultStorageBuffer; + return dftStorageBuffer; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.h b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.h index fd18b64c0f..4cca467c19 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.h @@ -24,8 +24,9 @@ ****************************************************************************/ #pragma once -#include -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "base/std/container/vector.h" #include "gfx-base/GFXBuffer.h" @@ -34,37 +35,28 @@ namespace gfx { struct CCWGPUBufferObject; -class CCWGPUBuffer final : public emscripten::wrapper { +class CCWGPUBuffer final : public Buffer { public: - EMSCRIPTEN_WRAPPER(CCWGPUBuffer); CCWGPUBuffer(); - ~CCWGPUBuffer() = default; + ~CCWGPUBuffer(); + + inline CCWGPUBufferObject *gpuBufferObject() const { return _gpuBufferObject; } + inline uint32_t getOffset() const { return _offset; } + void update(const DrawInfoList &drawInfos); + // used before unmap? + void check(); + // stamp current resource handler + void stamp(); + // resource handler changed? + inline bool internalChanged() const { return _internalChanged; } + + static CCWGPUBuffer *defaultUniformBuffer(); + static CCWGPUBuffer *defaultStorageBuffer(); void update(const void *buffer, uint32_t size) override; - inline CCWGPUBufferObject *gpuBufferObject() const { return _gpuBufferObject; } - - static CCWGPUBuffer *defaultUniformBuffer(); - - static CCWGPUBuffer *defaultStorageBuffer(); - - inline uint32_t getOffset() const { return _offset; } - - void update(const emscripten::val &v, uint32_t size) { - ccstd::vector buffer = emscripten::convertJSArrayToNumberVector(v); - update(reinterpret_cast(buffer.data()), size); - } - - void update(const DrawInfoList &drawInfos); - - // used before unmap? - void check(); - - // stamp current resource handler - void stamp(); - - // resource handler changed? - inline bool internalChanged() const { return _internalChanged; } + EXPORT_EMS( + void update(const emscripten::val &v, uint32_t size);) protected: void doInit(const BufferInfo &info) override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp index e5bc63475c..3c3f53fd34 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp @@ -36,6 +36,7 @@ #include "WGPUPipelineLayout.h" #include "WGPUPipelineState.h" #include "WGPUQueue.h" +#include "WGPUShader.h" #include "WGPUSwapchain.h" #include "WGPUTexture.h" #include "WGPUUtils.h" @@ -45,15 +46,22 @@ namespace gfx { namespace { uint32_t dynamicOffsetBuffer[256]; +uint32_t dynBufferStartIndex = 0; +} // namespace + +CCWGPUCommandBuffer::CCWGPUCommandBuffer() : CommandBuffer() { } -CCWGPUCommandBuffer::CCWGPUCommandBuffer() : wrapper(val::object()) { +CCWGPUCommandBuffer::~CCWGPUCommandBuffer() { + doDestroy(); } - void CCWGPUCommandBuffer::doInit(const CommandBufferInfo &info) { _gpuCommandBufferObj = ccnew CCWGPUCommandBufferObject; _gpuCommandBufferObj->type = info.type; _gpuCommandBufferObj->queue = static_cast(info.queue); + _gpuCommandBufferObj->stateCache.descriptorSets.resize(4); //(info.queue->getDevice()->getMaxDescriptorSetLayoutBindings()); + memset(dynamicOffsetBuffer, 0, sizeof(dynamicOffsetBuffer)); + dynBufferStartIndex = 0; } void CCWGPUCommandBuffer::doDestroy() { @@ -64,31 +72,35 @@ void CCWGPUCommandBuffer::doDestroy() { delete pair.second; } } - CC_SAFE_DELETE(_gpuCommandBufferObj); + delete _gpuCommandBufferObj; + _gpuCommandBufferObj = nullptr; } } void CCWGPUCommandBuffer::begin(RenderPass * /*renderPass*/, uint32_t /*subpass*/, Framebuffer * /*frameBuffer*/) { - //TODO_Zeqiang: subpass support - // printf("begin\n"); + // TODO_Zeqiang: subpass support + // printf("begin\n"); + reset(); + + _numTriangles = 0; + _numDrawCalls = 0; + _numInstances = 0; + _gpuCommandBufferObj->wgpuCommandEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); } void CCWGPUCommandBuffer::end() { - // printf("end\n"); auto *pipelineState = _gpuCommandBufferObj->stateCache.pipelineState; if (pipelineState) { if (pipelineState->getBindPoint() == PipelineBindPoint::GRAPHICS) { auto *queue = _gpuCommandBufferObj->queue; - auto wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); - wgpuQueueSubmit(queue->gpuQueueObject()->wgpuQueue, 1, &wgpuCommandBuffer); + _gpuCommandBufferObj->wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); wgpuCommandEncoderRelease(_gpuCommandBufferObj->wgpuCommandEncoder); _gpuCommandBufferObj->wgpuCommandEncoder = wgpuDefaultHandle; } else { - wgpuComputePassEncoderEndPass(_gpuCommandBufferObj->wgpuComputeEncoder); + wgpuComputePassEncoderEnd(_gpuCommandBufferObj->wgpuComputeEncoder); wgpuComputePassEncoderRelease(_gpuCommandBufferObj->wgpuComputeEncoder); - auto wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); - wgpuQueueSubmit(static_cast(_queue)->gpuQueueObject()->wgpuQueue, 1, &wgpuCommandBuffer); + _gpuCommandBufferObj->wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); wgpuCommandEncoderRelease(_gpuCommandBufferObj->wgpuCommandEncoder); _gpuCommandBufferObj->wgpuComputeEncoder = wgpuDefaultHandle; _gpuCommandBufferObj->wgpuCommandEncoder = wgpuDefaultHandle; @@ -115,10 +127,10 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f renderPassDesc.label = "swapchain"; WGPURenderPassColorAttachment color = { .view = swapchain->gpuSwapchainObject()->swapchainColor->gpuTextureObject()->selfView, - .resolveTarget = nullptr, //TODO_Zeqiang: wgpu offscr msaa - .loadOp = WGPULoadOp_Clear, //toWGPULoadOp(colorConfigs[0].loadOp), - .storeOp = WGPUStoreOp_Discard, //toWGPUStoreOp(colorConfigs[0].storeOp), - .clearColor = WGPUColor{0.2, 0.2, 0.2, 1.0}, + .resolveTarget = nullptr, // TODO_Zeqiang: wgpu offscr msaa + .loadOp = WGPULoadOp_Clear, // toWGPULoadOp(colorConfigs[0].loadOp), + .storeOp = WGPUStoreOp_Discard, // toWGPUStoreOp(colorConfigs[0].storeOp), + .clearValue = WGPUColor{0.2, 0.2, 0.2, 1.0}, }; colorAttachments.emplace_back(color); } else { @@ -129,10 +141,10 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f WGPURenderPassColorAttachment *colorAttchments = ccnew WGPURenderPassColorAttachment[colorConfigs.size()]; WGPURenderPassColorAttachment color = { .view = static_cast(textures[i])->gpuTextureObject()->selfView, - .resolveTarget = nullptr, //TODO_Zeqiang: wgpu offscr msaa + .resolveTarget = nullptr, // TODO_Zeqiang: wgpu offscr msaa .loadOp = toWGPULoadOp(colorConfigs[i].loadOp), .storeOp = toWGPUStoreOp(colorConfigs[i].storeOp), - .clearColor = toWGPUColor(colors[i]), + .clearValue = toWGPUColor(colors[i]), }; colorAttachments.emplace_back(color); } @@ -142,13 +154,13 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f if (dsTexture) { WGPURenderPassDepthStencilAttachment depthStencil = { .view = static_cast(dsTexture)->gpuTextureObject()->selfView, - .depthLoadOp = WGPULoadOp_Clear, //toWGPULoadOp(depthStencilConfig.depthLoadOp), + .depthLoadOp = WGPULoadOp_Clear, // toWGPULoadOp(depthStencilConfig.depthLoadOp), .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), - .clearDepth = depth, + .depthClearValue = depth, .depthReadOnly = false, .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), - .clearStencil = stencil, + .stencilClearValue = stencil, .stencilReadOnly = false, }; depthStencils.emplace_back(depthStencil); @@ -158,13 +170,13 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f } else { WGPURenderPassDepthStencilAttachment depthStencil = { .view = swapchain->gpuSwapchainObject()->swapchainDepthStencil->gpuTextureObject()->selfView, - .depthLoadOp = WGPULoadOp_Clear, //toWGPULoadOp(depthStencilConfig.depthLoadOp), + .depthLoadOp = WGPULoadOp_Clear, // toWGPULoadOp(depthStencilConfig.depthLoadOp), .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), - .clearDepth = depth, + .depthClearValue = depth, .depthReadOnly = false, .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), - .clearStencil = stencil, + .stencilClearValue = stencil, .stencilReadOnly = false, }; depthStencils.emplace_back(depthStencil); @@ -184,11 +196,16 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f void CCWGPUCommandBuffer::endRenderPass() { // printf("endr\n"); - wgpuRenderPassEncoderEndPass(_gpuCommandBufferObj->wgpuRenderPassEncoder); + wgpuRenderPassEncoderEnd(_gpuCommandBufferObj->wgpuRenderPassEncoder); wgpuRenderPassEncoderRelease(_gpuCommandBufferObj->wgpuRenderPassEncoder); _gpuCommandBufferObj->wgpuRenderPassEncoder = wgpuDefaultHandle; - _gpuCommandBufferObj->stateCache.descriptorSets.clear(); + for (auto &descObj : _gpuCommandBufferObj->stateCache.descriptorSets) { + descObj.descriptorSet = nullptr; + descObj.dynamicOffsetCount = 0; + descObj.dynamicOffsets = nullptr; + dynBufferStartIndex = 0; + } _gpuCommandBufferObj->renderPassBegan = false; } @@ -200,28 +217,23 @@ void CCWGPUCommandBuffer::bindDescriptorSet(uint32_t set, DescriptorSet *descrip uint32_t dynOffsetCount = dynamicOffsetCount; const uint32_t *dynOffsets = dynamicOffsets; auto &descriptorSets = _gpuCommandBufferObj->stateCache.descriptorSets; - auto iter = std::find_if(descriptorSets.begin(), descriptorSets.end(), [set](const CCWGPUDescriptorSetObject &descriptorSet) { - return descriptorSet.index == set; - }); auto *ccDescriptorSet = static_cast(descriptorSet); if (ccDescriptorSet->dynamicOffsetCount() == 0) { - dynOffsetCount = 0; dynOffsets = nullptr; + } else { + memcpy(dynamicOffsetBuffer + dynBufferStartIndex, dynamicOffsets, sizeof(uint32_t) * dynamicOffsetCount); + dynOffsets = dynamicOffsetBuffer + dynBufferStartIndex; + dynBufferStartIndex += dynamicOffsetCount; } CCWGPUDescriptorSetObject dsObj = { - .index = set, .descriptorSet = ccDescriptorSet, - .dynamicOffsetCount = dynOffsetCount, //dynamicOffsetCount, - .dynamicOffsets = dynOffsets, //dynamicOffsets, + .dynamicOffsetCount = dynOffsetCount, // dynamicOffsetCount, + .dynamicOffsets = dynOffsets, // dynamicOffsets, }; - if (iter != descriptorSets.end()) { - (*iter) = dsObj; - } else { - descriptorSets.push_back(dsObj); - } + descriptorSets[set] = dsObj; } void CCWGPUCommandBuffer::bindInputAssembler(InputAssembler *ia) { @@ -271,89 +283,86 @@ void CCWGPUCommandBuffer::bindStates() { } ccstd::set setInUse; - for (const auto &descriptorSet : _gpuCommandBufferObj->stateCache.descriptorSets) { - setInUse.insert(descriptorSet.index); - } - // printf("ppl binding %p\n", pipelineState); - - // ccstd::vector wgpuLayouts; + auto *pipelineLayout = static_cast(pipelineState->layout()); + const auto &setLayouts = pipelineLayout->getSetLayouts(); + bool pipelineLayoutChanged = false; if (pipelineState->getBindPoint() == PipelineBindPoint::GRAPHICS) { - //bindgroup & descriptorset + // bindgroup & descriptorset const auto &descriptorSets = _gpuCommandBufferObj->stateCache.descriptorSets; - for (size_t i = 0; i < descriptorSets.size(); i++) { - descriptorSets[i].descriptorSet->prepare(); + for (size_t i = 0; i < setLayouts.size(); i++) { + if (descriptorSets[i].descriptorSet) { + descriptorSets[i].descriptorSet->prepare(); - if (descriptorSets[i].descriptorSet->dynamicOffsetCount() != descriptorSets[i].dynamicOffsetCount) { - uint32_t *dynOffsets = dynamicOffsetBuffer; - const Pairs &dynamicOffsets = descriptorSets[i].descriptorSet->dynamicOffsets(); - uint32_t givenOffsetIndex = 0; - for (size_t j = 0; j < descriptorSets[i].descriptorSet->dynamicOffsetCount(); ++j) { - if (j >= descriptorSets[i].dynamicOffsetCount || dynamicOffsets[j].second == 0) { - dynOffsets[j] = 0; - } else { - dynOffsets[j] = descriptorSets[i].dynamicOffsets[givenOffsetIndex++]; + if (descriptorSets[i].descriptorSet->dynamicOffsetCount() != descriptorSets[i].dynamicOffsetCount) { + uint32_t *dynOffsets = dynamicOffsetBuffer; + const Pairs &dynamicOffsets = descriptorSets[i].descriptorSet->dynamicOffsets(); + uint32_t givenOffsetIndex = 0; + for (size_t j = 0; j < descriptorSets[i].descriptorSet->dynamicOffsetCount(); ++j) { + if (j >= descriptorSets[i].dynamicOffsetCount || dynamicOffsets[j].second == 0) { + dynOffsets[j] = 0; + } else { + dynOffsets[j] = descriptorSets[i].dynamicOffsets[givenOffsetIndex++]; + } } - } - // printf("set %d %p %p\n", descriptorSets[i].index, descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, - // descriptorSets[i].descriptorSet->bgl()); - // wgpuLayouts.push_back(descriptorSets[i].descriptorSet->bgl()); - wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, - descriptorSets[i].index, - descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, - descriptorSets[i].descriptorSet->dynamicOffsetCount(), - dynOffsets); - - } else { - wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, - descriptorSets[i].index, - descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, - descriptorSets[i].dynamicOffsetCount, - descriptorSets[i].dynamicOffsets); - // printf("set %d %p %p\n", i, descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, - // descriptorSets[i].descriptorSet->bgl()); - // wgpuLayouts.push_back(descriptorSets[i].descriptorSet->bgl()); - } - } - - // missing - if (setInUse.size() != pipelineState->getPipelineLayout()->getSetLayouts().size()) { - const auto &setLayouts = pipelineState->getPipelineLayout()->getSetLayouts(); - for (size_t i = 0; i < setLayouts.size(); i++) { - if (setInUse.find(i) == setInUse.end()) { wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, i, - static_cast(CCWGPUDescriptorSet::defaultBindGroup()), - 0, - nullptr); - // printf("default %d %p\n", i, CCWGPUDescriptorSetLayout::defaultBindGroupLayout()); - // wgpuLayouts.push_back(CCWGPUDescriptorSetLayout::defaultBindGroupLayout()); + descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, + descriptorSets[i].descriptorSet->dynamicOffsetCount(), + dynOffsets); + setInUse.insert(i); + if (setLayouts[i] != descriptorSets[i].descriptorSet->getLayout()) { + pipelineLayoutChanged = true; + } + } else { + wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, + i, + descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, + descriptorSets[i].dynamicOffsetCount, + descriptorSets[i].dynamicOffsets); } + setInUse.insert(i); + } else { + // missing + wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, + i, + static_cast(CCWGPUDescriptorSet::defaultBindGroup()), + 0, + nullptr); } } - pipelineState->check(_renderPass); + + for (size_t i = 0; i < setLayouts.size(); i++) { + if (setInUse.find(i) == setInUse.end()) { + wgpuRenderPassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuRenderPassEncoder, + i, + static_cast(CCWGPUDescriptorSet::defaultBindGroup()), + 0, + nullptr); + } + } + + if (1) { + ccstd::vector dsSets; + for (size_t i = 0; i < setLayouts.size(); i++) { + dsSets.push_back(descriptorSets[i].descriptorSet); + } + createPipelineLayoutFallback(dsSets, pipelineLayout); + } else { + pipelineLayout->prepare(setInUse); + } + + pipelineState->check(_renderPass, 1); pipelineState->prepare(setInUse); - // printf("ppshn: %s\n", static_cast(pipelineState->getShader())->gpuShaderObject()->name.c_str()); - const auto &pplLayout = static_cast(pipelineState->ppl()); - // for(size_t i = 0; i < pplLayout->layouts().size(); ++i) { - // // printf("bgl in ppl: %p\n", pplLayout->layouts()[i]); - // if(pplLayout->layouts()[i] != wgpuLayouts[i]) { - // printf("oooooooooooops %d %p %p\n", i, pplLayout->layouts()[i], wgpuLayouts[i]); - // static_cast(descriptorSets[i].descriptorSet->getLayout())->print(); - // static_cast(pplLayout->getSetLayouts()[i])->print(); - // } - // } - // if(pipelineState->ppl() != pipelineState->getPipelineLayout()){ - // printf("oooooooooooooooooooooooooooooooops\n"); - // } - //pipeline state + + // pipeline state wgpuRenderPassEncoderSetPipeline(_gpuCommandBufferObj->wgpuRenderPassEncoder, pipelineState->gpuPipelineStateObject()->wgpuRenderPipeline); - //input assembler + // input assembler const auto *ia = _gpuCommandBufferObj->stateCache.inputAssembler; const auto &vertexBufferList = ia->getVertexBuffers(); for (size_t i = 0; i < vertexBufferList.size(); i++) { @@ -364,9 +373,9 @@ void CCWGPUCommandBuffer::bindStates() { vertexBuffer->getOffset(), vertexBuffer->getSize()); } - +#if 1 { - //redundantVertexBufferMap + // redundantVertexBufferMap const uint32_t maxAttrLen = pipelineState->gpuPipelineStateObject()->maxAttrLength; if (maxAttrLen != 0) { CCWGPUBuffer *buffer = nullptr; @@ -382,6 +391,7 @@ void CCWGPUCommandBuffer::bindStates() { buffer = ccnew CCWGPUBuffer; buffer->initialize(info); _gpuCommandBufferObj->redundantVertexBufferMap.insert({maxAttrLen, buffer}); + printf("new vert buffer\n"); } wgpuRenderPassEncoderSetVertexBuffer(_gpuCommandBufferObj->wgpuRenderPassEncoder, vertexBufferList.size(), @@ -390,7 +400,7 @@ void CCWGPUCommandBuffer::bindStates() { maxAttrLen); } } - +#endif const auto *indexBuffer = static_cast(ia->getIndexBuffer()); if (indexBuffer) { wgpuRenderPassEncoderSetIndexBuffer(_gpuCommandBufferObj->wgpuRenderPassEncoder, @@ -411,11 +421,8 @@ void CCWGPUCommandBuffer::bindStates() { for (size_t i = 0; i < textures.size(); i++) { rtWidth = rtWidth > textures[i]->getWidth() ? textures[i]->getWidth() : rtWidth; rtHeight = rtHeight > textures[i]->getHeight() ? textures[i]->getHeight() : rtHeight; - // printf("w, h %d %d\n", textures[i]->getWidth(), textures[i]->getHeight()); } - // printf("minrt %u, %u\n", rtWidth, rtHeight); - const Viewport &vp = _gpuCommandBufferObj->stateCache.viewport; uint32_t left = vp.left > 0 ? vp.left : 0; uint32_t top = vp.top > 0 ? vp.top : 0; @@ -425,7 +432,6 @@ void CCWGPUCommandBuffer::bindStates() { uint32_t height = vp.top > 0 ? vp.height : vp.height + vp.top; height = top + height > rtHeight ? rtHeight - top : height; - // printf("vp %u, %u, %u, %u\n", left, top, width, height); wgpuRenderPassEncoderSetViewport(_gpuCommandBufferObj->wgpuRenderPassEncoder, left, top, width, height, vp.minDepth, vp.maxDepth); const Rect &rect = _gpuCommandBufferObj->stateCache.rect; @@ -435,19 +441,18 @@ void CCWGPUCommandBuffer::bindStates() { width = left + width > rtWidth ? rtWidth - left : width; height = rect.y > 0 ? rect.height : rect.height + rect.y; height = top + height > rtHeight ? rtHeight - top : height; - // printf("sc %u, %u, %u, %u\n", left, top, width, height); wgpuRenderPassEncoderSetScissorRect(_gpuCommandBufferObj->wgpuRenderPassEncoder, left, top, width, height); wgpuRenderPassEncoderSetStencilReference(_gpuCommandBufferObj->wgpuRenderPassEncoder, pipelineState->getDepthStencilState().stencilRefFront); } else if (pipelineState->getBindPoint() == PipelineBindPoint::COMPUTE) { auto *pipelineState = _gpuCommandBufferObj->stateCache.pipelineState; - //bindgroup & descriptorset + // bindgroup & descriptorset const auto &descriptorSets = _gpuCommandBufferObj->stateCache.descriptorSets; for (size_t i = 0; i < descriptorSets.size(); i++) { if (descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup) { wgpuComputePassEncoderSetBindGroup(_gpuCommandBufferObj->wgpuComputeEncoder, - descriptorSets[i].index, + i, descriptorSets[i].descriptorSet->gpuBindGroupObject()->bindgroup, descriptorSets[i].dynamicOffsetCount, descriptorSets[i].dynamicOffsets); @@ -481,7 +486,7 @@ void CCWGPUCommandBuffer::draw(const DrawInfo &info) { // todo } else { if (info.indexCount) { - //indexedIndirect not supported, emsdk 2.0.26 + // indexedIndirect not supported, emsdk 2.0.26 uint32_t drawInfoCount = indirectBuffer->getCount(); // for (size_t i = 0; i < drawInfoCount; i++) { // wgpuRenderPassEncoderDrawIndexedIndirect(_gpuCommandBufferObj->wgpuRenderPassEncoder, @@ -507,21 +512,38 @@ void CCWGPUCommandBuffer::draw(const DrawInfo &info) { } else { auto *indexBuffer = static_cast(ia->getIndexBuffer()); bool drawIndexed = indexBuffer && info.indexCount; + uint32_t instanceCount = std::max(info.instanceCount, 1U); if (drawIndexed) { wgpuRenderPassEncoderDrawIndexed(_gpuCommandBufferObj->wgpuRenderPassEncoder, info.indexCount, - info.instanceCount > 1 ? info.instanceCount : 1, + instanceCount, info.firstIndex, info.vertexOffset, info.firstInstance); } else { wgpuRenderPassEncoderDraw(_gpuCommandBufferObj->wgpuRenderPassEncoder, info.vertexCount, - info.instanceCount > 1 ? info.instanceCount : 1, + instanceCount, info.firstVertex, info.firstInstance); } + + ++_numDrawCalls; + _numInstances += info.instanceCount; + if (_gpuCommandBufferObj->stateCache.pipelineState) { + uint32_t indexCount = drawIndexed ? info.indexCount : info.vertexCount; + switch (_gpuCommandBufferObj->stateCache.pipelineState->getPrimitive()) { + case PrimitiveMode::TRIANGLE_LIST: + _numTriangles += indexCount / 3 * instanceCount; + break; + case PrimitiveMode::TRIANGLE_STRIP: + case PrimitiveMode::TRIANGLE_FAN: + _numTriangles += (indexCount - 2) * instanceCount; + break; + default: break; + } + } } } @@ -554,47 +576,131 @@ void CCWGPUCommandBuffer::updateBuffer(Buffer *buff, const void *data, uint32_t wgpuCommandEncoderCopyBufferToBuffer(cmdEncoder, stagingBuffer, 0, bufferObj->wgpuBuffer, offset, alignedSize); WGPUCommandBuffer commandBuffer = wgpuCommandEncoderFinish(cmdEncoder, nullptr); wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &commandBuffer); - wgpuBufferRelease(stagingBuffer); wgpuCommandEncoderRelease(cmdEncoder); wgpuCommandBufferRelease(commandBuffer); } + CCWGPUDevice::getInstance()->moveToTrash(stagingBuffer); } - +// WGPU_EXPORT void wgpuCommandEncoderCopyBufferToTexture(WGPUCommandEncoder commandEncoder, WGPUImageCopyBuffer const * source, WGPUImageCopyTexture const * destination, WGPUExtent3D const * copySize); void CCWGPUCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) { + auto encoder = _gpuCommandBufferObj->wgpuCommandEncoder; + if (!encoder) { + WGPUCommandEncoder cmdEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); + } + + Format dstFormat = texture->getFormat(); + auto wgpuDevice = CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice; + auto *ccTexture = static_cast(texture); + auto blockSize = formatAlignment(dstFormat); + + if (ccTexture->isTextureView()) { + ccTexture = static_cast(ccTexture->getViewInfo().texture); + } + for (size_t i = 0; i < count; i++) { - WGPUOrigin3D origin = { - .x = static_cast(regions[i].texOffset.x), - .y = static_cast(regions[i].texOffset.y), - .z = static_cast(regions[i].texOffset.z), + const auto ®ion = regions[i]; + auto bufferPixelWidth = region.buffStride > 0 ? region.buffStride : region.texExtent.width; + auto bufferPixelHeight = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; + auto bytesPerRow = formatSize(dstFormat, region.texExtent.width, 1, 1); + auto bufferBytesPerRow = formatSize(dstFormat, bufferPixelWidth, 1, 1); + auto bufferBytesPerImageSlice = formatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, 1); + auto bufferBytesPerImageLayer = formatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, region.texExtent.depth); + auto targetWidth = region.texExtent.width == 0 ? 0 : utils::alignTo(region.texExtent.width, blockSize.first); + auto targetHeight = region.texExtent.height == 0 ? 0 : utils::alignTo(region.texExtent.height, blockSize.second); + + // it's buffer data layout + WGPUTextureDataLayout texDataLayout = { + .offset = 0, // we always create a non-offset staging buffer or give interface a non-offset buffer address + .bytesPerRow = bufferBytesPerRow, + .rowsPerImage = bufferPixelHeight, }; - WGPUImageCopyTexture imageCopyTexture = { - .texture = static_cast(texture)->gpuTextureObject()->wgpuTexture, - .mipLevel = 0, - .origin = origin, - .aspect = WGPUTextureAspect_All, - }; + bool compactInWidth = bufferPixelWidth == region.texExtent.width; + for (size_t l = region.texSubres.baseArrayLayer; l < region.texSubres.layerCount + region.texSubres.baseArrayLayer; ++l) { + for (size_t d = region.texOffset.z; d < region.texExtent.depth + region.texOffset.z; ++d) { + if (compactInWidth) { + auto *srcData = buffers[i] + region.buffOffset + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + (d - region.texOffset.z) * bufferBytesPerImageSlice; + WGPUImageCopyTexture imageCopyTexture = { + .texture = ccTexture->gpuTextureObject()->wgpuTexture, + .mipLevel = region.texSubres.mipLevel, + .origin = WGPUOrigin3D{ + static_cast(region.texOffset.x), + static_cast(region.texOffset.y), + static_cast(d)}, + .aspect = WGPUTextureAspect_All, + }; - auto *ccTex = static_cast(texture); - uint32_t width = regions[i].texExtent.width; - uint32_t height = regions[i].texExtent.height; - uint32_t depth = regions[i].texExtent.depth; - uint32_t bytesPerRow = GFX_FORMAT_INFOS[static_cast(ccTex->getFormat())].size * width; - uint32_t dataSize = bytesPerRow * height * depth; + WGPUExtent3D extent = { + .width = targetWidth, + .height = targetHeight, + .depthOrArrayLayers = 1, + }; - WGPUTextureDataLayout texLayout = { - .offset = 0, - .bytesPerRow = bytesPerRow, - .rowsPerImage = height, - }; + WGPUBufferDescriptor bufferDesc = { + .usage = WGPUBufferUsage_CopySrc, + .size = bufferBytesPerImageSlice, + .mappedAtCreation = true, + }; - WGPUExtent3D extent = { - .width = width, - .height = height, - .depthOrArrayLayers = depth, - }; + auto stagingBuffer = wgpuDeviceCreateBuffer(wgpuDevice, &bufferDesc); + auto *mappedBuffer = wgpuBufferGetMappedRange(stagingBuffer, 0, bufferBytesPerImageSlice); + memcpy(mappedBuffer, buffers[i], bufferBytesPerImageSlice); + wgpuBufferUnmap(static_cast(stagingBuffer)); - wgpuQueueWriteTexture(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, &imageCopyTexture, buffers[i], dataSize, &texLayout, &extent); + WGPUImageCopyBuffer imageCopyBuffer = { + .layout = texDataLayout, + .buffer = stagingBuffer, + }; + wgpuCommandEncoderCopyBufferToTexture(encoder, &imageCopyBuffer, &imageCopyTexture, &extent); + CCWGPUDevice::getInstance()->moveToTrash(stagingBuffer); + } else { + for (size_t h = region.texOffset.y; h < region.texExtent.height + region.texOffset.y; h += blockSize.second) { + auto *srcData = buffers[i] + region.buffOffset + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + (d - region.texOffset.z) * bufferBytesPerImageSlice + + (h - region.texOffset.y) / blockSize.second * bufferBytesPerRow; + WGPUImageCopyTexture imageCopyTexture = { + .texture = ccTexture->gpuTextureObject()->wgpuTexture, + .mipLevel = region.texSubres.mipLevel, + .origin = WGPUOrigin3D{ + static_cast(region.texOffset.x), + static_cast(h), + static_cast(d)}, + .aspect = WGPUTextureAspect_All, + }; + + WGPUExtent3D extent = { + .width = targetWidth, + .height = blockSize.second, + .depthOrArrayLayers = 1, + }; + + WGPUBufferDescriptor bufferDesc = { + .usage = WGPUBufferUsage_CopySrc, + .size = bytesPerRow, + .mappedAtCreation = true, + }; + + auto stagingBuffer = wgpuDeviceCreateBuffer(wgpuDevice, &bufferDesc); + auto *mappedBuffer = wgpuBufferGetMappedRange(stagingBuffer, 0, bytesPerRow); + memcpy(mappedBuffer, buffers[i], bytesPerRow); + wgpuBufferUnmap(static_cast(stagingBuffer)); + + WGPUImageCopyBuffer imageCopyBuffer = { + .layout = texDataLayout, + .buffer = stagingBuffer, + }; + wgpuCommandEncoderCopyBufferToTexture(encoder, &imageCopyBuffer, &imageCopyTexture, &extent); + CCWGPUDevice::getInstance()->moveToTrash(stagingBuffer); + } + } + } + } + } + + if (!_gpuCommandBufferObj->wgpuCommandEncoder) { + WGPUCommandBuffer commandBuffer = wgpuCommandEncoderFinish(encoder, nullptr); + wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &commandBuffer); + wgpuCommandEncoderRelease(encoder); + wgpuCommandBufferRelease(commandBuffer); } } @@ -640,7 +746,7 @@ void CCWGPUCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, } void CCWGPUCommandBuffer::execute(CommandBuffer *const * /*cmdBuffs*/, uint32_t /*count*/) { - printf("....."); + printf(".....\n"); } void CCWGPUCommandBuffer::dispatch(const DispatchInfo &info) { @@ -651,24 +757,35 @@ void CCWGPUCommandBuffer::dispatch(const DispatchInfo &info) { if (info.indirectBuffer) { auto *indirectBuffer = static_cast(info.indirectBuffer); - wgpuComputePassEncoderDispatchIndirect(_gpuCommandBufferObj->wgpuComputeEncoder, - indirectBuffer->gpuBufferObject()->wgpuBuffer, - info.indirectOffset); + wgpuComputePassEncoderDispatchWorkgroupsIndirect(_gpuCommandBufferObj->wgpuComputeEncoder, + indirectBuffer->gpuBufferObject()->wgpuBuffer, + info.indirectOffset); } else { - wgpuComputePassEncoderDispatch(_gpuCommandBufferObj->wgpuComputeEncoder, - info.groupCountX, - info.groupCountY, - info.groupCountZ); + wgpuComputePassEncoderDispatchWorkgroups(_gpuCommandBufferObj->wgpuComputeEncoder, + info.groupCountX, + info.groupCountY, + info.groupCountZ); } } -void CCWGPUCommandBuffer::pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) { +void CCWGPUCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) { } void CCWGPUCommandBuffer::updateIndirectBuffer(Buffer *buffer, const DrawInfoList &list) { buffer->update(list.data(), 0); // indirectBuffer calc size inside. } +void CCWGPUCommandBuffer::reset() { + _gpuCommandBufferObj->renderPassBegan = false; + + _gpuCommandBufferObj->wgpuCommandBuffer = wgpuDefaultHandle; + _gpuCommandBufferObj->wgpuCommandEncoder = wgpuDefaultHandle; + _gpuCommandBufferObj->wgpuRenderPassEncoder = wgpuDefaultHandle; + _gpuCommandBufferObj->wgpuComputeEncoder = wgpuDefaultHandle; + + CCWGPUStateCache stateCache = {}; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h index c12794a271..01e7dcff64 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h @@ -24,8 +24,9 @@ ****************************************************************************/ #pragma once -#include -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include #include "base/std/container/vector.h" #include "gfx-base/GFXCommandBuffer.h" @@ -37,11 +38,10 @@ struct CCWGPUCommandBufferObject; typedef std::function EncodeFunc; -class CCWGPUCommandBuffer final : public emscripten::wrapper { +class CCWGPUCommandBuffer final : public CommandBuffer { public: - EMSCRIPTEN_WRAPPER(CCWGPUCommandBuffer); CCWGPUCommandBuffer(); - ~CCWGPUCommandBuffer() = default; + ~CCWGPUCommandBuffer(); void begin(RenderPass *renderPass, uint32_t subpass, Framebuffer *frameBuffer) override; void end() override; @@ -65,27 +65,32 @@ public: void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; - void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; + void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; - //TODO_Zeqiang: wgpu query pool + // TODO_Zeqiang: wgpu query pool void beginQuery(QueryPool *queryPool, uint32_t id) override{}; void endQuery(QueryPool *queryPool, uint32_t id) override{}; void resetQueryPool(QueryPool *queryPool) override{}; void completeQueryPool(QueryPool *queryPool) override{}; - inline CCWGPUCommandBufferObject *gpuCommandBufferObject() { return _gpuCommandBufferObj; } + inline CCWGPUCommandBufferObject *gpuCommandBufferObject() const { return _gpuCommandBufferObj; } void updateIndirectBuffer(Buffer *buffer, const DrawInfoList &list); - void updateBuffer(Buffer *buff, const emscripten::val &v, uint32_t size) { - ccstd::vector buffer = emscripten::convertJSArrayToNumberVector(v); - updateBuffer(buff, reinterpret_cast(buffer.data()), size); - } - void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const ColorList &colors, float depth, uint32_t stencil) { this->CommandBuffer::beginRenderPass(renderPass, fbo, renderArea, colors.data(), depth, stencil); } + void reset(); + + void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, const std::vector &dynamicOffsets) { + bindDescriptorSet(set, descriptorSet, dynamicOffsets.size(), dynamicOffsets.data()); + } + + // emscripten export + EXPORT_EMS( + void updateBuffer(Buffer *buff, const emscripten::val &v, uint32_t size);) + protected: virtual void doInit(const CommandBufferInfo &info); virtual void doDestroy(); @@ -99,8 +104,8 @@ protected: Framebuffer *_frameBuffer = nullptr; // command buffer inner impl - //std::queue _renderPassFuncQ; - //std::queue _computeFuncQ; + // std::queue _renderPassFuncQ; + // std::queue _computeFuncQ; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDef.h b/native/cocos/renderer/gfx-wgpu/WGPUDef.h index 775756a8b7..a04a735396 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDef.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDef.h @@ -1,321 +1,219 @@ #pragma once +#include #include +#include +#include +#include +#include +#include #include "../gfx-base/GFXDef-common.h" -#include "base/std/container/vector.h" +#include "../gfx-base/GFXDef.h" -namespace cc { -namespace gfx { +#ifdef CC_WGPU_WASM + #define EXPORT_EMS(expr) expr +#else + #define EXPORT_EMS(expr) +#endif -//emscripten export struct with pointers. -class TextureInfoInstance { -public: - TextureInfoInstance() = default; +#ifdef CC_WGPU_DAWN + #define EXPORT_DAWN(expr) expr +#else + #define EXPORT_DAWN(expr) +#endif - inline void setType(TextureType type) { info.type = type; } - inline void setUsage(uint32_t usageIn) { - TextureUsage usage = TextureUsageBit::NONE; - if (hasFlag(static_cast(usageIn), TextureUsageBit::TRANSFER_SRC)) { - usage |= TextureUsageBit::TRANSFER_SRC; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::TRANSFER_DST)) { - usage |= TextureUsageBit::TRANSFER_DST; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::SAMPLED)) { - usage |= TextureUsageBit::SAMPLED; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::STORAGE)) { - usage |= TextureUsageBit::STORAGE; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::COLOR_ATTACHMENT)) { - usage |= TextureUsageBit::COLOR_ATTACHMENT; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::DEPTH_STENCIL_ATTACHMENT)) { - usage |= TextureUsageBit::DEPTH_STENCIL_ATTACHMENT; - } - if (hasFlag(static_cast(usageIn), TextureUsageBit::INPUT_ATTACHMENT)) { - usage |= TextureUsageBit::INPUT_ATTACHMENT; - } - info.usage = usage; +#ifdef CC_WGPU_RS + #define EXPORT_RS(expr) expr +#else + #define EXPORT_RS(expr) +#endif + +// https://github.com/emscripten-core/emscripten/issues/11070#issuecomment-717675128 +namespace emscripten { + +template +std::vector vecFromEMS(const val &vals) { + uint32_t len = vals["length"].as(); + std::vector res(len); + const std::vector Ts = vecFromJSArray(vals); + for (size_t i = 0; i < len; ++i) { + const val &t = Ts[i]; + res[i] = static_cast(t.as(allow_raw_pointers())); } - inline void setFormat(Format format) { info.format = format; } - inline void setWidth(uint32_t width) { info.width = width; } - inline void setHeight(uint32_t height) { info.height = height; } - inline void setFlags(uint32_t flagsIn) { - TextureFlags flags = TextureFlagBit::NONE; + return res; +} - if (hasFlag(static_cast(flagsIn), TextureFlagBit::GEN_MIPMAP)) { - flags |= TextureFlagBit::GEN_MIPMAP; - } - if (hasFlag(static_cast(flagsIn), TextureFlagBit::GENERAL_LAYOUT)) { - flags |= TextureFlagBit::GENERAL_LAYOUT; - } - - info.flags = flags; +template +val vecToEMS(const std::vector &Ts) { + auto arr = val::array(); + for (size_t i = 0; i < Ts.size(); ++i) { + arr.set(i, TWrapper(Ts[i])); } - inline void setLevelCount(uint32_t levelCount) { info.levelCount = levelCount; } - inline void setLayerCount(uint32_t layerCount) { info.layerCount = layerCount; } - inline void setSamples(SampleCount sample) { info.samples = sample; } - inline void setDepth(uint32_t depth) { info.depth = depth; } - inline void setImageBuffer(intptr_t imgBuff) { info.externalRes = reinterpret_cast(imgBuff); } + return arr; +} - explicit operator const TextureInfo() const { return info; } +// template ::value, bool>::type = true> +// std::vector ptrVecFromEMS(const val& vals) { +// uint32_t len = vals["length"].as(); +// std::vector res(len); +// const std::vector Ts = vecFromJSArray(vals); +// for (size_t i = 0; i < len; ++i) { +// const val& t = Ts[i]; +// t.as(emscripten::allow_raw_pointers()); +// res[i] = reinterpret_cast(t.as()); +// } +// return res; +// } -private: - TextureInfo info; -}; - -class TextureViewInfoInstance { -public: - TextureViewInfoInstance() = default; - - inline void setTexture(Texture *tex) { info.texture = tex; } - inline void setType(TextureType type) { info.type = type; } - inline void setFormat(Format format) { info.format = format; } - inline void setBaseLevel(uint32_t baseLevel) { info.baseLevel = baseLevel; } - inline void setLevelCount(uint32_t levelCount) { info.levelCount = levelCount; } - inline void setBaseLayer(uint32_t baseLayer) { info.baseLayer = baseLayer; } - inline void setLayerCount(uint32_t layerCount) { info.layerCount = layerCount; } - - explicit operator const TextureViewInfo() const { return info; } - -private: - TextureViewInfo info; -}; - -class SwapchainInfoInstance { -public: - SwapchainInfoInstance() = default; - - inline void setWindowHandle(uintptr_t hwnd) { info.windowHandle = reinterpret_cast(hwnd); } - inline void setVsyncMode(VsyncMode mode) { info.vsyncMode = mode; } - inline void setWidth(uint32_t width) { info.width = width; } - inline void setHeight(uint32_t height) { info.height = height; } - - explicit operator const SwapchainInfo() const { return info; } - -private: - SwapchainInfo info; -}; - -class FramebufferInfoInstance { -public: - FramebufferInfoInstance() = default; - - inline void setRenderPass(RenderPass *renderPass) { info.renderPass = renderPass; } - inline void setColorTextures(TextureList colors) { info.colorTextures = colors; } - inline void setDepthStencilTexture(Texture *tex) { info.depthStencilTexture = tex; } - - explicit operator const FramebufferInfo() const { return info; } - -private: - FramebufferInfo info; -}; - -class BufferViewInfoInstance { -public: - BufferViewInfoInstance() = default; - - inline void setBuffer(Buffer *buffer) { info.buffer = buffer; } - inline void setOffset(uint32_t offset) { info.offset = offset; } - inline void setRange(uint32_t range) { info.range = range; } - - explicit operator const BufferViewInfo() const { return info; } - -private: - BufferViewInfo info; -}; - -class DescriptorSetInfoInstance { -public: - DescriptorSetInfoInstance() = default; - inline void setDescriptorSetLayout(DescriptorSetLayout *layout) { info.layout = layout; } - - explicit operator const DescriptorSetInfo() const { return info; } - -private: - DescriptorSetInfo info; -}; - -class PipelineStateInfoInstance { -public: - inline void setShader(Shader *shader) { info.shader = shader; } - inline void setPipelineLayout(PipelineLayout *pipelineLayout) { info.pipelineLayout = pipelineLayout; } - inline void setRenderPass(RenderPass *renderPass) { info.renderPass = renderPass; } - inline void setInputState(InputState inputState) { info.inputState = inputState; } - inline void setRasterizerState(RasterizerState rasterizerState) { info.rasterizerState = rasterizerState; } - inline void setDepthStencilState(DepthStencilState depthStencilState) { info.depthStencilState = depthStencilState; } - inline void setBlendState(BlendState blendState) { info.blendState = blendState; } - inline void setPrimitiveMode(PrimitiveMode primitive) { info.primitive = primitive; } - inline void setDynamicStateFlags(DynamicStateFlagBit dynamicStates) { info.dynamicStates = dynamicStates; } - inline void setPipelineBindPoint(PipelineBindPoint bindPoint) { info.bindPoint = bindPoint; } - inline void setSubpass(uint32_t subpass) { info.subpass = subpass; } - - explicit operator const PipelineStateInfo() const { return info; } - -private: - PipelineStateInfo info; -}; - -class InputAssemblerInfoInstance { -public: - inline void setAttributes(AttributeList attributes) { info.attributes = attributes; } - inline void setBuffers(BufferList buffers) { info.vertexBuffers = buffers; } - inline void setIndexBuffer(Buffer *buffer) { info.indexBuffer = buffer; } - inline void setIndirectBuffer(Buffer *buffer) { info.indirectBuffer = buffer; } - - explicit operator const InputAssemblerInfo() const { return info; } - -private: - InputAssemblerInfo info; -}; - -class CommandBufferInfoInstance { -public: - inline void setQueue(Queue *q) { info.queue = q; } - inline void setType(CommandBufferType type) { info.type = type; } - - explicit operator const CommandBufferInfo() const { return info; } - -private: - CommandBufferInfo info; -}; - -class DispatchInfoInstance { -public: - inline void setGroupCountX(uint32_t groupCountX) { info.groupCountX = groupCountX; } - inline void setGroupCountY(uint32_t groupCountY) { info.groupCountY = groupCountY; } - inline void setGroupCountZ(uint32_t groupCountZ) { info.groupCountZ = groupCountZ; } - inline void setIndirectBuffer(Buffer *indirectBuffer) { info.indirectBuffer = indirectBuffer; } - inline void setIndirectOffset(uint32_t offset) { info.indirectOffset = offset; } - - explicit operator const DispatchInfo() const { return info; } - -private: - DispatchInfo info; -}; - -class SPVShaderStageInstance { -public: - ShaderStageFlagBit stage{ShaderStageFlagBit::NONE}; - ccstd::vector spv; - - inline void setStage(ShaderStageFlagBit stageIn) { stage = stageIn; } - inline void setSPVData(const emscripten::val &v) { spv = emscripten::convertJSArrayToNumberVector(v); } -}; - -class SPVShaderInfoInstance { -public: - inline void setName(ccstd::string name) { info.name = name; } - inline void setAttributes(AttributeList attrs) { info.attributes = attrs; } - inline void setStages(ccstd::vector spvStages) { stages = spvStages; } - inline void setBlocks(UniformBlockList blocks) { info.blocks = blocks; } - inline void setBuffers(UniformStorageBufferList buffers) { info.buffers = buffers; } - inline void setSamplerTextures(UniformSamplerTextureList list) { info.samplerTextures = list; } - inline void setTextures(UniformTextureList textures) { info.textures = textures; } - inline void setSamplers(UniformSamplerList samplers) { info.samplers = samplers; } - inline void setImages(UniformStorageImageList images) { info.images = images; } - inline void setSubpasses(UniformInputAttachmentList subpassInputs) { info.subpassInputs = subpassInputs; } - - ShaderInfo info; - ccstd::vector stages; -}; - -class DescriptorSetLayoutBindingInstance { -public: - inline void setBinding(uint32_t binding) { info.binding = binding; } - inline void setDescriptorType(DescriptorType descriptorType) { info.descriptorType = descriptorType; } - inline void setCount(uint32_t count) { info.count = count; } - inline void setStageFlags(uint32_t stageFlags) { - ShaderStageFlags flag = ShaderStageFlagBit::NONE; - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::VERTEX)) { - flag |= ShaderStageFlagBit::VERTEX; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::CONTROL)) { - flag |= ShaderStageFlagBit::CONTROL; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::EVALUATION)) { - flag |= ShaderStageFlagBit::EVALUATION; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::GEOMETRY)) { - flag |= ShaderStageFlagBit::GEOMETRY; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::FRAGMENT)) { - flag |= ShaderStageFlagBit::FRAGMENT; - } - if (hasFlag(static_cast(stageFlags), ShaderStageFlagBit::COMPUTE)) { - flag |= ShaderStageFlagBit::COMPUTE; - } - info.stageFlags = flag; +template ::value, bool>::type = true> +val ptrVecToEMS(const std::vector &Ts) { + auto arr = val::array(); + for (size_t i = 0; i < Ts.size(); ++i) { + arr.set(i, Ts[i]); } - inline void setImmutableSamplers(SamplerList immutableSamplers) { info.immutableSamplers = immutableSamplers; } + return arr; +} - explicit operator const DescriptorSetLayoutBinding() const { return info; } +namespace internal { -private: - DescriptorSetLayoutBinding info; -}; +// vector -> [] & [] ->vector +template +struct BindingType> { + using ValBinding = BindingType; + using WireType = ValBinding::WireType; -class DescriptorSetLayoutInfoInstance { -public: - inline void setBindings(ccstd::vector bindings) { info.bindings = ccstd::vector(bindings.begin(), bindings.end()); } - - explicit operator const DescriptorSetLayoutInfo() const { return info; } - -private: - DescriptorSetLayoutInfo info; -}; - -class BufferInfoInstance { -public: - inline void setUsage(uint32_t usageIn) { - BufferUsage usage = BufferUsageBit::NONE; - if (hasFlag(static_cast(usageIn), BufferUsageBit::TRANSFER_SRC)) { - usage |= BufferUsageBit::TRANSFER_SRC; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::TRANSFER_DST)) { - usage |= BufferUsageBit::TRANSFER_DST; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::INDEX)) { - usage |= BufferUsageBit::INDEX; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::VERTEX)) { - usage |= BufferUsageBit::VERTEX; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::UNIFORM)) { - usage |= BufferUsageBit::UNIFORM; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::STORAGE)) { - usage |= BufferUsageBit::STORAGE; - } - if (hasFlag(static_cast(usageIn), BufferUsageBit::INDIRECT)) { - usage |= BufferUsageBit::INDIRECT; - } - - info.usage = usage; - } - inline void setMemUsage(uint32_t memUsageIn) { - MemoryUsage memUsage = MemoryUsageBit::NONE; - if (hasFlag(static_cast(memUsageIn), MemoryUsageBit::DEVICE)) { - memUsage |= MemoryUsageBit::DEVICE; - } - if (hasFlag(static_cast(memUsageIn), MemoryUsageBit::HOST)) { - memUsage |= MemoryUsageBit::HOST; - } - info.memUsage = memUsage; - } - inline void setSize(uint32_t size) { info.size = size; } - inline void setStride(uint32_t stride) { info.stride = stride; } - inline void setFlags(uint32_t flagsIn) { - BufferFlags flags = BufferFlagBit::NONE; - - info.flags = static_cast(flagsIn); + static WireType toWireType(const std::vector &vec) { + return ValBinding::toWireType(vecToEMS(vec)); } - explicit operator const BufferInfo() const { return info; } - -private: - BufferInfo info; + static std::vector fromWireType(WireType value) { + return vecFromJSArray(ValBinding::fromWireType(value), allow_raw_pointers()); + } }; -} // namespace gfx -} // namespace cc +template +struct TypeID::type, + std::vector::type::value_type, + typename Canonicalized::type::allocator_type>>::value>> { + static constexpr TYPEID get() { return TypeID::get(); } +}; + +} // namespace internal +} // namespace emscripten + +template +struct GenInstance { + static T instance() { + return T(); + } +}; + +template +R getMemberType(R T::*); + +#define MEMBER_TYPE(prop) decltype(getMemberType(prop)) + +template +struct Exporter { + Exporter(T &t, const char *propName, U V::*field, bool ignorePtrAssert = false) { + t.field(propName, field); + } +}; + +template +struct Exporter::value>::type> { + Exporter(T &t, const char *propName, U V::*field, bool ignorePtrAssert = false) { + std::function u)> set = [field](V &v, std::underlying_type_t u) { + v.*field = U{u}; + }; + std::function(const V &v)> get = [field](const V &v) { + return static_cast>(v.*field); + }; + t.field(propName, get, set); + } +}; + +template +struct Exporter::value>::type> { + Exporter(T &t, const char *propName, U V::*field) { + static_assert(!std::is_pointer::value, "Export pointer with struct, try EXPORT_STRUCT_NPOD!"); + } + + Exporter(T &t, const char *propName, U V::*field, bool ignorePtrAssert) { + t.field(propName, field); + } +}; + +#define PROCESS_STRUCT_MEMBERS(r, struct_name, property) \ + { Exporter exporter(obj, BOOST_PP_STRINGIZE(property), &struct_name::property); } + +#define EXPORT_STRUCT_POD(struct_name, ...) \ + { \ + auto obj = value_object(#struct_name); \ + BOOST_PP_SEQ_FOR_EACH(PROCESS_STRUCT_MEMBERS, struct_name, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#define PROCESS_STRUCT_MEMBERS_MAY_BE_PTR(r, struct_name, property) \ + { Exporter exporter(obj, BOOST_PP_STRINGIZE(property), &struct_name::property, true); } + +#define EXPORT_STRUCT_NPOD(struct_name, ...) \ + { \ + auto obj = value_object(#struct_name); \ + BOOST_PP_SEQ_FOR_EACH(PROCESS_STRUCT_MEMBERS_MAY_BE_PTR, struct_name, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#define SPECIALIZE_PTR_FOR_STRUCT(r, _, TYPE) \ + template <> \ + struct emscripten::internal::TypeID::type *, void> { \ + static constexpr emscripten::internal::TYPEID get() { return emscripten::internal::TypeID>::get(); } \ + }; \ + template <> \ + struct emscripten::internal::TypeID::type *, void> { \ + static constexpr emscripten::internal::TYPEID get() { return emscripten::internal::TypeID>::get(); } \ + }; + +#define REGISTER_GFX_PTRS_FOR_STRUCT(...) \ + BOOST_PP_SEQ_FOR_EACH(SPECIALIZE_PTR_FOR_STRUCT, _, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); + +// specialize for void* +template <> +struct emscripten::internal::TypeID { + static constexpr emscripten::internal::TYPEID get() { return emscripten::internal::TypeID::get(); } +}; + +template +struct emscripten::internal::TypeID::value>::type> { + static constexpr emscripten::internal::TYPEID get() { return emscripten::internal::TypeID::type>::get(); } +}; + +namespace cc::gfx { + +using ::emscripten::allow_raw_pointers; +using ::emscripten::convertJSArrayToNumberVector; +using ::emscripten::val; + +// template ::value, bool>::type = true> +// std::vector ptrVecFromEMS(const val& vals) { +// uint32_t len = vals["length"].as(); +// std::vector res(len); +// const std::vector Ts = vecFromJSArray(vals); +// for (size_t i = 0; i < len; ++i) { +// const val& t = Ts[i]; +// t.as(emscripten::allow_raw_pointers()); +// res[i] = reinterpret_cast(t.as()); +// } +// return res; +// } + +template +struct GetType { + using type = T; +}; + +template +struct GetType::value>::type> { + using type = typename std::underlying_type::type; +}; + +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp index a64723bf58..2da1a08a3c 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp @@ -36,13 +36,33 @@ namespace cc { namespace gfx { -namespace anoymous { -WGPUBindGroup defaultBindGroup = wgpuDefaultHandle; +namespace { +WGPUBindGroup dftBindGroup = wgpuDefaultHandle; + +struct BindGroupCache { + CCWGPUDescriptorSet *descriptorSet{nullptr}; + WGPUBindGroup bindGroup{wgpuDefaultHandle}; + ccstd::hash_t bornHash{0}; +}; + +thread_local ccstd::unordered_map bindGroupMap; +} // namespace + +CCWGPUDescriptorSet::CCWGPUDescriptorSet() : DescriptorSet() { } -using namespace emscripten; +CCWGPUDescriptorSet::~CCWGPUDescriptorSet() { + doDestroy(); +} -CCWGPUDescriptorSet::CCWGPUDescriptorSet() : wrapper(val::object()) { +void CCWGPUDescriptorSet::clearCache() { + if (!bindGroupMap.empty()) { + for (auto &it : bindGroupMap) { + wgpuBindGroupRelease(static_cast(it.second.bindGroup)); + it.second.descriptorSet->_isDirty = true; + } + bindGroupMap.clear(); + } } void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { @@ -55,7 +75,7 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { for (size_t i = 0; i < bindings.size(); i++) { // effect.ts: INPUT_ATTACHMENT as combined texture but no sampler_texture desc type. if (hasFlag(COMBINED_ST_IN_USE, bindings[i].descriptorType)) { - //1. texture + // 1. texture CCWGPUTexture *texture = deviceObj->defaultResources.commonTexture; WGPUBindGroupEntry texEntry = { .binding = bindings[i].binding, @@ -63,17 +83,17 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { }; _gpuBindGroupObj->bindGroupEntries.push_back(texEntry); _textureIdxMap.insert(std::make_pair(bindings[i].binding, _gpuBindGroupObj->bindGroupEntries.size() - 1)); - dsLayout->updateLayout(texEntry.binding, nullptr, texture); + dsLayout->updateTextureLayout(texEntry.binding, texture); // 2. sampler - CCWGPUSampler *sampler = deviceObj->defaultResources.sampler; + CCWGPUSampler *sampler = deviceObj->defaultResources.unfilterableSampler; WGPUBindGroupEntry smpEntry = { .binding = bindings[i].binding + CC_WGPU_MAX_ATTACHMENTS, .sampler = sampler->gpuSampler(), }; _gpuBindGroupObj->bindGroupEntries.push_back(smpEntry); _samplerIdxMap.insert(std::make_pair(bindings[i].binding, _gpuBindGroupObj->bindGroupEntries.size() - 1)); - dsLayout->updateLayout(smpEntry.binding, nullptr, nullptr, sampler); + dsLayout->updateSamplerLayout(smpEntry.binding, sampler); } else if (hasFlag(DESCRIPTOR_BUFFER_TYPE, bindings[i].descriptorType)) { CCWGPUBuffer *buffer = hasFlag(DescriptorType::DYNAMIC_STORAGE_BUFFER | DescriptorType::STORAGE_BUFFER, bindings[i].descriptorType) ? deviceObj->defaultResources.storageBuffer @@ -96,7 +116,23 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { .textureView = texture->gpuTextureObject()->selfView, }; _gpuBindGroupObj->bindGroupEntries.push_back(texEntry); - dsLayout->updateLayout(texEntry.binding, nullptr, texture); + dsLayout->updateTextureLayout(texEntry.binding, texture); + } else if (bindings[i].descriptorType == DescriptorType::TEXTURE) { + CCWGPUTexture *texture = deviceObj->defaultResources.commonTexture; + WGPUBindGroupEntry texEntry = { + .binding = bindings[i].binding, + .textureView = texture->gpuTextureObject()->selfView, + }; + _gpuBindGroupObj->bindGroupEntries.push_back(texEntry); + dsLayout->updateTextureLayout(texEntry.binding, texture); + } else if (bindings[i].descriptorType == DescriptorType::SAMPLER) { + CCWGPUSampler *sampler = deviceObj->defaultResources.unfilterableSampler; + WGPUBindGroupEntry smpEntry = { + .binding = bindings[i].binding, + .sampler = sampler->gpuSampler(), + }; + _gpuBindGroupObj->bindGroupEntries.push_back(smpEntry); + dsLayout->updateSamplerLayout(smpEntry.binding, sampler); } else { WGPUBindGroupEntry texEntry = { .binding = bindings[i].binding, @@ -106,10 +142,36 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { } (void)defaultBindGroup(); -} // namespace gfx +} + +ccstd::hash_t CCWGPUDescriptorSet::hash() const { + ccstd::hash_t hash = 9527; + for (const auto &buffer : _buffers) { + if (buffer) { + auto *wgpuBuffer = static_cast(buffer)->gpuBufferObject()->wgpuBuffer; + ccstd::hash_combine(hash, wgpuBuffer); + } + } + for (const auto &texture : _textures) { + if (texture) { + auto *wgpuTextureView = static_cast(texture)->gpuTextureObject()->selfView; + ccstd::hash_combine(hash, wgpuTextureView); + } + } + for (const auto &sampler : _samplers) { + if (sampler) { + auto *wgpuSampler = static_cast(sampler)->gpuSampler(); + ccstd::hash_combine(hash, wgpuSampler); + } + } + return hash; +} void CCWGPUDescriptorSet::doDestroy() { - delete _gpuBindGroupObj; + if (_gpuBindGroupObj) { + delete _gpuBindGroupObj; + _gpuBindGroupObj = nullptr; + } } void CCWGPUDescriptorSet::update() { @@ -131,28 +193,29 @@ void CCWGPUDescriptorSet::update() { bindGroupEntry.buffer = buffer->gpuBufferObject()->wgpuBuffer; bindGroupEntry.offset = buffer->getOffset(); bindGroupEntry.size = buffer->getSize(); - dsLayout->updateLayout(bindGroupEntry.binding, buffer); + dsLayout->updateBufferLayout(bindGroupEntry.binding, buffer); uint8_t bindIndex = binding.binding; if (hasAnyFlags(binding.descriptorType, DescriptorType::DYNAMIC_STORAGE_BUFFER | DescriptorType::DYNAMIC_UNIFORM_BUFFER)) { auto iter = std::find_if(_dynamicOffsets.begin(), _dynamicOffsets.end(), [bindIndex](const std::pair dynIndex) { return dynIndex.first == bindIndex; }); - //assert(iter != _dynamicOffsets.end()); //can't happen + // assert(iter != _dynamicOffsets.end()); //can't happen (*iter).second = 1; } } } else if (hasFlag(COMBINED_ST_IN_USE, bindings[i].descriptorType)) { auto texIter = _textureIdxMap.find(binding.binding); auto smpIter = _samplerIdxMap.find(binding.binding); - //assert((texIter != _textureIdxMap.end()) + (smpIter != _samplerIdxMap.end()) == 1); + // assert((texIter != _textureIdxMap.end()) + (smpIter != _samplerIdxMap.end()) == 1); uint8_t textureIdx = texIter != _textureIdxMap.end() ? texIter->second : 255; uint8_t samplerIdx = smpIter != _samplerIdxMap.end() ? smpIter->second : 255; + if (textureIdx != 255 && _textures[resourceIndex]) { auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[textureIdx]; auto *texture = static_cast(_textures[resourceIndex]); bindGroupEntry.binding = binding.binding; bindGroupEntry.textureView = texture->gpuTextureObject()->selfView; - dsLayout->updateLayout(bindGroupEntry.binding, nullptr, texture); + dsLayout->updateTextureLayout(bindGroupEntry.binding, texture); _gpuBindGroupObj->bindingSet.insert(binding.binding); } if (samplerIdx != 255 && _samplers[resourceIndex]) { @@ -160,87 +223,102 @@ void CCWGPUDescriptorSet::update() { auto *sampler = static_cast(_samplers[resourceIndex]); bindGroupEntry.binding = binding.binding + CC_WGPU_MAX_ATTACHMENTS; bindGroupEntry.sampler = sampler->gpuSampler(); - dsLayout->updateLayout(bindGroupEntry.binding, nullptr, nullptr, sampler); + dsLayout->updateSamplerLayout(bindGroupEntry.binding, sampler); _gpuBindGroupObj->bindingSet.insert(binding.binding + CC_WGPU_MAX_ATTACHMENTS); } - } else if (DescriptorType::STORAGE_IMAGE == bindings[i].descriptorType) { + } else if (DescriptorType::STORAGE_IMAGE == bindings[i].descriptorType || DescriptorType::TEXTURE == bindings[i].descriptorType) { if (_textures[resourceIndex]) { auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[resourceIndex]; auto *texture = static_cast(_textures[resourceIndex]); bindGroupEntry.binding = binding.binding; bindGroupEntry.textureView = texture->gpuTextureObject()->selfView; - dsLayout->updateLayout(bindGroupEntry.binding, nullptr, texture); + dsLayout->updateTextureLayout(bindGroupEntry.binding, texture); } + } else if (DescriptorType::SAMPLER == bindings[i].descriptorType) { + auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[resourceIndex]; + auto *sampler = static_cast(_samplers[resourceIndex]); + bindGroupEntry.binding = binding.binding; + bindGroupEntry.sampler = sampler->gpuSampler(); + dsLayout->updateSamplerLayout(bindGroupEntry.binding, sampler); + } else { + printf("*******unexpected binding type detected!\n"); } } } void CCWGPUDescriptorSet::prepare() { auto buffIter = std::find_if(_buffers.begin(), _buffers.end(), [](const Buffer *buffer) { - return buffer ? static_cast(buffer)->internalChanged() : false; + return buffer && static_cast(buffer)->internalChanged(); }); auto texIter = std::find_if(_textures.begin(), _textures.end(), [](const Texture *texture) { - return texture ? static_cast(texture)->internalChanged() : false; + return texture && static_cast(texture)->internalChanged(); }); bool forceUpdate = buffIter != _buffers.end() || texIter != _textures.end(); - if (forceUpdate) { - _isDirty = true; + + _isDirty |= forceUpdate; + if (_isDirty) { update(); } + const auto &entries = _gpuBindGroupObj->bindGroupEntries; + if (_isDirty || forceUpdate || !_gpuBindGroupObj->bindgroup) { auto *dsLayout = static_cast(_layout); - dsLayout->prepare(forceUpdate); - // ccstd::vector - // bindGroupEntries; + dsLayout->prepare(_gpuBindGroupObj->bindingSet, forceUpdate); + + // ccstd::vector bindGroupEntries; // bindGroupEntries.assign(_gpuBindGroupObj->bindGroupEntries.begin(), _gpuBindGroupObj->bindGroupEntries.end()); // bindGroupEntries.erase(std::remove_if( - // bindGroupEntries.begin(), bindGroupEntries.end(), [this, &bindGroupEntries](const WGPUBindGroupEntry& entry) { + // bindGroupEntries.begin(), bindGroupEntries.end(), [this, &bindGroupEntries](const WGPUBindGroupEntry &entry) { // return _gpuBindGroupObj->bindingSet.find(entry.binding) == _gpuBindGroupObj->bindingSet.end(); // }), // bindGroupEntries.end()); - - const auto &entries = _gpuBindGroupObj->bindGroupEntries; - - // for (size_t j = 0; j < entries.size(); j++) { - // const auto& entry = entries[j]; - // if ((entry.buffer != 0) + (entry.textureView != 0) + (entry.sampler != 0) != 1) { - // printf("***************missing binding, b, t, s %d, %p, %p, %p\n", entry.binding, entry.buffer, entry.textureView, entry.sampler); - // } - // } - - CCWGPUDeviceObject *deviceObj = CCWGPUDevice::getInstance()->gpuDeviceObject(); - if (_gpuBindGroupObj->bindgroup && _gpuBindGroupObj->bindgroup != anoymous::defaultBindGroup) { - wgpuBindGroupRelease(_gpuBindGroupObj->bindgroup); - } - if (entries.empty()) { - _gpuBindGroupObj->bindgroup = anoymous::defaultBindGroup; - // _bgl = CCWGPUDescriptorSetLayout::defaultBindGroupLayout(); + _gpuBindGroupObj->bindgroup = dftBindGroup; + _bornHash = 0; } else { - WGPUBindGroupDescriptor bindGroupDesc = { - .nextInChain = nullptr, - .label = nullptr, - .layout = dsLayout->gpuLayoutEntryObject()->bindGroupLayout, - .entryCount = entries.size(), - .entries = entries.data(), - }; - _gpuBindGroupObj->bindgroup = wgpuDeviceCreateBindGroup(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &bindGroupDesc); - // _bgl = dsLayout->gpuLayoutEntryObject()->bindGroupLayout; - // _local = dsLayout; + _hash = hash(); + auto iter = bindGroupMap.find(_hash); + if (iter == bindGroupMap.end()) { + // layout might be changed later. + _bornHash = dsLayout->getHash(); + CCWGPUDeviceObject *deviceObj = CCWGPUDevice::getInstance()->gpuDeviceObject(); + // if (_gpuBindGroupObj->bindgroup && _gpuBindGroupObj->bindgroup != dftBindGroup) { + // wgpuBindGroupRelease(_gpuBindGroupObj->bindgroup); + // } + label = std::to_string(_bornHash); + WGPUBindGroupDescriptor bindGroupDesc = { + .nextInChain = nullptr, + .label = label.c_str(), + .layout = dsLayout->gpuLayoutEntryObject()->bindGroupLayout, + .entryCount = entries.size(), + .entries = entries.data(), + }; + + _gpuBindGroupObj->bindgroup = wgpuDeviceCreateBindGroup(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &bindGroupDesc); + // printf("create new bg\n"); + + _isDirty = false; + if (buffIter != _buffers.end()) + std::for_each(_buffers.begin(), _buffers.end(), [](Buffer *buffer) { + if (buffer) + static_cast(buffer)->stamp(); + }); + if (texIter != _textures.end()) + std::for_each(_textures.begin(), _textures.end(), [](Texture *texture) { + if (texture) + static_cast(texture)->stamp(); + }); + + bindGroupMap.insert(std::make_pair(_hash, BindGroupCache{this, _gpuBindGroupObj->bindgroup, _bornHash})); + // CCWGPUDevice::getInstance()->destroyLater(_gpuBindGroupObj->bindgroup); + } else { + _gpuBindGroupObj->bindgroup = static_cast(iter->second.bindGroup); + _bornHash = iter->second.bornHash; + // printf("reuse bg\n"); + } } - _isDirty = false; - if (buffIter != _buffers.end()) - std::for_each(_buffers.begin(), _buffers.end(), [](Buffer *buffer) { - if (buffer) - static_cast(buffer)->stamp(); - }); - if (texIter != _textures.end()) - std::for_each(_textures.begin(), _textures.end(), [](Texture *texture) { - if (texture) - static_cast(texture)->stamp(); - }); } } @@ -251,7 +329,7 @@ uint8_t CCWGPUDescriptorSet::dynamicOffsetCount() const { void *CCWGPUDescriptorSet::defaultBindGroup() { CCWGPUDeviceObject *deviceObj = CCWGPUDevice::getInstance()->gpuDeviceObject(); - if (!anoymous::defaultBindGroup) { + if (!dftBindGroup) { CCWGPUBuffer *buffer = deviceObj->defaultResources.uniformBuffer; WGPUBindGroupEntry bufferEntry = { .binding = 0, @@ -262,15 +340,15 @@ void *CCWGPUDescriptorSet::defaultBindGroup() { WGPUBindGroupDescriptor bindGroupDesc = { .nextInChain = nullptr, - .label = nullptr, + .label = "defaultBindGroup", .layout = static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout()), .entryCount = 1, .entries = &bufferEntry, }; - anoymous::defaultBindGroup = wgpuDeviceCreateBindGroup(deviceObj->wgpuDevice, &bindGroupDesc); + dftBindGroup = wgpuDeviceCreateBindGroup(deviceObj->wgpuDevice, &bindGroupDesc); } - return anoymous::defaultBindGroup; + return dftBindGroup; } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.h b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.h index 743ef42faa..259bf4010b 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.h @@ -24,8 +24,9 @@ ****************************************************************************/ #pragma once - -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "base/std/container/unordered_map.h" #include "base/std/container/vector.h" #include "gfx-base/GFXDescriptorSet.h" @@ -36,31 +37,29 @@ struct CCWGPUBindGroupObject; using Pairs = ccstd::vector>; -class CCWGPUDescriptorSet final : public emscripten::wrapper { +class CCWGPUDescriptorSet final : public DescriptorSet { public: - EMSCRIPTEN_WRAPPER(CCWGPUDescriptorSet); CCWGPUDescriptorSet(); - ~CCWGPUDescriptorSet() = default; + ~CCWGPUDescriptorSet(); inline CCWGPUBindGroupObject *gpuBindGroupObject() { return _gpuBindGroupObj; } - - void update() override; - - uint8_t dynamicOffsetCount() const; - - void prepare(); - - static void *defaultBindGroup(); - inline Pairs &dynamicOffsets() { return _dynamicOffsets; } - // void* bgl() const{return _bgl;} + void update() override; + void forceUpdate() override{}; + uint8_t dynamicOffsetCount() const; + void prepare(); + ccstd::hash_t getHash() { return _bornHash; }; - // DescriptorSetLayout* local()const {return _local;} + static void *defaultBindGroup(); + static void clearCache(); + + std::string label; protected: void doInit(const DescriptorSetInfo &info) override; void doDestroy() override; + ccstd::hash_t hash() const; CCWGPUBindGroupObject *_gpuBindGroupObj = nullptr; @@ -70,10 +69,8 @@ protected: // dynamic offsets, inuse ? 1 : 0; Pairs _dynamicOffsets; - - // void* _bgl = nullptr; - - // DescriptorSetLayout* _local = nullptr; + ccstd::hash_t _hash{0}; + ccstd::hash_t _bornHash{0}; // hash when created, this relate to reuse bindgroup layout }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp index f26243b36a..e055cfad39 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp @@ -37,16 +37,19 @@ namespace cc { namespace gfx { -namespace anoymous { -WGPUBindGroupLayout defaultBindgroupLayout = wgpuDefaultHandle; +namespace { +WGPUBindGroupLayout dftBindgroupLayout = wgpuDefaultHandle; -ccstd::unordered_map layoutPool; -} // namespace anoymous +ccstd::unordered_map layoutPool; +} // namespace using namespace emscripten; -using namespace anoymous; -CCWGPUDescriptorSetLayout::CCWGPUDescriptorSetLayout() : wrapper(val::object()) { +CCWGPUDescriptorSetLayout::CCWGPUDescriptorSetLayout() : DescriptorSetLayout() { +} + +CCWGPUDescriptorSetLayout::~CCWGPUDescriptorSetLayout() { + doDestroy(); } void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { @@ -70,7 +73,7 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { .nextInChain = nullptr, .binding = _bindings[i].binding + CC_WGPU_MAX_ATTACHMENTS, .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), - .sampler.type = WGPUSamplerBindingType_Filtering, + .sampler.type = WGPUSamplerBindingType_NonFiltering, }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(samplerLayout); } else if (hasFlag(DESCRIPTOR_BUFFER_TYPE, _bindings[i].descriptorType)) { @@ -100,7 +103,7 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { .nextInChain = nullptr, .binding = _bindings[i].binding, .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), - .sampler = {nullptr, WGPUSamplerBindingType::WGPUSamplerBindingType_Comparison}, + .sampler = {nullptr, WGPUSamplerBindingType::WGPUSamplerBindingType_NonFiltering}, }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(layout); } else if (_bindings[i].descriptorType == DescriptorType::STORAGE_IMAGE) { @@ -125,90 +128,118 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(layout); } } + (void)defaultBindGroupLayout(); + + _hash = hash(); } -void CCWGPUDescriptorSetLayout::updateLayout(uint8_t binding, const CCWGPUBuffer *buffer, const CCWGPUTexture *tex, const CCWGPUSampler *sampler) { +void CCWGPUDescriptorSetLayout::updateBufferLayout(uint8_t binding, const CCWGPUBuffer *buffer) { + // auto iter = std::find_if(_gpuLayoutEntryObj->bindGroupLayoutEntries.begin(), _gpuLayoutEntryObj->bindGroupLayoutEntries.end(), [binding](const WGPUBindGroupLayoutEntry &entry) { + // return entry.binding == binding; + // }); + + // if (iter != _gpuLayoutEntryObj->bindGroupLayoutEntries.end()) { + // auto bindingIter = std::find_if(_bindings.begin(), _bindings.end(), [binding](const auto &binding) { + // return binding.binding == binding; + // }); + // } + + // _internalChanged = true; +} + +void CCWGPUDescriptorSetLayout::updateTextureLayout(uint8_t binding, const CCWGPUTexture *texture) { auto iter = std::find_if(_gpuLayoutEntryObj->bindGroupLayoutEntries.begin(), _gpuLayoutEntryObj->bindGroupLayoutEntries.end(), [binding](const WGPUBindGroupLayoutEntry &entry) { return entry.binding == binding; }); if (iter != _gpuLayoutEntryObj->bindGroupLayoutEntries.end()) { - if (buffer) { - // - } - if (sampler) { - const SamplerInfo &info = sampler->getInfo(); - if (info.minFilter == Filter::POINT && info.magFilter == Filter::POINT && info.mipFilter == Filter::POINT) - (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_NonFiltering; - else - (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_Filtering; - } - if (tex) { - if (tex->getInfo().usage == TextureUsageBit::STORAGE) { + auto bindingIter = std::find_if(_bindings.begin(), _bindings.end(), [binding](const auto &bindingElem) { + return bindingElem.binding == binding; + }); + if (texture) { + if (texture->getInfo().usage == TextureUsageBit::STORAGE) { (*iter).storageTexture.nextInChain = nullptr; (*iter).storageTexture.access = WGPUStorageTextureAccess::WGPUStorageTextureAccess_WriteOnly; - (*iter).storageTexture.format = toWGPUTextureFormat(tex->getFormat()); - TextureType type = tex->isTextureView() ? tex->getViewInfo().type : tex->getInfo().type; + (*iter).storageTexture.format = toWGPUTextureFormat(texture->getFormat()); + TextureType type = texture->isTextureView() ? texture->getViewInfo().type : texture->getInfo().type; (*iter).storageTexture.viewDimension = toWGPUTextureViewDimension(type); } else { (*iter).texture.nextInChain = nullptr; - (*iter).texture.sampleType = textureSampleTypeTrait(tex->getFormat()); - const CCWGPUTexture *ccTex = static_cast(tex->isTextureView() ? tex->getViewInfo().texture : tex); + (*iter).texture.sampleType = textureSampleTypeTrait(texture->getFormat()); + const CCWGPUTexture *ccTex = static_cast(texture->isTextureView() ? texture->getViewInfo().texture : texture); TextureType type = ccTex->getViewInfo().type; (*iter).texture.viewDimension = toWGPUTextureViewDimension(type); (*iter).texture.multisampled = ccTex->getInfo().samples != SampleCount::ONE; } + } else { + (*iter).texture.nextInChain = nullptr; + (*iter).texture.sampleType = WGPUTextureSampleType::WGPUTextureSampleType_Float; + (*iter).texture.viewDimension = WGPUTextureViewDimension::WGPUTextureViewDimension_2D; + (*iter).texture.multisampled = false; } + _internalChanged = true; } } -size_t CCWGPUDescriptorSetLayout::hash() const { +void CCWGPUDescriptorSetLayout::updateSamplerLayout(uint8_t binding, const CCWGPUSampler *sampler) { + auto iter = std::find_if(_gpuLayoutEntryObj->bindGroupLayoutEntries.begin(), _gpuLayoutEntryObj->bindGroupLayoutEntries.end(), [binding](const WGPUBindGroupLayoutEntry &entry) { + return entry.binding == binding; + }); + + if (iter != _gpuLayoutEntryObj->bindGroupLayoutEntries.end()) { + auto bindingIter = std::find_if(_bindings.begin(), _bindings.end(), [binding](const auto &bindingElem) { + return bindingElem.binding == binding; + }); + if (sampler) { + const SamplerInfo &info = sampler->getInfo(); + if ((info.minFilter == Filter::POINT || info.minFilter == Filter::NONE) && + (info.magFilter == Filter::POINT || info.magFilter == Filter::NONE) && + (info.mipFilter == Filter::POINT || info.mipFilter == Filter::NONE)) { + (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_NonFiltering; + } else { + (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_Filtering; + } + } else { + (*iter).sampler.type = WGPUSamplerBindingType::WGPUSamplerBindingType_NonFiltering; + } + _internalChanged = true; + } +} + +ccstd::hash_t CCWGPUDescriptorSetLayout::hash() const { const auto &entries = _gpuLayoutEntryObj->bindGroupLayoutEntries; - // size_t seed = 129; - // boost::hash_combine(seed, entries.size()); - // for(size_t i = 0; i < entries.size(); i++) { - // boost::hash_combine(seed, i); - // boost::hash_combine(seed, entries[i].binding); - // boost::hash_combine(seed, entries[i].buffer.type); - // boost::hash_combine(seed, entries[i].sampler.type); - // boost::hash_combine(seed, entries[i].texture.sampleType); - // boost::hash_combine(seed, entries[i].storageTexture.access); - // } - - ccstd::string hashStr = ""; - - std::size_t seed = entries.size(); + ccstd::hash_t hash = 9527; + ccstd::hash_combine(hash, entries.size()); for (size_t i = 0; i < entries.size(); i++) { - const auto &entry = entries[i]; - hashStr += std::to_string(entry.binding); - hashStr += std::to_string(entry.visibility); - if (entry.buffer.type != WGPUBufferBindingType_Undefined) { - hashStr += std::to_string(entry.buffer.type); - hashStr += std::to_string(entry.buffer.hasDynamicOffset ? 1 : 0); - hashStr += std::to_string(entry.buffer.minBindingSize); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, entries[i].binding); + ccstd::hash_combine(hash, entries[i].visibility); + if (entries[i].buffer.type != WGPUBufferBindingType_Undefined) { + ccstd::hash_combine(hash, entries[i].buffer.type); + ccstd::hash_combine(hash, entries[i].buffer.hasDynamicOffset); + ccstd::hash_combine(hash, entries[i].buffer.minBindingSize); } - if (entry.sampler.type == WGPUSamplerBindingType_Undefined) { - hashStr += std::to_string(entry.sampler.type); + if (entries[i].sampler.type != WGPUSamplerBindingType_Undefined) { + ccstd::hash_combine(hash, entries[i].sampler.type); } - if (entry.texture.sampleType != WGPUTextureSampleType_Undefined) { - hashStr += std::to_string(entry.texture.sampleType); - hashStr += std::to_string(entry.texture.viewDimension); - hashStr += std::to_string(entry.texture.multisampled ? 1 : 0); + if (entries[i].texture.sampleType != WGPUTextureSampleType_Undefined) { + ccstd::hash_combine(hash, entries[i].texture.sampleType); + ccstd::hash_combine(hash, entries[i].texture.viewDimension); + ccstd::hash_combine(hash, entries[i].texture.multisampled); } - if (entry.storageTexture.access != WGPUStorageTextureAccess_Undefined) { - hashStr += std::to_string(entry.storageTexture.access); - hashStr += std::to_string(entry.storageTexture.format); - hashStr += std::to_string(entry.storageTexture.viewDimension); + if (entries[i].storageTexture.access != WGPUStorageTextureAccess_Undefined) { + ccstd::hash_combine(hash, entries[i].storageTexture.access); + ccstd::hash_combine(hash, entries[i].storageTexture.format); + ccstd::hash_combine(hash, entries[i].storageTexture.viewDimension); } } - - return std::hash{}(hashStr); + return hash; } void CCWGPUDescriptorSetLayout::print() const { - size_t hashVal = this->hash(); - printf("pr this %p %p %zu\n", _gpuLayoutEntryObj, this, hashVal); + size_t hashVal = _hash; + printf("\npr this %p %p %zu\n", _gpuLayoutEntryObj, this, hashVal); const auto &entries = _gpuLayoutEntryObj->bindGroupLayoutEntries; for (size_t j = 0; j < entries.size(); j++) { const auto &entry = entries[j]; @@ -235,20 +266,21 @@ void CCWGPUDescriptorSetLayout::print() const { } } -void CCWGPUDescriptorSetLayout::prepare(bool forceUpdate) { - if (_gpuLayoutEntryObj->bindGroupLayout && !forceUpdate) { - return; - } +void CCWGPUDescriptorSetLayout::prepare(ccstd::set &bindingInUse, bool forceUpdate) { + // if (_gpuLayoutEntryObj->bindGroupLayout && !forceUpdate) { + // return; + // } // ccstd::vector bindGroupLayoutEntries; // bindGroupLayoutEntries.assign(_gpuLayoutEntryObj->bindGroupLayoutEntries.begin(), _gpuLayoutEntryObj->bindGroupLayoutEntries.end()); // bindGroupLayoutEntries.erase(std::remove_if( - // bindGroupLayoutEntries.begin(), bindGroupLayoutEntries.end(), [&bindingInUse, &bindGroupLayoutEntries](const WGPUBindGroupLayoutEntry& entry) { + // bindGroupLayoutEntries.begin(), bindGroupLayoutEntries.end(), [&bindingInUse, &bindGroupLayoutEntries](const WGPUBindGroupLayoutEntry &entry) { // return bindingInUse.find(entry.binding) == bindingInUse.end(); // }), // bindGroupLayoutEntries.end()); - size_t hashVal = hash(); - auto iter = layoutPool.find(hashVal); + _hash = hash(); + auto iter = layoutPool.find(_hash); + // printf("dsl upd %zu\n", _hash); if (iter != layoutPool.end()) { _gpuLayoutEntryObj->bindGroupLayout = iter->second; return; @@ -268,22 +300,31 @@ void CCWGPUDescriptorSetLayout::prepare(bool forceUpdate) { // } if (entries.empty()) { - _gpuLayoutEntryObj->bindGroupLayout = anoymous::defaultBindgroupLayout; + _gpuLayoutEntryObj->bindGroupLayout = dftBindgroupLayout; } else { WGPUBindGroupLayoutDescriptor descriptor = { .nextInChain = nullptr, - .label = nullptr, + .label = std::to_string(_hash).c_str(), .entryCount = entries.size(), .entries = entries.data(), }; _gpuLayoutEntryObj->bindGroupLayout = wgpuDeviceCreateBindGroupLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + printf("create new bglayout\n"); } - // printf("bgl %p\n", _gpuLayoutEntryObj->bindGroupLayout); - layoutPool.insert({hashVal, _gpuLayoutEntryObj->bindGroupLayout}); + layoutPool.insert({_hash, _gpuLayoutEntryObj->bindGroupLayout}); +} + +void *CCWGPUDescriptorSetLayout::getBindGroupLayoutByHash(ccstd::hash_t hash) { + void *ret = nullptr; + auto iter = layoutPool.find(hash); + if (iter != layoutPool.end()) { + ret = iter->second; + } + return ret; } void *CCWGPUDescriptorSetLayout::defaultBindGroupLayout() { - if (!anoymous::defaultBindgroupLayout) { + if (!dftBindgroupLayout) { // default bindgroupLayout: for empty set WGPUBindGroupLayoutEntry layout = { .nextInChain = nullptr, @@ -294,18 +335,21 @@ void *CCWGPUDescriptorSetLayout::defaultBindGroupLayout() { WGPUBindGroupLayoutDescriptor descriptor = { .nextInChain = nullptr, - .label = nullptr, + .label = "defaultBindgroupLayout", .entryCount = 1, .entries = &layout, }; - anoymous::defaultBindgroupLayout = wgpuDeviceCreateBindGroupLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + dftBindgroupLayout = wgpuDeviceCreateBindGroupLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); } - return anoymous::defaultBindgroupLayout; + return dftBindgroupLayout; } void CCWGPUDescriptorSetLayout::doDestroy() { - delete _gpuLayoutEntryObj; + if (_gpuLayoutEntryObj) { + delete _gpuLayoutEntryObj; + _gpuLayoutEntryObj = nullptr; + } } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.h b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.h index dc148f3e9d..713944e2b4 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.h @@ -24,9 +24,10 @@ ****************************************************************************/ #pragma once - -#include -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "base/std/container/set.h" #include "gfx-base/GFXDescriptorSetLayout.h" namespace cc { @@ -37,29 +38,37 @@ class CCWGPUTexture; class CCWGPUBuffer; class CCWGPUSampler; -class CCWGPUDescriptorSetLayout final : public emscripten::wrapper { +class CCWGPUDescriptorSetLayout final : public DescriptorSetLayout { public: - EMSCRIPTEN_WRAPPER(CCWGPUDescriptorSetLayout); CCWGPUDescriptorSetLayout(); - ~CCWGPUDescriptorSetLayout() = default; + ~CCWGPUDescriptorSetLayout(); inline CCWGPUBindGroupLayoutObject *gpuLayoutEntryObject() { return _gpuLayoutEntryObj; } - void updateLayout(uint8_t binding, const CCWGPUBuffer *buffer = nullptr, const CCWGPUTexture *tex = nullptr, const CCWGPUSampler *sampler = nullptr); + void updateBufferLayout(uint8_t binding, const CCWGPUBuffer *buffer); + void updateTextureLayout(uint8_t binding, const CCWGPUTexture *texture); + void updateSamplerLayout(uint8_t binding, const CCWGPUSampler *sampler); - void prepare(bool forceUpdate = false); + void prepare(ccstd::set &bindingInUse, bool forceUpdate = false); inline uint8_t dynamicOffsetCount() { return _dynamicOffsetCount; } static void *defaultBindGroupLayout(); + static void *getBindGroupLayoutByHash(ccstd::hash_t hash); void print() const; + ccstd::hash_t getHash() { + return _hash; + } + protected: void doInit(const DescriptorSetLayoutInfo &info) override; void doDestroy() override; - size_t hash() const; + ccstd::hash_t hash() const; + ccstd::hash_t _hash{0}; + bool _internalChanged{false}; CCWGPUBindGroupLayoutObject *_gpuLayoutEntryObj = nullptr; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp index 2c35ef6355..016d3edacc 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp @@ -49,6 +49,7 @@ namespace cc { namespace gfx { +namespace { struct BufferMapData { Semaphore *semaphore = nullptr; WGPUBuffer buffer = wgpuDefaultHandle; @@ -57,6 +58,22 @@ struct BufferMapData { bool finished = false; }; +} // namespace + +void onAdapterGot(WGPURequestAdapterStatus status, WGPUAdapter adapter, char const *message, void *userdata) { + if (message) { + printf("onAdapterGot: %s\n", message); + } + if (status == WGPURequestAdapterStatus_Success) { + auto *device = static_cast(userdata); + device->gpuDeviceObject()->instance.wgpuAdapter = adapter; + device->initConfigs(); + device->initLimits(); + } else { + printf("onAdapterGot: failed to get adapter\n"); + } +} + CCWGPUDevice *CCWGPUDevice::instance = nullptr; CCWGPUDevice *CCWGPUDevice::getInstance() { @@ -68,19 +85,30 @@ CCWGPUDevice *CCWGPUDevice::getInstance() { return instance; } -CCWGPUDevice::CCWGPUDevice() : wrapper(val::object()) { +CCWGPUDevice::CCWGPUDevice() : Device() { _api = API::WEBGPU; _deviceName = "WebGPU"; _caps.clipSpaceMinZ = 0.0F; _caps.screenSpaceSignY = -1.0F; - _caps.clipSpaceSignY = -1.0F; + _caps.clipSpaceSignY = 1.0F; + + // Sept 6th 2022: ems getLimits not implemented + _caps.uboOffsetAlignment = 256; + _caps.uboOffsetAlignment = 256; + _caps.maxVertexUniformVectors = 256; + _caps.maxFragmentUniformVectors = 256; + + _caps.maxComputeSharedMemorySize = 32768; + _caps.maxComputeWorkGroupInvocations = 256; + _caps.maxComputeWorkGroupSize = {65535, 65535, 65535}; + _caps.maxComputeWorkGroupCount = {256, 256, 64}; + instance = this; } CCWGPUDevice::~CCWGPUDevice() { + doDestroy(); instance = nullptr; - delete _gpuDeviceObj; - delete this; } bool CCWGPUDevice::doInit(const DeviceInfo &info) { @@ -92,7 +120,8 @@ bool CCWGPUDevice::doInit(const DeviceInfo &info) { _gpuDeviceObj->defaultResources.storageBuffer = CCWGPUBuffer::defaultStorageBuffer(); _gpuDeviceObj->defaultResources.commonTexture = CCWGPUTexture::defaultCommonTexture(); _gpuDeviceObj->defaultResources.storageTexture = CCWGPUTexture::defaultStorageTexture(); - _gpuDeviceObj->defaultResources.sampler = CCWGPUSampler::defaultSampler(); + _gpuDeviceObj->defaultResources.filterableSampler = CCWGPUSampler::defaultFilterableSampler(); + _gpuDeviceObj->defaultResources.unfilterableSampler = CCWGPUSampler::defaultUnfilterableSampler(); QueueInfo queueInfo = { .type = QueueType::GRAPHICS, @@ -104,10 +133,90 @@ bool CCWGPUDevice::doInit(const DeviceInfo &info) { .type = CommandBufferType::PRIMARY, }; _cmdBuff = this->Device::createCommandBuffer(cmdInfo); + // Sept 6th 2022: not implemented by emscripten + // _gpuDeviceObj->instance.wgpuInstance = wgpuCreateInstance({}); + +#ifdef CC_WGPU_WASM + WGPUSurfaceDescriptorFromCanvasHTMLSelector canvDesc = {}; + canvDesc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; + canvDesc.selector = "canvas"; + + WGPUSurfaceDescriptor surfDesc = {}; + surfDesc.nextInChain = reinterpret_cast(&canvDesc); + _gpuDeviceObj->instance.wgpuSurface = wgpuInstanceCreateSurface(nullptr, &surfDesc); + +#elif defined(CC_WGPU_DAWN) + _gpuDeviceObj->instance.wgpuInstance = wgpuCreateInstance({}); + WGPUSurfaceDescriptor sufaceDesc = { + .label = "DAWNSurface", + }; + _gpuDeviceObj->instance.wgpuSurface = wgpuInstanceCreateSurface(_gpuDeviceObj->instance.wgpuInstance, &sufaceDesc); + +#endif + WGPURequestAdapterOptions options = { + .compatibleSurface = _gpuDeviceObj->instance.wgpuSurface, + .powerPreference = WGPUPowerPreference_LowPower, + }; + + wgpuInstanceRequestAdapter(_gpuDeviceObj->instance.wgpuInstance, &options, onAdapterGot, this); + + // auto bufferRecycleFunc = [this](WGPUBuffer buffer) { + // _recycleBin[getCurrentFrameIndex()].bufferBin.collect(buffer); + // }; + // for (size_t i = 0; i < CC_WGPU_MAX_FRAME_COUNT; ++i) { + // _stagingBuffers[i] = new CCWGPUStagingBuffer(_gpuDeviceObj->wgpuDevice, bufferRecycleFunc); + // } + + initFeatures(); return true; } void CCWGPUDevice::doDestroy() { + if (_gpuDeviceObj) { + if (_gpuDeviceObj->defaultResources.uniformBuffer) { + delete _gpuDeviceObj->defaultResources.uniformBuffer; + } + if (_gpuDeviceObj->defaultResources.storageBuffer) { + delete _gpuDeviceObj->defaultResources.storageBuffer; + } + if (_gpuDeviceObj->defaultResources.commonTexture) { + delete _gpuDeviceObj->defaultResources.commonTexture; + } + if (_gpuDeviceObj->defaultResources.storageTexture) { + delete _gpuDeviceObj->defaultResources.storageTexture; + } + if (_gpuDeviceObj->defaultResources.filterableSampler) { + delete _gpuDeviceObj->defaultResources.filterableSampler; + } + if (_gpuDeviceObj->defaultResources.unfilterableSampler) { + delete _gpuDeviceObj->defaultResources.unfilterableSampler; + } + + for (size_t i = 0; i < CC_WGPU_MAX_FRAME_COUNT; ++i) { + _recycleBin[i].bufferBin.purge(); + _recycleBin[i].textureBin.purge(); + _recycleBin[i].queryBin.purge(); + } + + if (_gpuDeviceObj->wgpuQueue) { + wgpuQueueRelease(_gpuDeviceObj->wgpuQueue); + } + if (_gpuDeviceObj->instance.wgpuSurface) { + wgpuSurfaceRelease(_gpuDeviceObj->instance.wgpuSurface); + } + if (_gpuDeviceObj->instance.wgpuInstance) { + wgpuInstanceRelease(_gpuDeviceObj->instance.wgpuInstance); + } + if (_gpuDeviceObj->instance.wgpuAdapter) { + wgpuAdapterRelease(_gpuDeviceObj->instance.wgpuAdapter); + } + if (_gpuDeviceObj->wgpuDevice) { + wgpuDeviceRelease(_gpuDeviceObj->wgpuDevice); + } + + delete _gpuDeviceObj; + _gpuDeviceObj = nullptr; + } } Swapchain *CCWGPUDevice::createSwapchain() { @@ -162,147 +271,177 @@ CommandBuffer *CCWGPUDevice::createCommandBuffer(const CommandBufferInfo &info, return ccnew CCWGPUCommandBuffer; } -void CCWGPUDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) { +Shader *CCWGPUDevice::createShader(const ShaderInfo &info, const std::vector> &spvData) { + auto *shader = ccnew CCWGPUShader; + shader->initialize(info, spvData); + return shader; +} + +void CCWGPUDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { Format dstFormat = dst->getFormat(); - uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; + uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; auto *texture = static_cast(dst); + auto blockSize = formatAlignment(dstFormat); + + auto *ccTexture = static_cast(texture); + if (ccTexture->isTextureView()) { + ccTexture = static_cast(ccTexture->getViewInfo().texture); + } for (size_t i = 0; i < count; i++) { - uint32_t bufferSize = pxSize * regions[i].texExtent.width * regions[i].texExtent.height; + const auto ®ion = regions[i]; + auto bufferPixelWidth = region.buffStride > 0 ? region.buffStride : region.texExtent.width; + auto bufferPixelHeight = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; + auto bytesPerRow = formatSize(dstFormat, region.texExtent.width, 1, 1); + auto bufferBytesPerRow = formatSize(dstFormat, bufferPixelWidth, 1, 1); + auto bufferBytesPerImageSlice = formatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, 1); + auto bufferBytesPerImageLayer = formatSize(dstFormat, bufferPixelWidth, bufferPixelHeight, region.texExtent.depth); + auto targetWidth = region.texExtent.width == 0 ? 0 : utils::alignTo(region.texExtent.width, blockSize.first); + auto targetHeight = region.texExtent.height == 0 ? 0 : utils::alignTo(region.texExtent.height, blockSize.second); - uint32_t bytesPerRow = pxSize * regions[i].texExtent.width; - //it's buffer data layout + // it's buffer data layout WGPUTextureDataLayout texDataLayout = { - .offset = 0, - .bytesPerRow = bytesPerRow, - .rowsPerImage = regions[i].texExtent.height, + .offset = 0, // we always create a non-offset staging buffer or give interface a non-offset buffer address + .bytesPerRow = bufferBytesPerRow, + .rowsPerImage = bufferPixelHeight, }; - WGPUExtent3D extent = { - .width = regions[i].texExtent.width, - .height = regions[i].texExtent.height, - .depthOrArrayLayers = regions[i].texExtent.depth, - }; + bool compactInWidth = bufferPixelWidth == region.texExtent.width; + for (size_t l = region.texSubres.baseArrayLayer; l < region.texSubres.layerCount + region.texSubres.baseArrayLayer; ++l) { + for (size_t d = region.texOffset.z; d < region.texExtent.depth + region.texOffset.z; ++d) { + if (compactInWidth) { + auto *srcData = buffers[i] + region.buffOffset + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + (d - region.texOffset.z) * bufferBytesPerImageSlice; + WGPUImageCopyTexture imageCopyTexture = { + .texture = ccTexture->gpuTextureObject()->wgpuTexture, + .mipLevel = region.texSubres.mipLevel, + .origin = WGPUOrigin3D{ + static_cast(region.texOffset.x), + static_cast(region.texOffset.y), + static_cast(d)}, + .aspect = WGPUTextureAspect_All, + }; - WGPUImageCopyTexture imageCopyTexture = { - .texture = texture->gpuTextureObject()->wgpuTexture, - .mipLevel = regions[i].texSubres.mipLevel, - .origin = WGPUOrigin3D{ - static_cast(regions[i].texOffset.x), - static_cast(regions[i].texOffset.y), - static_cast(regions[i].texSubres.baseArrayLayer)}, - .aspect = WGPUTextureAspect_All, - }; - wgpuQueueWriteTexture(_gpuDeviceObj->wgpuQueue, &imageCopyTexture, buffers[i], bufferSize, &texDataLayout, &extent); + WGPUExtent3D extent = { + .width = targetWidth, + .height = targetHeight, + .depthOrArrayLayers = 1, + }; - // //genMipmap manually when level 0 updated. - // const TextureInfo& texInfo = dst->getInfo(); - // if (hasFlag(texInfo.flags, TextureFlagBit::GEN_MIPMAP) && regions[i].texSubres.mipLevel == 0) { - // for(size_t j = 1; j < texInfo.levelCount; j++) { - // imageCopyTexture.mipLevel = j; - // extent = { - // .width = (uint32_t)(regions[i].texExtent.width / float(std::pow(2, j))), - // .height = (uint32_t)(regions[i].texExtent.height / float(std::pow(2, j))), - // .depthOrArrayLayers = regions[i].texExtent.depth, - // }; + wgpuQueueWriteTexture(_gpuDeviceObj->wgpuQueue, &imageCopyTexture, srcData, bufferBytesPerImageSlice, &texDataLayout, &extent); + } else { + for (size_t h = region.texOffset.y; h < region.texExtent.height + region.texOffset.y; h += blockSize.second) { + auto *srcData = buffers[i] + region.buffOffset + (l - region.texSubres.baseArrayLayer) * bufferBytesPerImageLayer + (d - region.texOffset.z) * bufferBytesPerImageSlice + + (h - region.texOffset.y) / blockSize.second * bufferBytesPerRow; + WGPUImageCopyTexture imageCopyTexture = { + .texture = ccTexture->gpuTextureObject()->wgpuTexture, + .mipLevel = region.texSubres.mipLevel, + .origin = WGPUOrigin3D{ + static_cast(region.texOffset.x), + static_cast(h), + static_cast(d)}, + .aspect = WGPUTextureAspect_All, + }; - // wgpuQueueWriteTexture(_gpuDeviceObj->wgpuQueue, &imageCopyTexture, buffers[i], bufferSize, &texDataLayout, &extent); - // } - // } + WGPUExtent3D extent = { + .width = targetWidth, + .height = blockSize.second, + .depthOrArrayLayers = 1, + }; + + wgpuQueueWriteTexture(_gpuDeviceObj->wgpuQueue, &imageCopyTexture, srcData, bytesPerRow, &texDataLayout, &extent); + } + } + } + } } } void onQueueDone(WGPUQueueWorkDoneStatus status, void *userdata) { - printf("Q done beg\n"); if (status == WGPUQueueWorkDoneStatus_Success) { - printf("Q done beg0\n"); auto *bufferMapData = static_cast(userdata); - printf("Q done beg1\n"); // auto* mappedBuffer = wgpuBufferGetMappedRange(bufferMapData->buffer, 0, bufferMapData->size); auto *mappedBuffer = (uint8_t *)malloc(static_cast(bufferMapData->size)); - printf("Q done beg2\n"); *bufferMapData->retBuffer = emscripten::val(emscripten::typed_memory_view(bufferMapData->size, static_cast(mappedBuffer))); - printf("Q suc %d\n", bufferMapData->size); bufferMapData->finished = true; // memcpy(bufferMapData->dst, mappedBuffer, bufferMapData->size); } - printf("Q done\n"); } emscripten::val CCWGPUDevice::copyTextureToBuffers(Texture *src, const BufferTextureCopyList ®ions) { - auto *texture = static_cast(src); - Format dstFormat = src->getFormat(); - uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; - auto wgpuCommandEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); + // auto *texture = static_cast(src); + // Format dstFormat = src->getFormat(); + // uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; + // auto wgpuCommandEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); - uint64_t size = std::accumulate(regions.begin(), regions.end(), 0, [pxSize](uint64_t initVal, const BufferTextureCopy &in) { - uint32_t bytesPerRow = (pxSize * in.texExtent.width + 255) / 256 * 256; - uint32_t bufferSize = bytesPerRow * in.texExtent.height * in.texExtent.depth; - return initVal + bufferSize; - }); + // uint64_t size = std::accumulate(regions.begin(), regions.end(), 0, [pxSize](uint64_t initVal, const BufferTextureCopy &in) { + // uint32_t bytesPerRow = (pxSize * in.texExtent.width + 255) / 256 * 256; + // uint32_t bufferSize = bytesPerRow * in.texExtent.height * in.texExtent.depth; + // return initVal + bufferSize; + // }); - WGPUBufferDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, - .size = size, - .mappedAtCreation = false, - }; + // WGPUBufferDescriptor descriptor = { + // .nextInChain = nullptr, + // .label = nullptr, + // .usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, + // .size = size, + // .mappedAtCreation = false, + // }; - WGPUBuffer buffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); - uint64_t offset = 0; - for (size_t i = 0; i < regions.size(); i++) { - uint32_t bytesPerRow = (pxSize * regions[i].texExtent.width + 255) / 256 * 256; - WGPUImageCopyTexture imageCopyTexture = { - .texture = texture->gpuTextureObject()->wgpuTexture, - .mipLevel = regions[i].texSubres.mipLevel, - .origin = WGPUOrigin3D{ - static_cast(regions[i].texOffset.x), - static_cast(regions[i].texOffset.y), - static_cast(regions[i].texOffset.z)}, - .aspect = WGPUTextureAspect_All, - }; + // WGPUBuffer buffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + // uint64_t offset = 0; + // for (size_t i = 0; i < regions.size(); i++) { + // uint32_t bytesPerRow = (pxSize * regions[i].texExtent.width + 255) / 256 * 256; + // WGPUImageCopyTexture imageCopyTexture = { + // .texture = texture->gpuTextureObject()->wgpuTexture, + // .mipLevel = regions[i].texSubres.mipLevel, + // .origin = WGPUOrigin3D{ + // static_cast(regions[i].texOffset.x), + // static_cast(regions[i].texOffset.y), + // static_cast(regions[i].texOffset.z)}, + // .aspect = WGPUTextureAspect_All, + // }; - WGPUTextureDataLayout texDataLayout = { - .offset = offset, - .bytesPerRow = bytesPerRow, - .rowsPerImage = regions[i].texExtent.height, - }; - uint32_t bufferSize = pxSize * regions[i].texExtent.width * regions[i].texExtent.depth; - offset += bufferSize; + // WGPUTextureDataLayout texDataLayout = { + // .offset = offset, + // .bytesPerRow = bytesPerRow, + // .rowsPerImage = regions[i].texExtent.height, + // }; + // uint32_t bufferSize = pxSize * regions[i].texExtent.width * regions[i].texExtent.depth; + // offset += bufferSize; - WGPUImageCopyBuffer imageCopyBuffer = { - .layout = texDataLayout, - .buffer = buffer, - }; + // WGPUImageCopyBuffer imageCopyBuffer = { + // .layout = texDataLayout, + // .buffer = buffer, + // }; - WGPUExtent3D extent = { - .width = regions[i].texExtent.width, - .height = regions[i].texExtent.height, - .depthOrArrayLayers = regions[i].texExtent.depth, - }; + // WGPUExtent3D extent = { + // .width = regions[i].texExtent.width, + // .height = regions[i].texExtent.height, + // .depthOrArrayLayers = regions[i].texExtent.depth, + // }; - wgpuCommandEncoderCopyTextureToBuffer(wgpuCommandEncoder, &imageCopyTexture, &imageCopyBuffer, &extent); - } - auto wgpuCommandBuffer = wgpuCommandEncoderFinish(wgpuCommandEncoder, nullptr); - wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &wgpuCommandBuffer); - printf("Q submit\n"); - Semaphore sem{0}; - BufferMapData *bufferMapData = ccnew BufferMapData{ - &sem, - buffer, - nullptr, - size, - false, - }; + // wgpuCommandEncoderCopyTextureToBuffer(wgpuCommandEncoder, &imageCopyTexture, &imageCopyBuffer, &extent); + // } - wgpuQueueOnSubmittedWorkDone(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, onQueueDone, bufferMapData); + // auto wgpuCommandBuffer = wgpuCommandEncoderFinish(wgpuCommandEncoder, nullptr); + // wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &wgpuCommandBuffer); + // printf("Q submit\n"); + // Semaphore sem{0}; + // BufferMapData *bufferMapData = ccnew BufferMapData{ + // &sem, + // buffer, + // nullptr, + // size, + // false, + // }; - while (!bufferMapData->finished) { - ; - } - // wgpuBufferRelease(buffer); - return *bufferMapData->retBuffer; + // wgpuQueueOnSubmittedWorkDone(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, onQueueDone, bufferMapData); + + // while (!bufferMapData->finished) { + // ; + // } + // // wgpuBufferRelease(buffer); + // return *bufferMapData->retBuffer; } void CCWGPUDevice::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) { @@ -314,12 +453,6 @@ void CCWGPUDevice::acquire(Swapchain *const *swapchains, uint32_t count) { } } -Shader *CCWGPUDevice::createShader(const SPVShaderInfoInstance &info) { - CCWGPUShader *shader = ccnew CCWGPUShader; - shader->initialize(info); - return shader; -} - QueryPool *CCWGPUDevice::createQueryPool() { return ccnew CCWGPUQueryPool; } @@ -329,6 +462,15 @@ Sampler *CCWGPUDevice::createSampler(const SamplerInfo &info) { } void CCWGPUDevice::present() { + auto *queue = static_cast(_queue); + _numDrawCalls = queue->getNumDrawCalls(); + _numInstances = queue->getNumInstances(); + _numTriangles = queue->getNumTris(); + queue->resetStatus(); + + CCWGPUDescriptorSet::clearCache(); + + _currentFrameIndex = (++_currentFrameIndex) % CC_WGPU_MAX_FRAME_COUNT; } void CCWGPUDevice::getQueryPoolResults(QueryPool *queryPool) { @@ -341,6 +483,266 @@ void CCWGPUDevice::debug() { wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &wgpuCommandBuffer); } +void CCWGPUDevice::initConfigs() { + WGPUAdapterProperties props; + wgpuAdapterGetProperties(_gpuDeviceObj->instance.wgpuAdapter, &props); + // _deviceName = props.name; + // _vendor = props.driverDescription; + + const auto &adapterName = getAdapterTypeName(props.adapterType); + const auto &backendName = getBackendTypeName(props.backendType); + + printf("WebGPU:%s enabled with: %s , adapter:%s, backend: %s, vendorID: %u, deviceID:%u\n", + _deviceName.c_str(), _vendor.c_str(), adapterName.c_str(), backendName.c_str(), props.vendorID, props.deviceID); + + if (wgpuAdapterHasFeature(_gpuDeviceObj->instance.wgpuAdapter, WGPUFeatureName_TextureCompressionBC)) { + _formatFeatures[toNumber(Format::BC1_ALPHA)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC1_SRGB_ALPHA)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC2)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC2_SRGB)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC3)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC3_SRGB)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC4_SNORM)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC5_SNORM)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC6H_SF16)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC6H_UF16)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC7)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BC7_SRGB)] = FormatFeature::SAMPLED_TEXTURE; + } + + if (wgpuAdapterHasFeature(_gpuDeviceObj->instance.wgpuAdapter, WGPUFeatureName_TextureCompressionETC2)) { + _formatFeatures[toNumber(Format::ETC2_RGBA8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_SRGB8_A8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_RGB8_A1)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_SRGB8_A1)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_RGB8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ETC2_SRGB8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::EAC_R11)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::EAC_R11SN)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::EAC_RG11)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::EAC_RG11SN)] = FormatFeature::SAMPLED_TEXTURE; + } + + if (wgpuAdapterHasFeature(_gpuDeviceObj->instance.wgpuAdapter, WGPUFeatureName_TextureCompressionASTC)) { + _formatFeatures[toNumber(Format::ASTC_RGBA_4X4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_4X4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_5X4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_5X4)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_5X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_5X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_6X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_6X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_6X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_6X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_8X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_8X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_8X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_8X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_8X8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_8X8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_10X5)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X6)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_10X8)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X10)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_10X10)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_12X10)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_SRGBA_12X10)] = FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::ASTC_RGBA_12X12)] = FormatFeature::SAMPLED_TEXTURE; + } +} + +void CCWGPUDevice::initLimits() { + WGPUSupportedLimits supportLimits; + + // Aug-19th 2022: getlimits not impled. + +#if 0 + wgpuAdapterGetLimits(_gpuDeviceObj->instance.wgpuAdapter, &supportLimits); + + const auto &limits = supportLimits.limits; + _caps.maxVertexAttributes = limits.maxVertexAttributes; + _caps.maxVertexUniformVectors = 256; + _caps.maxFragmentUniformVectors = 256; + _caps.maxTextureUnits = limits.maxSamplersPerShaderStage; + _caps.maxImageUnits = limits.maxSampledTexturesPerShaderStage; + _caps.maxVertexTextureUnits = limits.maxSampledTexturesPerShaderStage; + _caps.maxShaderStorageBufferBindings = limits.maxStorageBuffersPerShaderStage; + _caps.maxUniformBlockSize = limits.maxUniformBufferBindingSize; + _caps.maxShaderStorageBlockSize = limits.maxStorageBufferBindingSize; + _caps.maxShaderStorageBufferBindings = limits.maxStorageBuffersPerShaderStage; + _caps.maxTextureSize = limits.maxTextureDimension2D; + _caps.uboOffsetAlignment = limits.minUniformBufferOffsetAlignment; + + _caps.maxComputeSharedMemorySize = limits.maxComputeWorkgroupStorageSize; + _caps.maxComputeWorkGroupInvocations = limits.maxComputeInvocationsPerWorkgroup; + _caps.maxComputeWorkGroupSize = {limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension, limits.maxComputeWorkgroupsPerDimension}; + _caps.maxComputeWorkGroupCount = {limits.maxComputeWorkgroupSizeX, limits.maxComputeWorkgroupSizeY, limits.maxComputeWorkgroupSizeZ}; + +#endif +} + +void CCWGPUDevice::initFeatures() { + const FormatFeature completeFeature = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::LINEAR_FILTER | FormatFeature::STORAGE_TEXTURE; + + FormatFeature tempFeature = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::STORAGE_TEXTURE; + + // render target + _formatFeatures[toNumber(Format::R8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R8UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R8I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG8UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG8I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::SRGB8_A8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA8UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA8I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::BGRA8)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R16UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R16I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R16F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG16UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG16I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG16F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA16UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA16I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA16F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RG32F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA32UI)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA32I)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGBA32F)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::RGB10A2)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::DEPTH)] |= FormatFeature::RENDER_TARGET; + _formatFeatures[toNumber(Format::DEPTH_STENCIL)] |= FormatFeature::RENDER_TARGET; + + // storage + _formatFeatures[toNumber(Format::RGBA8)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8SN)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16F)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32F)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RG32F)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32UI)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32I)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32F)] |= FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::RGB10A2)] |= FormatFeature::STORAGE_TEXTURE; + + // sampled + _formatFeatures[toNumber(Format::R8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R8SN)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R8UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R8I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG8SN)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG8UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG8I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::SRGB8_A8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8SN)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA8I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::BGRA8)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R16UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R16I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R16F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG16UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG16I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG16F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA16F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RG32F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32UI)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32I)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGBA32F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGB10A2)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::R11G11B10F)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::DEPTH)] |= FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::DEPTH_STENCIL)] |= FormatFeature::SAMPLED_TEXTURE; + + _formatFeatures[toNumber(Format::RGB9E5)] |= FormatFeature::SAMPLED_TEXTURE; + + _formatFeatures[toNumber(Format::R8)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG8)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB8)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA8)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R8SN)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG8SN)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB8SN)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA8SN)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R8I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG8I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB8I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA8I)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R8UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG8UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB8UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA8UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R16I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG16I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB16I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA16I)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R16UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG16UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB16UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA16UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R16F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG16F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB16F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA16F)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R32UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG32UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB32UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA32UI)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R32I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG32I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB32I)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA32I)] |= FormatFeature::VERTEX_ATTRIBUTE; + + _formatFeatures[toNumber(Format::R32F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RG32F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGB32F)] |= FormatFeature::VERTEX_ATTRIBUTE; + _formatFeatures[toNumber(Format::RGBA32F)] |= FormatFeature::VERTEX_ATTRIBUTE; + + // + _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; + _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; + _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; + _features[toNumber(Feature::BLEND_MINMAX)] = true; + _features[toNumber(Feature::COMPUTE_SHADER)] = true; + _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = true; +} + } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDevice.h b/native/cocos/renderer/gfx-wgpu/WGPUDevice.h index a0972fb007..b9dc6bba7c 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDevice.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDevice.h @@ -28,14 +28,13 @@ #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) #include #endif - -#include -#include -#include "WGPUDef.h" +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "WGPUObject.h" #include "base/std/container/vector.h" #include "gfx-base/GFXDevice.h" -#define EMSArraysToU8Vec(v, i) (emscripten::convertJSArrayToNumberVector(v[i])) namespace cc { namespace gfx { @@ -43,22 +42,24 @@ struct CCWGPUDeviceObject; class CCWGPUSwapchain; class CCWGPUTexture; +class WGPUGeneralBarrier; -using namespace emscripten; - -class CCWGPUDevice final : public wrapper { +class CCWGPUDevice final : public Device { public: - EMSCRIPTEN_WRAPPER(CCWGPUDevice); - static CCWGPUDevice *getInstance(); + CCWGPUDevice(); ~CCWGPUDevice(); + void acquire(const std::vector &swapchains) { + return acquire(swapchains.data(), swapchains.size()); + } void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; inline CCWGPUDeviceObject *gpuDeviceObject() { return _gpuDeviceObj; } - + inline uint8_t getCurrentFrameIndex() const { return _currentFrameIndex; } + inline CCWGPURecycleBin *recycleBin() { return &_recycleBin[_currentFrameIndex]; } inline void registerSwapchain(CCWGPUSwapchain *swapchain) { _swapchains.push_back(swapchain); } inline void unRegisterSwapchain(CCWGPUSwapchain *swapchain) { auto iter = std::find(_swapchains.begin(), _swapchains.end(), swapchain); @@ -67,74 +68,66 @@ public: } } - // ems export override - Swapchain *createSwapchain(const SwapchainInfoInstance &info) { - return Device::createSwapchain(static_cast(info)); - } + template + void moveToTrash(T t); - Framebuffer *createFramebuffer(const FramebufferInfoInstance &info) { - return Device::createFramebuffer(static_cast(info)); - } - - Texture *createTexture(const TextureInfoInstance &info) { - return Device::createTexture(static_cast(info)); - } - - Texture *createTexture(const TextureViewInfoInstance &info) { - return Device::createTexture(static_cast(info)); - } - - Buffer *createBuffer(const BufferInfoInstance &info) { - return Device::createBuffer(static_cast(info)); - } - - Buffer *createBuffer(const BufferViewInfoInstance &info) { - return Device::createBuffer(static_cast(info)); - } - - DescriptorSet *createDescriptorSet(const DescriptorSetInfoInstance &info) { - return Device::createDescriptorSet(static_cast(info)); - } - - DescriptorSetLayout *createDescriptorSetLayout(const DescriptorSetLayoutInfoInstance &info) { - return Device::createDescriptorSetLayout(static_cast(info)); - } - - InputAssembler *createInputAssembler(const InputAssemblerInfoInstance &info) { - return Device::createInputAssembler(static_cast(info)); - } - - PipelineState *createPipelineState(const PipelineStateInfoInstance &info) { - return Device::createPipelineState(static_cast(info)); - } - - CommandBuffer *createCommandBuffer(const CommandBufferInfoInstance &info) { - return Device::createCommandBuffer(static_cast(info)); - } - - emscripten::val copyTextureToBuffers(Texture *src, const BufferTextureCopyList ®ions); - - Shader *createShader(const SPVShaderInfoInstance &spvInfo); - - void copyBuffersToTexture(const emscripten::val &v, Texture *dst, const BufferTextureCopyList ®ions) { - uint32_t len = v["length"].as(); - ccstd::vector> lifeProlonger(len); - ccstd::vector buffers; - for (size_t i = 0; i < len; i++) { - lifeProlonger[i] = EMSArraysToU8Vec(v, i); - buffers.push_back(lifeProlonger[i].data()); - } - - return copyBuffersToTexture(buffers.data(), dst, regions.data(), regions.size()); - } + // CCWGPUStagingBuffer *stagingBuffer() { + // return _stagingBuffers[_currentFrameIndex]; + // } void debug(); + using Device::createBuffer; + using Device::createDescriptorSet; + using Device::createDescriptorSetLayout; + using Device::createFramebuffer; + using Device::createInputAssembler; + using Device::createPipelineLayout; + using Device::createPipelineState; + using Device::createRenderPass; + using Device::createShader; + using Device::createSwapchain; + using Device::createTexture; + using Device::getGeneralBarrier; + using Device::getSampler; + using Device::initialize; + + Shader *createShader(const ShaderInfo &, const std::vector> &); + + void copyBuffersToTexture(const std::vector> &buffers, Texture *dst, const std::vector ®ions) { + std::vector datas(buffers.size()); + for (size_t i = 0; i < buffers.size(); ++i) { + datas[i] = buffers[i].data(); + } + return copyBuffersToTexture(datas.data(), dst, regions.data(), regions.size()); + } + uint32_t getGFXAPI() const { + return static_cast(Device::getGfxAPI()); + }; + uint32_t hasFeature(uint32_t feature) { + return static_cast(Device::hasFeature(Feature{feature})); + }; + inline MemoryStatus getMemStatus() const { + return _memoryStatus; + } + uint32_t getFormatFeatures(uint32_t format) { + return static_cast(Device::getFormatFeatures(Format{format})); + }; + + // ems export override + EXPORT_EMS( + void copyTextureToBuffers(Texture *src, const emscripten::val &buffers, const emscripten::val ®ions); + emscripten::val copyTextureToBuffers(Texture * src, const BufferTextureCopyList ®ions); + Shader * createShader(const ShaderInfo &info, const emscripten::val &spirvVal); + void copyBuffersToTexture(const emscripten::val &v, Texture *dst, const std::vector ®ions);) + + void initFeatures(); + void initLimits(); + void initConfigs(); + protected: static CCWGPUDevice *instance; - CCWGPUDevice(); - bool doInit(const DeviceInfo &info) override; void doDestroy() override; CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; @@ -157,10 +150,28 @@ protected: void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; void getQueryPoolResults(QueryPool *queryPool) override; + uint8_t _currentFrameIndex{0}; CCWGPUDeviceObject *_gpuDeviceObj = nullptr; ccstd::vector _swapchains; + + CCWGPURecycleBin _recycleBin[CC_WGPU_MAX_FRAME_COUNT]; }; +template <> +inline void CCWGPUDevice::moveToTrash(WGPUBuffer t) { + _recycleBin[_currentFrameIndex].bufferBin.collect(t); +} + +template <> +inline void CCWGPUDevice::moveToTrash(WGPUTexture t) { + _recycleBin[_currentFrameIndex].textureBin.collect(t); +} + +template <> +inline void CCWGPUDevice::moveToTrash(WGPUQuerySet t) { + _recycleBin[_currentFrameIndex].queryBin.collect(t); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp b/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp new file mode 100644 index 0000000000..fbe6da4a0e --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp @@ -0,0 +1,161 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include "WGPUBuffer.h" +#include "WGPUCommandBuffer.h" +#include "WGPUDef.h" +#include "WGPUDescriptorSet.h" +#include "WGPUDescriptorSetLayout.h" +#include "WGPUDevice.h" +#include "WGPUFrameBuffer.h" +#include "WGPUInputAssembler.h" +#include "WGPUQueue.h" +#include "WGPURenderPass.h" +#include "WGPUSampler.h" +#include "WGPUShader.h" +#include "WGPUSwapchain.h" +#include "WGPUTexture.h" +#include "gfx-base/GFXDef-common.h" +#include "states/WGPUBufferBarrier.h" +#include "states/WGPUGeneralBarrier.h" +#include "states/WGPUTextureBarrier.h" +namespace cc::gfx { + +using ::emscripten::allow_raw_pointers; +// using ::emscripten::convertJSArrayToNumberVector_local; +using ::emscripten::val; + +#define CACHE_NAME(r, _, property) \ + const val BOOST_PP_CAT(property, _val){BOOST_PP_STRINGIZE(property)}; + +#define CACHE_EMS_VAL(...) \ + BOOST_PP_SEQ_FOR_EACH(CACHE_NAME, _, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); + +CACHE_EMS_VAL(length) + +template +std::vector convertJSArrayToNumberVector_local(const val& v) { + const size_t l = v[length_val].as(); + + std::vector rv; + rv.resize(l); + + // Copy the array into our vector through the use of typed arrays. + // It will try to convert each element through Number(). + // See https://www.ecma-international.org/ecma-262/6.0/#sec-%typedarray%.prototype.set-array-offset + // and https://www.ecma-international.org/ecma-262/6.0/#sec-tonumber + val memoryView{emscripten::typed_memory_view(l, rv.data())}; + memoryView.call("set", v); + + return rv; +} + +template +std::vector vecFromJSArray_local(const val& v) { + const size_t l = v[length_val].as(); + + std::vector rv; + rv.reserve(l); + for (size_t i = 0; i < l; ++i) { + rv.push_back(v[i].as()); + } + + return rv; +} + +#define UNREACHABLE_CONDITION CC_ASSERT(false); + +#define NUMARGS(...) (sizeof((int[]){__VA_ARGS__}) / sizeof(int)) + +#define ASSIGN_PROERTY_BY_SEQ(r, obj, property) \ + if (!ems_##obj[BOOST_PP_CAT(property, _val)].isUndefined() && !ems_##obj[BOOST_PP_CAT(property, _val)].isNull()) { \ + obj.property = decltype(obj.property){ems_##obj[BOOST_PP_CAT(property, _val)].as::type>(allow_raw_pointers())}; \ + } + +#define ASSIGN_FROM_EMS(obj, ...) \ + { \ + BOOST_PP_SEQ_FOR_EACH(ASSIGN_PROERTY_BY_SEQ, obj, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#define SET_PROERTY_BY_SEQ(r, obj, property) \ + ems_##obj.set(BOOST_STRINGIZE(property), static_cast::type>(obj.property)); + +#define SET_TO_EMS(obj, ...) \ + { \ + BOOST_PP_SEQ_FOR_EACH(SET_PROERTY_BY_SEQ, obj, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#define ASSIGN_VEC_BY_SEQ(r, obj, property) \ + obj.property = std::move(convertJSArrayToNumberVector_local(ems_##obj[#property])); + +#define ASSIGN_FROM_EMSARRAY(obj, ...) \ + { \ + BOOST_PP_SEQ_FOR_EACH(ASSIGN_VEC_BY_SEQ, obj, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \ + } + +#ifdef CC_DEBUG + #define CHECK_VOID(v) \ + if (v.isUndefined() || v.isNull()) { \ + return; \ + } + + #define CHECK_PTR(v) \ + if (v.isUndefined() || v.isNull()) { \ + return nullptr; \ + } +#else + #define CHECK_VOID(v) + #define CHECK_PTR(v) +#endif + +#define EMSArraysToU8Vec(v, i) (convertJSArrayToNumberVector_local(v[i])) + +void CCWGPUCommandBuffer::updateBuffer(Buffer* buff, const emscripten::val& v, uint32_t size) { + ccstd::vector buffer = convertJSArrayToNumberVector_local(v); + updateBuffer(buff, reinterpret_cast(buffer.data()), size); +} + +void CCWGPUBuffer::update(const val& v, uint32_t size) { + // this is the most fastest way from js array to vector now + ccstd::vector buffer = convertJSArrayToNumberVector_local(v); + update(reinterpret_cast(buffer.data()), size); +} + +void CCWGPUDevice::copyTextureToBuffers(Texture* src, const emscripten::val& buffers, const emscripten::val& regions) { + // @hana-alice +} + +Shader* CCWGPUDevice::createShader(const ShaderInfo& info, const emscripten::val& spirvVal) { + CHECK_PTR(spirvVal); + + auto len = spirvVal[length_val].as(); + std::vector> spvData; + for (size_t i = 0; i < len; ++i) { + spvData.emplace_back(std::move(convertJSArrayToNumberVector_local(spirvVal[i]))); + } + + auto* shader = new CCWGPUShader(); + // shader->initialize(shaderInfo); + shader->initialize(info, spvData); + return shader; +} + +void CCWGPUDevice::copyBuffersToTexture(const emscripten::val& v, Texture* dst, const std::vector& regions) { + CHECK_VOID(v); + auto len = v[length_val].as(); + len = v[length_val].as(); + std::vector> lifeProlonger(len); + std::vector buffers; + for (size_t i = 0; i < len; i++) { + lifeProlonger[i] = EMSArraysToU8Vec(v, i); + buffers.push_back(lifeProlonger[i].data()); + } + + return copyBuffersToTexture(buffers.data(), dst, regions.data(), regions.size()); +} + +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUExports.h b/native/cocos/renderer/gfx-wgpu/WGPUExports.h index b02a3dea3d..81bdbe6ded 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUExports.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUExports.h @@ -15,970 +15,245 @@ #include "WGPUShader.h" #include "WGPUSwapchain.h" #include "WGPUTexture.h" +#include "boost/pfr.hpp" +#include "boost/type_index.hpp" +#include "states/WGPUBufferBarrier.h" +#include "states/WGPUGeneralBarrier.h" +#include "states/WGPUTextureBarrier.h" + +REGISTER_GFX_PTRS_FOR_STRUCT(Device, Buffer, Texture, GeneralBarrier, Queue, RenderPass, Shader, PipelineLayout, DescriptorSetLayout, CommandBuffer, DescriptorSet); -// #define OBJECT_EXPORT(c) \ -// static c c##Instance() { return c(); } namespace cc::gfx { -template -struct GenInstance { - static T instance() { - return T(); - } -}; +using ::emscripten::allow_raw_pointer; +using ::emscripten::allow_raw_pointers; +using ::emscripten::arg; +using ::emscripten::base; +using ::emscripten::class_; +using ::emscripten::constant; +using ::emscripten::enum_; +using ::emscripten::function; +using ::emscripten::pure_virtual; +using ::emscripten::register_vector; +using ::emscripten::select_overload; +using ::emscripten::val; +using ::emscripten::value_object; -// template -// struct GenInstances { -// OBJECT_EXPORT(T); -// GenInstance; -// }; - -// template -// struct GenInstances { -// OBJECT_EXPORT(T); -// }; - -// GenInstances; +using String = ccstd::string; +using ccstd::vector; EMSCRIPTEN_BINDINGS(WEBGPU_DEVICE_WASM_EXPORT) { - // TODO_Zeqiang: compile time traverse enum - - //------------------------------------------------ENUM------------------------------------------------------------ - enum_("Format") - .value("UNKNOWN", Format::UNKNOWN) - .value("A8", Format::A8) - .value("L8", Format::L8) - .value("LA8", Format::LA8) - .value("R8", Format::R8) - .value("R8SN", Format::R8SN) - .value("R8UI", Format::R8UI) - .value("R8I", Format::R8I) - .value("R16F", Format::R16F) - .value("R16UI", Format::R16UI) - .value("R16I", Format::R16I) - .value("R32F", Format::R32F) - .value("R32UI", Format::R32UI) - .value("R32I", Format::R32I) - .value("RG8", Format::RG8) - .value("RG8SN", Format::RG8SN) - .value("RG8UI", Format::RG8UI) - .value("RG8I", Format::RG8I) - .value("RG16F", Format::RG16F) - .value("RG16UI", Format::RG16UI) - .value("RG16I", Format::RG16I) - .value("RG32F", Format::RG32F) - .value("RG32UI", Format::RG32UI) - .value("RG32I", Format::RG32I) - .value("RGB8", Format::RGB8) - .value("SRGB8", Format::SRGB8) - .value("RGB8SN", Format::RGB8SN) - .value("RGB8UI", Format::RGB8UI) - .value("RGB8I", Format::RGB8I) - .value("RGB16F", Format::RGB16F) - .value("RGB16UI", Format::RGB16UI) - .value("RGB16I", Format::RGB16I) - .value("RGB32F", Format::RGB32F) - .value("RGB32UI", Format::RGB32UI) - .value("RGB32I", Format::RGB32I) - .value("RGBA8", Format::RGBA8) - .value("BGRA8", Format::BGRA8) - .value("SRGB8_A8", Format::SRGB8_A8) - .value("RGBA8SN", Format::RGBA8SN) - .value("RGBA8UI", Format::RGBA8UI) - .value("RGBA8I", Format::RGBA8I) - .value("RGBA16F", Format::RGBA16F) - .value("RGBA16UI", Format::RGBA16UI) - .value("RGBA16I", Format::RGBA16I) - .value("RGBA32F", Format::RGBA32F) - .value("RGBA32UI", Format::RGBA32UI) - .value("RGBA32I", Format::RGBA32I) - .value("R5G6B5", Format::R5G6B5) - .value("R11G11B10F", Format::R11G11B10F) - .value("RGB5A1", Format::RGB5A1) - .value("RGBA4", Format::RGBA4) - .value("RGB10A2", Format::RGB10A2) - .value("RGB10A2UI", Format::RGB10A2UI) - .value("RGB9E5", Format::RGB9E5) - .value("DEPTH", Format::DEPTH) - .value("DEPTH_STENCIL", Format::DEPTH_STENCIL) - .value("BC1", Format::BC1) - .value("BC1_ALPHA", Format::BC1_ALPHA) - .value("BC1_SRGB", Format::BC1_SRGB) - .value("BC1_SRGB_ALPHA", Format::BC1_SRGB_ALPHA) - .value("BC2", Format::BC2) - .value("BC2_SRGB", Format::BC2_SRGB) - .value("BC3", Format::BC3) - .value("BC3_SRGB", Format::BC3_SRGB) - .value("BC4", Format::BC4) - .value("BC4_SNORM", Format::BC4_SNORM) - .value("BC5", Format::BC5) - .value("BC5_SNORM", Format::BC5_SNORM) - .value("BC6H_UF16", Format::BC6H_UF16) - .value("BC6H_SF16", Format::BC6H_SF16) - .value("BC7", Format::BC7) - .value("BC7_SRGB", Format::BC7_SRGB) - .value("ETC_RGB8", Format::ETC_RGB8) - .value("ETC2_RGB8", Format::ETC2_RGB8) - .value("ETC2_SRGB8", Format::ETC2_SRGB8) - .value("ETC2_RGB8_A1", Format::ETC2_RGB8_A1) - .value("ETC2_SRGB8_A1", Format::ETC2_SRGB8_A1) - .value("ETC2_RGBA8", Format::ETC2_RGBA8) - .value("ETC2_SRGB8_A8", Format::ETC2_SRGB8_A8) - .value("EAC_R11", Format::EAC_R11) - .value("EAC_R11SN", Format::EAC_R11SN) - .value("EAC_RG11", Format::EAC_RG11) - .value("EAC_RG11SN", Format::EAC_RG11SN) - .value("PVRTC_RGB2", Format::PVRTC_RGB2) - .value("PVRTC_RGBA2", Format::PVRTC_RGBA2) - .value("PVRTC_RGB4", Format::PVRTC_RGB4) - .value("PVRTC_RGBA4", Format::PVRTC_RGBA4) - .value("PVRTC2_2BPP", Format::PVRTC2_2BPP) - .value("PVRTC2_4BPP", Format::PVRTC2_4BPP) - .value("ASTC_RGBA_4X4", Format::ASTC_RGBA_4X4) - .value("ASTC_RGBA_5X4", Format::ASTC_RGBA_5X4) - .value("ASTC_RGBA_5X5", Format::ASTC_RGBA_5X5) - .value("ASTC_RGBA_6X5", Format::ASTC_RGBA_6X5) - .value("ASTC_RGBA_6X6", Format::ASTC_RGBA_6X6) - .value("ASTC_RGBA_8X5", Format::ASTC_RGBA_8X5) - .value("ASTC_RGBA_8X6", Format::ASTC_RGBA_8X6) - .value("ASTC_RGBA_8X8", Format::ASTC_RGBA_8X8) - .value("ASTC_RGBA_10X5", Format::ASTC_RGBA_10X5) - .value("ASTC_RGBA_10X6", Format::ASTC_RGBA_10X6) - .value("ASTC_RGBA_10X8", Format::ASTC_RGBA_10X8) - .value("ASTC_RGBA_10X10", Format::ASTC_RGBA_10X10) - .value("ASTC_RGBA_12X10", Format::ASTC_RGBA_12X10) - .value("ASTC_RGBA_12X12", Format::ASTC_RGBA_12X12) - .value("ASTC_SRGBA_4X4", Format::ASTC_SRGBA_4X4) - .value("ASTC_SRGBA_5X4", Format::ASTC_SRGBA_5X4) - .value("ASTC_SRGBA_5X5", Format::ASTC_SRGBA_5X5) - .value("ASTC_SRGBA_6X5", Format::ASTC_SRGBA_6X5) - .value("ASTC_SRGBA_6X6", Format::ASTC_SRGBA_6X6) - .value("ASTC_SRGBA_8X5", Format::ASTC_SRGBA_8X5) - .value("ASTC_SRGBA_8X6", Format::ASTC_SRGBA_8X6) - .value("ASTC_SRGBA_8X8", Format::ASTC_SRGBA_8X8) - .value("ASTC_SRGBA_10X5", Format::ASTC_SRGBA_10X5) - .value("ASTC_SRGBA_10X6", Format::ASTC_SRGBA_10X6) - .value("ASTC_SRGBA_10X8", Format::ASTC_SRGBA_10X8) - .value("ASTC_SRGBA_10X10", Format::ASTC_SRGBA_10X10) - .value("ASTC_SRGBA_12X10", Format::ASTC_SRGBA_12X10) - .value("ASTC_SRGBA_12X12", Format::ASTC_SRGBA_12X12) - .value("COUNT", Format::COUNT); - - enum_("VsyncMode") - .value("OFF", VsyncMode::OFF) - .value("ON", VsyncMode::ON) - .value("RELAXED", VsyncMode::RELAXED) - .value("MAILBOX", VsyncMode::MAILBOX) - .value("HALF", VsyncMode::HALF); - - enum_("SampleCount") - .value("ONE", SampleCount::ONE) - .value("MULTIPLE_PERFORMANCE", SampleCount::MULTIPLE_PERFORMANCE) - .value("MULTIPLE_BALANCE", SampleCount::MULTIPLE_BALANCE) - .value("MULTIPLE_QUALITY", SampleCount::MULTIPLE_QUALITY); - - enum_("LoadOp") - .value("LOAD", LoadOp::LOAD) - .value("CLEAR", LoadOp::CLEAR) - .value("DISCARD", LoadOp::DISCARD); - - enum_("StoreOp") - .value("STORE", StoreOp::STORE) - .value("DISCARD", StoreOp::DISCARD); - - enum_("AccessType") - .value("NONE", AccessType::NONE) - .value("INDIRECT_BUFFER", AccessType::INDIRECT_BUFFER) - .value("INDEX_BUFFER", AccessType::INDEX_BUFFER) - .value("VERTEX_BUFFER", AccessType::VERTEX_BUFFER) - .value("VERTEX_SHADER_READ_UNIFORM_BUFFER", AccessType::VERTEX_SHADER_READ_UNIFORM_BUFFER) - .value("VERTEX_SHADER_READ_TEXTURE", AccessType::VERTEX_SHADER_READ_TEXTURE) - .value("VERTEX_SHADER_READ_OTHER", AccessType::VERTEX_SHADER_READ_OTHER); - - enum_("ResolveMode") - .value("NONE", ResolveMode::NONE) - .value("SAMPLE_ZERO", ResolveMode::SAMPLE_ZERO) - .value("AVERAGE", ResolveMode::AVERAGE) - .value("MIN", ResolveMode::MIN) - .value("MAX", ResolveMode::MAX); - - enum_("TextureType") - .value("TEX1D", TextureType::TEX1D) - .value("TEX2D", TextureType::TEX2D) - .value("TEX3D", TextureType::TEX3D) - .value("CUBE", TextureType::CUBE) - .value("TEX1D_ARRAY", TextureType::TEX1D_ARRAY) - .value("TEX2D_ARRAY", TextureType::TEX2D_ARRAY); - - enum_("TextureUsage") - .value("NONE", TextureUsageBit::NONE) - .value("TRANSFER_SRC", TextureUsageBit::TRANSFER_SRC) - .value("TRANSFER_DST", TextureUsageBit::TRANSFER_DST) - .value("SAMPLED", TextureUsageBit::SAMPLED) - .value("STORAGE", TextureUsageBit::STORAGE) - .value("COLOR_ATTACHMENT", TextureUsageBit::COLOR_ATTACHMENT) - .value("DEPTH_STENCIL_ATTACHMENT", TextureUsageBit::DEPTH_STENCIL_ATTACHMENT) - .value("INPUT_ATTACHMENT", TextureUsageBit::INPUT_ATTACHMENT); - - enum_("TextureFlags") - .value("NONE", TextureFlagBit::NONE) - .value("GEN_MIPMAP", TextureFlagBit::GEN_MIPMAP) - .value("GENERAL_LAYOUT", TextureFlagBit::GENERAL_LAYOUT); - - enum_("SurfaceTransform") - .value("IDENTITY", SurfaceTransform::IDENTITY) - .value("ROTATE_90", SurfaceTransform::ROTATE_90) - .value("ROTATE_180", SurfaceTransform::ROTATE_180) - .value("ROTATE_270", SurfaceTransform::ROTATE_270); - - enum_("Filter") - .value("NONE", Filter::NONE) - .value("POINT", Filter::POINT) - .value("LINEAR", Filter::LINEAR) - .value("ANISOTROPIC", Filter::ANISOTROPIC); - - enum_
("Address") - .value("WRAP", Address::WRAP) - .value("MIRROR", Address::MIRROR) - .value("CLAMP", Address::CLAMP) - .value("BORDER", Address::BORDER); - - enum_("ComparisonFunc") - .value("NEVER", ComparisonFunc::NEVER) - .value("LESS", ComparisonFunc::LESS) - .value("EQUAL", ComparisonFunc::EQUAL) - .value("LESS_EQUAL", ComparisonFunc::LESS_EQUAL) - .value("GREATER", ComparisonFunc::GREATER) - .value("NOT_EQUAL", ComparisonFunc::NOT_EQUAL) - .value("GREATER_EQUAL", ComparisonFunc::GREATER_EQUAL) - .value("ALWAYS", ComparisonFunc::ALWAYS); - - enum_("BufferUsage") - .value("NONE", BufferUsageBit::NONE) - .value("TRANSFER_SRC", BufferUsageBit::TRANSFER_SRC) - .value("TRANSFER_DST", BufferUsageBit::TRANSFER_DST) - .value("INDEX", BufferUsageBit::INDEX) - .value("VERTEX", BufferUsageBit::VERTEX) - .value("UNIFORM", BufferUsageBit::UNIFORM) - .value("STORAGE", BufferUsageBit::STORAGE) - .value("INDIRECT", BufferUsageBit::INDIRECT); - - enum_("MemoryUsage") - .value("NONE", MemoryUsageBit::NONE) - .value("DEVICE", MemoryUsageBit::DEVICE) - .value("HOST", MemoryUsageBit::HOST); - - enum_("BufferFlags") - .value("NONE", BufferFlagBit::NONE); - - enum_("DescriptorType") - .value("UNKNOWN", DescriptorType::UNKNOWN) - .value("UNIFORM_BUFFER", DescriptorType::UNIFORM_BUFFER) - .value("DYNAMIC_UNIFORM_BUFFER", DescriptorType::DYNAMIC_UNIFORM_BUFFER) - .value("STORAGE_BUFFER", DescriptorType::STORAGE_BUFFER) - .value("DYNAMIC_STORAGE_BUFFER", DescriptorType::DYNAMIC_STORAGE_BUFFER) - .value("SAMPLER_TEXTURE", DescriptorType::SAMPLER_TEXTURE) - .value("SAMPLER", DescriptorType::SAMPLER) - .value("TEXTURE", DescriptorType::TEXTURE) - .value("STORAGE_IMAGE", DescriptorType::STORAGE_IMAGE) - .value("INPUT_ATTACHMENT", DescriptorType::INPUT_ATTACHMENT); - - enum_("ShaderStageFlags") - .value("NONE", ShaderStageFlagBit::NONE) - .value("VERTEX", ShaderStageFlagBit::VERTEX) - .value("CONTROL", ShaderStageFlagBit::CONTROL) - .value("EVALUATION", ShaderStageFlagBit::EVALUATION) - .value("GEOMETRY", ShaderStageFlagBit::GEOMETRY) - .value("FRAGMENT", ShaderStageFlagBit::FRAGMENT) - .value("COMPUTE", ShaderStageFlagBit::COMPUTE) - .value("ALL", ShaderStageFlagBit::ALL); - - enum_("MemoryAccess") - .value("NONE", MemoryAccessBit::NONE) - .value("READ_ONLY", MemoryAccessBit::READ_ONLY) - .value("WRITE_ONLY", MemoryAccessBit::WRITE_ONLY) - .value("READ_WRITE", MemoryAccessBit::READ_WRITE); - - enum_("Type") - .value("UNKNOWN", Type::UNKNOWN) - .value("BOOL", Type::BOOL) - .value("BOOL2", Type::BOOL2) - .value("BOOL3", Type::BOOL3) - .value("BOOL4", Type::BOOL4) - .value("INT", Type::INT) - .value("INT2", Type::INT2) - .value("INT3", Type::INT3) - .value("INT4", Type::INT4) - .value("UINT", Type::UINT) - .value("UINT2", Type::UINT2) - .value("UINT3", Type::UINT3) - .value("UINT4", Type::UINT4) - .value("FLOAT", Type::FLOAT) - .value("FLOAT2", Type::FLOAT2) - .value("FLOAT3", Type::FLOAT3) - .value("FLOAT4", Type::FLOAT4) - .value("MAT2", Type::MAT2) - .value("MAT2X3", Type::MAT2X3) - .value("MAT2X4", Type::MAT2X4) - .value("MAT3X2", Type::MAT3X2) - .value("MAT3X4", Type::MAT3X4) - .value("MAT4X2", Type::MAT4X2) - .value("MAT4X3", Type::MAT4X3) - .value("MAT4", Type::MAT4) - .value("SAMPLER1D", Type::SAMPLER1D) - .value("SAMPLER1D_ARRAY", Type::SAMPLER1D_ARRAY) - .value("SAMPLER2D", Type::SAMPLER2D) - .value("SAMPLER2D_ARRAY", Type::SAMPLER2D_ARRAY) - .value("SAMPLER3D", Type::SAMPLER3D) - .value("SAMPLER_CUBE", Type::SAMPLER_CUBE) - .value("SAMPLER", Type::SAMPLER) - .value("TEXTURE1D", Type::TEXTURE1D) - .value("TEXTURE1D_ARRAY", Type::TEXTURE1D_ARRAY) - .value("TEXTURE2D", Type::TEXTURE2D) - .value("TEXTURE2D_ARRAY", Type::TEXTURE2D_ARRAY) - .value("TEXTURE3D", Type::TEXTURE3D) - .value("TEXTURE_CUBE", Type::TEXTURE_CUBE) - .value("IMAGE1D", Type::IMAGE1D) - .value("IMAGE1D_ARRAY", Type::IMAGE1D_ARRAY) - .value("IMAGE2D", Type::IMAGE2D) - .value("IMAGE2D_ARRAY", Type::IMAGE2D_ARRAY) - .value("IMAGE3D", Type::IMAGE3D) - .value("IMAGE_CUBE", Type::IMAGE_CUBE) - .value("IMAGE3D", Type::IMAGE3D) - .value("SUBPASS_INPUT", Type::SUBPASS_INPUT) - .value("COUNT", Type::COUNT); - - enum_("PolygonMode") - .value("FILL", PolygonMode::FILL) - .value("POINT", PolygonMode::POINT) - .value("LINE", PolygonMode::LINE); - - enum_("ShadeModel") - .value("GOURAND", ShadeModel::GOURAND) - .value("FLAT", ShadeModel::FLAT); - - enum_("CullMode") - .value("NONE", CullMode::NONE) - .value("FRONT", CullMode::FRONT) - .value("BACK", CullMode::BACK); - - enum_("StencilOp") - .value("ZERO", StencilOp::ZERO) - .value("KEEP", StencilOp::KEEP) - .value("REPLACE", StencilOp::REPLACE) - .value("INCR", StencilOp::INCR) - .value("DECR", StencilOp::DECR) - .value("INVERT", StencilOp::INVERT) - .value("INCR_WRAP", StencilOp::INCR_WRAP) - .value("DECR_WRAP", StencilOp::DECR_WRAP); - - enum_("BlendFactor") - .value("ZERO", BlendFactor::ZERO) - .value("ONE", BlendFactor::ONE) - .value("SRC_ALPHA", BlendFactor::SRC_ALPHA) - .value("DST_ALPHA", BlendFactor::DST_ALPHA) - .value("ONE_MINUS_SRC_ALPHA", BlendFactor::ONE_MINUS_SRC_ALPHA) - .value("ONE_MINUS_DST_ALPHA", BlendFactor::ONE_MINUS_DST_ALPHA) - .value("SRC_COLOR", BlendFactor::SRC_COLOR) - .value("DST_COLOR", BlendFactor::DST_COLOR) - .value("ONE_MINUS_SRC_COLOR", BlendFactor::ONE_MINUS_SRC_COLOR) - .value("ONE_MINUS_DST_COLOR", BlendFactor::ONE_MINUS_DST_COLOR) - .value("SRC_ALPHA_SATURATE", BlendFactor::SRC_ALPHA_SATURATE) - .value("CONSTANT_COLOR", BlendFactor::CONSTANT_COLOR) - .value("ONE_MINUS_CONSTANT_COLOR", BlendFactor::ONE_MINUS_CONSTANT_COLOR) - .value("CONSTANT_ALPHA", BlendFactor::CONSTANT_ALPHA) - .value("ONE_MINUS_CONSTANT_ALPHA", BlendFactor::ONE_MINUS_CONSTANT_ALPHA); - - enum_("BlendOp") - .value("ADD", BlendOp::ADD) - .value("SUB", BlendOp::SUB) - .value("REV_SUB", BlendOp::REV_SUB) - .value("MIN", BlendOp::MIN) - .value("MAX", BlendOp::MAX); - - enum_("ColorMask") - .value("NONE", ColorMask::NONE) - .value("R", ColorMask::R) - .value("G", ColorMask::G) - .value("B", ColorMask::B) - .value("A", ColorMask::A) - .value("ALL", ColorMask::ALL); - - enum_("PrimitiveMode") - .value("POINT_LIST", PrimitiveMode::POINT_LIST) - .value("LINE_LIST", PrimitiveMode::LINE_LIST) - .value("LINE_STRIP", PrimitiveMode::LINE_STRIP) - .value("LINE_LOOP", PrimitiveMode::LINE_LOOP) - .value("LINE_LIST_ADJACENCY", PrimitiveMode::LINE_LIST_ADJACENCY) - .value("LINE_STRIP_ADJACENCY", PrimitiveMode::LINE_STRIP_ADJACENCY) - .value("ISO_LINE_LIST", PrimitiveMode::ISO_LINE_LIST) - .value("TRIANGLE_LIST", PrimitiveMode::TRIANGLE_LIST) - .value("TRIANGLE_STRIP", PrimitiveMode::TRIANGLE_STRIP) - .value("TRIANGLE_FAN", PrimitiveMode::TRIANGLE_FAN) - .value("TRIANGLE_LIST_ADJACENCY", PrimitiveMode::TRIANGLE_LIST_ADJACENCY) - .value("TRIANGLE_STRIP_ADJACENCY", PrimitiveMode::TRIANGLE_STRIP_ADJACENCY) - .value("TRIANGLE_PATCH_ADJACENCY", PrimitiveMode::TRIANGLE_PATCH_ADJACENCY) - .value("QUAD_PATCH_LIST", PrimitiveMode::QUAD_PATCH_LIST); - - enum_("DynamicStateFlagBit") - .value("NONE", DynamicStateFlagBit::NONE) - .value("LINE_WIDTH", DynamicStateFlagBit::LINE_WIDTH) - .value("DEPTH_BIAS", DynamicStateFlagBit::DEPTH_BIAS) - .value("BLEND_CONSTANTS", DynamicStateFlagBit::BLEND_CONSTANTS) - .value("DEPTH_BOUNDS", DynamicStateFlagBit::DEPTH_BOUNDS) - .value("STENCIL_WRITE_MASK", DynamicStateFlagBit::STENCIL_WRITE_MASK) - .value("STENCIL_COMPARE_MASK", DynamicStateFlagBit::STENCIL_COMPARE_MASK); - - enum_("PipelineBindPoint") - .value("GRAPHICS", PipelineBindPoint::GRAPHICS) - .value("COMPUTE", PipelineBindPoint::COMPUTE) - .value("RAY_TRACING", PipelineBindPoint::RAY_TRACING); - - enum_("QueueType") - .value("GRAPHICS", QueueType::GRAPHICS) - .value("COMPUTE", QueueType::COMPUTE) - .value("TRANSFER", QueueType::TRANSFER); - - //-----------------------------------------------STRUCT------------------------------------------------------------------- - value_object("ColorAttachment") - .field("format", &ColorAttachment::format) - .field("sampleCount", &ColorAttachment::sampleCount) - .field("loadOp", &ColorAttachment::loadOp) - .field("storeOp", &ColorAttachment::storeOp) - .field("beginAccesses", &ColorAttachment::beginAccesses) - .field("endAccesses", &ColorAttachment::endAccesses) - .field("isGeneralLayout", &ColorAttachment::isGeneralLayout); - function("ColorAttachmentInstance", &GenInstance::instance); - - value_object("DepthStencilAttachment") - .field("format", &DepthStencilAttachment::format) - .field("sampleCount", &DepthStencilAttachment::sampleCount) - .field("depthLoadOp", &DepthStencilAttachment::depthLoadOp) - .field("depthStoreOp", &DepthStencilAttachment::depthStoreOp) - .field("stencilLoadOp", &DepthStencilAttachment::stencilLoadOp) - .field("stencilStoreOp", &DepthStencilAttachment::stencilStoreOp) - .field("beginAccesses", &DepthStencilAttachment::beginAccesses) - .field("endAccesses", &DepthStencilAttachment::endAccesses) - .field("isGeneralLayout", &DepthStencilAttachment::isGeneralLayout); - function("DepthStencilAttachmentInstance", &GenInstance::instance); - - value_object("SubpassInfo") - .field("inputs", &SubpassInfo::inputs) - .field("colors", &SubpassInfo::colors) - .field("resolves", &SubpassInfo::resolves) - .field("preserves", &SubpassInfo::preserves) - .field("depthStencil", &SubpassInfo::depthStencil) - .field("depthStencilResolve", &SubpassInfo::depthStencilResolve) - .field("depthResolveMode", &SubpassInfo::depthResolveMode) - .field("stencilResolveMode", &SubpassInfo::stencilResolveMode); - function("SubpassInfoInstance", &GenInstance::instance); - - value_object("SubpassDependency") - .field("srcSubpass", &SubpassDependency::srcSubpass) - .field("dstSubpass", &SubpassDependency::dstSubpass) - .field("srcAccesses", &SubpassDependency::srcAccesses) - .field("dstAccesses", &SubpassDependency::dstAccesses); - function("SubpassDependencyInstance", &GenInstance::instance); - - value_object("RenderPassInfo") - .field("colorAttachments", &RenderPassInfo::colorAttachments) - .field("depthStencilAttachment", &RenderPassInfo::depthStencilAttachment) - .field("subpasses", &RenderPassInfo::subpasses) - .field("dependencies", &RenderPassInfo::dependencies); - function("RenderPassInfoInstance", &GenInstance::instance); - - value_object("BindingMappingInfo") - .field("bufferOffsets", &BindingMappingInfo::bufferOffsets) - .field("samplerOffsets", &BindingMappingInfo::samplerOffsets) - .field("flexibleSet", &BindingMappingInfo::flexibleSet); - function("BindingMappingInfoInstance", &GenInstance::instance); - - value_object("DeviceInfo") - .field("bindingMappingInfo", &DeviceInfo::bindingMappingInfo); - function("DeviceInfoInstance", &GenInstance::instance); - - value_object("Offset") - .field("x", &Offset::x) - .field("y", &Offset::y) - .field("z", &Offset::z); - function("OffsetInstance", &GenInstance::instance); - - value_object("Extent") - .field("width", &Extent::width) - .field("height", &Extent::height) - .field("depth", &Extent::depth); - function("ExtentInstance", &GenInstance::instance); - - value_object("TextureSubresLayers") - .field("mipLevel", &TextureSubresLayers::mipLevel) - .field("baseArrayLayer", &TextureSubresLayers::baseArrayLayer) - .field("layerCount", &TextureSubresLayers::layerCount); - function("TextureSubresLayersInstance", &GenInstance::instance); - - value_object("BufferTextureCopy") - .field("buffStride", &BufferTextureCopy::buffStride) - .field("buffTexHeight", &BufferTextureCopy::buffTexHeight) - .field("texOffset", &BufferTextureCopy::texOffset) - .field("texExtent", &BufferTextureCopy::texExtent) - .field("texSubres", &BufferTextureCopy::texSubres); - function("BufferTextureCopyInstance", &GenInstance::instance); - - value_object("SamplerInfo") - .field("minFilter", &SamplerInfo::minFilter) - .field("magFilter", &SamplerInfo::magFilter) - .field("mipFilter", &SamplerInfo::mipFilter) - .field("addressU", &SamplerInfo::addressU) - .field("addressV", &SamplerInfo::addressV) - .field("addressW", &SamplerInfo::addressW) - .field("maxAnisotropy", &SamplerInfo::maxAnisotropy) - .field("cmpFunc", &SamplerInfo::cmpFunc); - function("SamplerInfoInstance", &GenInstance::instance); - - // value_object("BufferInfo") - // .field("usage", &BufferInfo::usage) - // .field("memUsage", &BufferInfo::memUsage) - // .field("size", &BufferInfo::size) - // .field("stride", &BufferInfo::stride) - // .field("flags", &BufferInfo::flags); - // function("BufferInfoInstance", &GenInstance::instance); - - // value_object("DescriptorSetLayoutInfo") - // .field("bindings", &DescriptorSetLayoutInfo::bindings); - // function("DescriptorSetLayoutInfoInstance", &GenInstance::instance); - - // value_object("DescriptorSetLayoutBinding") - // .field("binding", &DescriptorSetLayoutBinding::binding) - // .field("descriptorType", &DescriptorSetLayoutBinding::descriptorType) - // .field("count", &DescriptorSetLayoutBinding::count) - // .field("stageFlags", &DescriptorSetLayoutBinding::stageFlags) - // .field("immutableSamplers", &DescriptorSetLayoutBinding::immutableSamplers); - // function("DescriptorSetLayoutBindingInstance", &GenInstance::instance); - - value_object("PipelineLayoutInfo") - .field("setLayouts", &PipelineLayoutInfo::setLayouts); - function("PipelineLayoutInfoInstance", &GenInstance::instance); - - value_object("UniformStorageImage") - .field("set", &UniformStorageImage::set) - .field("binding", &UniformStorageImage::binding) - .field("name", &UniformStorageImage::name) - .field("type", &UniformStorageImage::type) - .field("count", &UniformStorageImage::count) - .field("memoryAccess", &UniformStorageImage::memoryAccess); - function("UniformStorageImageInstance", &GenInstance::instance); - - value_object("ShaderStage") - .field("stage", &ShaderStage::stage) - .field("source", &ShaderStage::source); - function("ShaderStageInstance", &GenInstance::instance); - - value_object("Attribute") - .field("name", &Attribute::name) - .field("format", &Attribute::format) - .field("isNormalized", &Attribute::isNormalized) - .field("stream", &Attribute::stream) - .field("isInstanced", &Attribute::isInstanced) - .field("location", &Attribute::location); - function("AttributeInstance", &GenInstance::instance); - - value_object("Uniform") - .field("name", &Uniform::name) - .field("type", &Uniform::type) - .field("count", &Uniform::count); - function("UniformInstance", &GenInstance::instance); - - value_object("UniformBlock") - .field("set", &UniformBlock::set) - .field("binding", &UniformBlock::binding) - .field("name", &UniformBlock::name) - .field("members", &UniformBlock::members) - .field("count", &UniformBlock::count); - function("UniformBlockInstance", &GenInstance::instance); - - value_object("UniformStorageBuffer") - .field("set", &UniformStorageBuffer::set) - .field("binding", &UniformStorageBuffer::binding) - .field("name", &UniformStorageBuffer::name) - .field("count", &UniformStorageBuffer::count) - .field("memoryAccess", &UniformStorageBuffer::memoryAccess); - function("UniformStorageBufferInstance", &GenInstance::instance); - - value_object("UniformSamplerTexture") - .field("set", &UniformSamplerTexture::set) - .field("binding", &UniformSamplerTexture::binding) - .field("name", &UniformSamplerTexture::name) - .field("type", &UniformSamplerTexture::type) - .field("count", &UniformSamplerTexture::count); - function("UniformSamplerTextureInstance", &GenInstance::instance); - - value_object("UniformSampler") - .field("set", &UniformSampler::set) - .field("binding", &UniformSampler::binding) - .field("name", &UniformSampler::name) - .field("count", &UniformSampler::count); - function("UniformSamplerInstance", &GenInstance::instance); - - value_object("UniformTexture") - .field("set", &UniformTexture::set) - .field("binding", &UniformTexture::binding) - .field("name", &UniformTexture::name) - .field("type", &UniformTexture::type) - .field("count", &UniformTexture::count); - function("UniformTextureInstance", &GenInstance::instance); - - value_object("UniformInputAttachment") - .field("set", &UniformInputAttachment::set) - .field("binding", &UniformInputAttachment::binding) - .field("name", &UniformInputAttachment::name) - .field("count", &UniformInputAttachment::count); - function("UniformInputAttachmentInstance", &GenInstance::instance); - - value_object("ShaderInfo") - .field("name", &ShaderInfo::name) - .field("stages", &ShaderInfo::stages) - .field("attributes", &ShaderInfo::attributes) - .field("blocks", &ShaderInfo::blocks) - .field("buffers", &ShaderInfo::buffers) - .field("samplerTextures", &ShaderInfo::samplerTextures) - .field("samplers", &ShaderInfo::samplers) - .field("textures", &ShaderInfo::textures) - .field("images", &ShaderInfo::images) - .field("subpassInputs", &ShaderInfo::subpassInputs); - function("ShaderInfoInstance", &GenInstance::instance); - - value_object("InputState") - .field("attributes", &InputState::attributes); - function("InputStateInstance", &GenInstance::instance); - - value_object("RasterizerState") - .field("isDiscard", &RasterizerState::isDiscard) - .field("polygonMode", &RasterizerState::polygonMode) - .field("shadeModel", &RasterizerState::shadeModel) - .field("cullMode", &RasterizerState::cullMode) - .field("isFrontFaceCCW", &RasterizerState::isFrontFaceCCW) - .field("depthBiasEnabled", &RasterizerState::depthBiasEnabled) - .field("depthBias", &RasterizerState::depthBias) - .field("depthBiasClamp", &RasterizerState::depthBiasClamp) - .field("depthBiasSlop", &RasterizerState::depthBiasSlop) - .field("isDepthClip", &RasterizerState::isDepthClip) - .field("isMultisample", &RasterizerState::isMultisample) - .field("lineWidth", &RasterizerState::lineWidth); - function("RasterizerStateInstance", &GenInstance::instance); - - value_object("DepthStencilState") - .field("depthTest", &DepthStencilState::depthTest) - .field("depthWrite", &DepthStencilState::depthWrite) - .field("depthFunc", &DepthStencilState::depthFunc) - .field("stencilTestFront", &DepthStencilState::stencilTestFront) - .field("stencilFuncFront", &DepthStencilState::stencilFuncFront) - .field("stencilReadMaskFront", &DepthStencilState::stencilReadMaskFront) - .field("stencilWriteMaskFront", &DepthStencilState::stencilWriteMaskFront) - .field("stencilFailOpFront", &DepthStencilState::stencilFailOpFront) - .field("stencilZFailOpFront", &DepthStencilState::stencilZFailOpFront) - .field("stencilPassOpFront", &DepthStencilState::stencilPassOpFront) - .field("stencilRefFront", &DepthStencilState::stencilRefFront) - .field("stencilFuncBack", &DepthStencilState::stencilFuncBack) - .field("stencilReadMaskBack", &DepthStencilState::stencilReadMaskBack) - .field("stencilWriteMaskBack", &DepthStencilState::stencilWriteMaskBack) - .field("stencilFailOpBack", &DepthStencilState::stencilFailOpBack) - .field("stencilZFailOpBack", &DepthStencilState::stencilZFailOpBack) - .field("stencilPassOpBack", &DepthStencilState::stencilPassOpBack) - .field("stencilRefBack", &DepthStencilState::stencilRefBack); - function("DepthStencilStateInstance", &GenInstance::instance); - - value_object("BlendTarget") - .field("blend", &BlendTarget::blend) - .field("blendSrc", &BlendTarget::blendSrc) - .field("blendDst", &BlendTarget::blendDst) - .field("blendEq", &BlendTarget::blendEq) - .field("blendSrcAlpha", &BlendTarget::blendSrcAlpha) - .field("blendDstAlpha", &BlendTarget::blendDstAlpha) - .field("blendAlphaEq", &BlendTarget::blendAlphaEq) - .field("blendColorMask", &BlendTarget::blendColorMask); - function("BlendTargetInstance", &GenInstance::instance); - - value_object("BlendState") - .field("isA2C", &BlendState::isA2C) - .field("isIndepend", &BlendState::isIndepend) - .field("blendColor", &BlendState::blendColor) - .field("targets", &BlendState::targets); - function("BlendStateInstance", &GenInstance::instance); - - value_object("Color") - .field("x", &Color::x) - .field("y", &Color::y) - .field("z", &Color::z) - .field("w", &Color::w); - function("Color", &GenInstance::instance); - - value_object("QueueInfo") - .field("type", &QueueInfo::type); - function("QueueInfo", &GenInstance::instance); - - value_object("Rect") - .field("x", &Rect::x) - .field("y", &Rect::y) - .field("width", &Rect::width) - .field("height", &Rect::height); - function("Rect", &GenInstance::instance); - - value_object("Viewport") - .field("left", &Viewport::left) - .field("top", &Viewport::top) - .field("width", &Viewport::width) - .field("height", &Viewport::height) - .field("minDepth", &Viewport::minDepth) - .field("maxDepth", &Viewport::maxDepth); - function("Viewport", &GenInstance::instance); - - value_object("DrawInfo") - .field("vertexCount", &DrawInfo::vertexCount) - .field("firstVertex", &DrawInfo::firstVertex) - .field("indexCount", &DrawInfo::indexCount) - .field("firstIndex", &DrawInfo::firstIndex) - .field("vertexOffset", &DrawInfo::vertexOffset) - .field("instanceCount", &DrawInfo::instanceCount) - .field("firstInstance", &DrawInfo::firstInstance); - function("DrawInfo", &GenInstance::instance); - - value_object("TextureBlit") - .field("srcSubres", &TextureBlit::srcSubres) - .field("srcOffset", &TextureBlit::srcOffset) - .field("srcExtent", &TextureBlit::srcExtent) - .field("dstSubres", &TextureBlit::dstSubres) - .field("dstOffset", &TextureBlit::dstOffset) - .field("dstExtent", &TextureBlit::dstExtent); - function("TextureBlit", &GenInstance::instance); - - // struct with pointers - class_("TextureInfoInstance") - .constructor<>() - .function("setType", &TextureInfoInstance::setType) - .function("setUsage", &TextureInfoInstance::setUsage) - .function("setFormat", &TextureInfoInstance::setFormat) - .function("setWidth", &TextureInfoInstance::setWidth) - .function("setHeight", &TextureInfoInstance::setHeight) - .function("setFlags", &TextureInfoInstance::setFlags) - .function("setLevelCount", &TextureInfoInstance::setLevelCount) - .function("setLayerCount", &TextureInfoInstance::setLayerCount) - .function("setSamples", &TextureInfoInstance::setSamples) - .function("setDepth", &TextureInfoInstance::setDepth) - .function("setImageBuffer", &TextureInfoInstance::setImageBuffer, allow_raw_pointer>()); - - class_("TextureViewInfoInstance") - .constructor<>() - .function("setTexture", &TextureViewInfoInstance::setTexture, allow_raw_pointer>()) - .function("setType", &TextureViewInfoInstance::setType) - .function("setFormat", &TextureViewInfoInstance::setFormat) - .function("setBaseLevel", &TextureViewInfoInstance::setBaseLevel) - .function("setLevelCount", &TextureViewInfoInstance::setLevelCount) - .function("setBaseLayer", &TextureViewInfoInstance::setBaseLayer) - .function("setLayerCount", &TextureViewInfoInstance::setLayerCount); - - class_("FramebufferInfoInstance") - .constructor<>() - .function("setRenderPass", &FramebufferInfoInstance::setRenderPass, allow_raw_pointer>()) - .function("setColorTextures", &FramebufferInfoInstance::setColorTextures, allow_raw_pointer>()) - .function("setDepthStencilTexture", &FramebufferInfoInstance::setDepthStencilTexture, allow_raw_pointer>()); - - class_("SwapchainInfoInstance") - .constructor<>() - .function("setWindowHandle", &SwapchainInfoInstance::setWindowHandle) - .function("setVsyncMode", &SwapchainInfoInstance::setVsyncMode) - .function("setWidth", &SwapchainInfoInstance::setWidth) - .function("setHeight", &SwapchainInfoInstance::setHeight); - - class_("BufferViewInfoInstance") - .constructor<>() - .function("setBuffer", &BufferViewInfoInstance::setBuffer, allow_raw_pointer>()) - .function("setOffset", &BufferViewInfoInstance::setOffset) - .function("setRange", &BufferViewInfoInstance::setRange); - - class_("DescriptorSetInfoInstance") - .constructor<>() - .function("setDescriptorSetLayout", &DescriptorSetInfoInstance::setDescriptorSetLayout, allow_raw_pointer>()); - - class_("PipelineStateInfoInstance") - .constructor<>() - .function("setShader", &PipelineStateInfoInstance::setShader, allow_raw_pointer>()) - .function("setPipelineLayout", &PipelineStateInfoInstance::setPipelineLayout, allow_raw_pointer>()) - .function("setRenderPass", &PipelineStateInfoInstance::setRenderPass, allow_raw_pointer>()) - .function("setInputState", &PipelineStateInfoInstance::setInputState) - .function("setRasterizerState", &PipelineStateInfoInstance::setRasterizerState) - .function("setDepthStencilState", &PipelineStateInfoInstance::setDepthStencilState) - .function("setBlendState", &PipelineStateInfoInstance::setBlendState) - .function("setPrimitiveMode", &PipelineStateInfoInstance::setPrimitiveMode) - .function("setDynamicStateFlags", &PipelineStateInfoInstance::setDynamicStateFlags) - .function("setPipelineBindPoint", &PipelineStateInfoInstance::setPipelineBindPoint) - .function("setSubpass", &PipelineStateInfoInstance::setSubpass); - - class_("InputAssemblerInfoInstance") - .constructor<>() - .function("setAttributes", &InputAssemblerInfoInstance::setAttributes) - .function("setBuffers", &InputAssemblerInfoInstance::setBuffers) - .function("setIndexBuffer", &InputAssemblerInfoInstance::setIndexBuffer, allow_raw_pointer>()) - .function("setIndirectBuffer", &InputAssemblerInfoInstance::setIndirectBuffer, allow_raw_pointer>()); - - class_("CommandBufferInfoInstance") - .constructor<>() - .function("setQueue", &CommandBufferInfoInstance::setQueue, allow_raw_pointer>()) - .function("setType", &CommandBufferInfoInstance::setType, allow_raw_pointer>()); - - class_("SPVShaderInfoInstance") - .constructor<>() - .function("setName", &SPVShaderInfoInstance::setName) - .function("setStages", &SPVShaderInfoInstance::setStages) - .function("setAttributes", &SPVShaderInfoInstance::setAttributes) - .function("setBlocks", &SPVShaderInfoInstance::setBlocks) - .function("setBuffers", &SPVShaderInfoInstance::setBuffers) - .function("setSamplerTextures", &SPVShaderInfoInstance::setSamplerTextures) - .function("setTextures", &SPVShaderInfoInstance::setTextures) - .function("setSamplers", &SPVShaderInfoInstance::setSamplers) - .function("setImages", &SPVShaderInfoInstance::setImages) - .function("setSubpasses", &SPVShaderInfoInstance::setSubpasses); - - class_("SPVShaderStageInstance") - .constructor<>() - .function("setStage", &SPVShaderStageInstance::setStage) - .function("setSPVData", &SPVShaderStageInstance::setSPVData); - - class_("DescriptorSetLayoutBindingInstance") - .constructor<>() - .function("setBinding", &DescriptorSetLayoutBindingInstance::setBinding) - .function("setDescriptorType", &DescriptorSetLayoutBindingInstance::setDescriptorType) - .function("setCount", &DescriptorSetLayoutBindingInstance::setCount) - .function("setStageFlags", &DescriptorSetLayoutBindingInstance::setStageFlags) - .function("setImmutableSamplers", &DescriptorSetLayoutBindingInstance::setImmutableSamplers); - - class_("BufferInfoInstance") - .constructor<>() - .function("setUsage", &BufferInfoInstance::setUsage) - .function("setMemUsage", &BufferInfoInstance::setMemUsage) - .function("setSize", &BufferInfoInstance::setSize) - .function("setStride", &BufferInfoInstance::setStride) - .function("setFlags", &BufferInfoInstance::setFlags); - - class_("DescriptorSetLayoutInfoInstance") - .constructor<>() - .function("setBindings", &DescriptorSetLayoutInfoInstance::setBindings); - + // register_vector("Uint32Vector"); + + EXPORT_STRUCT_POD(Size, x, y, z); + EXPORT_STRUCT_POD(DeviceCaps, maxVertexAttributes, maxVertexUniformVectors, maxFragmentUniformVectors, maxTextureUnits, maxImageUnits, maxVertexTextureUnits, maxColorRenderTargets, + maxShaderStorageBufferBindings, maxShaderStorageBlockSize, maxUniformBufferBindings, maxUniformBlockSize, maxTextureSize, maxCubeMapTextureSize, uboOffsetAlignment, + maxComputeSharedMemorySize, maxComputeWorkGroupInvocations, maxComputeWorkGroupSize, maxComputeWorkGroupCount, supportQuery, clipSpaceMinZ, screenSpaceSignY, clipSpaceSignY); + EXPORT_STRUCT_POD(Offset, x, y, z); + EXPORT_STRUCT_POD(Rect, x, y, width, height); + EXPORT_STRUCT_POD(Extent, width, height, depth); + EXPORT_STRUCT_POD(TextureSubresLayers, mipLevel, baseArrayLayer, layerCount); + EXPORT_STRUCT_POD(TextureCopy, srcSubres, srcOffset, dstSubres, dstOffset, extent); + EXPORT_STRUCT_POD(TextureBlit, srcSubres, srcOffset, srcExtent, dstSubres, dstOffset, dstExtent); + EXPORT_STRUCT_POD(BufferTextureCopy, buffOffset, buffStride, buffTexHeight, texOffset, texExtent, texSubres); + EXPORT_STRUCT_POD(Viewport, left, top, width, height, minDepth, maxDepth); + EXPORT_STRUCT_POD(Color, x, y, z, w); + EXPORT_STRUCT_POD(BindingMappingInfo, maxBlockCounts, maxSamplerTextureCounts, maxSamplerCounts, maxTextureCounts, maxBufferCounts, maxImageCounts, maxSubpassInputCounts, setIndices); + // SwapchainInfo ignore windowHandle + EXPORT_STRUCT_NPOD(SwapchainInfo, vsyncMode, width, height); + EXPORT_STRUCT_POD(DeviceInfo, bindingMappingInfo); + EXPORT_STRUCT_POD(BufferInfo, usage, memUsage, size, stride, flags); + EXPORT_STRUCT_NPOD(BufferViewInfo, buffer, offset, range); + EXPORT_STRUCT_POD(DrawInfo, vertexCount, firstVertex, indexCount, firstIndex, vertexOffset, instanceCount, firstInstance); + EXPORT_STRUCT_NPOD(DispatchInfo, groupCountX, groupCountY, groupCountZ, indirectBuffer, indirectOffset); + EXPORT_STRUCT_POD(IndirectBuffer, drawInfos); + EXPORT_STRUCT_NPOD(TextureInfo, type, usage, format, width, height, flags, layerCount, levelCount, samples, depth, externalRes); + EXPORT_STRUCT_NPOD(TextureViewInfo, texture, type, format, baseLevel, levelCount, baseLayer, layerCount); + EXPORT_STRUCT_POD(SamplerInfo, minFilter, magFilter, mipFilter, addressU, addressV, addressW, maxAnisotropy, cmpFunc); + EXPORT_STRUCT_POD(Uniform, name, type, count); + EXPORT_STRUCT_POD(UniformBlock, set, binding, name, members, count); + EXPORT_STRUCT_POD(UniformSamplerTexture, set, binding, name, type, count); + EXPORT_STRUCT_POD(UniformSampler, set, binding, name, count); + EXPORT_STRUCT_POD(UniformTexture, set, binding, name, type, count); + EXPORT_STRUCT_POD(UniformStorageImage, set, binding, name, type, count, memoryAccess); + EXPORT_STRUCT_POD(UniformStorageBuffer, set, binding, name, count, memoryAccess); + EXPORT_STRUCT_POD(UniformInputAttachment, set, binding, name, count); + EXPORT_STRUCT_POD(ShaderStage, stage, source); + EXPORT_STRUCT_POD(Attribute, name, format, isNormalized, stream, isInstanced, location); + EXPORT_STRUCT_POD(ShaderInfo, name, stages, attributes, blocks, buffers, samplerTextures, samplers, textures, images, subpassInputs); + EXPORT_STRUCT_NPOD(InputAssemblerInfo, attributes, vertexBuffers, indexBuffer, indirectBuffer); + EXPORT_STRUCT_NPOD(ColorAttachment, format, sampleCount, loadOp, storeOp, barrier, isGeneralLayout); + EXPORT_STRUCT_NPOD(DepthStencilAttachment, format, sampleCount, depthLoadOp, depthStoreOp, stencilLoadOp, stencilStoreOp, barrier, isGeneralLayout); + EXPORT_STRUCT_POD(SubpassInfo, inputs, colors, resolves, preserves, depthStencil, depthStencilResolve, depthResolveMode, stencilResolveMode); + + // MAYBE TODO(Zeqiang): all ts related backend no need to care about barriers. + EXPORT_STRUCT_POD(SubpassDependency, srcSubpass, dstSubpass, bufferBarrierCount, textureBarrierCount); + EXPORT_STRUCT_POD(RenderPassInfo, colorAttachments, depthStencilAttachment, subpasses, dependencies); + EXPORT_STRUCT_POD(GeneralBarrierInfo, prevAccesses, nextAccesses, type); + EXPORT_STRUCT_NPOD(TextureBarrierInfo, prevAccesses, nextAccesses, type, baseMipLevel, levelCount, baseSlice, sliceCount, discardContents, srcQueue, dstQueue); + EXPORT_STRUCT_NPOD(BufferBarrierInfo, prevAccesses, nextAccesses, type, offset, size, discardContents, srcQueue, dstQueue); + EXPORT_STRUCT_NPOD(FramebufferInfo, renderPass, colorTextures, depthStencilTexture); + EXPORT_STRUCT_NPOD(DescriptorSetLayoutBinding, binding, descriptorType, count, stageFlags, immutableSamplers); + EXPORT_STRUCT_POD(DescriptorSetLayoutInfo, bindings); + EXPORT_STRUCT_NPOD(DescriptorSetInfo, layout); + EXPORT_STRUCT_NPOD(PipelineLayoutInfo, setLayouts); + EXPORT_STRUCT_POD(InputState, attributes); + EXPORT_STRUCT_POD(RasterizerState, isDiscard, polygonMode, shadeModel, cullMode, isFrontFaceCCW, depthBiasEnabled, depthBias, depthBiasClamp, depthBiasSlop, isDepthClip, isMultisample, lineWidth); + EXPORT_STRUCT_POD(DepthStencilState, depthTest, depthWrite, depthFunc, stencilTestFront, stencilFuncFront, stencilReadMaskFront, stencilWriteMaskFront, stencilFailOpFront, stencilZFailOpFront, stencilPassOpFront, + stencilRefFront, stencilTestBack, stencilFuncBack, stencilReadMaskBack, stencilWriteMaskBack, stencilFailOpBack, stencilZFailOpBack, stencilPassOpBack, stencilRefBack); + EXPORT_STRUCT_POD(BlendTarget, blend, blendSrc, blendDst, blendEq, blendSrcAlpha, blendDstAlpha, blendAlphaEq, blendColorMask); + EXPORT_STRUCT_POD(BlendState, isA2C, isIndepend, blendColor, targets) + // MAYBE TODO(Zeqiang): no subpass in TS now + EXPORT_STRUCT_NPOD(PipelineStateInfo, shader, pipelineLayout, renderPass, inputState, rasterizerState, depthStencilState, blendState, primitive, dynamicStates, bindPoint); + EXPORT_STRUCT_NPOD(CommandBufferInfo, queue); + EXPORT_STRUCT_POD(QueueInfo, type); + EXPORT_STRUCT_POD(QueryPoolInfo, type, maxQueryObjects, forceWait); + // EXPORT_STRUCT_POD(FormatInfo, name, size, count, type, hasAlpha, hasDepth, hasStencil, isCompressed); + EXPORT_STRUCT_POD(MemoryStatus, bufferSize, textureSize); + EXPORT_STRUCT_POD(DynamicStencilStates, writeMask, compareMask, reference); + EXPORT_STRUCT_POD(DynamicStates, viewport, scissor, blendConstant, lineWidth, depthBiasConstant, depthBiasClamp, depthBiasSlope, depthMinBounds, depthMaxBounds, stencilStatesFront, stencilStatesBack); //--------------------------------------------------CLASS--------------------------------------------------------------------------- - class_("Swapchain") - .function("initialize", &cc::gfx::Swapchain::initialize, allow_raw_pointer>()) - .function("destroy", &cc::gfx::Swapchain::destroy) - .function("resize", select_overload(&cc::gfx::Swapchain::resize)) - .function("destroySurface", &cc::gfx::Swapchain::destroySurface) - .function("createSurface", &cc::gfx::Swapchain::createSurface, allow_raw_pointer>()) - .function("getWidth", &cc::gfx::Swapchain::getWidth) - .function("getHeight", &cc::gfx::Swapchain::getHeight); + class_("Swapchain") + .function("initialize", &Swapchain::initialize, allow_raw_pointer>()) + .function("destroy", &Swapchain::destroy) + .function("resize", select_overload(&Swapchain::resize)) + .function("destroySurface", &Swapchain::destroySurface) + .function("createSurface", &Swapchain::createSurface, allow_raw_pointer>()) + .property("width", &Swapchain::getWidth) + .property("height", &Swapchain::getHeight) + .property("surfaceTransform", &Swapchain::getSurfaceTransform) + .property("objectID", &Swapchain::getObjectID); class_>("CCWGPUSwapchain") - .function("getColorTexture", select_overload(&cc::gfx::CCWGPUSwapchain::getColorTexture), allow_raw_pointer>()) - .function("getDepthStencilTexture", select_overload(&cc::gfx::CCWGPUSwapchain::getDepthStencilTexture), allow_raw_pointer>()); + .property("depthStencilTexture", &CCWGPUSwapchain::getDepthStencilTexture, &CCWGPUSwapchain::setDepthStencilTexture) + .property("colorTexture", &CCWGPUSwapchain::getColorTexture, &CCWGPUSwapchain::setColorTexture); class_("Device") - .function("initialize", &Device::initialize, allow_raw_pointer>()) + .function("initialize", &Device::initialize) .function("destroy", &Device::destroy, pure_virtual()) .function("present", &Device::present, pure_virtual()) - .function("createQueue", select_overload(&Device::createQueue), - /* pure_virtual(), */ allow_raw_pointer>()) + .function("createQueue", select_overload(&Device::createQueue), allow_raw_pointer>()) + .function("createSwapchain", select_overload(&Device::createSwapchain), allow_raw_pointer>()) + .function("createRenderPass", select_overload(&Device::createRenderPass)) + .function("createFramebuffer", select_overload(&Device::createFramebuffer), allow_raw_pointer>()) + .function("createBuffer", select_overload(&Device::createBuffer), allow_raw_pointer>()) + .function("createBufferView", select_overload(&Device::createBuffer), allow_raw_pointer>()) + .function("createTexture", select_overload(&Device::createTexture), allow_raw_pointer>()) + .function("createTextureView", select_overload(&Device::createTexture), allow_raw_pointer>()) + .function("createDescriptorSetLayout", select_overload(&Device::createDescriptorSetLayout), allow_raw_pointer>()) + .function("createInputAssembler", select_overload(&Device::createInputAssembler), allow_raw_pointer>()) + .function("createPipelineState", select_overload(&Device::createPipelineState), allow_raw_pointer>()) + .function("createDescriptorSet", select_overload(&Device::createDescriptorSet), allow_raw_pointer>()) + .function("createPipelineLayout", select_overload(&Device::createPipelineLayout), allow_raw_pointer>()) .function("getSampler", &Device::getSampler, allow_raw_pointer>()) - .function("createRenderPass", select_overload(&Device::createRenderPass), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createPipelineLayout", select_overload(&Device::createPipelineLayout), - /* pure_virtual(), */ allow_raw_pointer>()) - // .function("createGlobalBarrier", select_overload(&Device::createGlobalBarrier), - // /* pure_virtual(), */ allow_raw_pointer>()) + .function("getGeneralBarrier", &Device::getGeneralBarrier, allow_raw_pointer>()) // .function("createTextureBarrier", select_overload(&Device::createTextureBarrier), // /* pure_virtual(), */ allow_raw_pointer>()) - .function("getCommandBuffer", &Device::getCommandBuffer, allow_raw_pointers()) - .function("getQueue", &Device::getQueue, allow_raw_pointers()) - .function("acquire", select_overload &)>(&Device::acquire), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("present", select_overload(&Device::present), - /* pure_virtual(), */ allow_raw_pointer>()); + // .function("flushCommands", &Device::flushCommands, allow_raw_pointers()) + .function("present", select_overload(&Device::present)) + .property("queue", &Device::getQueue) + .property("commandBuffer", &Device::getCommandBuffer) + .property("capabilities", &Device::getCapabilities) + .property("name", &Device::getDeviceName) + .property("renderer", &Device::getRenderer) + .property("vendor", &Device::getVendor) + .property("numDrawCalls", &Device::getNumDrawCalls) + .property("numInstances", &Device::getNumInstances) + .property("numTris", &Device::getNumTris); class_>("CCWGPUDevice") - .class_function("getInstance", &CCWGPUDevice::getInstance, allow_raw_pointer>()) - .function("debug", &CCWGPUDevice::debug) - .function("createSwapchain", select_overload(&CCWGPUDevice::createSwapchain), - /* pure_virtual(), */ allow_raw_pointers()) - .function("createCommandBuffer", select_overload(&CCWGPUDevice::createCommandBuffer), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createFramebuffer", select_overload(&CCWGPUDevice::createFramebuffer), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createBuffer", select_overload(&CCWGPUDevice::createBuffer), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createBufferView", select_overload(&CCWGPUDevice::createBuffer), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createTexture", select_overload(&CCWGPUDevice::createTexture), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createTextureView", select_overload(&CCWGPUDevice::createTexture), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createShader", select_overload(&CCWGPUDevice::createShader), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createDescriptorSetLayout", select_overload(&CCWGPUDevice::createDescriptorSetLayout), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createInputAssembler", select_overload(&CCWGPUDevice::createInputAssembler), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createPipelineState", select_overload(&CCWGPUDevice::createPipelineState), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("createDescriptorSet", select_overload(&CCWGPUDevice::createDescriptorSet), - /* pure_virtual(), */ allow_raw_pointer>()) - .function("copyTextureToBuffers", select_overload(&CCWGPUDevice::copyTextureToBuffers), - /* pure_virtual(), */ allow_raw_pointers()) - .function("copyBuffersToTexture", select_overload(&CCWGPUDevice::copyBuffersToTexture), - /* pure_virtual(), */ allow_raw_pointers()); - - class_("RenderPass") - .class_function("computeHash", select_overload(&RenderPass::computeHash), allow_raw_pointer>()) - .function("initialize", &cc::gfx::RenderPass::initialize, allow_raw_pointer>()) - .function("destroy", &cc::gfx::RenderPass::destroy) - .function("getColorAttachments", &cc::gfx::RenderPass::getColorAttachments) - .function("DepthStencilAttachment", &cc::gfx::RenderPass::getDepthStencilAttachment) - .function("SubpassInfoList", &cc::gfx::RenderPass::getSubpasses) - .function("SubpassDependencyList", &cc::gfx::RenderPass::getDependencies) - .function("getHash", &cc::gfx::RenderPass::getHash); - class_>("CCWGPURenderPass") + // .class_function("getInstance", &CCWGPUDevice::getInstance, allow_raw_pointer>()) .constructor<>() - .function("getThis", select_overload(&cc::gfx::getThis), allow_raw_pointer>()); + .function("debug", &CCWGPUDevice::debug) - class_("Texture") + .function("acquire", select_overload &)>(&CCWGPUDevice::acquire), + /* pure_virtual(), */ allow_raw_pointer>()) + .function("createShaderNative", select_overload(&CCWGPUDevice::createShader), + /* pure_virtual(), */ allow_raw_pointer>()) + .function("copyTextureToBuffers", select_overload(&CCWGPUDevice::copyTextureToBuffers), + /* pure_virtual(), */ allow_raw_pointers()) + .function("copyBuffersToTexture", select_overload &)>(&CCWGPUDevice::copyBuffersToTexture), + /* pure_virtual(), */ allow_raw_pointers()) + .function("getFormatFeatures", select_overload(&CCWGPUDevice::getFormatFeatures)) + .function("hasFeature", &CCWGPUDevice::hasFeature) + .property("gfxAPI", &CCWGPUDevice::getGFXAPI) + .property("memoryStatus", &CCWGPUDevice::getMemStatus); + + class_("RenderPass") + .class_function("computeHash", select_overload(&RenderPass::computeHash), allow_raw_pointer>()) + .function("destroy", &RenderPass::destroy) + .function("initialize", select_overload(&CCWGPURenderPass::initialize), allow_raw_pointer>()) + .property("colorAttachments", &RenderPass::getColorAttachments) + .property("depthStencilAttachment", &RenderPass::getDepthStencilAttachment) + .property("subpasses", &RenderPass::getSubpasses) + .property("dependencies", &RenderPass::getDependencies) + .property("hash", &RenderPass::getHash) + .property("objectID", &RenderPass::getObjectID); + class_>("CCWGPURenderPass") + .constructor<>(); + + class_("Texture") .class_function("computeHash", select_overload(&Texture::computeHash), allow_raw_pointer>()) - .function("initialize", select_overload(&cc::gfx::Texture::initialize), allow_raw_pointer>()) - .function("initialize", select_overload(&cc::gfx::Texture::initialize), allow_raw_pointer>()) - .function("destroy", &cc::gfx::Texture::destroy) - .function("resize", &cc::gfx::Texture::resize); - class_>("CCWGPUTexture") + .function("initialize", select_overload(&Texture::initialize), allow_raw_pointer>()) + .function("initializeView", select_overload(&Texture::initialize), allow_raw_pointer>()) + .function("destroy", &Texture::destroy) + .function("resize", &Texture::resize) + .property("info", &Texture::getInfo) + .property("viewInfo", &Texture::getViewInfo) + .property("width", &Texture::getWidth) + .property("height", &Texture::getHeight) + .property("size", &Texture::getSize) + .property("isTextureView", &Texture::isTextureView) + .property("objectID", &Texture::getObjectID); + class_>("CCWGPUTexture") + .property("depth", &CCWGPUTexture::getDepth) + .property("layerCount", &CCWGPUTexture::getLayerCount) + .property("levelCount", &CCWGPUTexture::getLevelCount) + .property("type", &CCWGPUTexture::getTextureType) + .property("usage", &CCWGPUTexture::getTextureUsage) + .property("format", &CCWGPUTexture::getTextureFormat) + .property("samples", &CCWGPUTexture::getTextureSamples) + .property("flags", &CCWGPUTexture::getTextureFlags) .constructor<>(); - class_("Framebuffer") + class_("Framebuffer") .class_function("computeHash", select_overload(&Framebuffer::computeHash), allow_raw_pointer>()) - .function("initialize", &cc::gfx::Framebuffer::initialize, allow_raw_pointer>()) - .function("destroy", &cc::gfx::Framebuffer::destroy) - .function("getRenderPass", &cc::gfx::Framebuffer::getRenderPass, allow_raw_pointer>()) - .function("getColorTextures", &cc::gfx::Framebuffer::getColorTextures, allow_raw_pointer>()) - .function("getDepthStencilTexture", &cc::gfx::Framebuffer::getDepthStencilTexture, allow_raw_pointer>()); + .function("destroy", &Framebuffer::destroy) + .function("initialize", &Framebuffer::initialize, allow_raw_pointer>()) + .property("objectID", &Framebuffer::getObjectID); class_>("CCWGPUFramebuffer") - .constructor<>(); + .constructor<>() + .property("renderPass", &CCWGPUFramebuffer::getRenderPass, &CCWGPUFramebuffer::setRenderPass) + .property("colorTextures", &CCWGPUFramebuffer::getColorTextures, &CCWGPUFramebuffer::setColorTextures) + .property("depthStencilTexture", &CCWGPUFramebuffer::getDepthStencilTexture, &CCWGPUFramebuffer::setDepthStencilTexture); class_("Sampler") - .function("getInfo", &Sampler::getInfo); + .function("getInfo", &Sampler::getInfo) + .property("hash", &Sampler::getHash) + .property("objectID", &Sampler::getObjectID); class_>("CCWGPUSampler") .constructor(); class_("Buffer") - .function("initialize", select_overload(&Buffer::initialize), allow_raw_pointer>()) - .function("initialize", select_overload(&Buffer::initialize), allow_raw_pointer>()) .function("resize", &Buffer::resize) - .function("destroy", &Buffer::destroy); + .function("destroy", &Buffer::destroy) + .property("size", &Buffer::getSize) + .property("stride", &Buffer::getStride) + .property("count", &Buffer::getCount) + .property("usage", &Buffer::getUsage) + .property("memUsage", &Buffer::getMemUsage) + .property("flags", &Buffer::getFlags) + .property("objectID", &Buffer::getObjectID); class_>("CCWGPUBuffer") - .function("update", select_overload(&CCWGPUBuffer::update), allow_raw_pointer>()) - .function("updateDrawInfo", select_overload(&CCWGPUBuffer::update), allow_raw_pointer>()) + // .function("update", select_overload(&CCWGPUBuffer::update), allow_raw_pointer>()) + .function("update", select_overload(&CCWGPUBuffer::update)) .constructor<>(); class_("DescriptorSetLayout") .function("initialize", &DescriptorSetLayout::initialize) - .function("destroy", &DescriptorSetLayout::destroy); + .function("destroy", &DescriptorSetLayout::destroy) + .property("bindings", &DescriptorSetLayout::getBindings) + .property("bindingIndices", &DescriptorSetLayout::getBindingIndices) + .property("descriptorIndices", &DescriptorSetLayout::getDescriptorIndices) + .property("objectID", &DescriptorSetLayout::getObjectID); class_>("CCWGPUDescriptorSetLayout") .constructor<>(); @@ -987,110 +262,148 @@ EMSCRIPTEN_BINDINGS(WEBGPU_DEVICE_WASM_EXPORT) { .function("destroy", &DescriptorSet::destroy) .function("update", &DescriptorSet::update) .function("bindBuffer", select_overload(&DescriptorSet::bindBuffer), allow_raw_pointer>()) + .function("bindBuffer", select_overload(&DescriptorSet::bindBuffer), allow_raw_pointer>()) .function("bindTexture", select_overload(&DescriptorSet::bindTexture), allow_raw_pointer>()) - .function("bindSampler", select_overload(&DescriptorSet::bindSampler), allow_raw_pointer>()); + .function("bindTexture", select_overload(&DescriptorSet::bindTexture), allow_raw_pointer>()) + .function("bindSampler", select_overload(&DescriptorSet::bindSampler), allow_raw_pointer>()) + .function("bindSampler", select_overload(&DescriptorSet::bindSampler), allow_raw_pointer>()) + .function("getBuffer", select_overload(&DescriptorSet::getBuffer), allow_raw_pointers()) + .function("getBuffer", select_overload(&DescriptorSet::getBuffer), allow_raw_pointers()) + .function("getTexture", select_overload(&DescriptorSet::getTexture), allow_raw_pointers()) + .function("getTexture", select_overload(&DescriptorSet::getTexture), allow_raw_pointers()) + .function("getSampler", select_overload(&DescriptorSet::getSampler), allow_raw_pointers()) + .function("getSampler", select_overload(&DescriptorSet::getSampler), allow_raw_pointers()) + .property("layout", &DescriptorSet::getLayout) + .property("objectID", &DescriptorSet::getObjectID); class_>("CCWGPUDescriptorSet") .constructor<>(); class_("PipelineLayout") .function("initialize", &PipelineLayout::initialize) - .function("destroy", &PipelineLayout::destroy); + .function("destroy", &PipelineLayout::destroy) + .property("setLayouts", &PipelineLayout::getSetLayouts) + .property("objectID", &PipelineLayout::getObjectID); class_>("CCWGPUPipelineLayout") .constructor<>(); class_("Shader") .function("initialize", &Shader::initialize) - .function("destroy", &Shader::destroy); + .function("destroy", &Shader::destroy) + .property("name", &Shader::getName) + .property("attributes", &Shader::getAttributes) + .property("blocks", &Shader::getBlocks) + .property("samplers", &Shader::getSamplers) + .property("stages", &Shader::getStages) + .property("buffers", &Shader::getBuffers) + .property("samplerTextures", &Shader::getSamplerTextures) + .property("textures", &Shader::getTextures) + .property("images", &Shader::getImages) + .property("subpassInputs", &Shader::getSubpassInputs) + .property("objectID", &Shader::getObjectID); class_>("CCWGPUShader") .constructor<>(); class_("InputAssembler") .function("initialize", &InputAssembler::initialize) - .function("destroy", &InputAssembler::destroy); + .function("destroy", &InputAssembler::destroy) + .property("drawInfo", &InputAssembler::getDrawInfo, &InputAssembler::setDrawInfo) + .property("vertexCount", &InputAssembler::getVertexCount, &InputAssembler::setVertexCount) + .property("firstVertex", &InputAssembler::getFirstVertex, &InputAssembler::setFirstVertex) + .property("indexCount", &InputAssembler::getIndexCount, &InputAssembler::setIndexCount) + .property("firstIndex", &InputAssembler::getFirstIndex, &InputAssembler::setFirstIndex) + .property("vertexOffset", &InputAssembler::getVertexOffset, &InputAssembler::setVertexOffset) + .property("instanceCount", &InputAssembler::getInstanceCount, &InputAssembler::setInstanceCount) + .property("firstInstance", &InputAssembler::getFirstInstance, &InputAssembler::setFirstInstance) + .property("attributesHash", &InputAssembler::getAttributesHash) + .property("attributes", &InputAssembler::getAttributes) + .property("vertexBuffers", &InputAssembler::getVertexBuffers) + .property("indexBuffer", &InputAssembler::getIndexBuffer) + .property("indirectBuffer", &InputAssembler::getIndirectBuffer) + .property("objectID", &InputAssembler::getObjectID); class_>("CCWGPUInputAssembler") - .function("update", &CCWGPUInputAssembler::update) .constructor<>(); class_("CommandBuffer") .function("initialize", &CommandBuffer::initialize) .function("destroy", &CommandBuffer::destroy) - .function("begin", select_overload(&CommandBuffer::begin), allow_raw_pointers()) .function("end", &CommandBuffer::end) .function("endRenderPass", &CommandBuffer::endRenderPass) - .function("bindPipelineState", &CommandBuffer::bindPipelineState, allow_raw_pointer>()) - .function("bindDescriptorSet", select_overload &)>(&CommandBuffer::bindDescriptorSet), allow_raw_pointers()) - .function("bindInputAssembler", &CommandBuffer::bindInputAssembler, allow_raw_pointer>()) - .function("setViewport", &CommandBuffer::setViewport) - .function("setScissor", &CommandBuffer::setScissor) .function("setDepthBias", &CommandBuffer::setDepthBias) .function("setBlendConstants", &CommandBuffer::setBlendConstants) .function("setDepthBound", &CommandBuffer::setDepthBound) .function("setStencilWriteMask", &CommandBuffer::setStencilWriteMask) .function("setStencilCompareMask", &CommandBuffer::setStencilCompareMask) .function("nextSubpass", &CommandBuffer::nextSubpass) - .function("draw", select_overload(&CommandBuffer::draw)) .function("copyBuffersToTexture", select_overload(&CommandBuffer::copyBuffersToTexture), allow_raw_pointers()) .function("blitTexture", select_overload(&CommandBuffer::blitTexture), allow_raw_pointers()) .function("execute", select_overload(&CommandBuffer::execute), allow_raw_pointer>()) .function("dispatch", &CommandBuffer::dispatch) - .function("begin4", select_overload(&CommandBuffer::begin)) - .function("begin3", select_overload(&CommandBuffer::begin), allow_raw_pointers()) - .function("begin2", select_overload(&CommandBuffer::begin), allow_raw_pointers()) - .function("execute", select_overload(&CommandBuffer::execute)) - .function("bindDescriptorSet2", select_overload(&CommandBuffer::bindDescriptorSet), allow_raw_pointer>()) - .function("drawIA", select_overload(&CommandBuffer::draw), allow_raw_pointer>()) + .function("begin", select_overload(&CommandBuffer::begin)) + .function("begin", select_overload(&CommandBuffer::begin), allow_raw_pointers()) + .function("begin", select_overload(&CommandBuffer::begin), allow_raw_pointers()) + .function("begin", select_overload(&CommandBuffer::begin), allow_raw_pointers()) + .function("execute", select_overload(&CommandBuffer::execute), allow_raw_pointers()) .function("blitTexture2", select_overload(&CommandBuffer::blitTexture), allow_raw_pointers()) - .function("getQueue", &CommandBuffer::getQueue, allow_raw_pointer>()); + .function("draw", select_overload(&CommandBuffer::draw), allow_raw_pointers()) + .function("type", &CommandBuffer::getType) + .property("queue", &CommandBuffer::getQueue) + .property("numDrawCalls", &CommandBuffer::getNumDrawCalls) + .property("numInstances", &CommandBuffer::getNumInstances) + .property("numTris", &CommandBuffer::getNumTris) + .property("objectID", &CommandBuffer::getObjectID); class_>("CCWGPUCommandBuffer") .constructor<>() + .function("setViewport", select_overload(&CCWGPUCommandBuffer::setViewport)) + .function("setScissor", select_overload(&CCWGPUCommandBuffer::setScissor)) .function("beginRenderPass", select_overload(&CCWGPUCommandBuffer::beginRenderPass), allow_raw_pointers()) + .function("bindDescriptorSet", select_overload &)>(&CCWGPUCommandBuffer::bindDescriptorSet), allow_raw_pointers()) + .function("bindPipelineState", select_overload(&CCWGPUCommandBuffer::bindPipelineState), allow_raw_pointer>()) + .function("bindInputAssembler", select_overload(&CCWGPUCommandBuffer::bindInputAssembler), allow_raw_pointer>()) + .function("drawByInfo", select_overload(&CCWGPUCommandBuffer::draw)) .function("updateIndirectBuffer", select_overload(&CCWGPUCommandBuffer::updateIndirectBuffer), allow_raw_pointers()) .function("updateBuffer", select_overload(&CCWGPUCommandBuffer::updateBuffer), allow_raw_pointers()); class_("Queue") .function("initialize", &Queue::initialize) .function("destroy", &Queue::destroy) - .function("submit", select_overload(&Queue::submit)); - class_("CCWGPUQueue") + .function("submit", select_overload(&Queue::submit)) + .property("type", &Queue::getType) + .property("objectID", &Queue::getObjectID); + class_>("CCWGPUQueue") .constructor<>(); class_("PipelineState") .function("initialize", &Queue::initialize) - .function("destroy", &Queue::destroy); - class_("CCWGPUPipelineState") + .function("destroy", &Queue::destroy) + .property("shader", &PipelineState::getShader) + .property("pipelineLayout", &PipelineState::getPipelineLayout) + .property("primitive", &PipelineState::getPrimitive) + .property("rasterizerState", &PipelineState::getRasterizerState) + .property("depthStencilState", &PipelineState::getDepthStencilState) + .property("blendState", &PipelineState::getBlendState) + .property("inputState", &PipelineState::getInputState) + .property("dynamicStates", &PipelineState::getDynamicStates) + .property("renderPass", &PipelineState::getRenderPass) + .property("objectID", &PipelineState::getObjectID); + class_>("CCWGPUPipelineState") .constructor<>(); - //--------------------------------------------------CONTAINER----------------------------------------------------------------------- - register_vector("vector_int"); - register_vector("vector_uint32"); - register_vector("AccessTypeList"); - register_vector("SubpassInfoList"); - register_vector("ColorAttachmentList"); - register_vector("SubpassDependencyList"); - register_vector("TextureList"); - register_vector("BufferTextureCopyList"); - register_vector("SamplerList"); - register_vector("DescriptorSetLayoutBindingList"); - register_vector("DescriptorSetLayoutList"); - register_vector("UniformStorageImageList"); - register_vector("ShaderStageList"); - register_vector("AttributeList"); - register_vector("UniformBlockList"); - register_vector("UniformStorageBufferList"); - register_vector("UniformSamplerTextureList"); - register_vector("UniformTextureList"); - register_vector("UniformSamplerList"); - register_vector("UniformInputAttachmentList"); - register_vector("UniformList"); - register_vector("BlendTargetList"); - register_vector("CommandBufferList"); - register_vector("ColorList"); - register_vector("TextureBlitList"); - register_vector("DrawInfoList"); - register_vector("StringList"); - register_vector("BufferList"); - register_vector("SwapchainList"); - register_vector("SPVShaderStageList"); -}; + class_("GeneralBarrier") + .constructor() + .property("objectID", &GeneralBarrier::getObjectID); + class_("WGPUGeneralBarrier") + .constructor(); -} // namespace cc::gfx \ No newline at end of file + class_("BufferBarrier") + .constructor() + .property("objectID", &BufferBarrier::getObjectID); + class_("WGPUBufferBarrier") + .constructor(); + + class_("TextureBarrier") + .constructor() + .property("objectID", &TextureBarrier::getObjectID); + class_("WGPUTextureBarrier") + .constructor(); +}; +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp index 156252b5d8..965386bfd8 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp @@ -30,7 +30,11 @@ using namespace emscripten; namespace cc { namespace gfx { -CCWGPUFramebuffer::CCWGPUFramebuffer() : wrapper(val::object()) { +CCWGPUFramebuffer::CCWGPUFramebuffer() : Framebuffer() { +} + +CCWGPUFramebuffer::~CCWGPUFramebuffer() { + doDestroy(); } void CCWGPUFramebuffer::doInit(const FramebufferInfo &info) { diff --git a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.h b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.h index a66ddbef64..d0fcc4b039 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.h @@ -24,7 +24,9 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXFramebuffer.h" namespace cc { @@ -32,13 +34,19 @@ namespace gfx { class CCWGPUSwapchain; -class CCWGPUFramebuffer final : public emscripten::wrapper { +class CCWGPUFramebuffer final : public Framebuffer { public: CCWGPUFramebuffer(); - ~CCWGPUFramebuffer() = default; + ~CCWGPUFramebuffer(); inline CCWGPUSwapchain *swapchain() { return _swapchain; } + using Framebuffer::initialize; + + inline void setRenderPass(RenderPass *rp) { _renderPass = rp; } + inline void setColorTextures(const TextureList &colors) { _colorTextures = colors; } + inline void setDepthStencilTexture(Texture *dsTex) { _depthStencilTexture = dsTex; } + protected: void doInit(const FramebufferInfo &info) override; void doDestroy() override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.cpp b/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.cpp index 8e591ec0e3..01771be27d 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.cpp @@ -26,32 +26,25 @@ #include "WGPUInputAssembler.h" #include "WGPUObject.h" -using namespace emscripten; namespace cc { namespace gfx { -CCWGPUInputAssembler::CCWGPUInputAssembler() : wrapper(val::object()) { +CCWGPUInputAssembler::CCWGPUInputAssembler() : InputAssembler() { +} + +CCWGPUInputAssembler::~CCWGPUInputAssembler() { + doDestroy(); } void CCWGPUInputAssembler::doInit(const InputAssemblerInfo &info) { _gpuInputAssemblerObj = ccnew CCWGPUInputAssemblerObject; - // // typedef struct WGPUVertexState { - // // WGPUChainedStruct const * nextInChain; - // // WGPUShaderModule module; - // // char const * entryPoint; - // // uint32_t bufferCount; - // // WGPUVertexBufferLayout const * buffers; - // // } WGPUVertexState; - - // _gpuInputAssemblerObj->wgpuVertexState.nextInChain = nullptr; - // _gpuInputAssemblerObj->wgpuVertexState.module = } void CCWGPUInputAssembler::doDestroy() { -} - -void CCWGPUInputAssembler::update(const DrawInfo &info) { - _drawInfo = info; + if (_gpuInputAssemblerObj) { + delete _gpuInputAssemblerObj; + _gpuInputAssemblerObj = nullptr; + } } } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.h b/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.h index 65a9db4fe7..bc4094a677 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUInputAssembler.h @@ -24,24 +24,26 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXInputAssembler.h" namespace cc { namespace gfx { class CCWGPUInputAssemblerObject; - -class CCWGPUInputAssembler final : public emscripten::wrapper { +class CCWGPUBuffer; +class CCWGPUInputAssembler final : public InputAssembler { public: CCWGPUInputAssembler(); - ~CCWGPUInputAssembler() = default; + ~CCWGPUInputAssembler(); + + using InputAssembler::destroy; + using InputAssembler::initialize; inline CCWGPUInputAssemblerObject *gpuInputAssemblerObject() { return _gpuInputAssemblerObj; } - // ems export - void update(const DrawInfo &info); - protected: void doInit(const InputAssemblerInfo &info) override; void doDestroy() override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUObject.h b/native/cocos/renderer/gfx-wgpu/WGPUObject.h index deeab6dbe3..9e62b8bb45 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUObject.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUObject.h @@ -29,8 +29,10 @@ #include "WGPUDef.h" #include "base/Utils.h" #include "base/std/container/map.h" +#include "base/std/container/set.h" #include "base/std/container/unordered_map.h" #include "base/std/container/vector.h" +#include "base/threading/Semaphore.h" #include "gfx-base/GFXDef.h" class WGPURenderPassDescriptor; @@ -41,10 +43,10 @@ namespace cc { namespace gfx { constexpr uint8_t CC_WGPU_MAX_ATTACHMENTS = 16; - -constexpr uint8_t CC_WGPU_MAX_STREAM = 256; //not sure - +constexpr uint8_t CC_WGPU_MAX_STREAM = 256; // not sure constexpr decltype(nullptr) wgpuDefaultHandle = nullptr; +constexpr ccstd::hash_t WGPU_HASH_SEED = 0x811C9DC5; +constexpr uint8_t CC_WGPU_MAX_FRAME_COUNT = 3; const DescriptorType COMBINED_ST_IN_USE = DescriptorType::SAMPLER_TEXTURE | DescriptorType::INPUT_ATTACHMENT; @@ -63,20 +65,27 @@ struct CCWGPUResource { CCWGPUTexture *commonTexture = nullptr; CCWGPUTexture *storageTexture = nullptr; - CCWGPUSampler *sampler = nullptr; + CCWGPUSampler *filterableSampler = nullptr; + CCWGPUSampler *unfilterableSampler = nullptr; +}; + +struct CCWGPUInstanceObject { + WGPUInstance wgpuInstance = wgpuDefaultHandle; + WGPUSurface wgpuSurface = wgpuDefaultHandle; + WGPUAdapter wgpuAdapter = wgpuDefaultHandle; }; struct CCWGPUDeviceObject { WGPUDevice wgpuDevice = wgpuDefaultHandle; WGPUQueue wgpuQueue = wgpuDefaultHandle; + CCWGPUInstanceObject instance; CCWGPUResource defaultResources; }; struct CCWGPUSwapchainObject { WGPUSwapChain wgpuSwapChain = wgpuDefaultHandle; WGPUSurface wgpuSurface = wgpuDefaultHandle; - WGPUInstance wgpuInstance = wgpuDefaultHandle; CCWGPUTexture *swapchainColor = nullptr; CCWGPUTexture *swapchainDepthStencil = nullptr; @@ -95,14 +104,14 @@ struct CCWGPUTextureObject { WGPUTextureView selfView = wgpuDefaultHandle; }; -//The indirect drawIndexed parameters encoded in the buffer must be a tightly packed block -//of five 32-bit unsigned integer values (20 bytes total), given in the same order as the arguments for drawIndexed(). -// let drawIndexedIndirectParameters = new Uint32Array(5); -// drawIndexedIndirectParameters[0] = indexCount; -// drawIndexedIndirectParameters[1] = instanceCount; -// drawIndexedIndirectParameters[2] = firstIndex; -// drawIndexedIndirectParameters[3] = baseVertex; -// drawIndexedIndirectParameters[4] = 0; // firstInstance. Must be 0. +// The indirect drawIndexed parameters encoded in the buffer must be a tightly packed block +// of five 32-bit unsigned integer values (20 bytes total), given in the same order as the arguments for drawIndexed(). +// let drawIndexedIndirectParameters = new Uint32Array(5); +// drawIndexedIndirectParameters[0] = indexCount; +// drawIndexedIndirectParameters[1] = instanceCount; +// drawIndexedIndirectParameters[2] = firstIndex; +// drawIndexedIndirectParameters[3] = baseVertex; +// drawIndexedIndirectParameters[4] = 0; // firstInstance. Must be 0. struct CCWGPUDrawIndexedIndirectObject { uint32_t indexCount = 0; uint32_t instanceCount = 0; @@ -112,8 +121,8 @@ struct CCWGPUDrawIndexedIndirectObject { }; static_assert(sizeof(CCWGPUDrawIndexedIndirectObject) == 20, "WGPU drawIndexedIndirect structure validation failed!"); -//The indirect draw parameters encoded in the buffer must be a tightly packed block -//of four 32-bit unsigned integer values (16 bytes total), given in the same order as the arguments for draw(). +// The indirect draw parameters encoded in the buffer must be a tightly packed block +// of four 32-bit unsigned integer values (16 bytes total), given in the same order as the arguments for draw(). // let drawIndirectParameters = new Uint32Array(4); // drawIndirectParameters[0] = vertexCount; @@ -191,7 +200,6 @@ struct CCWGPUQueueObject { }; struct CCWGPUDescriptorSetObject { - uint32_t index = 0; CCWGPUDescriptorSet *descriptorSet = nullptr; uint32_t dynamicOffsetCount = 0; const uint32_t *dynamicOffsets = nullptr; @@ -227,6 +235,7 @@ struct CCWGPUStateCache { struct CCWGPUCommandBufferObject { bool renderPassBegan = false; + WGPUCommandBuffer wgpuCommandBuffer = wgpuDefaultHandle; WGPUCommandEncoder wgpuCommandEncoder = wgpuDefaultHandle; WGPURenderPassEncoder wgpuRenderPassEncoder = wgpuDefaultHandle; WGPUComputePassEncoder wgpuComputeEncoder = wgpuDefaultHandle; @@ -245,6 +254,158 @@ struct CCWGPUQueryPoolObject { ccstd::vector idPool; }; +template +class RecycleBin { +public: + RecycleBin() = default; + ~RecycleBin() = default; + RecycleBin(const RecycleBin &) = delete; + RecycleBin &operator=(const RecycleBin &) = delete; + + void collect(T t) { + _recycleBin.emplace(t); + } + + void purge() { + for (auto &t : _recycleBin) { + purge(t); + } + _recycleBin.clear(); + } + +private: + void purge(T t); + + ccstd::set _recycleBin; +}; + +template <> +inline void RecycleBin::purge(WGPUBuffer buffer) { + wgpuBufferDestroy(buffer); + wgpuBufferRelease(buffer); +} + +template <> +inline void RecycleBin::purge(WGPUQuerySet querySet) { + wgpuQuerySetDestroy(querySet); + wgpuQuerySetRelease(querySet); +} + +template <> +inline void RecycleBin::purge(WGPUTexture texture) { + wgpuTextureDestroy(texture); + wgpuTextureRelease(texture); +} + +struct CCWGPURecycleBin { + RecycleBin bufferBin; + RecycleBin textureBin; + RecycleBin queryBin; +}; + +namespace { +inline void onStagingBufferMapDone(WGPUBufferMapAsyncStatus status, void *userdata) { + if (status == WGPUBufferMapAsyncStatus_Success) { + auto *semaphore = static_cast(userdata); + semaphore->signal(); + } +} +} // namespace +constexpr uint32_t INIT_BUFFER_SIZE = 1024 * 1024 * 1; // 1MB + +class CCWGPUStagingBuffer { + CCWGPUStagingBuffer(const CCWGPUStagingBuffer &) = delete; + CCWGPUStagingBuffer &operator=(const CCWGPUStagingBuffer &) = delete; + CCWGPUStagingBuffer() = default; + ~CCWGPUStagingBuffer() = default; + +public: + explicit CCWGPUStagingBuffer(WGPUDevice device, const std::function &recycleFunc) + : _device(device), _size(INIT_BUFFER_SIZE), _recycleFunc(recycleFunc) { + WGPUBufferDescriptor desc = { + .label = "staging buffer", + .usage = WGPUBufferUsage_CopySrc | WGPUBufferUsage_MapWrite, + .size = _size, + .mappedAtCreation = true, + }; + _buffer = wgpuDeviceCreateBuffer(device, &desc); + _mappedData = wgpuBufferGetMappedRange(_buffer, 0, _size); + } + + uint32_t alloc(uint32_t size) { + // 1. what if it's still unmapped + if (!_mapped) { + Semaphore sem{0}; + wgpuBufferMapAsync(_buffer, WGPUMapMode_Write, 0, _size, onStagingBufferMapDone, &sem); + sem.wait(); + _mappedData = wgpuBufferGetMappedRange(_buffer, 0, _size); + _mapped = true; + } + + const auto oldOffset = _offset; + if (_offset + size > _size) { + const auto oldBuffer = _buffer; + const auto oldSize = _size; + const auto *oldMappedData = _mappedData; + + _size = utils::nextPOT(_offset + size); + WGPUBufferDescriptor desc = { + .label = "staging buffer", + .usage = WGPUBufferUsage_CopySrc | WGPUBufferUsage_MapWrite, + .size = _size, + .mappedAtCreation = true, + }; + _buffer = wgpuDeviceCreateBuffer(_device, &desc); + _mappedData = wgpuBufferGetMappedRange(_buffer, 0, _size); + _offset = 0; + + if (_mapped) { + memcpy(_mappedData, oldMappedData, oldSize); + _offset = oldOffset; + } else { + // do nothing, unmap means this buffer has flush its data to gpu + } + _recycleFunc(oldBuffer); + } + _offset += size; + return oldOffset; + } + + void destroy() { + if (_mapped) { + wgpuBufferUnmap(_buffer); + } + if (_recycleFunc) { + _recycleFunc(_buffer); + } + } + + void unmap() { + if (_mapped) { + wgpuBufferUnmap(_buffer); + _mapped = false; + } + _offset = 0; + } + + void *getMappedData(uint32_t offset) { + return static_cast(_mappedData) + offset; + } + + WGPUBuffer getBuffer() { + return _buffer; + } + +private: + WGPUDevice _device{wgpuDefaultHandle}; + WGPUBuffer _buffer{wgpuDefaultHandle}; + void *_mappedData{nullptr}; + uint32_t _size{0}; + uint32_t _offset{0}; + std::function _recycleFunc; + bool _mapped{false}; +}; + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp index 9727ea1ec5..65ca01c858 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp @@ -33,9 +33,15 @@ namespace cc { namespace gfx { +ccstd::map CCWGPUPipelineLayout::layoutMap; + using namespace emscripten; -CCWGPUPipelineLayout::CCWGPUPipelineLayout() : wrapper(val::object()) { +CCWGPUPipelineLayout::CCWGPUPipelineLayout() : PipelineLayout() { +} + +CCWGPUPipelineLayout::~CCWGPUPipelineLayout() { + doDestroy(); } void CCWGPUPipelineLayout::doInit(const PipelineLayoutInfo &info) { @@ -43,31 +49,42 @@ void CCWGPUPipelineLayout::doInit(const PipelineLayoutInfo &info) { } void CCWGPUPipelineLayout::prepare(const ccstd::set &setInUse) { + ccstd::hash_t hash = _setLayouts.size() * 2 + 1; + ccstd::hash_combine(hash, _setLayouts.size()); ccstd::vector layouts; - // _bgLayouts.clear(); for (size_t i = 0; i < _setLayouts.size(); i++) { auto *descriptorSetLayout = static_cast(_setLayouts[i]); if (setInUse.find(i) == setInUse.end()) { // give it default bindgrouplayout if not in use layouts.push_back(static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout())); - // _bgLayouts.push_back(static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout())); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, 9527); } else { if (!descriptorSetLayout->gpuLayoutEntryObject()->bindGroupLayout) { - descriptorSetLayout->prepare(); + printf("bgl in ppl is null\n"); + while (1) { + } } layouts.push_back(descriptorSetLayout->gpuLayoutEntryObject()->bindGroupLayout); - // _bgLayouts.push_back(descriptorSetLayout->gpuLayoutEntryObject()->bindGroupLayout); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, descriptorSetLayout->getHash()); } } + _hash = hash; + WGPUPipelineLayoutDescriptor descriptor = { .nextInChain = nullptr, .label = nullptr, .bindGroupLayoutCount = layouts.size(), .bindGroupLayouts = layouts.data(), }; - - _gpuPipelineLayoutObj->wgpuPipelineLayout = wgpuDeviceCreatePipelineLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + if (layoutMap.find(hash) != layoutMap.end()) { + _gpuPipelineLayoutObj->wgpuPipelineLayout = static_cast(layoutMap[hash]); + } else { + _gpuPipelineLayoutObj->wgpuPipelineLayout = wgpuDeviceCreatePipelineLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + layoutMap.emplace(hash, _gpuPipelineLayoutObj->wgpuPipelineLayout); + } } void CCWGPUPipelineLayout::doDestroy() { @@ -80,4 +97,4 @@ void CCWGPUPipelineLayout::doDestroy() { } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.h b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.h index 5cd33872bf..8a94aec3b8 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.h @@ -24,26 +24,35 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "WGPUUtils.h" +#include "base/std/container/map.h" #include "base/std/container/set.h" #include "gfx-base/GFXPipelineLayout.h" - namespace cc { namespace gfx { struct CCWGPUPipelineLayoutObject; +class DescriptorSet; -class CCWGPUPipelineLayout final : public emscripten::wrapper { +class CCWGPUPipelineLayout final : public PipelineLayout { public: CCWGPUPipelineLayout(); - ~CCWGPUPipelineLayout() = default; + ~CCWGPUPipelineLayout(); inline CCWGPUPipelineLayoutObject *gpuPipelineLayoutObject() { return _gpuPipelineLayoutObj; } - //bindgroup not ready yet so delay creation + // bindgroup not ready yet so delay creation void prepare(const ccstd::set &setInUse); - // const ccstd::vector & layouts()const{return _bgLayouts;} + const ccstd::vector &layouts() const { return _bgLayouts; } + const ccstd::vector &cclayouts() const { return _ccbgLayouts; } + + static ccstd::map layoutMap; + + inline ccstd::hash_t getHash() const { return _hash; } protected: void doInit(const PipelineLayoutInfo &info) override; @@ -51,7 +60,12 @@ protected: CCWGPUPipelineLayoutObject *_gpuPipelineLayoutObj = nullptr; - // ccstd::vector _bgLayouts; + ccstd::vector _bgLayouts; + ccstd::vector _ccbgLayouts; + + ccstd::hash_t _hash{0}; + + friend void createPipelineLayoutFallback(const ccstd::vector &descriptorSets, PipelineLayout *pipelineLayout); }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp index 2769a0f778..ef40d51c5d 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp @@ -37,21 +37,120 @@ namespace cc { namespace gfx { +ccstd::map CCWGPUPipelineState::pipelineMap; -using namespace emscripten; +namespace { +using ccstd::hash_combine; +ccstd::hash_t hash(const WGPURenderPipelineDescriptor &desc) { + ccstd::hash_t hash = 9527; + hash_combine(hash, desc.layout); + hash_combine(hash, desc.vertex.module); + hash_combine(hash, desc.vertex.entryPoint); + hash_combine(hash, desc.vertex.constantCount); + for (uint32_t i = 0; i < desc.vertex.constantCount; ++i) { + hash_combine(hash, desc.vertex.constants[i].key); + hash_combine(hash, desc.vertex.constants[i].value); + } -CCWGPUPipelineState::CCWGPUPipelineState() : wrapper(val::object()) { + hash_combine(hash, desc.vertex.bufferCount); + for (size_t i = 0; i < desc.vertex.bufferCount; ++i) { + const auto &buffer = desc.vertex.buffers[i]; + hash_combine(hash, buffer.arrayStride); + hash_combine(hash, buffer.stepMode); + hash_combine(hash, buffer.attributeCount); + for (size_t j = 0; j < buffer.attributeCount; ++j) { + const auto &attribute = buffer.attributes[j]; + hash_combine(hash, attribute.shaderLocation); + hash_combine(hash, attribute.offset); + hash_combine(hash, attribute.format); + } + } + + hash_combine(hash, desc.primitive.topology); + hash_combine(hash, desc.primitive.stripIndexFormat); + hash_combine(hash, desc.primitive.frontFace); + hash_combine(hash, desc.primitive.cullMode); + + if (desc.depthStencil) { + hash_combine(hash, desc.depthStencil->format); + hash_combine(hash, desc.depthStencil->depthWriteEnabled); + hash_combine(hash, desc.depthStencil->depthCompare); + hash_combine(hash, desc.depthStencil->stencilFront.compare); + hash_combine(hash, desc.depthStencil->stencilFront.failOp); + hash_combine(hash, desc.depthStencil->stencilFront.depthFailOp); + hash_combine(hash, desc.depthStencil->stencilFront.passOp); + hash_combine(hash, desc.depthStencil->stencilBack.compare); + hash_combine(hash, desc.depthStencil->stencilBack.failOp); + hash_combine(hash, desc.depthStencil->stencilBack.depthFailOp); + hash_combine(hash, desc.depthStencil->stencilBack.passOp); + hash_combine(hash, desc.depthStencil->stencilReadMask); + hash_combine(hash, desc.depthStencil->stencilWriteMask); + hash_combine(hash, desc.depthStencil->depthBias); + hash_combine(hash, desc.depthStencil->depthBiasSlopeScale); + hash_combine(hash, desc.depthStencil->depthBiasClamp); + } else { + hash_combine(hash, 0); + } + + hash_combine(hash, desc.multisample.count); + hash_combine(hash, desc.multisample.mask); + hash_combine(hash, desc.multisample.alphaToCoverageEnabled); + + if (desc.fragment) { + hash_combine(hash, desc.fragment->module); + hash_combine(hash, desc.fragment->entryPoint); + hash_combine(hash, desc.fragment->constantCount); + for (uint32_t i = 0; i < desc.fragment->constantCount; ++i) { + hash_combine(hash, desc.fragment->constants[i].key); + hash_combine(hash, desc.fragment->constants[i].value); + } + hash_combine(hash, desc.fragment->targetCount); + for (uint32_t i = 0; i < desc.fragment->targetCount; ++i) { + hash_combine(hash, desc.fragment->targets[i].format); + if (desc.fragment->targets[i].blend) { + hash_combine(hash, desc.fragment->targets[i].blend->color.operation); + hash_combine(hash, desc.fragment->targets[i].blend->color.srcFactor); + hash_combine(hash, desc.fragment->targets[i].blend->color.dstFactor); + hash_combine(hash, desc.fragment->targets[i].blend->alpha.operation); + hash_combine(hash, desc.fragment->targets[i].blend->alpha.srcFactor); + hash_combine(hash, desc.fragment->targets[i].blend->alpha.dstFactor); + } else { + hash_combine(hash, 0); + } + hash_combine(hash, desc.fragment->targets[i].writeMask); + } + } else { + hash_combine(hash, 0); + } + return hash; +} + +ccstd::hash_t hash(const WGPUComputePipelineDescriptor &desc) { + ccstd::hash_t hash = 9527; + hash_combine(hash, desc.layout); + // hash_combine(hash, desc.compute); + return hash; +} + +} // namespace + +CCWGPUPipelineState::CCWGPUPipelineState() : PipelineState() { +} + +CCWGPUPipelineState::~CCWGPUPipelineState() { + doDestroy(); } void CCWGPUPipelineState::doInit(const PipelineStateInfo &info) { _gpuPipelineStateObj = ccnew CCWGPUPipelineStateObject; } -void CCWGPUPipelineState::check(RenderPass *renderPass) { +void CCWGPUPipelineState::check(RenderPass *renderPass, bool forceUpdate) { if (_renderPass != renderPass) { _renderPass = renderPass; - _forceUpdate = true; + // _forceUpdate = true; } + _forceUpdate |= forceUpdate; } void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { @@ -63,6 +162,10 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { return; } + if (!_gpuPipelineStateObj->redundantAttr.empty()) { + _gpuPipelineStateObj->redundantAttr.clear(); + } + auto maxStreamAttr = std::max_element(_inputState.attributes.begin(), _inputState.attributes.end(), [&](const Attribute &lhs, const Attribute &rhs) { return lhs.stream < rhs.stream; }); @@ -80,9 +183,31 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { const AttributeList &attrs = _shader->getAttributes(); uint64_t offset[256] = {0}; // ccstd::vector wgpuAttrs; - bool isInstance = attrs.empty() ? false : attrs[0].isInstanced; - uint8_t index = 0; + for (size_t i = 0; i < _inputState.attributes.size(); ++i) { + const auto &attr = _inputState.attributes[i]; + const auto &attrName = attr.name; + auto iter = std::find_if(attrs.begin(), attrs.end(), [attrName](const Attribute &attr) { + return strcmp(attrName.c_str(), attr.name.c_str()) == 0; + }); + if (iter != attrs.end()) { + Format format = attr.format; + WGPUVertexAttribute attrInfo = { + .format = toWGPUVertexFormat(format), + .offset = offset[attr.stream], + .shaderLocation = (*iter).location, + }; + wgpuAttrsVec[attr.stream].push_back(attrInfo); + offset[attr.stream] += GFX_FORMAT_INFOS[static_cast(format)].size; + vbLayouts[attr.stream].stepMode = attr.isInstanced ? WGPUVertexStepMode_Instance : WGPUVertexStepMode_Vertex; + } else { + // all none-input attr are put in 1st buffer layout with offset = 0; + Format format = attr.format; + offset[attr.stream] += GFX_FORMAT_INFOS[static_cast(format)].size; + } + } + + // printf("cr shname %s %d\n", _shader->getName().c_str(), streamCount); // wgpuAttrsVec[0] ∪ wgpuAttrsVec[1] ∪ ... ∪ wgpuAttrsVec[n] == shader.attrs for (size_t i = 0; i < attrs.size(); i++) { ccstd::string attrName = attrs[i].name; @@ -90,16 +215,7 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { return strcmp(attrName.c_str(), attr.name.c_str()) == 0; }); - if (iter != _inputState.attributes.end()) { - Format format = (*iter).format; - WGPUVertexAttribute attr = { - .format = toWGPUVertexFormat(format), - .offset = offset[(*iter).stream], - .shaderLocation = attrs[i].location, - }; - wgpuAttrsVec[(*iter).stream].push_back(attr); - offset[(*iter).stream] += GFX_FORMAT_INFOS[static_cast(format)].size; - } else { + if (iter == _inputState.attributes.end()) { // all none-input attr are put in 1st buffer layout with offset = 0; Format format = attrs[i].format; WGPUVertexAttribute attr = { @@ -109,8 +225,8 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { }; if (GFX_FORMAT_INFOS[static_cast(format)].size > GFX_FORMAT_INFOS[static_cast((*longestAttr).format)].size) { - printf("found attr %s %s in shader exceed size of longest attr %s %s\n", attrName.c_str(), GFX_FORMAT_INFOS[static_cast(format)].name.c_str(), - (*longestAttr).name.c_str(), GFX_FORMAT_INFOS[static_cast((*longestAttr).format)].name.c_str()); + // printf("found attr %s %s in shader exceed size of longest attr %s %s\n", attrName.c_str(), GFX_FORMAT_INFOS[static_cast(format)].name.c_str(), + // (*longestAttr).name.c_str(), GFX_FORMAT_INFOS[static_cast((*longestAttr).format)].name.c_str()); _gpuPipelineStateObj->redundantAttr.push_back(attr); if (GFX_FORMAT_INFOS[static_cast(format)].size > _gpuPipelineStateObj->maxAttrLength) { _gpuPipelineStateObj->maxAttrLength = GFX_FORMAT_INFOS[static_cast(format)].size; @@ -119,41 +235,32 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { wgpuAttrsVec[mostToleranceStream].push_back(attr); } } - } - // input state has attr which shader hasnt. - for (size_t i = 0; i < _inputState.attributes.size(); ++i) { - ccstd::string attrName = _inputState.attributes[i].name; - const auto &attribute = _inputState.attributes[i]; - auto iter = std::find_if(attrs.begin(), attrs.end(), [attrName](const Attribute &attr) { - return strcmp(attrName.c_str(), attr.name.c_str()) == 0; - }); - if (iter == attrs.end()) { - Format format = attribute.format; - offset[attribute.stream] += GFX_FORMAT_INFOS[static_cast(format)].size; - } + // printf("sl %s, %d, %d\n", attrName.c_str(), attrs[i].location, attrs[i].stream); } if (_gpuPipelineStateObj->maxAttrLength > 0) { wgpuAttrsVec.push_back(_gpuPipelineStateObj->redundantAttr); vbLayouts.resize(vbLayouts.size() + 1); } + // _gpuPipelineStateObj->slotCount = vbLayouts.size(); + // std::set locSet; for (size_t i = 0; i < wgpuAttrsVec.size(); ++i) { - vbLayouts[i] = { - .arrayStride = offset[i], - .stepMode = isInstance ? WGPUVertexStepMode_Instance : WGPUVertexStepMode_Vertex, - .attributeCount = wgpuAttrsVec[i].size(), - .attributes = wgpuAttrsVec[i].data(), - }; - } + vbLayouts[i].arrayStride = offset[i]; + vbLayouts[i].attributeCount = static_cast(wgpuAttrsVec[i].size()); + vbLayouts[i].attributes = wgpuAttrsVec[i].data(); + // for (size_t j = 0; j < wgpuAttrsVec[i].size(); ++j) { + // printf("wg %d, %llu, %d\n", wgpuAttrsVec[i][j].shaderLocation, wgpuAttrsVec[i][j].offset, wgpuAttrsVec[i][j].format); - // WGPUVertexBufferLayout vertexBufferLayout = { - // .arrayStride = stride, // TODO_Zeqiang: ??? - // .stepMode = isInstance ? WGPUVertexStepMode_Instance : WGPUVertexStepMode_Vertex, - // .attributeCount = wgpuAttrs.size(), - // .attributes = wgpuAttrs.data(), - // }; + // // if (locSet.find(wgpuAttrsVec[i][j].shaderLocation) != locSet.end() && wgpuAttrsVec[i][j].shaderLocation != 0) { + // // printf("duplicate location %d\n", wgpuAttrsVec[i][j].shaderLocation); + // // while (1) { + // // } + // // } + // // locSet.insert(wgpuAttrsVec[i][j].shaderLocation); + // } + } WGPUVertexState vertexState = { .nextInChain = nullptr, @@ -168,7 +275,7 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { WGPUPrimitiveState primitiveState = { .nextInChain = nullptr, .topology = toWGPUPrimTopology(_primitive), - .stripIndexFormat = stripTopology ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Undefined, //TODO_Zeqiang: ??? + .stripIndexFormat = stripTopology ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Undefined, // TODO_Zeqiang: ??? .frontFace = _rasterizerState.isFrontFaceCCW ? WGPUFrontFace::WGPUFrontFace_CCW : WGPUFrontFace::WGPUFrontFace_CW, .cullMode = _rasterizerState.cullMode == CullMode::FRONT ? WGPUCullMode::WGPUCullMode_Front : _rasterizerState.cullMode == CullMode::BACK ? WGPUCullMode::WGPUCullMode_Back @@ -181,7 +288,6 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { .depthFailOp = toWGPUStencilOperation(_depthStencilState.stencilZFailOpFront), .passOp = toWGPUStencilOperation(_depthStencilState.stencilPassOpFront), }; - WGPUStencilFaceState stencilBack = { .compare = toWGPUCompareFunction(_depthStencilState.stencilFuncBack), .failOp = toWGPUStencilOperation(_depthStencilState.stencilFailOpBack), @@ -216,17 +322,20 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { for (size_t i = 0, targetIndex = 0; i < colors.size(); i++) { colorTargetStates[i].format = toWGPUTextureFormat(colors[i].format); + auto colorBO = _blendState.targets[targetIndex].blendEq; blendState[i].color = { - .operation = toWGPUBlendOperation(_blendState.targets[targetIndex].blendEq), - .srcFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendSrc), - .dstFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendDst), + .operation = toWGPUBlendOperation(colorBO), + .srcFactor = toWGPUBlendFactor(colorBO == BlendOp::MAX ? BlendFactor::ONE : _blendState.targets[targetIndex].blendSrc), + .dstFactor = toWGPUBlendFactor(colorBO == BlendOp::MAX ? BlendFactor::ONE : _blendState.targets[targetIndex].blendDst), }; + auto alphaBO = _blendState.targets[targetIndex].blendAlphaEq; blendState[i].alpha = { - .operation = toWGPUBlendOperation(_blendState.targets[targetIndex].blendAlphaEq), - .srcFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendSrcAlpha), - .dstFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendDstAlpha), + .operation = toWGPUBlendOperation(alphaBO), + .srcFactor = toWGPUBlendFactor(alphaBO == BlendOp::MAX ? BlendFactor::ONE : _blendState.targets[targetIndex].blendSrcAlpha), + .dstFactor = toWGPUBlendFactor(alphaBO == BlendOp::MAX ? BlendFactor::ONE : _blendState.targets[targetIndex].blendDstAlpha), }; - colorTargetStates[i].blend = &blendState[i]; + // only textureSampleType with float can be blended. + colorTargetStates[i].blend = textureSampleTypeTrait(colors[i].format) == WGPUTextureSampleType_Float ? &blendState[i] : nullptr; colorTargetStates[i].writeMask = toWGPUColorWriteMask(_blendState.targets[targetIndex].blendColorMask); if (targetIndex < _blendState.targets.size() - 1) { ++targetIndex; @@ -240,19 +349,11 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { .targets = colorTargetStates.data(), }; - pipelineLayout->prepare(setInUse); - // const auto setLayouts = pipelineLayout->getSetLayouts(); - // for (size_t i = 0; i < setLayouts.size(); ++i) { - // const auto* layout = setLayouts[i]; - // if (layout) { - // printf("---set %d---\n", i); - // static_cast(layout)->print(); - // } - // } + // pipelineLayout->prepare(setInUse); WGPURenderPipelineDescriptor piplineDesc = { .nextInChain = nullptr, - .label = nullptr, + .label = static_cast(_shader)->getName().c_str(), .layout = pipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout, .vertex = vertexState, .primitive = primitiveState, @@ -260,22 +361,45 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { .multisample = msState, .fragment = &fragmentState, }; - _gpuPipelineStateObj->wgpuRenderPipeline = wgpuDeviceCreateRenderPipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); + + auto hashVal = hash(piplineDesc); + _hash = hashVal; + + auto iter = pipelineMap.find(hashVal); + if (iter == pipelineMap.end()) { + _gpuPipelineStateObj->wgpuRenderPipeline = wgpuDeviceCreateRenderPipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); + printf("ppl %s\n", static_cast(_shader)->getName().c_str()); + pipelineMap[hashVal] = _gpuPipelineStateObj->wgpuRenderPipeline; + } else { + _gpuPipelineStateObj->wgpuRenderPipeline = static_cast(iter->second); + } _ppl = pipelineLayout; _forceUpdate = false; } else if (_bindPoint == PipelineBindPoint::COMPUTE) { - if (_gpuPipelineStateObj->wgpuComputePipeline) + if (_gpuPipelineStateObj->wgpuComputePipeline && !_forceUpdate) return; WGPUProgrammableStageDescriptor psDesc = { .module = static_cast(_shader)->gpuShaderObject()->wgpuShaderComputeModule, .entryPoint = "main", }; - pipelineLayout->prepare(setInUse); + // pipelineLayout->prepare(setInUse); WGPUComputePipelineDescriptor piplineDesc = { .layout = pipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout, .compute = psDesc, }; - _gpuPipelineStateObj->wgpuComputePipeline = wgpuDeviceCreateComputePipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); + auto hashVal = hash(piplineDesc); + _hash = hashVal; + + auto iter = pipelineMap.find(hashVal); + if (iter == pipelineMap.end()) { + _gpuPipelineStateObj->wgpuComputePipeline = wgpuDeviceCreateComputePipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); + printf("ppl %s\n", static_cast(_shader)->getName().c_str()); + pipelineMap[hashVal] = _gpuPipelineStateObj->wgpuComputePipeline; + } else { + _gpuPipelineStateObj->wgpuComputePipeline = static_cast(iter->second); + } + _ppl = pipelineLayout; + _forceUpdate = false; } else { printf("unsupport pipeline bind point"); } @@ -291,8 +415,9 @@ void CCWGPUPipelineState::doDestroy() { } delete _gpuPipelineStateObj; + _gpuPipelineStateObj = nullptr; } } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h index 6fca6fcc2b..e6ea201e99 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h @@ -24,7 +24,10 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "base/std/container/map.h" #include "base/std/container/set.h" #include "gfx-base/GFXPipelineState.h" @@ -33,19 +36,23 @@ namespace gfx { struct CCWGPUPipelineStateObject; -class CCWGPUPipelineState final : public emscripten::wrapper { +class CCWGPUPipelineState final : public PipelineState { public: CCWGPUPipelineState(); - ~CCWGPUPipelineState() = default; + ~CCWGPUPipelineState(); inline CCWGPUPipelineStateObject *gpuPipelineStateObject() { return _gpuPipelineStateObj; } - void check(RenderPass *renderPass); - + void check(RenderPass *renderPass, bool forceUpdate = false); void prepare(const ccstd::set &setInUse); + PipelineLayout *layout() const { return _pipelineLayout; } void *ppl() const { return _ppl; } + static ccstd::map pipelineMap; + + inline ccstd::hash_t getHash() const { return _hash; } + protected: void doInit(const PipelineStateInfo &info) override; void doDestroy() override; @@ -54,6 +61,7 @@ protected: void *_ppl = nullptr; bool _forceUpdate = false; + ccstd::hash_t _hash{0}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp b/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp index f154de7953..dae0bbd6c9 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp @@ -36,7 +36,7 @@ CCWGPUQueryPool::CCWGPUQueryPool() { } CCWGPUQueryPool::~CCWGPUQueryPool() { - destroy(); + doDestroy(); } void CCWGPUQueryPool::doInit(const QueryPoolInfo & /*info*/) { @@ -46,14 +46,14 @@ void CCWGPUQueryPool::doInit(const QueryPoolInfo & /*info*/) { _gpuQueryPool->maxQueryObjects = _maxQueryObjects; _gpuQueryPool->idPool.resize(_maxQueryObjects, 0U); - //TODO_Zeqiang: wgpu query + // TODO_Zeqiang: wgpu query - //cmdFuncGLES3CreateQuery(device, _gpuQueryPool); + // cmdFuncGLES3CreateQuery(device, _gpuQueryPool); } void CCWGPUQueryPool::doDestroy() { if (_gpuQueryPool) { - //cmdFuncGLES3DestroyQuery(GLES3Device::getInstance(), _gpuQueryPool); + // cmdFuncGLES3DestroyQuery(GLES3Device::getInstance(), _gpuQueryPool); delete _gpuQueryPool; _gpuQueryPool = nullptr; } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp b/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp index 1d5837a0c6..a0bad34207 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp @@ -35,7 +35,11 @@ namespace gfx { using namespace emscripten; -CCWGPUQueue::CCWGPUQueue() : wrapper(val::object()) { +CCWGPUQueue::CCWGPUQueue() : Queue() { +} + +CCWGPUQueue::~CCWGPUQueue() { + doDestroy(); } void CCWGPUQueue::doInit(const QueueInfo &info) { @@ -50,9 +54,20 @@ void CCWGPUQueue::doDestroy() { wgpuQueueRelease(_gpuQueueObject->wgpuQueue); } delete _gpuQueueObject; + _gpuQueueObject = nullptr; } } +namespace { + +void wgpuQueueSubmitCallback(WGPUQueueWorkDoneStatus status, void *userdata) { + auto *recycleBin = static_cast(userdata); + recycleBin->bufferBin.purge(); + recycleBin->textureBin.purge(); + recycleBin->queryBin.purge(); +} +} // namespace + void CCWGPUQueue::submit(CommandBuffer *const *cmdBuffs, uint32_t count) { // ccstd::vector commandBuffs(count); // for (size_t i = 0; i < count; i++) { @@ -64,7 +79,25 @@ void CCWGPUQueue::submit(CommandBuffer *const *cmdBuffs, uint32_t count) { // auto* commandBuff = static_cast(cmdBuffs[i]); // wgpuCommandBufferRelease(commandBuff->gpuCommandBufferObject()->wgpuCommandBuffer); // } + + // CCWGPUDevice::getInstance()->stagingBuffer()->unmap(); + + ccstd::vector wgpuCmdBuffs(count); + for (size_t i = 0; i < count; ++i) { + const auto *cmdBuff = static_cast(cmdBuffs[i]); + wgpuCmdBuffs[i] = cmdBuff->gpuCommandBufferObject()->wgpuCommandBuffer; + + _numDrawCalls += cmdBuff->getNumDrawCalls(); + _numInstances += cmdBuff->getNumInstances(); + _numTriangles += cmdBuff->getNumTris(); + } + + wgpuQueueSubmit(_gpuQueueObject->wgpuQueue, count, wgpuCmdBuffs.data()); + std::for_each(wgpuCmdBuffs.begin(), wgpuCmdBuffs.end(), [](auto wgpuCmdBuffer) { wgpuCommandBufferRelease(wgpuCmdBuffer); }); + + auto *recycleBin = CCWGPUDevice::getInstance()->recycleBin(); + wgpuQueueOnSubmittedWorkDone(_gpuQueueObject->wgpuQueue, 0, wgpuQueueSubmitCallback, recycleBin); } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueue.h b/native/cocos/renderer/gfx-wgpu/WGPUQueue.h index 163ed709c2..c6e6469123 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueue.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueue.h @@ -25,7 +25,9 @@ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXQueue.h" namespace cc { @@ -33,21 +35,28 @@ namespace gfx { struct CCWGPUQueueObject; -class CCWGPUQueue final : public emscripten::wrapper { +class CCWGPUQueue final : public Queue { public: - EMSCRIPTEN_WRAPPER(CCWGPUQueue); CCWGPUQueue(); - ~CCWGPUQueue() = default; + ~CCWGPUQueue(); void submit(CommandBuffer *const *cmdBuffs, uint32_t count) override; - inline CCWGPUQueueObject *gpuQueueObject() { return _gpuQueueObject; } + inline uint32_t getNumDrawCalls() const { return _numDrawCalls; } + inline uint32_t getNumInstances() const { return _numInstances; } + inline uint32_t getNumTris() const { return _numTriangles; } + + inline void resetStatus() { _numDrawCalls = _numInstances = _numTriangles = 0; } protected: void doInit(const QueueInfo &info) override; void doDestroy() override; CCWGPUQueueObject *_gpuQueueObject = nullptr; + + uint32_t _numDrawCalls = 0; + uint32_t _numInstances = 0; + uint32_t _numTriangles = 0; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp index e3d1442357..22c10b664c 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp @@ -41,7 +41,7 @@ public: for (size_t i = 0; i < info.colorAttachments.size(); i++) { colors[i].loadOp = toWGPULoadOp(info.colorAttachments[i].loadOp); colors[i].storeOp = toWGPUStoreOp(info.colorAttachments[i].storeOp); - colors[i].clearColor = defaultClearColor; + colors[i].clearValue = defaultClearColor; // TODO_Zeqaing : subpass if (info.colorAttachments[i].sampleCount != SampleCount::ONE) samples = info.colorAttachments[i].sampleCount; @@ -52,7 +52,7 @@ public: depthStencils[0].depthStoreOp = toWGPUStoreOp(info.depthStencilAttachment.depthStoreOp); depthStencils[0].stencilLoadOp = toWGPULoadOp(info.depthStencilAttachment.stencilLoadOp); depthStencils[0].stencilStoreOp = toWGPUStoreOp(info.depthStencilAttachment.stencilStoreOp); - depthStencils[0].clearDepth = defaultClearDepth; + depthStencils[0].depthClearValue = defaultClearDepth; depthStencils[0].depthReadOnly = false; depthStencils[0].stencilReadOnly = false; if (samples == SampleCount::ONE) @@ -60,7 +60,7 @@ public: renderPassDesc = ccnew WGPURenderPassDescriptor; - //TODO_Zeqiang: Metal-like subpass + // TODO_Zeqiang: Metal-like subpass renderPassDesc->colorAttachmentCount = info.colorAttachments.size(); renderPassDesc->colorAttachments = colors.data(); renderPassDesc->depthStencilAttachment = depthStencils.data(); @@ -81,7 +81,11 @@ public: int sampleCount = 1; }; -CCWGPURenderPass::CCWGPURenderPass() : wrapper(val::object()) { +CCWGPURenderPass::CCWGPURenderPass() : RenderPass() { +} + +CCWGPURenderPass::~CCWGPURenderPass() { + doDestroy(); } void CCWGPURenderPass::doInit(const RenderPassInfo &info) { diff --git a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h index 1f86efeee6..08d5103742 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h +++ b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h @@ -25,7 +25,9 @@ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXRenderPass.h" namespace cc { @@ -34,14 +36,15 @@ namespace gfx { struct CCWGPURenderPassObject; class CCWGPURenderPassHelper; -class CCWGPURenderPass final : public emscripten::wrapper { +class CCWGPURenderPass final : public RenderPass { public: - EMSCRIPTEN_WRAPPER(CCWGPURenderPass); CCWGPURenderPass(); - ~CCWGPURenderPass() = default; + ~CCWGPURenderPass(); inline CCWGPURenderPassObject *gpuRenderPassObject() { return _renderPassObject; } + using RenderPass::initialize; + protected: void doInit(const RenderPassInfo &info) override; void doDestroy() override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp b/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp index 8ef8d292e7..64972e3a9f 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp @@ -32,16 +32,17 @@ namespace cc { namespace gfx { -namespace anoymous { -CCWGPUSampler *defaultSampler = nullptr; -} +namespace { +CCWGPUSampler *dftFilterableSampler = nullptr; +CCWGPUSampler *dftUnfilterableSampler = nullptr; +} // namespace using namespace emscripten; -CCWGPUSampler::CCWGPUSampler(const SamplerInfo &info) : wrapper(val::object(), info) { +CCWGPUSampler::CCWGPUSampler(const SamplerInfo &info) : Sampler(info) { WGPUSamplerDescriptor descriptor = { .nextInChain = nullptr, - .label = nullptr, + .label = (std::to_string(static_cast(info.minFilter)) + " " + std::to_string(static_cast(info.magFilter)) + " " + std::to_string(static_cast(info.mipFilter))).c_str(), .addressModeU = toWGPUAddressMode(info.addressU), .addressModeV = toWGPUAddressMode(info.addressV), .addressModeW = toWGPUAddressMode(info.addressW), @@ -50,7 +51,7 @@ CCWGPUSampler::CCWGPUSampler(const SamplerInfo &info) : wrapper(val::ob .mipmapFilter = toWGPUFilterMode(info.mipFilter), .lodMinClamp = 0.0f, .lodMaxClamp = std::numeric_limits::max(), - .compare = WGPUCompareFunction_Undefined, //toWGPUCompareFunction(info.cmpFunc), + .compare = WGPUCompareFunction_Undefined, // toWGPUCompareFunction(info.cmpFunc), .maxAnisotropy = static_cast(info.maxAnisotropy), }; @@ -62,21 +63,38 @@ CCWGPUSampler::~CCWGPUSampler() { wgpuSamplerRelease(_wgpuSampler); } -CCWGPUSampler *CCWGPUSampler::defaultSampler() { - if (!anoymous::defaultSampler) { +CCWGPUSampler *CCWGPUSampler::defaultFilterableSampler() { + if (!dftFilterableSampler) { SamplerInfo info = { .minFilter = Filter::LINEAR, .magFilter = Filter::LINEAR, - .mipFilter = Filter::NONE, + .mipFilter = Filter::LINEAR, .addressU = Address::WRAP, .addressV = Address::WRAP, .addressW = Address::WRAP, .maxAnisotropy = 0, .cmpFunc = ComparisonFunc::ALWAYS, }; - anoymous::defaultSampler = ccnew CCWGPUSampler(info); + dftFilterableSampler = ccnew CCWGPUSampler(info); } - return anoymous::defaultSampler; + return dftFilterableSampler; +} + +CCWGPUSampler *CCWGPUSampler::defaultUnfilterableSampler() { + if (!dftUnfilterableSampler) { + SamplerInfo info = { + .minFilter = Filter::POINT, + .magFilter = Filter::POINT, + .mipFilter = Filter::POINT, + .addressU = Address::WRAP, + .addressV = Address::WRAP, + .addressW = Address::WRAP, + .maxAnisotropy = 0, + .cmpFunc = ComparisonFunc::ALWAYS, + }; + dftUnfilterableSampler = ccnew CCWGPUSampler(info); + } + return dftUnfilterableSampler; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSampler.h b/native/cocos/renderer/gfx-wgpu/WGPUSampler.h index b49737d854..7873b7f64b 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSampler.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUSampler.h @@ -24,7 +24,9 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/states/GFXSampler.h" #include "WGPUobject.h" @@ -32,19 +34,18 @@ namespace cc { namespace gfx { -class CCWGPUSampler final : public emscripten::wrapper { +class CCWGPUSampler final : public Sampler { public: - EMSCRIPTEN_WRAPPER(CCWGPUSampler); explicit CCWGPUSampler(const SamplerInfo &info); ~CCWGPUSampler(); - inline WGPUSampler gpuSampler() { return _wgpuSampler; } + inline WGPUSampler gpuSampler() const { return _wgpuSampler; } - static CCWGPUSampler *defaultSampler(); + static CCWGPUSampler *defaultFilterableSampler(); + static CCWGPUSampler *defaultUnfilterableSampler(); - //stamp current state + // stamp current state void stamp() {} - bool internalChanged() const { return false; } protected: diff --git a/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp b/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp index 18291820c9..43d7cf09c0 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp @@ -28,18 +28,29 @@ #include "WGPUDevice.h" #include "WGPUObject.h" #include "WGPUUtils.h" +#define USE_NATRIVE_SPIRV 0 +#if USE_NATRIVE_SPIRV + #include "gfx-base/SPIRVUtils.h" + #ifndef SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS + #define SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS + #endif + #include "spirv_cross/spirv_msl.hpp" +#endif namespace cc { namespace gfx { - using namespace emscripten; +SPIRVUtils *CCWGPUShader::spirv = nullptr; -CCWGPUShader::CCWGPUShader() : wrapper(val::object()) { +CCWGPUShader::CCWGPUShader() : Shader() { } -void CCWGPUShader::initialize(const SPVShaderInfoInstance &spvInfo) { +CCWGPUShader::~CCWGPUShader() { + doDestroy(); +} + +void CCWGPUShader::initialize(const ShaderInfo &info, const std::vector> &spirvs) { _gpuShaderObject = ccnew CCWGPUShaderObject; - const ShaderInfo &info = spvInfo.info; _name = info.name; _stages = info.stages; @@ -53,10 +64,98 @@ void CCWGPUShader::initialize(const SPVShaderInfoInstance &spvInfo) { _subpassInputs = info.subpassInputs; _gpuShaderObject->name = info.name; - for (size_t i = 0; i < spvInfo.stages.size(); i++) { - const auto &stage = spvInfo.stages[i]; - auto *spvData = spvInfo.stages[i].spv.data(); - size_t size = spvInfo.stages[i].spv.size(); + for (size_t i = 0; i < info.stages.size(); i++) { + const auto &stage = info.stages[i]; + auto *spvData = spirvs[i].data(); + size_t size = spirvs[i].size(); + + WGPUShaderModuleSPIRVDescriptor spv = {}; + spv.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor; + spv.codeSize = size; + spv.code = spvData; + WGPUShaderModuleDescriptor desc = {}; + desc.nextInChain = reinterpret_cast(&spv); + desc.label = _name.c_str(); + if (stage.stage == ShaderStageFlagBit::VERTEX) { + _gpuShaderObject->wgpuShaderVertexModule = wgpuDeviceCreateShaderModule(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &desc); + } else if (stage.stage == ShaderStageFlagBit::FRAGMENT) { + _gpuShaderObject->wgpuShaderFragmentModule = wgpuDeviceCreateShaderModule(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &desc); + } else if (stage.stage == ShaderStageFlagBit::COMPUTE) { + _gpuShaderObject->wgpuShaderComputeModule = wgpuDeviceCreateShaderModule(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &desc); + } else { + printf("unsupport shader stage."); + } + } +} + +const std::string spirvProcess(const uint32_t *data, size_t size, const UniformSamplerTextureList &list) { +#if USE_NATRIVE_SPIRV + spirv_cross::CompilerMSL compiler(data, size); + auto executionModel = compiler.get_execution_model(); + + auto active = compiler.get_active_interface_variables(); + spirv_cross::ShaderResources resources = compiler.get_shader_resources(active); + compiler.set_enabled_interface_variables(std::move(active)); + + // Set some options. + spirv_cross::CompilerMSL::Options options; + options.enable_decoration_binding = true; + options.set_msl_version(2, 3, 0); + compiler.set_msl_options(options); + + printf("size should be eq %d ,%d\n", list.size(), resources.sampled_images.size()); + + for (size_t i = 0; i < resources.sampled_images.size(); ++i) { + const auto &sampler = resources.sampled_images[i]; + auto set = compiler.get_decoration(sampler.id, spv::DecorationDescriptorSet); + auto binding = compiler.get_decoration(sampler.id, spv::DecorationBinding); + int size = 1; + // const spirv_cross::SPIRType &type = msl.get_type(sampler.type_id); + // if (type.array_size_literal[0]) { + // size = type.array[0]; + // } + + // for (int i = 0; i < size; ++i) { + spirv_cross::MSLResourceBinding newBinding; + newBinding.stage = executionModel; + newBinding.desc_set = set; + newBinding.binding = list[i].binding; + newBinding.msl_texture = binding; + newBinding.msl_sampler = binding + 16; + compiler.add_msl_resource_binding(newBinding); + + // if (gpuShader->samplers.find(mappedBinding) == gpuShader->samplers.end()) { + // gpuShader->samplers[mappedBinding] = {sampler.name, set, binding, newBinding.msl_texture, newBinding.msl_sampler, shaderType}; + // } else { + // gpuShader->samplers[mappedBinding].stages |= shaderType; + // } + // ++gpuShader->samplerIndex; + // } + } + + const std::string &msl = compiler.compile(); + return msl; +#else + return std::string{}; +#endif +} + +void CCWGPUShader::doInit(const ShaderInfo &info) { +#if USE_NATRIVE_SPIRV + _gpuShaderObject = ccnew CCWGPUShaderObject; + if (!spirv) { + spirv = SPIRVUtils::getInstance(); + spirv->initialize(1); + } + _gpuShaderObject->name = info.name; + for (auto &stage : info.stages) { + spirv->compileGLSL(stage.stage, "#version 450\n" + stage.source); + // const auto &data = spirv->getOutputData(); + + std::string glsl = spirvProcess(spirv->getOutputData(), spirv->getOutputSize() / sizeof(uint32_t), _samplerTextures); + spirv->compileGLSL(stage.stage, glsl); + auto *spvData = spirv->getOutputData(); + size_t size = spirv->getOutputSize() / sizeof(uint32_t); WGPUShaderModuleSPIRVDescriptor spv = {}; spv.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor; @@ -75,9 +174,8 @@ void CCWGPUShader::initialize(const SPVShaderInfoInstance &spvInfo) { printf("unsupport shader stage."); } } -} - -void CCWGPUShader::doInit(const ShaderInfo &info) { +// printf("sahdername: %s\n", info.name.c_str()); +#endif } void CCWGPUShader::doDestroy() { @@ -92,6 +190,7 @@ void CCWGPUShader::doDestroy() { wgpuShaderModuleRelease(_gpuShaderObject->wgpuShaderComputeModule); } delete _gpuShaderObject; + _gpuShaderObject = nullptr; } } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUShader.h b/native/cocos/renderer/gfx-wgpu/WGPUShader.h index c46c694c8c..8f8729572e 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUShader.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUShader.h @@ -24,31 +24,37 @@ ****************************************************************************/ #pragma once - -#include -#include "WGPUDef.h" +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif #include "gfx-base/GFXShader.h" namespace cc { namespace gfx { struct CCWGPUShaderObject; +class SPIRVUtils; -class CCWGPUShader final : public emscripten::wrapper { +class CCWGPUShader final : public Shader { public: - EMSCRIPTEN_WRAPPER(CCWGPUShader); CCWGPUShader(); - ~CCWGPUShader() = default; + ~CCWGPUShader(); inline CCWGPUShaderObject *gpuShaderObject() { return _gpuShaderObject; } - void initialize(const SPVShaderInfoInstance &info); + void initialize(const ShaderInfo &info) { doInit(info); } + + // ems export + EXPORT_EMS( + void initialize(const ShaderInfo &info, emscripten::val &spirvs);) + void initialize(const ShaderInfo &info, const std::vector> &spirvs); protected: void doInit(const ShaderInfo &info) override; void doDestroy() override; CCWGPUShaderObject *_gpuShaderObject = nullptr; + static SPIRVUtils *spirv; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp index 5fba3a178c..d35e75249b 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp @@ -37,17 +37,22 @@ CCWGPUSwapchain::CCWGPUSwapchain(CCWGPUDevice *device) { CCWGPUSwapchain::~CCWGPUSwapchain() { _device = nullptr; + doDestroy(); } void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { - WGPUSurfaceDescriptorFromCanvasHTMLSelector canvDesc = {}; - canvDesc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; - canvDesc.selector = "canvas"; + printf("swapchain init %d, %d\n", info.width, info.height); + // WGPUSurfaceDescriptorFromCanvasHTMLSelector canvDesc = {}; + // canvDesc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; + // canvDesc.selector = "canvas"; - WGPUSurfaceDescriptor surfDesc = {}; - surfDesc.nextInChain = reinterpret_cast(&canvDesc); - WGPUSurface surface = wgpuInstanceCreateSurface(nullptr, &surfDesc); + // WGPUSurfaceDescriptor surfDesc = {}; + // surfDesc.nextInChain = reinterpret_cast(&canvDesc); + // WGPUSurface surface = wgpuInstanceCreateSurface(nullptr, &surfDesc); + auto *device = CCWGPUDevice::getInstance(); + CCWGPUDeviceObject *gpuDeviceObj = device->gpuDeviceObject(); + auto surface = gpuDeviceObj->instance.wgpuSurface; WGPUPresentMode presentMode; switch (info.vsyncMode) { case VsyncMode::OFF: @@ -69,7 +74,6 @@ void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { presentMode = WGPUPresentMode_Fifo; } - auto *device = CCWGPUDevice::getInstance(); WGPUSwapChainDescriptor swapChainDesc; swapChainDesc.nextInChain = nullptr; swapChainDesc.label = "defaultSwapChain"; @@ -79,7 +83,6 @@ void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { swapChainDesc.height = info.height; swapChainDesc.presentMode = presentMode; - CCWGPUDeviceObject *gpuDeviceObj = device->gpuDeviceObject(); WGPUSwapChain swapChain = wgpuDeviceCreateSwapChain(gpuDeviceObj->wgpuDevice, surface, &swapChainDesc); _gpuSwapchainObj = ccnew CCWGPUSwapchainObject; _gpuSwapchainObj->wgpuSwapChain = swapChain; @@ -92,6 +95,10 @@ void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { .height = info.height, }; + printf("swapchain init %d, %d\n", info.width, info.height); + + printf("swapchain tex init %d, %d\n", textureInfo.width, textureInfo.height); + _colorTexture = _gpuSwapchainObj->swapchainColor = ccnew CCWGPUTexture; initTexture(textureInfo, _gpuSwapchainObj->swapchainColor); textureInfo.format = Format::DEPTH_STENCIL; @@ -104,14 +111,16 @@ void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { } void CCWGPUSwapchain::doDestroy() { - // wgpuSurfaceRelease(_gpuSwapchainObj->wgpuSurface); - // wgpuSwapChainRelease(_gpuSwapchainObj->wgpuSwapChain); + wgpuSwapChainRelease(_gpuSwapchainObj->wgpuSwapChain); CCWGPUDevice::getInstance()->unRegisterSwapchain(this); - delete _gpuSwapchainObj->swapchainColor; - delete _gpuSwapchainObj->swapchainDepthStencil; - delete _gpuSwapchainObj; + if (_gpuSwapchainObj) { + delete _gpuSwapchainObj->swapchainColor; + delete _gpuSwapchainObj->swapchainDepthStencil; + delete _gpuSwapchainObj; + _gpuSwapchainObj = nullptr; + } } void CCWGPUSwapchain::doResize(uint32_t width, uint32_t height, SurfaceTransform transform) { @@ -119,16 +128,10 @@ void CCWGPUSwapchain::doResize(uint32_t width, uint32_t height, SurfaceTransform _depthStencilTexture->resize(height, height); } -CCWGPUTexture *CCWGPUSwapchain::getColorTexture() { - return static_cast(_colorTexture); -} - -CCWGPUTexture *CCWGPUSwapchain::getDepthStencilTexture() { - return static_cast(_depthStencilTexture); -} - void CCWGPUSwapchain::update() { - static_cast(_colorTexture)->gpuTextureObject()->selfView = wgpuSwapChainGetCurrentTextureView(_gpuSwapchainObj->wgpuSwapChain); + auto swapchainView = static_cast(_colorTexture.get())->gpuTextureObject()->selfView; + wgpuTextureViewRelease(swapchainView); + static_cast(_colorTexture.get())->gpuTextureObject()->selfView = wgpuSwapChainGetCurrentTextureView(_gpuSwapchainObj->wgpuSwapChain); } void CCWGPUSwapchain::doDestroySurface() { diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h index 2d78812b9e..8e9c064d7f 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h @@ -42,9 +42,8 @@ public: inline CCWGPUSwapchainObject *gpuSwapchainObject() { return _gpuSwapchainObj; } - CCWGPUTexture *getColorTexture(); - - CCWGPUTexture *getDepthStencilTexture(); + inline void setColorTexture(Texture *tex) { _colorTexture = tex; } + inline void setDepthStencilTexture(Texture *tex) { _depthStencilTexture = tex; } void update(); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp index fadbbd29f9..654845c276 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp @@ -33,22 +33,27 @@ namespace cc { namespace gfx { -namespace anoymous { -CCWGPUTexture *defaultCommonTexture = nullptr; -CCWGPUTexture *defaultStorageTexture = nullptr; -} // namespace anoymous +namespace { +CCWGPUTexture *dftCommonTexture = nullptr; +CCWGPUTexture *dftStorageTexture = nullptr; +} // namespace using namespace emscripten; -CCWGPUTexture::CCWGPUTexture() : wrapper(val::object()) { +CCWGPUTexture::CCWGPUTexture() : Texture() { _gpuTextureObj = ccnew CCWGPUTextureObject; } +CCWGPUTexture::~CCWGPUTexture() { + doDestroy(); +} + void CCWGPUTexture::doInit(const TextureInfo &info) { uint8_t depthOrArrayLayers = info.depth; if (info.type == TextureType::CUBE) { depthOrArrayLayers = 6; } + WGPUTextureDescriptor descriptor = { .nextInChain = nullptr, .label = nullptr, @@ -61,6 +66,7 @@ void CCWGPUTexture::doInit(const TextureInfo &info) { }; _gpuTextureObj->wgpuTexture = wgpuDeviceCreateTexture(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize += _size; WGPUTextureViewDescriptor texViewDesc = { .nextInChain = nullptr, @@ -99,6 +105,7 @@ void CCWGPUTexture::doInit(const TextureViewInfo &info) { void CCWGPUTexture::doInit(const SwapchainTextureInfo &info) { if (_swapchain) { + printf("swapchain %d, %d\n", info.width, info.height); auto *swapchain = static_cast(_swapchain); if (info.format == Format::DEPTH || info.format == Format::DEPTH_STENCIL) { WGPUTextureDescriptor descriptor = { @@ -112,6 +119,7 @@ void CCWGPUTexture::doInit(const SwapchainTextureInfo &info) { .sampleCount = 1, }; _gpuTextureObj->wgpuTexture = wgpuDeviceCreateTexture(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize += _size; WGPUTextureAspect aspect = info.format == Format::DEPTH ? WGPUTextureAspect_DepthOnly : WGPUTextureAspect_All; WGPUTextureViewDescriptor texViewDesc = { @@ -136,16 +144,17 @@ void CCWGPUTexture::doInit(const SwapchainTextureInfo &info) { void CCWGPUTexture::doDestroy() { if (_gpuTextureObj) { if (_gpuTextureObj->wgpuTexture) { - wgpuTextureDestroy(_gpuTextureObj->wgpuTexture); - wgpuTextureRelease(_gpuTextureObj->wgpuTexture); + CCWGPUDevice::getInstance()->moveToTrash(_gpuTextureObj->wgpuTexture); + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize -= _size; } if (_gpuTextureObj->wgpuTextureView) { wgpuTextureViewRelease(_gpuTextureObj->wgpuTextureView); } - if (_gpuTextureObj->selfView) { + if (_gpuTextureObj->selfView && !_isTextureView) { wgpuTextureViewRelease(_gpuTextureObj->selfView); } delete _gpuTextureObj; + _gpuTextureObj = nullptr; } _internalChanged = true; } @@ -156,9 +165,14 @@ void CCWGPUTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { printf("Resize is not support on texture view!"); return; } + // swapchain color tex using canvas + if (_swapchain && _info.format != Format::DEPTH && _info.format != Format::DEPTH_STENCIL) { + auto *swapchain = static_cast(_swapchain); + _gpuTextureObj->selfView = wgpuSwapChainGetCurrentTextureView(swapchain->gpuSwapchainObject()->wgpuSwapChain); + return; + } if (_gpuTextureObj->wgpuTexture) { - wgpuTextureDestroy(_gpuTextureObj->wgpuTexture); - wgpuTextureRelease(_gpuTextureObj->wgpuTexture); + CCWGPUDevice::getInstance()->moveToTrash(_gpuTextureObj->wgpuTexture); } if (_gpuTextureObj->wgpuTextureView) { wgpuTextureViewRelease(_gpuTextureObj->wgpuTextureView); @@ -167,6 +181,9 @@ void CCWGPUTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { wgpuTextureViewRelease(_gpuTextureObj->selfView); } + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize -= _size; + CCWGPUDevice::getInstance()->getMemoryStatus().textureSize += size; + uint8_t depthOrArrayLayers = _info.depth; if (_info.type == TextureType::CUBE) { depthOrArrayLayers = 6; @@ -176,7 +193,7 @@ void CCWGPUTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { .label = nullptr, .usage = toWGPUTextureUsage(_info.usage), .dimension = toWGPUTextureDimension(_info.type), - .size = {_info.width, _info.height, depthOrArrayLayers}, + .size = {width, height, depthOrArrayLayers}, .format = toWGPUTextureFormat(_info.format), .mipLevelCount = _info.levelCount, .sampleCount = toWGPUSampleCount(_info.samples), @@ -204,7 +221,7 @@ void CCWGPUTexture::stamp() { } CCWGPUTexture *CCWGPUTexture::defaultCommonTexture() { - if (!anoymous::defaultCommonTexture) { + if (!dftCommonTexture) { TextureInfo info = { .type = TextureType::TEX2D, .usage = TextureUsageBit::SAMPLED, @@ -218,15 +235,15 @@ CCWGPUTexture *CCWGPUTexture::defaultCommonTexture() { .depth = 1, .externalRes = nullptr, }; - anoymous::defaultCommonTexture = ccnew CCWGPUTexture; - anoymous::defaultCommonTexture->initialize(info); + dftCommonTexture = ccnew CCWGPUTexture; + dftCommonTexture->initialize(info); } - return anoymous::defaultCommonTexture; + return dftCommonTexture; } CCWGPUTexture *CCWGPUTexture::defaultStorageTexture() { - if (!anoymous::defaultStorageTexture) { + if (!dftStorageTexture) { TextureInfo info = { .type = TextureType::TEX2D, .usage = TextureUsageBit::STORAGE, @@ -240,11 +257,11 @@ CCWGPUTexture *CCWGPUTexture::defaultStorageTexture() { .depth = 1, .externalRes = nullptr, }; - anoymous::defaultStorageTexture = ccnew CCWGPUTexture; - anoymous::defaultStorageTexture->initialize(info); + dftStorageTexture = ccnew CCWGPUTexture; + dftStorageTexture->initialize(info); } - return anoymous::defaultStorageTexture; + return dftStorageTexture; } CCWGPUSwapchain *CCWGPUTexture::swapchain() { diff --git a/native/cocos/renderer/gfx-wgpu/WGPUTexture.h b/native/cocos/renderer/gfx-wgpu/WGPUTexture.h index 1985c36702..c451e8c1de 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUTexture.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUTexture.h @@ -24,7 +24,10 @@ ****************************************************************************/ #pragma once -#include +#ifdef CC_WGPU_WASM + #include "WGPUDef.h" +#endif +#include "WGPUDef.h" #include "gfx-base/GFXTexture.h" namespace cc { @@ -33,13 +36,12 @@ namespace gfx { struct CCWGPUTextureObject; class CCWGPUSwapchain; -class CCWGPUTexture final : public emscripten::wrapper { +class CCWGPUTexture final : public Texture { public: - EMSCRIPTEN_WRAPPER(CCWGPUTexture); CCWGPUTexture(); - ~CCWGPUTexture() = default; + ~CCWGPUTexture(); - inline CCWGPUTextureObject *gpuTextureObject() { return _gpuTextureObj; } + inline CCWGPUTextureObject *gpuTextureObject() const { return _gpuTextureObj; } static CCWGPUTexture *defaultCommonTexture(); @@ -53,6 +55,15 @@ public: // resource handler changed? inline bool internalChanged() const { return _internalChanged; } + inline uint32_t getDepth() const { return _info.depth; }; + inline uint32_t getLayerCount() const { return _info.layerCount; }; + inline uint32_t getLevelCount() const { return _info.levelCount; }; + inline auto getTextureType() const { return _info.type; }; + inline auto getTextureUsage() const { return _info.usage; }; + inline auto getTextureFormat() const { return _info.format; }; + inline auto getTextureSamples() const { return _info.samples; }; + inline auto getTextureFlags() const { return _info.flags; }; + protected: void doInit(const TextureInfo &info) override; void doInit(const TextureViewInfo &info) override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUUtils.cpp b/native/cocos/renderer/gfx-wgpu/WGPUUtils.cpp new file mode 100644 index 0000000000..42b888b61e --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/WGPUUtils.cpp @@ -0,0 +1,49 @@ +#include "WGPUUtils.h" +#include "WGPUDescriptorSet.h" +#include "WGPUDescriptorSetLayout.h" +#include "WGPUDevice.h" +#include "WGPUObject.h" +#include "WGPUPipelineLayout.h" + +namespace cc::gfx { + +void createPipelineLayoutFallback(const ccstd::vector& descriptorSets, PipelineLayout* pipelineLayout) { + ccstd::hash_t hash = descriptorSets.size() * 2 + 1; + ccstd::hash_combine(hash, descriptorSets.size()); + std::string label = ""; + ccstd::vector descriptorSetLayouts; + for (size_t i = 0; i < descriptorSets.size(); ++i) { + auto* descriptorSet = static_cast(descriptorSets[i]); + if (descriptorSet && descriptorSet->getHash() != 0) { + auto* descriptorSetLayout = static_cast(descriptorSet->getLayout()); + auto* wgpuBindGroupLayout = static_cast(CCWGPUDescriptorSetLayout::getBindGroupLayoutByHash(descriptorSet->getHash())); + descriptorSetLayouts.push_back(wgpuBindGroupLayout); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, descriptorSet->getHash()); + label += std::to_string(descriptorSet->getHash()) + "-" + descriptorSet->label + "-" + std::to_string(descriptorSetLayout->getHash()) + " "; + } else { + descriptorSetLayouts.push_back(static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout())); + ccstd::hash_combine(hash, i); + ccstd::hash_combine(hash, 0); + } + } + + auto* ccPipelineLayout = static_cast(pipelineLayout); + WGPUPipelineLayoutDescriptor descriptor = { + .nextInChain = nullptr, + .label = label.c_str(), + .bindGroupLayoutCount = descriptorSetLayouts.size(), + .bindGroupLayouts = descriptorSetLayouts.data(), + }; + + auto iter = ccPipelineLayout->layoutMap.find(hash); + if (iter == ccPipelineLayout->layoutMap.end()) { + ccPipelineLayout->layoutMap[hash] = wgpuDeviceCreatePipelineLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); + ccPipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout = static_cast(ccPipelineLayout->layoutMap[hash]); + printf("create new ppl\n"); + } else { + ccPipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout = static_cast(iter->second); + } + ccPipelineLayout->_hash = hash; +} +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUUtils.h b/native/cocos/renderer/gfx-wgpu/WGPUUtils.h index feed8d4b32..9a73bb7946 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUUtils.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUUtils.h @@ -1,5 +1,6 @@ #pragma once #include +#include "base/std/container/vector.h" #include "cocos/base/Macros.h" #include "cocos/base/TypeDef.h" #include "gfx-base/GFXDef-common.h" @@ -146,6 +147,10 @@ static WGPUTextureSampleType textureSampleTypeTrait(Format format) { } } +static bool isFilterable(Format format) { + return textureSampleTypeTrait(format) != WGPUTextureSampleType_UnfilterableFloat; +} + static WGPUTextureAspect textureAspectTrait(Format format) { switch (format) { case Format::DEPTH: @@ -283,7 +288,7 @@ static WGPUAddressMode toWGPUAddressMode(Address addrMode) { static WGPUFilterMode toWGPUFilterMode(Filter filter) { switch (filter) { case Filter::NONE: - return WGPUFilterMode::WGPUFilterMode_Linear; + return WGPUFilterMode::WGPUFilterMode_Nearest; case Filter::POINT: return WGPUFilterMode::WGPUFilterMode_Nearest; case Filter::LINEAR: @@ -364,9 +369,9 @@ static WGPUShaderStageFlags toWGPUShaderStageFlag(ShaderStageFlagBit flag) { return result; } -//TODO_Zeqiang: more flexible strategy +// TODO_Zeqiang: more flexible strategy static uint32_t toWGPUSampleCount(SampleCount sampleCount) { - //TODO_Zeqiang: msaa + // TODO_Zeqiang: msaa return 1; switch (sampleCount) { case SampleCount::ONE: @@ -433,7 +438,7 @@ static WGPUBufferUsageFlags toWGPUBufferUsage(BufferUsageBit usage) { return res; } -static WGPUColor toWGPUColor(const Color &color) { +static WGPUColor toWGPUColor(const Color& color) { return WGPUColor{color.x, color.y, color.z, color.w}; } @@ -583,9 +588,52 @@ static WGPUFlags toWGPUColorWriteMask(ColorMask mask) { return result; } +static ccstd::string getAdapterTypeName(WGPUAdapterType type) { + switch(type) { + case WGPUAdapterType_DiscreteGPU: + return "WGPUAdapterType_DiscreteGPU"; + case WGPUAdapterType_IntegratedGPU: + return "WGPUAdapterType_IntegratedGPU"; + case WGPUAdapterType_CPU: + return "WGPUAdapterType_CPU"; + case WGPUAdapterType_Unknown: + return "WGPUAdapterType_Unknown"; + default: + return "unknown adapter by cc.gfx!"; + } +} + +static ccstd::string getBackendTypeName(WGPUBackendType type) { + switch(type) { + case WGPUBackendType_Null: + return "WGPUBackendType_Null"; + case WGPUBackendType_WebGPU: + return "WGPUBackendType_WebGPU"; + case WGPUBackendType_D3D11: + return "WGPUBackendType_D3D11"; + case WGPUBackendType_D3D12: + return "WGPUBackendType_D3D12"; + case WGPUBackendType_Metal: + return "WGPUBackendType_Metal"; + case WGPUBackendType_Vulkan: + return "WGPUBackendType_Vulkan"; + case WGPUBackendType_OpenGL: + return "WGPUBackendType_OpenGL"; + case WGPUBackendType_OpenGLES: + return "WGPUBackendType_OpenGLES"; + default: + return "unknown backend by cc.gfx!"; + } +} + +class DescriptorSet; +class PipelineLayout; +// descriptor set layout in descriptor set not consistent with the binding in pipeline layout. +void createPipelineLayoutFallback(const ccstd::vector& descriptorSets, PipelineLayout* pipelineLayout); + static constexpr WGPUColor defaultClearColor{0.2, 0.2, 0.2, 1.0}; static constexpr float defaultClearDepth = 1.0f; } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.cpp b/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.cpp new file mode 100644 index 0000000000..412d73a6be --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "WGPUBufferBarrier.h" + +namespace cc { +namespace gfx { + +WGPUBufferBarrier::WGPUBufferBarrier(const BufferBarrierInfo &info) : BufferBarrier(info) { +} + +ccstd::hash_t WGPUBufferBarrier::computeHash(const BufferBarrierInfo &info) { + return 0; +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.h b/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.h new file mode 100644 index 0000000000..875bbeb3c5 --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUBufferBarrier.h @@ -0,0 +1,45 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include "gfx-base/states/GFXBufferBarrier.h" + +namespace cc { +namespace gfx { + +class CC_DLL WGPUBufferBarrier : public BufferBarrier { +public: + explicit WGPUBufferBarrier(const BufferBarrierInfo &info); + + static ccstd::hash_t computeHash(const BufferBarrierInfo &info); + + // inline const GeneralBarrierInfo &getInfo() const { return _info; } + // inline const ccstd::hash_t &getHash() const { return _hash; } +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.cpp b/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.cpp new file mode 100644 index 0000000000..85199e2b2e --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "WGPUGeneralBarrier.h" + +namespace cc { +namespace gfx { + +WGPUGeneralBarrier::WGPUGeneralBarrier(const GeneralBarrierInfo &info) : GeneralBarrier(info) { +} + +ccstd::hash_t WGPUGeneralBarrier::computeHash(const GeneralBarrierInfo &info) { + return 0; +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.h b/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.h new file mode 100644 index 0000000000..f995478bab --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUGeneralBarrier.h @@ -0,0 +1,45 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include "gfx-base/states/GFXGeneralBarrier.h" + +namespace cc { +namespace gfx { + +class CC_DLL WGPUGeneralBarrier : public GeneralBarrier { +public: + explicit WGPUGeneralBarrier(const GeneralBarrierInfo &info); + + static ccstd::hash_t computeHash(const GeneralBarrierInfo &info); + + // inline const GeneralBarrierInfo &getInfo() const { return _info; } + // inline const ccstd::hash_t &getHash() const { return _hash; } +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.cpp b/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.cpp new file mode 100644 index 0000000000..445461bae5 --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "WGPUTextureBarrier.h" + +namespace cc { +namespace gfx { + +WGPUTextureBarrier::WGPUTextureBarrier(const TextureBarrierInfo &info) : TextureBarrier(info) { +} + +ccstd::hash_t WGPUTextureBarrier::computeHash(const TextureBarrierInfo &info) { + return 0; +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.h b/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.h new file mode 100644 index 0000000000..0f38a42e66 --- /dev/null +++ b/native/cocos/renderer/gfx-wgpu/states/WGPUTextureBarrier.h @@ -0,0 +1,42 @@ +/**************************************************************************** + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include "gfx-base/states/GFXTextureBarrier.h" + +namespace cc { +namespace gfx { + +class CC_DLL WGPUTextureBarrier : public TextureBarrier { +public: + explicit WGPUTextureBarrier(const TextureBarrierInfo &info); + + static ccstd::hash_t computeHash(const TextureBarrierInfo &info); +}; + +} // namespace gfx +} // namespace cc 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 3de1ca0d97..38a7b319d3 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/SceneCulling.cpp b/native/cocos/renderer/pipeline/SceneCulling.cpp index cceddb405a..86f639395a 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.cpp +++ b/native/cocos/renderer/pipeline/SceneCulling.cpp @@ -34,6 +34,7 @@ #include "core/geometry/Intersect.h" #include "core/geometry/Sphere.h" #include "core/scene-graph/Node.h" +#include "core/platform/Debug.h" #include "math/Quaternion.h" #include "profiler/Profiler.h" #include "scene/Camera.h" @@ -146,8 +147,12 @@ void sceneCulling(const RenderPipeline *pipeline, scene::Camera *camera) { csmLayers->clearCastShadowObjects(); csmLayers->clearLayerObjects(); - if (skyBox != nullptr && skyBox->isEnabled() && skyBox->getModel() && (static_cast(camera->getClearFlag()) & skyboxFlag)) { - sceneData->addRenderObject(genRenderObject(skyBox->getModel(), camera)); + if (static_cast(camera->getClearFlag()) & skyboxFlag) { + if (skyBox != nullptr && skyBox->isEnabled() && skyBox->getModel()) { + sceneData->addRenderObject(genRenderObject(skyBox->getModel(), camera)); + } else { + debug::warnID(15100, camera->getName()); + } } const scene::Octree *octree = scene->getOctree(); 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/Ambient.cpp b/native/cocos/scene/Ambient.cpp index 2e029e69aa..997a6b5f32 100644 --- a/native/cocos/scene/Ambient.cpp +++ b/native/cocos/scene/Ambient.cpp @@ -63,7 +63,7 @@ const Color &AmbientInfo::getSkyLightingColor() const { const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); Vec4 v4(isHDR ? _skyColorHDR : _skyColorLDR); normalizeHDRColor(v4); - col.set(static_cast(v4.x) * 255, static_cast(v4.y) * 255, static_cast(v4.z) * 255, 255); + col.set(static_cast(v4.x * 255.F), static_cast(v4.y * 255.F), static_cast(v4.z * 255.F), 255); return col; } @@ -116,7 +116,7 @@ const Color &AmbientInfo::getGroundLightingColor() const { const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); Vec4 v4(isHDR ? _groundAlbedoHDR : _groundAlbedoLDR); normalizeHDRColor(v4); - col.set(static_cast(v4.x) * 255, static_cast(v4.y) * 255, static_cast(v4.z) * 255, 255); + col.set(static_cast(v4.x * 255.F), static_cast(v4.y * 255.F), static_cast(v4.z * 255.F), 255); return col; } diff --git a/native/cocos/scene/DrawBatch2D.cpp b/native/cocos/scene/DrawBatch2D.cpp index ffa2c8577a..30757c7ee1 100644 --- a/native/cocos/scene/DrawBatch2D.cpp +++ b/native/cocos/scene/DrawBatch2D.cpp @@ -35,7 +35,6 @@ void DrawBatch2D::clear() { _inputAssembler = nullptr; _descriptorSet = nullptr; _model = nullptr; - _useLocalData = nullptr; _visFlags = 1 << 23; } diff --git a/native/cocos/scene/DrawBatch2D.h b/native/cocos/scene/DrawBatch2D.h index 00ccfdea9e..086ce4a07c 100644 --- a/native/cocos/scene/DrawBatch2D.h +++ b/native/cocos/scene/DrawBatch2D.h @@ -52,7 +52,6 @@ public: inline void setInputAssembler(gfx::InputAssembler *ia) { _inputAssembler = ia; } inline void setDescriptorSet(gfx::DescriptorSet *descriptorSet) { _descriptorSet = descriptorSet; } inline void setVisFlags(uint32_t flags) { _visFlags = flags; } - inline void setUseLocalFlag(Node *node) { _useLocalData = node; } inline void setModel(Model *model) { _model = model; } inline gfx::InputAssembler *getInputAssembler() const { return _inputAssembler; } @@ -60,7 +59,6 @@ public: inline uint32_t getVisFlags() const { return _visFlags; } inline const ccstd::vector &getShaders() const { return _shaders; } inline const ccstd::vector> &getPasses() const { return _passes; } - inline Node *getUseLocalFlag() const { return _useLocalData; } inline Model *getModel() const { return _model; } protected: @@ -70,7 +68,6 @@ protected: ccstd::vector> _passes; ccstd::vector _shaders; - Node *_useLocalData{nullptr}; // May don`t need Model *_model{nullptr}; CC_DISALLOW_COPY_MOVE_ASSIGN(DrawBatch2D); 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/external-config.json b/native/external-config.json index 49bed37fd5..d08209b352 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -5,4 +5,4 @@ "name": "engine-native-external", "checkout": "develop-3" } -} +} \ No newline at end of file diff --git a/native/tools/tojs/2d.ini b/native/tools/tojs/2d.ini index e941cc1354..951f59d1c4 100644 --- a/native/tools/tojs/2d.ini +++ b/native/tools/tojs/2d.ini @@ -47,14 +47,14 @@ classes = RenderDrawInfo UIMeshBuffer Batcher2d RenderEntity UIModelProxy # will apply to all class names. This is a convenience wildcard to be able to skip similar named # functions from all classes. skip = RenderDrawInfo::[getBatcher setBatcher parseAttrLayout getRender2dLayout getEnumDrawInfoType resetDrawInfo], - Batcher2d::[addVertDirtyRenderer getMeshBuffer getDevice updateDescriptorSet fillBuffersAndMergeBatches walk generateBatch resetRenderStates handleDrawInfo handleComponentDraw handleModelDraw handleIADraw handleSubNode], + Batcher2d::[addVertDirtyRenderer getMeshBuffer getDevice updateDescriptorSet fillBuffersAndMergeBatches walk generateBatch generateBatchForMiddleware resetRenderStates handleDrawInfo handleComponentDraw handleModelDraw handleMiddlewareDraw handleSubNode], UIMeshBuffer::[requireFreeIA createNewIA recycleIA resetIA parseLayout getByteOffset setByteOffset getVertexOffset setVertexOffset getIndexOffset setIndexOffset getDirty setDirty getAttributes], RenderEntity::[getDynamicRenderDrawInfo getDynamicRenderDrawInfos getRenderEntityType getColorDirty getColor isEnabled getEnumStencilStage setEnumStencilStage getVBColorDirty setVBColorDirty] rename_functions = getter_setter = RenderDrawInfo::[bufferId accId vertexOffset indexOffset vbBuffer ibBuffer vDataBuffer iDataBuffer vbCount ibCount vertDirty dataHash isMeshBuffer material texture sampler model drawInfoType subNode stride], - UIMeshBuffer::[vData iData useLinkData], + UIMeshBuffer::[vData iData], RenderEntity::[node staticDrawInfoSize stencilStage renderTransform] field = diff --git a/native/tools/tojs/dragonbones.ini b/native/tools/tojs/dragonbones.ini index c1aeb140bd..39379605ea 100644 --- a/native/tools/tojs/dragonbones.ini +++ b/native/tools/tojs/dragonbones.ini @@ -12,6 +12,7 @@ android_flags = -target armv7-none-linux-androideabi -D_LIBCPP_DISABLE_VISIBILIT clang_headers = clang_flags = -nostdinc -x c++ -std=c++17 -fsigned-char -mfloat-abi=soft -U__SSE__ +cpp_headers = cocos/bindings/auto/jsb_2d_auto.h cocos/bindings/auto/jsb_assets_auto.h cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/bindings/jswrapper -I%(cocosdir)s/cocos/platform/android -I%(cocosdir)s/external/sources -I%(cocosdir)s/cocos/editor-support cocos_flags = -DANDROID -DCC_PLATFORM=3 -DCC_PLATFORM_IOS=1 -DCC_PLATFORM_MACOS=4 -DCC_PLATFORM_WINDOWS=2 -DCC_PLATFORM_ANDROID=3 @@ -28,9 +29,9 @@ classes = Rectangle DragonBonesData CCFactory CCArmatureDisplay Armature CCSlot abstract_classes = DragonBonesData Armature CCSlot WorldClock Animation Slot BaseFactory BaseObject TextureData CCTextureData TextureAtlasData CCTextureAtlasData AnimationState EventObject Bone Transform Matrix TransformObject ArmatureData BoneData SlotData SkinData AnimationData AttachUtilBase -skip = CCFactory::[destroyInstance loadDragonBonesData loadTextureAtlasData getRenderOrder], +skip = CCFactory::[destroyInstance loadDragonBonesData loadTextureAtlasData], BaseFactory::[replaceDisplay getAllTextureAtlasData getAllDragonBonesData getClassTypeIndex replaceSlotDisplayList getTextureAtlasData parseTextureAtlasData], - Armature::[intersectsSegment getAnimatable _addConstraint getReplacedTexture setReplacedTexture getBoneByDisplay getSlotByDisplay init _sortZOrder getBones getSlots getDisplay getTypeIndex getRenderOrder], + Armature::[intersectsSegment getAnimatable _addConstraint getReplacedTexture setReplacedTexture getBoneByDisplay getSlotByDisplay init _sortZOrder getBones getSlots getDisplay getTypeIndex], Animation::[playConfig getAnimationConfig getTypeIndex getStates setAnimations getAnimations], Slot::[setRawDisplayDatas replaceDisplayData intersectsSegment init getDisplay getRawDisplay getMeshDisplay setDisplay _updateBlendMode _updateVisible _setDisplayIndex _setDisplayList getDisplayList _setColor _setDisplayList], AnimationState::[init copyFrom getTypeIndex], @@ -51,11 +52,11 @@ skip = CCFactory::[destroyInstance loadDragonBonesData loadTextureAtlasData getR TextureData::[copyFrom], CCTextureAtlasData::[setRenderTexture getRenderTexture getTypeIndex], CCTextureData::[getTypeIndex], - CCArmatureDisplay::[render update getRenderOrder], + CCArmatureDisplay::[render update requestDrawInfo requestMaterial], RealTimeAttachUtil::[syncAttachedNode], CacheModeAttachUtil::[syncAttachedNode], AttachUtilBase::[releaseAttachedNode], - CCArmatureCacheDisplay::[getRenderOrder] + CCArmatureCacheDisplay::[requestDrawInfo requestMaterial] field = Transform::[x y skew scaleX scaleY rotation], Slot::[displayController _zOrder], diff --git a/native/tools/tojs/editor_support.ini b/native/tools/tojs/editor_support.ini index c5d45f75d7..94776c88db 100644 --- a/native/tools/tojs/editor_support.ini +++ b/native/tools/tojs/editor_support.ini @@ -30,7 +30,9 @@ classes_need_extend = skip = MiddlewareManager::[addTimer removeTimer getMeshBuffer], SharedBufferManager::[getBuffer reset], - Texture2D::[setTexParameters] + Texture2D::[setTexParameters], + MeshBuffer::[getUIMeshBuffer uiMeshBuffers] + remove_prefix = diff --git a/native/tools/tojs/genbindings.py b/native/tools/tojs/genbindings.py index 8a0063b213..c8e9fcd22b 100755 --- a/native/tools/tojs/genbindings.py +++ b/native/tools/tojs/genbindings.py @@ -23,14 +23,14 @@ defaultSections = [ 'gfx', 'pipeline', 'render', - 'spine', - 'editor_support', - 'dragonbones', 'physics', 'scene', 'geometry', 'assets', - '2d' + '2d', + 'editor_support', + 'spine', + 'dragonbones' ] projectRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) diff --git a/native/tools/tojs/scene.ini b/native/tools/tojs/scene.ini index ed933d8453..f9c218fb21 100644 --- a/native/tools/tojs/scene.ini +++ b/native/tools/tojs/scene.ini @@ -71,6 +71,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], @@ -88,7 +89,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] @@ -107,7 +108,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], diff --git a/native/tools/tojs/spine.ini b/native/tools/tojs/spine.ini index 94df9ae5c6..1875f6f475 100644 --- a/native/tools/tojs/spine.ini +++ b/native/tools/tojs/spine.ini @@ -12,6 +12,7 @@ android_flags = -target armv7-none-linux-androideabi -D_LIBCPP_DISABLE_VISIBILIT clang_headers = clang_flags = -nostdinc -x c++ -std=c++17 -fsigned-char -mfloat-abi=soft -U__SSE__ +cpp_headers = cocos/bindings/auto/jsb_2d_auto.h cocos/bindings/auto/jsb_assets_auto.h cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/bindings/jswrapper -I%(cocosdir)s/cocos/platform/android -I%(cocosdir)s/external/sources -I%(cocosdir)s/cocos/editor-support cocos_flags = -DANDROID -DCC_PLATFORM=3 -DCC_PLATFORM_IOS=1 -DCC_PLATFORM_MACOS=4 -DCC_PLATFORM_WINDOWS=2 -DCC_PLATFORM_ANDROID=3 @@ -28,7 +29,7 @@ classes = SkeletonRenderer SkeletonAnimation VertexEffectDelegate Animation Tra classes_need_extend = -skip = SkeletonRenderer::[create initWithJsonFile initWithBinaryFile createWithData initWithData createWithSkeleton createWithFile getRenderOrder], +skip = SkeletonRenderer::[create initWithJsonFile initWithBinaryFile createWithData initWithData createWithSkeleton createWithFile requestDrawInfo requestMaterial], SkeletonAnimation::[createWithData onTrackEntryEvent onAnimationStateEvent], Animation::[apply], TrackEntry::[setListener], @@ -70,7 +71,7 @@ skip = SkeletonRenderer::[create initWithJsonFile initWithBinaryFile createWithD SwirlVertexEffect::[begin transform end], VertexAttachment::[computeWorldVertices getBones getRTTI], SkeletonDataMgr::[destroyInstance hasSkeletonData setSkeletonData retainByUUID releaseByUUID], - SkeletonCacheAnimation::[render getRenderOrder] + SkeletonCacheAnimation::[render requestDrawInfo requestMaterial] field = Color::[r g b a] diff --git a/package-lock.json b/package-lock.json index ebcec1ad14..64088e59ad 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "cocos-creator", - "version": "3.6.1", + "version": "3.6.2", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 4b3553ddb6..742cbe8132 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cocos-creator", - "version": "3.6.1", + "version": "3.6.2", "description": "Cocos Creator is a cross-platform 2D & 3D game engine written in TypeScript, licensed under MIT.", "homepage": "http://www.cocos.com", "license": "MIT", diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts index 488a6fdc91..2cefc4d9ff 100644 --- a/pal/audio/minigame/player-minigame.ts +++ b/pal/audio/minigame/player-minigame.ts @@ -47,6 +47,9 @@ export class OneShotAudioMinigame { export class AudioPlayerMinigame implements OperationQueueable { private _innerAudioContext: InnerAudioContext; private _state: AudioState = AudioState.INIT; + private _cacheTime = 0; + private _needSeek = false; + private _seeking = false; private _onPlay: () => void; private _onPause: () => void; @@ -55,6 +58,11 @@ export class AudioPlayerMinigame implements OperationQueueable { private _onEnded: () => void; private _readyToHandleOnShow = false; + private _resetSeekCache () { + this._cacheTime = 0; + this._needSeek = false; + this._seeking = false; + } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @@ -75,22 +83,37 @@ export class AudioPlayerMinigame implements OperationQueueable { this._onPlay = () => { this._state = AudioState.PLAYING; eventTarget.emit(AudioEvent.PLAYED); + if (this._needSeek) { + this._needSeek = false; + this.seek(this._cacheTime).catch((e) => {}); + } }; innerAudioContext.onPlay(this._onPlay); this._onPause = () => { this._state = AudioState.PAUSED; + this._cacheTime = this._innerAudioContext.currentTime; eventTarget.emit(AudioEvent.PAUSED); }; innerAudioContext.onPause(this._onPause); this._onStop = () => { this._state = AudioState.STOPPED; + // Reset all properties + this._resetSeekCache(); eventTarget.emit(AudioEvent.STOPPED); }; innerAudioContext.onStop(this._onStop); - this._onSeeked = () => { eventTarget.emit(AudioEvent.SEEKED); }; + this._onSeeked = () => { + eventTarget.emit(AudioEvent.SEEKED); + this._seeking = false; + if (this._needSeek) { + this._needSeek = false; + this.seek(this._cacheTime).catch((e) => {}); + } + }; innerAudioContext.onSeeked(this._onSeeked); this._onEnded = () => { this._state = AudioState.INIT; + this._resetSeekCache(); eventTarget.emit(AudioEvent.ENDED); }; innerAudioContext.onEnded(this._onEnded); @@ -204,13 +227,12 @@ export class AudioPlayerMinigame implements OperationQueueable { get duration (): number { // KNOWN ISSUES: duration doesn't work well // On WeChat platform, duration is 0 at the time audio is loaded. - // On Native or Runtime platform, duration is 0 before playing. return this._innerAudioContext.duration; } get currentTime (): number { - // KNOWN ISSUES: currentTime doesn't work well - // on Baidu: currentTime returns without numbers on decimal places - // on WeChat iOS: we can't reset currentTime to 0 when stop audio + if (this._state !== AudioState.PLAYING) { + return this._cacheTime; + } return this._innerAudioContext.currentTime; } @@ -225,14 +247,16 @@ export class AudioPlayerMinigame implements OperationQueueable { @enqueueOperation seek (time: number): Promise { return new Promise((resolve) => { - time = clamp(time, 0, this.duration); - if (time === 0 && this.currentTime === 0) { - // skip invalid seek - resolve(); - } else { - this._eventTarget.once(AudioEvent.SEEKED, resolve); + // KNOWN ISSUES: on Baidu: currentTime returns without numbers on decimal places + if (this._state === AudioState.PLAYING && !this._seeking) { + time = clamp(time, 0, this.duration); + this._seeking = true; this._innerAudioContext.seek(time); + } else if (this._cacheTime !== time) { // Skip the invalid seek + this._cacheTime = time; + this._needSeek = true; } + resolve(); }); } diff --git a/pal/system-info/minigame/system-info.ts b/pal/system-info/minigame/system-info.ts index 3fc5de8202..bed493f382 100644 --- a/pal/system-info/minigame/system-info.ts +++ b/pal/system-info/minigame/system-info.ts @@ -97,13 +97,7 @@ class SystemInfo extends EventTarget { this.isXR = false; // init capability - const _tmpCanvas1 = document.createElement('canvas'); // TODO: remove this - let supportWebp; - try { - supportWebp = TEST ? false : _tmpCanvas1.toDataURL('image/webp').startsWith('data:image/webp'); - } catch (e) { - supportWebp = false; - } + const supportWebp = this._supportsWebp(); const isPCWechat = WECHAT && this.os === OS.WINDOWS && !minigame.isDevTool; this._featureMap = { @@ -126,6 +120,23 @@ class SystemInfo extends EventTarget { this._registerEvent(); } + private _supportsWebp (): boolean { + // NOTE: canvas.toDataURL() is not supported on WeChat iOS end (Found on iPhone 7p) + const isIOSWechat = WECHAT && this.os === OS.IOS; + const _tmpCanvas = document.createElement('canvas'); // TODO: remove this + let supportWebp: boolean; + if (isIOSWechat) { + supportWebp = true; + } else { + try { + supportWebp = TEST ? false : _tmpCanvas.toDataURL('image/webp').startsWith('data:image/webp'); + } catch (e) { + supportWebp = false; + } + } + return supportWebp; + } + private _registerEvent () { minigame.onHide(() => { this.emit('hide'); diff --git a/platforms/native/engine/jsb-dragonbones.js b/platforms/native/engine/jsb-dragonbones.js index bdfe3677c7..a92de6c8aa 100644 --- a/platforms/native/engine/jsb-dragonbones.js +++ b/platforms/native/engine/jsb-dragonbones.js @@ -255,6 +255,7 @@ const cacheManager = require('./jsb-cache-manager'); this.jsbTexture.setRealTextureIndex(index); this.jsbTexture.setPixelsWide(this._texture.width); this.jsbTexture.setPixelsHigh(this._texture.height); + this.jsbTexture.setRealTexture(this._texture); this._textureAtlasData = factory.parseTextureAtlasData(this.atlasJson, this.jsbTexture, this._uuid); _textureIdx2Name[url] = { name: this._textureAtlasData.name, index }; @@ -452,10 +453,6 @@ const cacheManager = require('./jsb-cache-manager'); this._sharedBufferOffset = this._nativeDisplay.getSharedBufferOffset(); this._sharedBufferOffset[0] = 0; this._useAttach = false; - this._renderOrder = -1; - // store render order and world matrix - this._paramsBuffer = this._nativeDisplay.getParamsBuffer(); - this._paramsBuffer[0] = -1.0; this._nativeDisplay.setOpacityModifyRGB(this.premultipliedAlpha); @@ -466,13 +463,16 @@ const cacheManager = require('./jsb-cache-manager'); this._eventTarget.emit(eventObject.type, eventObject); }); + const materialTemplate = this.getMaterialTemplate(); + this._nativeDisplay.setMaterial(materialTemplate); + this._nativeDisplay.setRenderEntity(this._renderEntity.nativeObj); + this.attachUtil.init(this); if (this.animationName) { this.playAnimation(this.animationName, this.playTimes); } - this.syncTransform(true); this.markForUpdateRenderData(); }; @@ -523,7 +523,6 @@ const cacheManager = require('./jsb-cache-manager'); if (this._armature && !this.isAnimationCached()) { this._factory.add(this._armature); } - this.syncTransform(true); this._flushAssembler(); armatureSystem.getInstance().add(this); middleware.retain(); @@ -584,35 +583,6 @@ const cacheManager = require('./jsb-cache-manager'); } }; - armatureDisplayProto.syncTransform = function (force) { - const node = this.node; - if (!node) return; - - const paramsBuffer = this._paramsBuffer; - if (!paramsBuffer) return; - - if (force || node.hasChangedFlags || node._dirtyFlags) { - // sync node world matrix to native - const worldMat = node.getWorldMatrix(); - paramsBuffer[1] = worldMat.m00; - paramsBuffer[2] = worldMat.m01; - paramsBuffer[3] = worldMat.m02; - paramsBuffer[4] = worldMat.m03; - paramsBuffer[5] = worldMat.m04; - paramsBuffer[6] = worldMat.m05; - paramsBuffer[7] = worldMat.m06; - paramsBuffer[8] = worldMat.m07; - paramsBuffer[9] = worldMat.m08; - paramsBuffer[10] = worldMat.m09; - paramsBuffer[11] = worldMat.m10; - paramsBuffer[12] = worldMat.m11; - paramsBuffer[13] = worldMat.m12; - paramsBuffer[14] = worldMat.m13; - paramsBuffer[15] = worldMat.m14; - paramsBuffer[16] = worldMat.m15; - } - }; - armatureDisplayProto.setAnimationCacheMode = function (cacheMode) { if (this._preCacheMode !== cacheMode) { this._cacheMode = cacheMode; @@ -632,15 +602,6 @@ const cacheManager = require('./jsb-cache-manager'); const node = this.node; if (!node) return; - const paramsBuffer = this._paramsBuffer; - if (this._renderOrder !== middleware.renderOrder) { - paramsBuffer[0] = middleware.renderOrder; - this._renderOrder = middleware.renderOrder; - middleware.renderOrder++; - } - - this.syncTransform(); - if (this.__preColor__ === undefined || !this.color.equals(this.__preColor__)) { const compColor = this.color; nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a); @@ -693,33 +654,22 @@ const cacheManager = require('./jsb-cache-manager'); }; const _tempAttachMat4 = cc.mat4(); - let _tempBufferIndex; let _tempIndicesOffset; let _tempIndicesCount; - armatureDisplayProto._render = function (ui) { + armatureDisplayProto._render = function () { const nativeDisplay = this._nativeDisplay; if (!nativeDisplay) return; - const node = this.node; - if (!node) return; - - const entity = this.renderEntity; - entity.clearDynamicRenderDrawInfos(); - const sharedBufferOffset = this._sharedBufferOffset; if (!sharedBufferOffset) return; - const renderInfoOffset = sharedBufferOffset[0]; - // reset render info offset - sharedBufferOffset[0] = 0; - const sockets = this.sockets; if (sockets.length > 0) { const attachInfoMgr = middleware.attachInfoMgr; const attachInfo = attachInfoMgr.attachInfo; - const attachInfoOffset = sharedBufferOffset[1]; + const attachInfoOffset = sharedBufferOffset[0]; // reset attach info offset - sharedBufferOffset[1] = 0; + sharedBufferOffset[0] = 0; const socketNodes = this.socketNodes; @@ -747,47 +697,12 @@ const cacheManager = require('./jsb-cache-manager'); boneNode.matrix = tm; } } + }; - const renderInfoMgr = middleware.renderInfoMgr; - const renderInfo = renderInfoMgr.renderInfo; - - let materialIdx = 0; let realTextureIndex; let realTexture; - // verify render border - const border = renderInfo[renderInfoOffset + materialIdx++]; - if (border !== 0xffffffff) return; - - const matLen = renderInfo[renderInfoOffset + materialIdx++]; - - if (matLen === 0) return; - - for (let index = 0; index < matLen; index++) { - realTextureIndex = renderInfo[renderInfoOffset + materialIdx++]; - realTexture = this.dragonAtlasAsset.getTextureByIndex(realTextureIndex); - if (!realTexture) return; - //HACK - const mat = this.material; - // cache material - this.material = this.getMaterialForBlend( - renderInfo[renderInfoOffset + materialIdx++], - renderInfo[renderInfoOffset + materialIdx++], - ); - - _tempBufferIndex = renderInfo[renderInfoOffset + materialIdx++]; - _tempIndicesOffset = renderInfo[renderInfoOffset + materialIdx++]; - _tempIndicesCount = renderInfo[renderInfoOffset + materialIdx++]; - - const renderData = middleware.RenderInfoLookup[middleware.vfmtPosUvColor][_tempBufferIndex]; - const drawInfo = this.requestDrawInfo(index); - drawInfo.setDrawInfoType(renderData.drawInfoType); - drawInfo.setAccAndBuffer(renderData.accessor.id, renderData.chunk.bufferId); - drawInfo.setTexture(realTexture.getGFXTexture()); - drawInfo.setSampler(realTexture.getGFXSampler()); - drawInfo.setMaterial(this.material); - drawInfo.setIndexOffset(_tempIndicesOffset); - drawInfo.setIBCount(_tempIndicesCount); - - entity.setDynamicRenderDrawInfo(drawInfo, index); - this.material = mat; + armatureDisplayProto._updateBatch = function () { + if (this.nativeDisplay) { + this.nativeDisplay.setBatchEnabled(this.enableBatch); + this.markForUpdateRenderData(); } }; diff --git a/platforms/native/engine/jsb-editor-support.js b/platforms/native/engine/jsb-editor-support.js index 92d3b338e9..656607d5ce 100644 --- a/platforms/native/engine/jsb-editor-support.js +++ b/platforms/native/engine/jsb-editor-support.js @@ -26,29 +26,15 @@ // @ts-expect-error jsb polyfills (function () { if (!window.middleware) return; - const RenderDrawInfoType_IA = 2; const middleware = window.middleware; const middlewareMgr = middleware.MiddlewareManager.getInstance(); let reference = 0; const director = cc.director; const game = cc.game; - const _accessors = []; - - const nativeXYZUVC = middleware.vfmtPosUvColor = 6; - const nativeXYZUVCC = middleware.vfmtPosUvTwoColor = 7; - - const vfmtPosUvColor4B = cc.internal.vfmtPosUvColor4B; - const vfmtPosUvTwoColor4B = cc.internal.vfmtPosUvTwoColor4B; - - const renderInfoLookup = middleware.RenderInfoLookup = {}; - renderInfoLookup[nativeXYZUVC] = []; - renderInfoLookup[nativeXYZUVCC] = []; middleware.reset = function () { middleware.preRenderComponent = null; middleware.preRenderBufferIndex = 0; - middleware.preRenderBufferType = nativeXYZUVC; - middleware.renderOrder = 0; middleware.indicesStart = 0; middleware.resetIndicesStart = false; }; @@ -62,45 +48,8 @@ return; } reference--; - if (reference === 0) { - const uvcBuffers = renderInfoLookup[nativeXYZUVC]; - for (let i = 0; i < uvcBuffers.length; i++) { - cc.UI.RenderData.remove(uvcBuffers[i]); - } - uvcBuffers.length = 0; - const uvccBuffers = renderInfoLookup[nativeXYZUVCC]; - for (let i = 0; i < uvccBuffers.length; i++) { - cc.UI.RenderData.remove(uvccBuffers[i]); - } - uvccBuffers.length = 0; - _accessors.forEach((accessor) => { - accessor.destroy(); - }); - } }; - function CopyNativeBufferToJS (renderer, nativeFormat, jsFormat) { - if (!renderer) return; - - const bufferCount = middlewareMgr.getBufferCount(nativeFormat); - for (let i = 0; i < bufferCount; i++) { - let buffer = renderInfoLookup[nativeFormat][i]; - if (!buffer) { - if (!_accessors[jsFormat]) { - _accessors[jsFormat] = cc.UI.RenderData.createStaticVBAccessor(jsFormat, 65535, 524280); - } - buffer = cc.UI.RenderData.add(jsFormat, _accessors[jsFormat]); - buffer.multiOwner = true; - buffer.drawInfoType = RenderDrawInfoType_IA; - // vertex count 65535, indices count 8 * 65535 - buffer.resize(65535, 524280); - const meshBuffer = buffer.getMeshBuffer(); - meshBuffer.useLinkedData = true; - renderInfoLookup[nativeFormat][i] = buffer; - } - } - } - director.on(cc.Director.EVENT_BEFORE_UPDATE, () => { if (reference === 0) return; middlewareMgr.update(game.deltaTime); @@ -113,9 +62,7 @@ // reset render order middleware.reset(); - const batcher2D = director.root.batcher2D; - CopyNativeBufferToJS(batcher2D, nativeXYZUVC, vfmtPosUvColor4B); - CopyNativeBufferToJS(batcher2D, nativeXYZUVCC, vfmtPosUvTwoColor4B); + //const batcher2D = director.root.batcher2D; if (window.dragonBones) { const armaSystem = cc.internal.ArmatureSystem.getInstance(); armaSystem.prepareRenderData(); @@ -126,20 +73,11 @@ } }); - const renderInfoMgr = middlewareMgr.getRenderInfoMgr(); - renderInfoMgr.renderInfo = renderInfoMgr.getSharedBuffer(); - renderInfoMgr.setResizeCallback(function () { - this.attachInfo = this.getSharedBuffer(); - }); - renderInfoMgr.__middleware__ = middleware; - const attachInfoMgr = middlewareMgr.getAttachInfoMgr(); attachInfoMgr.attachInfo = attachInfoMgr.getSharedBuffer(); attachInfoMgr.setResizeCallback(function () { this.attachInfo = this.getSharedBuffer(); }); - - middleware.renderInfoMgr = renderInfoMgr; middleware.attachInfoMgr = attachInfoMgr; // generate get set function diff --git a/platforms/native/engine/jsb-spine-skeleton.js b/platforms/native/engine/jsb-spine-skeleton.js index 48b5b70236..5c88feb9b6 100644 --- a/platforms/native/engine/jsb-spine-skeleton.js +++ b/platforms/native/engine/jsb-spine-skeleton.js @@ -120,6 +120,7 @@ const cacheManager = require('./jsb-cache-manager'); spTex.setRealTextureIndex(textureIdx); spTex.setPixelsWide(texture.width); spTex.setPixelsHigh(texture.height); + spTex.setRealTexture(texture); jsbTextures[textureNames[i]] = spTex; } this._jsbTextures = jsbTextures; @@ -275,6 +276,14 @@ const cacheManager = require('./jsb-cache-manager'); } }; + skeleton._updateBatch = function () { + if (this._nativeSkeleton) { + this._renderEntity.setUseLocal(!this.enableBatch); + this._nativeSkeleton.setBatchEnabled(this.enableBatch); + this.markForUpdateRenderData(); + } + }; + skeleton.setSkeletonData = function (skeletonData) { if (skeletonData.width != null && skeletonData.height != null) { const uiTrans = this.node._uiProps.uiTransformComp; @@ -325,6 +334,10 @@ const cacheManager = require('./jsb-cache-manager'); nativeSkeleton.setBatchEnabled(this.enableBatch); const compColor = this.color; nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a); + const materialTemplate = this.getMaterialTemplate(); + nativeSkeleton.setMaterial(materialTemplate); + this._renderEntity.setUseLocal(!this.enableBatch); + nativeSkeleton.setRenderEntity(this._renderEntity.nativeObj); this._skeleton = nativeSkeleton.getSkeleton(); @@ -335,16 +348,9 @@ const cacheManager = require('./jsb-cache-manager'); this._eventListener && this.setEventListener(this._eventListener); this._interruptListener && this.setInterruptListener(this._interruptListener); this._disposeListener && this.setDisposeListener(this._disposeListener); - this._sharedBufferOffset = nativeSkeleton.getSharedBufferOffset(); - this._sharedBufferOffset[0] = 0; this._useAttach = false; - this._renderOrder = -1; - // store render order and world matrix - this._paramsBuffer = nativeSkeleton.getParamsBuffer(); - - this.syncTransform(true); this.markForUpdateRenderData(); }; @@ -372,7 +378,6 @@ const cacheManager = require('./jsb-cache-manager'); if (this._nativeSkeleton) { this._nativeSkeleton.onEnable(); } - this.syncTransform(true); middleware.retain(); }; @@ -394,35 +399,6 @@ const cacheManager = require('./jsb-cache-manager'); } }; - skeleton.syncTransform = function (force) { - const node = this.node; - if (!node) return; - - const paramsBuffer = this._paramsBuffer; - if (!paramsBuffer) return; - - if (force || node.hasChangedFlags || node._dirtyFlags) { - // sync node world matrix to native - const worldMat = node.getWorldMatrix(); - paramsBuffer[1] = worldMat.m00; - paramsBuffer[2] = worldMat.m01; - paramsBuffer[3] = worldMat.m02; - paramsBuffer[4] = worldMat.m03; - paramsBuffer[5] = worldMat.m04; - paramsBuffer[6] = worldMat.m05; - paramsBuffer[7] = worldMat.m06; - paramsBuffer[8] = worldMat.m07; - paramsBuffer[9] = worldMat.m08; - paramsBuffer[10] = worldMat.m09; - paramsBuffer[11] = worldMat.m10; - paramsBuffer[12] = worldMat.m11; - paramsBuffer[13] = worldMat.m12; - paramsBuffer[14] = worldMat.m13; - paramsBuffer[15] = worldMat.m14; - paramsBuffer[16] = worldMat.m15; - } - }; - // eslint-disable-next-line no-unused-vars skeleton.updateAnimation = function (dt) { const nativeSkeleton = this._nativeSkeleton; @@ -431,15 +407,6 @@ const cacheManager = require('./jsb-cache-manager'); const node = this.node; if (!node) return; - const paramsBuffer = this._paramsBuffer; - if (this._renderOrder !== middleware.renderOrder) { - paramsBuffer[0] = middleware.renderOrder; - this._renderOrder = middleware.renderOrder; - middleware.renderOrder++; - } - - this.syncTransform(); - if (this.__preColor__ === undefined || !this.color.equals(this.__preColor__)) { const compColor = this.color; nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a); @@ -801,32 +768,21 @@ const cacheManager = require('./jsb-cache-manager'); }; const _tempAttachMat4 = cc.mat4(); - let _tempVfmt; let _tempBufferIndex; let _tempIndicesOffset; let _tempIndicesCount; - skeleton._render = function (ui) { + skeleton._render = function () { const nativeSkeleton = this._nativeSkeleton; if (!nativeSkeleton) return; - const node = this.node; - if (!node) return; - const entity = this.renderEntity; - entity.clearDynamicRenderDrawInfos(); - - const sharedBufferOffset = this._sharedBufferOffset; - if (!sharedBufferOffset) return; - - const renderInfoOffset = sharedBufferOffset[0]; - // reset render info offset - sharedBufferOffset[0] = 0; - const socketNodes = this.socketNodes; if (socketNodes.size > 0) { + const sharedBufferOffset = this._sharedBufferOffset; + if (!sharedBufferOffset) return; const attachInfoMgr = middleware.attachInfoMgr; const attachInfo = attachInfoMgr.attachInfo; - const attachInfoOffset = sharedBufferOffset[1]; + const attachInfoOffset = sharedBufferOffset[0]; // reset attach info offset - sharedBufferOffset[1] = 0; + sharedBufferOffset[0] = 0; for (const boneIdx of socketNodes.keys()) { const boneNode = socketNodes.get(boneIdx); // Node has been destroy @@ -846,56 +802,6 @@ const cacheManager = require('./jsb-cache-manager'); boneNode.matrix = tm; } } - - const renderInfoMgr = middleware.renderInfoMgr; - const renderInfo = renderInfoMgr.renderInfo; - - let materialIdx = 0; let realTextureIndex; let realTexture; - // verify render border - const border = renderInfo[renderInfoOffset + materialIdx++]; - if (border !== 0xffffffff) return; - - const matLen = renderInfo[renderInfoOffset + materialIdx++]; - const useTint = this.useTint || this.isAnimationCached(); - const vfmt = useTint ? middleware.vfmtPosUvTwoColor : middleware.vfmtPosUvColor; - - _tempVfmt = vfmt; - - if (matLen === 0) return; - - for (let index = 0; index < matLen; index++) { - realTextureIndex = renderInfo[renderInfoOffset + materialIdx++]; - realTexture = this.skeletonData.getTextureByIndex(realTextureIndex); - if (!realTexture) return; - - // SpineMaterialType.TWO_COLORED 1 - // SpineMaterialType.COLORED_TEXTURED 0 - //HACK - const mat = this.material; - // cache material - this.material = this.getMaterialForBlendAndTint( - renderInfo[renderInfoOffset + materialIdx++], - renderInfo[renderInfoOffset + materialIdx++], - useTint ? 1 : 0, - ); - - _tempBufferIndex = renderInfo[renderInfoOffset + materialIdx++]; - _tempIndicesOffset = renderInfo[renderInfoOffset + materialIdx++]; - _tempIndicesCount = renderInfo[renderInfoOffset + materialIdx++]; - - const renderData = middleware.RenderInfoLookup[_tempVfmt][_tempBufferIndex]; - const drawInfo = this.requestDrawInfo(index); - drawInfo.setDrawInfoType(renderData.drawInfoType); - drawInfo.setAccAndBuffer(renderData.accessor.id, renderData.chunk.bufferId); - drawInfo.setTexture(realTexture.getGFXTexture()); - drawInfo.setSampler(realTexture.getGFXSampler()); - drawInfo.setMaterial(this.material); - drawInfo.setIndexOffset(_tempIndicesOffset); - drawInfo.setIBCount(_tempIndicesCount); - - entity.setDynamicRenderDrawInfo(drawInfo, index); - this.material = mat; - } }; ////////////////////////////////////////// diff --git a/scripts/build-engine/.vscode/launch.json b/scripts/build-engine/.vscode/launch.json index 5b9ae88daa..127a470180 100644 --- a/scripts/build-engine/.vscode/launch.json +++ b/scripts/build-engine/.vscode/launch.json @@ -1,5 +1,5 @@ { - // 使用 IntelliSense 了解相关属性。 + // 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", @@ -28,6 +28,7 @@ "base", "gfx-webgl", "gfx-webgl2", + "gfx-webgpu", "3d", "2d", "ui", diff --git a/scripts/build-engine/package-lock.json b/scripts/build-engine/package-lock.json index bcaefd691e..4fd4e62d5d 100644 --- a/scripts/build-engine/package-lock.json +++ b/scripts/build-engine/package-lock.json @@ -1,6 +1,6 @@ { "name": "@cocos/build-engine", - "version": "4.4.0", + "version": "4.4.0-webgpu.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/scripts/build-engine/package.json b/scripts/build-engine/package.json index ee18e92ccd..a0b14b007b 100644 --- a/scripts/build-engine/package.json +++ b/scripts/build-engine/package.json @@ -1,6 +1,6 @@ { "name": "@cocos/build-engine", - "version": "4.4.0", + "version": "4.4.0-webgpu.0", "description": "", "repository": { "type": "git", diff --git a/scripts/build-engine/src/constant-manager.ts b/scripts/build-engine/src/constant-manager.ts index c85e0b6960..bdfcf53f21 100644 --- a/scripts/build-engine/src/constant-manager.ts +++ b/scripts/build-engine/src/constant-manager.ts @@ -6,7 +6,7 @@ export type ModeType = 'EDITOR' | 'PREVIEW' | 'BUILD' | 'TEST'; export type PlatformType = 'HTML5' | 'NATIVE' | 'WECHAT' | 'BAIDU' | 'XIAOMI' | 'ALIPAY' | 'BYTEDANCE' | 'OPPO' | 'VIVO' | 'HUAWEI' | 'COCOSPLAY' | 'QTT' | 'LINKSURE'; -export type InternalFlagType = 'SERVER_MODE' | 'NOT_PACK_PHYSX_LIBS'; +export type InternalFlagType = 'SERVER_MODE' | 'NOT_PACK_PHYSX_LIBS' | 'WEBGPU'; export type PublicFlagType = 'DEBUG' | 'NET_MODE'; export type FlagType = InternalFlagType | PublicFlagType; diff --git a/scripts/build-engine/src/index.ts b/scripts/build-engine/src/index.ts index 3d81f4faf0..e03386708e 100644 --- a/scripts/build-engine/src/index.ts +++ b/scripts/build-engine/src/index.ts @@ -29,6 +29,7 @@ import { filePathToModuleRequest } from './utils'; import { assetRef as rpAssetRef, pathToAssetRefURL } from './rollup-plugins/asset-ref'; import { codeAsset } from './rollup-plugins/code-asset'; import { ModeType, PlatformType } from './constant-manager'; +import { assetUrl } from './rollup-plugins/asset-url'; export { ModeType, PlatformType, FlagType, ConstantOptions, BuildTimeConstants, CCEnvConstants } from './constant-manager'; export { StatsQuery }; @@ -275,9 +276,11 @@ async function doBuild ({ // HACK: get platform, mode, flags from build time constants const flags: Record = {}; - ['SERVER_MODE', 'NOT_PACK_PHYSX_LIBS', 'DEBUG', 'NET_MODE'].forEach((key) => { + ['SERVER_MODE', 'NOT_PACK_PHYSX_LIBS', 'DEBUG', 'NET_MODE', 'WEBGPU'].forEach((key) => { flags[key] = buildTimeConstants[key]; }); + // Wether use webgpu + const useWebGPU = flags['WEBGPU']; let platform = options.platform as PlatformType; if (!platform) { ["HTML5", "NATIVE", "WECHAT", "BAIDU", "XIAOMI", "ALIPAY", "BYTEDANCE", "OPPO", "VIVO", "HUAWEI", "COCOSPLAY", "QTT", "LINKSURE"].some(key => { @@ -537,6 +540,11 @@ async function doBuild ({ defaultHandler(warning); }; + rollupPlugins.unshift(assetUrl({ + engineRoot, + useWebGPU, + })); + const rollupOptions: rollup.InputOptions = { input: rollupEntries, plugins: rollupPlugins, diff --git a/scripts/build-engine/src/rollup-plugins/asset-url.ts b/scripts/build-engine/src/rollup-plugins/asset-url.ts new file mode 100644 index 0000000000..e71f51a1a1 --- /dev/null +++ b/scripts/build-engine/src/rollup-plugins/asset-url.ts @@ -0,0 +1,65 @@ +import type * as rollup from 'rollup'; +import fs from 'fs-extra'; +import ps, { join } from 'path'; + +interface IOptions { + engineRoot: string, + useWebGPU?: boolean; +} +const URL_PROTOCOL = 'url:'; +const PREFIX = `\0${URL_PROTOCOL}`; + +export function assetUrl ({ + engineRoot, + useWebGPU = false, +}: IOptions): rollup.Plugin { + const files = new Set(); + return { + name: '@cocos/build-engine|external-asset', + + async resolveId (this, source, importer) { + if (source.startsWith(URL_PROTOCOL) && importer) { + const subPath = source.substring(URL_PROTOCOL.length); + const externalAssetPath = join(engineRoot, subPath); + return PREFIX + externalAssetPath; + } + + return null; + }, + + async load (id) { + if (id.startsWith(PREFIX)) { + const path = id.substring(PREFIX.length); + if (!useWebGPU) { + return `export default '';`; + } + const referenceId = this.emitFile({ + type: 'asset', + name: ps.basename(path), + source: await fs.readFile(path), + }); + files.add(referenceId); + return `export default import.meta.ROLLUP_FILE_URL_${referenceId};`; + } + return null; + }, + + // Generates the `import.meta.ROLLUP_FILE_URL_referenceId`. + resolveFileUrl ({ + // > The path and file name of the emitted asset, relative to `output.dir` without a leading `./`. + fileName, + // > The path and file name of the emitted file, + // > relative to the chunk the file is referenced from. + // > This will path will contain no leading `./` but may contain a leading `../`. + relativePath, + + referenceId, + }) { + if (files.has(referenceId)) { + return `'${fileName}'`; + } else { + return undefined; + } + }, + }; +} \ No newline at end of file diff --git a/scripts/build-engine/tests/stats-query/cc.config.json b/scripts/build-engine/tests/stats-query/cc.config.json index f6c887b65b..d4fb68f9fb 100644 --- a/scripts/build-engine/tests/stats-query/cc.config.json +++ b/scripts/build-engine/tests/stats-query/cc.config.json @@ -5,6 +5,7 @@ "base": { "modules": [ "base" ], "dependentAssets": ["0835f102-5471-47a3-9a76-01c07ac9cdb2", "b5475517-23b9-4873-bc1a-968d96616081", "0ed97c56-390e-4dd1-96b7-e7f2d93a98ed", "b23391b6-52eb-46a6-8da1-6244d9d315fb"] }, "gfx-webgl": { "modules": [ "gfx-webgl" ] }, "gfx-webgl2": { "modules": [ "gfx-webgl2" ] }, + "gfx-webgpu": { "modules": [ "gfx-webgpu" ] }, "3d": { "modules": [ "3d" ] }, "animation": { "modules": ["animation"] }, "skeletal-animation": { "modules": ["animation", "skeletal-animation"] }, diff --git a/templates/baidu-mini-game/build-template.json b/templates/baidu-mini-game/build-template.json new file mode 100644 index 0000000000..a9dca61c48 --- /dev/null +++ b/templates/baidu-mini-game/build-template.json @@ -0,0 +1,7 @@ +{ + "version": "1.0.0", + "templates": [ + "game.json", + "project.swan.json" + ] +} \ No newline at end of file diff --git a/templates/bytedance-mini-game/build-template.json b/templates/bytedance-mini-game/build-template.json new file mode 100644 index 0000000000..17666383c6 --- /dev/null +++ b/templates/bytedance-mini-game/build-template.json @@ -0,0 +1,8 @@ +{ + "version": "1.0.0", + "templates": [ + "game.ejs", + "game.json", + "project.config.json" + ] +} \ No newline at end of file diff --git a/templates/cmake/emscripten.cmake b/templates/cmake/emscripten.cmake new file mode 100644 index 0000000000..e69de29bb2 diff --git a/templates/common/.gitignore b/templates/common/.gitignore new file mode 100644 index 0000000000..fc9806a6c4 --- /dev/null +++ b/templates/common/.gitignore @@ -0,0 +1 @@ +localCfg.cmake \ No newline at end of file diff --git a/templates/common/CMakeLists.txt b/templates/common/CMakeLists.txt index 790e2cc806..1446ba8212 100755 --- a/templates/common/CMakeLists.txt +++ b/templates/common/CMakeLists.txt @@ -35,6 +35,10 @@ endif() include(${RES_DIR}/proj/cfg.cmake) +if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/localCfg.cmake) + include(${CMAKE_CURRENT_LIST_DIR}/localCfg.cmake) +endif() + if(NOT COCOS_X_PATH) message(FATAL_ERROR "COCOS_X_PATH is not set!") endif() diff --git a/templates/common/localCfg.cmake b/templates/common/localCfg.cmake new file mode 100644 index 0000000000..f17333e75d --- /dev/null +++ b/templates/common/localCfg.cmake @@ -0,0 +1,3 @@ +## Add or overwrite options from cfg.cmake. +## This file is ignored from git. +# set(NODE_EXECUTABLE /opt/...) \ No newline at end of file diff --git a/templates/web-desktop/build-template.json b/templates/web-desktop/build-template.json new file mode 100644 index 0000000000..0fd8d9f4cc --- /dev/null +++ b/templates/web-desktop/build-template.json @@ -0,0 +1,6 @@ +{ + "version": "1.0.0", + "templates": [ + "index.ejs" + ] +} \ No newline at end of file diff --git a/templates/web-mobile/build-template.json b/templates/web-mobile/build-template.json new file mode 100644 index 0000000000..0fd8d9f4cc --- /dev/null +++ b/templates/web-mobile/build-template.json @@ -0,0 +1,6 @@ +{ + "version": "1.0.0", + "templates": [ + "index.ejs" + ] +} \ No newline at end of file diff --git a/templates/wechatgame/build-template.json b/templates/wechatgame/build-template.json new file mode 100644 index 0000000000..17666383c6 --- /dev/null +++ b/templates/wechatgame/build-template.json @@ -0,0 +1,8 @@ +{ + "version": "1.0.0", + "templates": [ + "game.ejs", + "game.json", + "project.config.json" + ] +} \ No newline at end of file diff --git a/tests/core/math/color.test.ts b/tests/core/math/color.test.ts index 878e33b584..8574681b29 100644 --- a/tests/core/math/color.test.ts +++ b/tests/core/math/color.test.ts @@ -1,4 +1,5 @@ -import { Color } from '../../../cocos/core/math/color'; +import { Vec4 } from '../../../cocos/core'; +import { Color, linearToSrgb8Bit, srgb8BitToLinear, srgbToLinear } from '../../../cocos/core/math/color'; // test Color describe('Test Color', () => { @@ -28,4 +29,17 @@ describe('Test Color', () => { expect(color4._val).toBe(color3._val); }); }); + + test('linearToSrgb', () => { + expect(linearToSrgb8Bit(1.1)).toBe(255); + expect(linearToSrgb8Bit(-1)).toBe(0); + expect(linearToSrgb8Bit(0.5)).toBe(188); + expect(srgb8BitToLinear(188)).toBe(0.5028864580325687); + for (let i = 0; i != 256; i++) { + expect(linearToSrgb8Bit(srgb8BitToLinear(i))).toBe(i); + expect(srgb8BitToLinear(i)).toBe(srgbToLinear(i / 255.0)); + } + expect(Color.toVec4(new Color(255, 188, 0, 255))).toEqual(new Vec4(1, 0.5028864580325687, 0, 1)); + expect(Color.fromVec4(new Vec4 (1, 0.5, 0, 1))).toEqual(new Color(255, 188, 0, 255)); + }); }); diff --git a/tests/general/sealed-global-variables.json b/tests/general/sealed-global-variables.json index fcb3bf4e51..86b73c89f7 100644 --- a/tests/general/sealed-global-variables.json +++ b/tests/general/sealed-global-variables.json @@ -8,7 +8,7 @@ "cc.AmbientInfo", "cc.AnimCurve", "cc.AnimationClip", - "cc.Animation", + "cc.Animation", "cc.AnimationComponent", "cc.AnimationManager", "cc.AnimationState", @@ -25,7 +25,7 @@ "cc.Boolean", "cc.BoxColliderComponent", "cc.BufferAsset", - "cc.Button", + "cc.Button", "cc.ButtonComponent", "cc.CCBoolean", "cc.CCFloat", @@ -119,18 +119,18 @@ "cc.GFX_MAX_TEXTURE_UNITS", "cc.GFX_MAX_VERTEX_ATTRIBUTES", "cc.Game", - "cc.Graphics", + "cc.Graphics", "cc.GraphicsComponent", "cc.ImageAsset", "cc.Integer", "cc.JsonAsset", "cc.LabelAtlas", - "cc.Label", + "cc.Label", "cc.LabelComponent", - "cc.LabelOutline", + "cc.LabelOutline", "cc.LabelOutlineComponent", "cc.Layers", - "cc.Layout", + "cc.Layout", "cc.LayoutComponent", "cc.LightComponent", "cc.LineComponent", @@ -146,9 +146,9 @@ "cc.NodeEventProcessor", "cc.NodePool", "cc.Object", - "cc.PageView", + "cc.PageView", "cc.PageViewComponent", - "cc.PageViewIndicator", + "cc.PageViewIndicator", "cc.PageViewIndicatorComponent", "cc.ParticleAsset", "cc.ParticleSystemComponent", @@ -161,7 +161,7 @@ "cc.Prefab", "cc.Primitive", "cc.PrivateNode", - "cc.ProgressBar", + "cc.ProgressBar", "cc.ProgressBarComponent", "cc.Quat", "cc.RatioSampler", @@ -173,19 +173,19 @@ "cc.RenderTexture", "cc.RenderableComponent", "cc.ResolutionPolicy", - "cc.RichText", + "cc.RichText", "cc.RichTextComponent", "cc.RigidBodyComponent", "cc.Root", - "cc.SafeArea", + "cc.SafeArea", "cc.SafeAreaComponent", "cc.Scene", "cc.SceneAsset", "cc.SceneGlobals", "cc.Scheduler", - "cc.ScrollBar", + "cc.ScrollBar", "cc.ScrollBarComponent", - "cc.ScrollView", + "cc.ScrollView", "cc.ScrollViewComponent", "cc.Shadows", "cc.ShadowsInfo", @@ -197,13 +197,13 @@ "cc.SkinningModelUnit", "cc.Skybox", "cc.SkyboxInfo", - "cc.Slider", + "cc.Slider", "cc.SliderComponent", "cc.SphereColliderComponent", "cc.SphereLightComponent", "cc.SpotLightComponent", "cc.SpriteAtlas", - "cc.Sprite", + "cc.Sprite", "cc.SpriteComponent", "cc.SpriteFrame", "cc.String", @@ -215,14 +215,14 @@ "cc.Texture2D", "cc.TextureBase", "cc.TextureCube", - "cc.Toggle", + "cc.Toggle", "cc.ToggleComponent", - "cc.ToggleContainer", + "cc.ToggleContainer", "cc.ToggleContainerComponent", "cc.Touch", "cc.Tween", "cc.UI", - "cc.UIMeshRenderer", + "cc.UIMeshRenderer", "cc.UIModelComponent", "cc.UIReorderComponent", "cc.UITransformComponent", @@ -234,7 +234,7 @@ "cc.VisibilityFlags", "cc.WebGL2Device", "cc.WebGLDevice", - "cc.Widget", + "cc.Widget", "cc.WidgetComponent", "cc._JavaScript", "cc._MissingScript", diff --git a/tsconfig.json b/tsconfig.json index 6d4555fe2e..6cfec7d726 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -26,6 +26,7 @@ "./@types/editor-extends", "./@types/webGL.extras", "./@types/webGL2.extras", + "./@types/url", "./node_modules/@cocos/cannon/CANNON", "./node_modules/@cocos/bullet/bullet", "./node_modules/@cocos/physx/PhysX",