From 330386b22ea20ed13b2cc15529af1eb93c5a6249 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 17 May 2023 14:22:13 +0800 Subject: [PATCH 01/22] Update web-interface-check.yml (#15085) --- .github/workflows/web-interface-check.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/web-interface-check.yml b/.github/workflows/web-interface-check.yml index f9d2074b6e..304aa755d3 100644 --- a/.github/workflows/web-interface-check.yml +++ b/.github/workflows/web-interface-check.yml @@ -48,7 +48,7 @@ jobs: name: Checkout Head Ref with: repository: ${{ github.event.pull_request.head.repo.full_name }} - ref: ${{ github.head_ref }} +# ref: ${{ github.head_ref }} Don't check out the head commit, checkout the "merge commit" instead path: './engine-HEAD' - run: | "EXT_VERSION_HEAD=$(node ./engine-HEAD/.github/workflows/get-native-external-version.js)" >> $env:GITHUB_ENV From 79b132d85ef99129bd9812eca65ae2792afb3b69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 17 May 2023 14:33:41 +0800 Subject: [PATCH 02/22] Update web-interface-check.yml (#15087) --- .github/workflows/web-interface-check.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/web-interface-check.yml b/.github/workflows/web-interface-check.yml index 304aa755d3..c1cce0c4df 100644 --- a/.github/workflows/web-interface-check.yml +++ b/.github/workflows/web-interface-check.yml @@ -48,7 +48,7 @@ jobs: name: Checkout Head Ref with: repository: ${{ github.event.pull_request.head.repo.full_name }} -# ref: ${{ github.head_ref }} Don't check out the head commit, checkout the "merge commit" instead + ref: 'refs/pull/${{ github.event.number }}/merge' # Don't check out the head commit, checkout the "merge commit" instead path: './engine-HEAD' - run: | "EXT_VERSION_HEAD=$(node ./engine-HEAD/.github/workflows/get-native-external-version.js)" >> $env:GITHUB_ENV From 923278904acef47c5e5da96d5234bc4dcf53d32c Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Wed, 17 May 2023 15:23:35 +0800 Subject: [PATCH 03/22] Fix hinge constraint rotation (#14085) * Fix hinge constraint rotation 1. fixed hinge constraint rotation 2. correct docs 3. add tooltip for hinge constraint * stage * updates * update * vanishing pivotB when connected to world frame * stage * update fixed constraint behavior when bind to world frame --- cocos/physics/bullet/bullet-cache.ts | 1 + .../constraints/bullet-fixed-constraint.ts | 35 +++---- .../constraints/bullet-hinge-constraint.ts | 24 +++-- .../constraints/bullet-p2p-constraint.ts | 2 +- .../constraints/cannon-hinge-constraint.ts | 28 +++--- .../cannon-point-to-point-constraint.ts | 2 +- .../constraints/hinge-constraint.ts | 16 ++-- .../physics/physx/joints/physx-fixed-joint.ts | 34 ++++--- .../physx/joints/physx-revolute-joint.ts | 91 +++++++++++++------ .../physx/joints/physx-spherical-joint.ts | 2 +- editor/i18n/en/localization.js | 7 ++ editor/i18n/zh/localization.js | 7 ++ .../physics/physx/joints/PhysXRevolute.cpp | 39 +++++++- .../physics/physx/joints/PhysXSpherical.cpp | 8 +- 14 files changed, 201 insertions(+), 95 deletions(-) diff --git a/cocos/physics/bullet/bullet-cache.ts b/cocos/physics/bullet/bullet-cache.ts index 65ba81d14c..21e8d57cd4 100644 --- a/cocos/physics/bullet/bullet-cache.ts +++ b/cocos/physics/bullet/bullet-cache.ts @@ -77,6 +77,7 @@ export const CC_V3_0 = new Vec3(); export const CC_V3_1 = new Vec3(); export const CC_V3_2 = new Vec3(); export const CC_QUAT_0 = new Quat(); +export const CC_QUAT_1 = new Quat(); export const CC_MAT4_0 = new Mat4(); export const CC_MAT4_1 = new Mat4(); diff --git a/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts b/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts index 334c4ac192..c05209062c 100644 --- a/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts @@ -30,8 +30,7 @@ import { FixedConstraint, HingeConstraint, PhysicsSystem } from '../../framework import { BulletRigidBody } from '../bullet-rigid-body'; import { BulletCache, CC_MAT4_0, CC_QUAT_0, CC_V3_0 } from '../bullet-cache'; import { bt } from '../instantiated'; -import { bullet2CocosVec3, cocos2BulletQuat, cocos2BulletVec3 } from '../bullet-utils'; -import { BulletWorld } from '../bullet-world'; +import { cocos2BulletQuat, cocos2BulletVec3 } from '../bullet-utils'; export class BulletFixedConstraint extends BulletConstraint implements IFixedConstraint { setBreakForce (v: number): void { @@ -48,11 +47,11 @@ export class BulletFixedConstraint extends BulletConstraint implements IFixedCon onComponentSet () { const cb = this.constraint.connectedBody; - const bodyA = (this._rigidBody.body as BulletRigidBody).sharedBody; - const bodyB = cb ? (cb.body as BulletRigidBody).sharedBody : (PhysicsSystem.instance.physicsWorld as BulletWorld).getSharedBody(bodyA.node); + const bodyA = (this._rigidBody.body as BulletRigidBody).impl; + const bodyB = cb ? (cb.body as BulletRigidBody).impl : bt.TypedConstraint_getFixedBody(); const trans0 = BulletCache.instance.BT_TRANSFORM_0; const trans1 = BulletCache.instance.BT_TRANSFORM_1; - this._impl = bt.FixedConstraint_new(bodyA.body, bodyB.body, trans0, trans1); + this._impl = bt.FixedConstraint_new(bodyA, bodyB, trans0, trans1); this.setBreakForce(this.constraint.breakForce); this.setBreakTorque(this.constraint.breakTorque); this.updateFrames(); @@ -61,10 +60,9 @@ export class BulletFixedConstraint extends BulletConstraint implements IFixedCon updateFrames () { const cb = this.constraint.connectedBody; const bodyA = (this._rigidBody.body as BulletRigidBody).sharedBody; - const bodyB = cb ? (cb.body as BulletRigidBody).sharedBody : (PhysicsSystem.instance.physicsWorld as BulletWorld).getSharedBody(bodyA.node); - const pos : Vec3 = CC_V3_0; - const rot : Quat = CC_QUAT_0; + const pos = CC_V3_0; + const rot = CC_QUAT_0; const trans0 = BulletCache.instance.BT_TRANSFORM_0; const trans1 = BulletCache.instance.BT_TRANSFORM_1; const quat = BulletCache.instance.BT_QUAT_0; @@ -79,14 +77,19 @@ export class BulletFixedConstraint extends BulletConstraint implements IFixedCon cocos2BulletQuat(quat, rot); bt.Transform_setRotation(trans0, quat); - // the local frame transform respect to bodyB - Mat4.fromRT(trans, bodyB.node.worldRotation, bodyB.node.worldPosition); - Mat4.invert(trans, trans); - Mat4.getRotation(rot, trans); - Mat4.getTranslation(pos, trans); - cocos2BulletVec3(bt.Transform_getOrigin(trans1), pos); - cocos2BulletQuat(quat, rot); - bt.Transform_setRotation(trans1, quat); + if (cb) { + // the local frame transform respect to bodyB + const bodyB = (cb.body as BulletRigidBody).sharedBody; + Mat4.fromRT(trans, bodyB.node.worldRotation, bodyB.node.worldPosition); + Mat4.invert(trans, trans); + Mat4.getRotation(rot, trans); + Mat4.getTranslation(pos, trans); + cocos2BulletVec3(bt.Transform_getOrigin(trans1), pos); + cocos2BulletQuat(quat, rot); + bt.Transform_setRotation(trans1, quat); + } else { + bt.Transform_setIdentity(trans1); + } bt.FixedConstraint_setFrames(this._impl, trans0, trans1); } diff --git a/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts b/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts index aab0cbc767..3b3b135d2e 100644 --- a/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts @@ -28,7 +28,7 @@ import { IHingeConstraint } from '../../spec/i-physics-constraint'; import { IVec3Like, Quat, Vec3 } from '../../../core'; import { HingeConstraint } from '../../framework'; import { BulletRigidBody } from '../bullet-rigid-body'; -import { BulletCache, CC_QUAT_0, CC_V3_0 } from '../bullet-cache'; +import { BulletCache, CC_QUAT_0, CC_QUAT_1, CC_V3_0 } from '../bullet-cache'; import { bt } from '../instantiated'; import { cocos2BulletQuat, cocos2BulletVec3 } from '../bullet-utils'; @@ -64,26 +64,38 @@ export class BulletHingeConstraint extends BulletConstraint implements IHingeCon const node = cs.node; const v3_0 = CC_V3_0; const rot_0 = CC_QUAT_0; + const rot_1 = CC_QUAT_1; const trans0 = BulletCache.instance.BT_TRANSFORM_0; + + // offset of axis in local frame of bodyA Vec3.multiply(v3_0, node.worldScale, cs.pivotA); cocos2BulletVec3(bt.Transform_getOrigin(trans0), v3_0); + // rotation of axis in local frame of bodyA const quat = BulletCache.instance.BT_QUAT_0; - Quat.rotationTo(rot_0, Vec3.UNIT_Z, cs.axis); - cocos2BulletQuat(quat, rot_0); + Vec3.normalize(v3_0, cs.axis); + Quat.rotationTo(rot_1, Vec3.UNIT_Z, v3_0); + cocos2BulletQuat(quat, rot_1); bt.Transform_setRotation(trans0, quat); const trans1 = BulletCache.instance.BT_TRANSFORM_1; const cb = this.constraint.connectedBody; if (cb) { + // offset of axis in local frame of bodyB Vec3.multiply(v3_0, cb.node.worldScale, cs.pivotB); + // rotation of axis in local frame of bodyB + Quat.multiply(rot_1, node.worldRotation, rot_1); + Quat.invert(rot_0, cb.node.worldRotation); + Quat.multiply(rot_1, rot_0, rot_1); } else { + // offset of axis in local frame of bodyB Vec3.multiply(v3_0, node.worldScale, cs.pivotA); + Vec3.transformQuat(v3_0, v3_0, node.worldRotation); Vec3.add(v3_0, v3_0, node.worldPosition); - Vec3.add(v3_0, v3_0, cs.pivotB); - Quat.multiply(rot_0, rot_0, node.worldRotation); + // rotation of axis in local frame of bodyB + Quat.multiply(rot_1, node.worldRotation, rot_1); } cocos2BulletVec3(bt.Transform_getOrigin(trans1), v3_0); - cocos2BulletQuat(quat, rot_0); + cocos2BulletQuat(quat, rot_1); bt.Transform_setRotation(trans1, quat); bt.HingeConstraint_setFrames(this._impl, trans0, trans1); } diff --git a/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts b/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts index 5b1fa1a7cd..6ece8df795 100644 --- a/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts @@ -52,8 +52,8 @@ export class BulletP2PConstraint extends BulletConstraint implements IPointToPoi cocos2BulletVec3(pivotB, CC_V3_0); } else { Vec3.multiply(CC_V3_0, node.worldScale, cs.pivotA); + Vec3.transformQuat(CC_V3_0, CC_V3_0, node.worldRotation); Vec3.add(CC_V3_0, CC_V3_0, node.worldPosition); - Vec3.add(CC_V3_0, CC_V3_0, cs.pivotB); cocos2BulletVec3(pivotB, CC_V3_0); } bt.P2PConstraint_setPivotB(this._impl, pivotB); diff --git a/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts b/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts index 8c5b5d08b1..1558b75dd1 100644 --- a/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts @@ -27,9 +27,10 @@ import { CannonConstraint } from './cannon-constraint'; import { IHingeConstraint } from '../../spec/i-physics-constraint'; import { HingeConstraint } from '../../framework'; import { CannonRigidBody } from '../cannon-rigid-body'; -import { IVec3Like, Vec3 } from '../../../core'; +import { IVec3Like, Quat, Vec3 } from '../../../core'; const v3_0 = new Vec3(); +const quat_0 = new Quat(); export class CannonHingeConstraint extends CannonConstraint implements IHingeConstraint { public get impl () { @@ -54,27 +55,30 @@ export class CannonHingeConstraint extends CannonConstraint implements IHingeCon } else { const node = this.constraint.node; Vec3.multiply(v3_0, node.worldScale, cs.pivotA); + Vec3.transformQuat(v3_0, v3_0, node.worldRotation); Vec3.add(v3_0, v3_0, node.worldPosition); - Vec3.add(v3_0, v3_0, cs.pivotB); Vec3.copy(this.impl.pivotB, v3_0); } } setAxis (v: IVec3Like): void { + const equations = this.impl.equations; Vec3.copy(this.impl.axisA, v); - Vec3.copy((this.impl.equations[3] as CANNON.RotationalEquation).axisA, v); - Vec3.copy((this.impl.equations[4] as CANNON.RotationalEquation).axisA, v); - Vec3.copy((this.impl.equations[5] as CANNON.RotationalMotorEquation).axisA, v); + Vec3.copy((equations[3] as CANNON.RotationalEquation).axisA, v); + Vec3.copy((equations[4] as CANNON.RotationalEquation).axisA, v); + Vec3.copy((equations[5] as CANNON.RotationalMotorEquation).axisA, v); if (this.constraint.connectedBody) { - Vec3.copy(this.impl.axisB, v); - Vec3.copy((this.impl.equations[3] as CANNON.RotationalEquation).axisB, v); - Vec3.copy((this.impl.equations[4] as CANNON.RotationalEquation).axisB, v); - Vec3.copy((this.impl.equations[5] as CANNON.RotationalMotorEquation).axisB, v); + Vec3.transformQuat(this.impl.axisB, v, this.constraint.node.worldRotation); + Quat.invert(quat_0, this.constraint.connectedBody.node.worldRotation); + Vec3.transformQuat(this.impl.axisB, this.impl.axisB, quat_0); + Vec3.copy((equations[3] as CANNON.RotationalEquation).axisB, this.impl.axisB); + Vec3.copy((equations[4] as CANNON.RotationalEquation).axisB, this.impl.axisB); + Vec3.copy((equations[5] as CANNON.RotationalMotorEquation).axisB, this.impl.axisB); } else { Vec3.transformQuat(this.impl.axisB, v, this.constraint.node.worldRotation); - Vec3.copy((this.impl.equations[3] as CANNON.RotationalEquation).axisB, this.impl.axisB); - Vec3.copy((this.impl.equations[4] as CANNON.RotationalEquation).axisB, this.impl.axisB); - Vec3.copy((this.impl.equations[5] as CANNON.RotationalMotorEquation).axisB, this.impl.axisB); + Vec3.copy((equations[3] as CANNON.RotationalEquation).axisB, this.impl.axisB); + Vec3.copy((equations[4] as CANNON.RotationalEquation).axisB, this.impl.axisB); + Vec3.copy((equations[5] as CANNON.RotationalMotorEquation).axisB, this.impl.axisB); } } diff --git a/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts b/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts index 55d3499449..7b3d9b55b8 100644 --- a/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts @@ -54,8 +54,8 @@ export class CannonPointToPointConstraint extends CannonConstraint implements IP } else { const node = cs.node; Vec3.multiply(v3_0, node.worldScale, cs.pivotA); + Vec3.transformQuat(v3_0, v3_0, node.worldRotation); Vec3.add(v3_0, v3_0, node.worldPosition); - Vec3.add(v3_0, v3_0, cs.pivotB); Vec3.copy(this.impl.pivotB, v3_0); } } diff --git a/cocos/physics/framework/components/constraints/hinge-constraint.ts b/cocos/physics/framework/components/constraints/hinge-constraint.ts index 1e153f91b5..5fd5158592 100644 --- a/cocos/physics/framework/components/constraints/hinge-constraint.ts +++ b/cocos/physics/framework/components/constraints/hinge-constraint.ts @@ -29,6 +29,7 @@ import { serializable, formerlySerializedAs, type, + tooltip, } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Constraint } from './constraint'; @@ -42,11 +43,12 @@ import { IHingeConstraint } from '../../../spec/i-physics-constraint'; export class HingeConstraint extends Constraint { /** * @en - * The position of the own rigid body in local space with respect to the constraint axis. + * The pivot point of the hinge in the local coordinate system of the own rigid body. * @zh - * 在本地空间中,自身刚体相对于约束关节的位置。 + * 在自身刚体的本地坐标系中,旋转轴的锚点位置。 */ @type(Vec3) + @tooltip('i18n:physics3d.constraint.hinge.pivotA') get pivotA (): Vec3 { return this._pivotA; } @@ -60,11 +62,12 @@ export class HingeConstraint extends Constraint { /** * @en - * The position of the connected rigid body in the local space with respect to the constraint axis. + * The pivot point of the hinge in the local coordinate system of the connected rigid body. * @zh - * 在本地空间中,连接刚体相对于约束关节的位置。 + * 在连接刚体的本地坐标系中,旋转轴的锚点位置。 */ @type(Vec3) + @tooltip('i18n:physics3d.constraint.hinge.pivotB') get pivotB (): Vec3 { return this._pivotB; } @@ -78,11 +81,12 @@ export class HingeConstraint extends Constraint { /** * @en - * The direction of the constraint axis rotation in local space. + * The axis of the hinge in the local coordinate system of the own rigid body. * @zh - * 在本地空间中,约束关节旋转的方向。 + * 在自身刚体的本地坐标系中,旋转轴的方向。 */ @type(Vec3) + @tooltip('i18n:physics3d.constraint.hinge.axis') get axis (): Vec3 { return this._axis; } diff --git a/cocos/physics/physx/joints/physx-fixed-joint.ts b/cocos/physics/physx/joints/physx-fixed-joint.ts index 543c2f12e0..58a27b4d14 100644 --- a/cocos/physics/physx/joints/physx-fixed-joint.ts +++ b/cocos/physics/physx/joints/physx-fixed-joint.ts @@ -32,6 +32,10 @@ import { PhysXRigidBody } from '../physx-rigid-body'; import { PhysXWorld } from '../physx-world'; import { PhysXJoint } from './physx-joint'; +const v3_0 = new Vec3(); +const quat_0 = new Quat(); +const mat_0 = new Mat4(); + export class PhysXFixedJoint extends PhysXJoint implements IFixedConstraint { setBreakForce (v: number): void { this._breakForce = this.constraint.breakForce; @@ -60,23 +64,23 @@ export class PhysXFixedJoint extends PhysXJoint implements IFixedConstraint { updateFrame () { const bodyA = (this._rigidBody.body as PhysXRigidBody).sharedBody; const cb = this.constraint.connectedBody; - const bodyB = cb ? (cb.body as PhysXRigidBody).sharedBody : (PhysicsSystem.instance.physicsWorld as PhysXWorld).getSharedBody(bodyA.node); - const pos : Vec3 = new Vec3(); - const rot : Quat = new Quat(); + Mat4.fromRT(mat_0, bodyA.node.worldRotation, bodyA.node.worldPosition); + Mat4.invert(mat_0, mat_0); + Mat4.getRotation(quat_0, mat_0); + Mat4.getTranslation(v3_0, mat_0); + this._impl.setLocalPose(0, getTempTransform(v3_0, quat_0)); - const trans = new Mat4(); - Mat4.fromRT(trans, bodyA.node.worldRotation, bodyA.node.worldPosition); - Mat4.invert(trans, trans); - Mat4.getRotation(rot, trans); - Mat4.getTranslation(pos, trans); - this._impl.setLocalPose(0, getTempTransform(pos, rot)); - - Mat4.fromRT(trans, bodyB.node.worldRotation, bodyB.node.worldPosition); - Mat4.invert(trans, trans); - Mat4.getRotation(rot, trans); - Mat4.getTranslation(pos, trans); - this._impl.setLocalPose(1, getTempTransform(pos, rot)); + if (cb) { + const bodyB = (cb.body as PhysXRigidBody).sharedBody; + Mat4.fromRT(mat_0, bodyB.node.worldRotation, bodyB.node.worldPosition); + Mat4.invert(mat_0, mat_0); + Mat4.getRotation(quat_0, mat_0); + Mat4.getTranslation(v3_0, mat_0); + this._impl.setLocalPose(1, getTempTransform(v3_0, quat_0)); + } else { + this._impl.setLocalPose(1, getTempTransform(Vec3.ZERO, Quat.IDENTITY)); + } } updateScale0 () { diff --git a/cocos/physics/physx/joints/physx-revolute-joint.ts b/cocos/physics/physx/joints/physx-revolute-joint.ts index 52694c1273..3c3c78dd6b 100644 --- a/cocos/physics/physx/joints/physx-revolute-joint.ts +++ b/cocos/physics/physx/joints/physx-revolute-joint.ts @@ -22,44 +22,30 @@ THE SOFTWARE. */ -import { IVec3Like, Quat, Vec3 } from '../../../core'; +import { IVec3Like, Mat4, Quat, Vec3 } from '../../../core'; import { HingeConstraint } from '../../framework'; import { IHingeConstraint } from '../../spec/i-physics-constraint'; import { getTempTransform, PX, _pxtrans, _trans } from '../physx-adapter'; import { PhysXJoint } from './physx-joint'; +const v3_0 = new Vec3(); +const v3_1 = new Vec3(); +const v3_2 = new Vec3(); +const mat_0 = new Mat4(); + export class PhysXRevoluteJoint extends PhysXJoint implements IHingeConstraint { + private _rot = new Quat(Quat.IDENTITY); + setPivotA (v: IVec3Like): void { - const cs = this.constraint; - const pos = _trans.translation; - const rot = _trans.rotation; - Vec3.multiply(pos, cs.node.worldScale, cs.pivotA); - Quat.rotationTo(rot, Vec3.UNIT_X, cs.axis); - this._impl.setLocalPose(0, getTempTransform(pos, rot)); - if (!cs.connectedBody) this.setPivotB(cs.pivotB); + this.updateFrames(); } setPivotB (v: IVec3Like): void { - const cs = this.constraint; - const cb = cs.connectedBody; - const pos = _trans.translation; - const rot = _trans.rotation; - Quat.rotationTo(rot, Vec3.UNIT_X, cs.axis); - if (cb) { - Vec3.multiply(pos, cb.node.worldScale, cs.pivotB); - } else { - const node = cs.node; - Vec3.multiply(pos, node.worldScale, cs.pivotA); - Vec3.add(pos, pos, node.worldPosition); - Vec3.add(pos, pos, cs.pivotB); - Quat.multiply(rot, rot, node.worldRotation); - } - this._impl.setLocalPose(1, getTempTransform(pos, rot)); + this.updateFrames(); } setAxis (v: IVec3Like): void { - this.setPivotA(this.constraint.pivotA); - this.setPivotB(this.constraint.pivotB); + this.updateFrames(); } get constraint (): HingeConstraint { @@ -68,15 +54,62 @@ export class PhysXRevoluteJoint extends PhysXJoint implements IHingeConstraint { onComponentSet (): void { this._impl = PX.createRevoluteJoint(PhysXJoint.tempActor, _pxtrans, null, _pxtrans); - this.setPivotA(this.constraint.pivotA); - this.setPivotB(this.constraint.pivotB); + this.updateFrames(); + } + + updateFrames () { + const cs = this.constraint; + const cb = cs.connectedBody; + const pos = _trans.translation; + const rot = _trans.rotation; + const node = cs.node; + + Vec3.normalize(v3_0, cs.axis); + Vec3.cross(v3_2, v3_0, Vec3.UNIT_Y); // z + if (Vec3.len(v3_2) < 0.0001) { + Vec3.cross(v3_1, Vec3.UNIT_Z, v3_0); // y + Vec3.cross(v3_2, v3_0, v3_1); // z + } else { + Vec3.cross(v3_1, v3_2, v3_0); // y + } + + Vec3.normalize(v3_1, v3_1); + Vec3.normalize(v3_2, v3_2); + + mat_0.set( + v3_0.x, v3_0.y, v3_0.z, 0, // x + v3_1.x, v3_1.y, v3_1.z, 0, // y + v3_2.x, v3_2.y, v3_2.z, 0, // z + 0, 0, 0, 1, + ); + + mat_0.getRotation(this._rot); + Vec3.multiply(pos, cs.node.worldScale, cs.pivotA); + this._impl.setLocalPose(0, getTempTransform(pos, this._rot)); + + if (cb) { + // orientation of axis in local space of body1 + Quat.multiply(this._rot, node.worldRotation, this._rot); + Quat.invert(rot, cb.node.worldRotation); + Quat.multiply(this._rot, rot, this._rot); + // position in local space body0 + Vec3.multiply(pos, cb.node.worldScale, cs.pivotB); + } else { + // orientation of axis in local space of body1 + Quat.multiply(this._rot, node.worldRotation, this._rot); + // position in world space + Vec3.multiply(pos, node.worldScale, cs.pivotA); + Vec3.transformQuat(pos, pos, node.worldRotation); + Vec3.add(pos, pos, node.worldPosition); + } + this._impl.setLocalPose(1, getTempTransform(pos, this._rot)); } updateScale0 () { - this.setPivotA(this.constraint.pivotA); + this.updateFrames(); } updateScale1 () { - this.setPivotB(this.constraint.pivotB); + this.updateFrames(); } } diff --git a/cocos/physics/physx/joints/physx-spherical-joint.ts b/cocos/physics/physx/joints/physx-spherical-joint.ts index d85af26c14..9edaa6642d 100644 --- a/cocos/physics/physx/joints/physx-spherical-joint.ts +++ b/cocos/physics/physx/joints/physx-spherical-joint.ts @@ -51,8 +51,8 @@ export class PhysXSphericalJoint extends PhysXJoint implements IPointToPointCons } else { const node = cs.node; Vec3.multiply(pos, node.worldScale, cs.pivotA); + Vec3.transformQuat(pos, pos, node.worldRotation); Vec3.add(pos, pos, node.worldPosition); - Vec3.add(pos, pos, cs.pivotB); Quat.multiply(rot, rot, node.worldRotation); } this._impl.setLocalPose(1, getTempTransform(pos, rot)); diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 3984ed7e4e..9e2a4b217e 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -1106,6 +1106,13 @@ module.exports = { torque: 'The torque applied to the rigid body in the world coordinate system', localTorque: 'The torque applied to the rigid body in the local coordinate system', }, + constraint: { + hinge: { + pivotA: 'The pivot point of the hinge in the local coordinate system of the own rigid body', + pivotB: 'The pivot point of the hinge in the local coordinate system of the connected rigid body', + axis: 'The axis of the hinge in the local coordinate system of the own rigid body', + }, + }, character_controller: { group: 'Collision Group of the character controller.', minMoveDistance: 'The minimum movement distance of the character controller.', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 9f5aa55540..c09bbbef81 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -1087,6 +1087,13 @@ module.exports = { torque: '在世界坐标系中,对刚体施加的扭转力', localTorque: '在本地坐标系中,对刚体施加的扭转力', }, + constraint: { + hinge: { + pivotA: '在自身刚体的本地坐标系中,旋转轴的锚点位置', + pivotB: '在连接刚体的本地坐标系中,旋转轴的锚点位置', + axis: '在自身刚体的本地坐标系中,旋转轴的方向', + }, + }, character_controller: { group: '碰撞分组', minMoveDistance: '最小移动距离', diff --git a/native/cocos/physics/physx/joints/PhysXRevolute.cpp b/native/cocos/physics/physx/joints/PhysXRevolute.cpp index 32fa2e724d..db266808d9 100644 --- a/native/cocos/physics/physx/joints/PhysXRevolute.cpp +++ b/native/cocos/physics/physx/joints/PhysXRevolute.cpp @@ -60,21 +60,50 @@ void PhysXRevolute::updateScale1() { void PhysXRevolute::updatePose() { physx::PxTransform pose0{physx::PxIdentity}; physx::PxTransform pose1{physx::PxIdentity}; + + auto xAxis = _mAxis.getNormalized(); + auto yAxis = physx::PxVec3(0, 1, 0); + auto zAxis = _mAxis.cross(yAxis); + if (zAxis.magnitude() < 0.0001) { + yAxis = physx::PxVec3(0, 0, 1).cross(xAxis); + zAxis = xAxis.cross(yAxis); + } else { + yAxis = zAxis.cross(xAxis); + } + + yAxis = yAxis.getNormalized(); + zAxis = zAxis.getNormalized(); + + Mat4 transform( + xAxis.x, xAxis.y, xAxis.z, 0, + yAxis.x, yAxis.y, yAxis.z, 0, + zAxis.x, zAxis.y, zAxis.z, 0, + 0.F, 0.F, 0.F, 1.F); + + auto quat = Quaternion(); + transform.getRotation(&quat); + + // pos and rot in with respect to bodyA auto *node0 = _mSharedBody->getNode(); node0->updateWorldTransform(); pose0.p = _mPivotA * node0->getWorldScale(); - pxSetFromTwoVectors(pose0.q, physx::PxVec3{1.F, 0.F, 0.F}, _mAxis); + pose0.q = physx::PxQuat(quat.x, quat.y, quat.z, quat.w); _mJoint->setLocalPose(physx::PxJointActorIndex::eACTOR0, pose0); - pose1.q = pose0.q; + if (_mConnectedBody) { auto *node1 = _mConnectedBody->getNode(); node1->updateWorldTransform(); pose1.p = _mPivotB * node1->getWorldScale(); + const auto &rot_0 = node0->getWorldRotation(); + const auto &rot_1_i = node1->getWorldRotation().getInversed(); + pose1.q = physx::PxQuat(rot_1_i.x, rot_1_i.y, rot_1_i.z, rot_1_i.w) * physx::PxQuat(rot_0.x, rot_0.y, rot_0.z, rot_0.w) * pose0.q; } else { - pose1.p = _mPivotA * node0->getWorldScale(); - pose1.p += _mPivotB + node0->getWorldPosition(); const auto &wr = node0->getWorldRotation(); - pose1.q *= physx::PxQuat{wr.x, wr.y, wr.z, wr.w}; + auto rot = physx::PxQuat{wr.x, wr.y, wr.z, wr.w}; + pose1.p = _mPivotA * node0->getWorldScale(); + rot.rotate(pose1.p); + pose1.p = pose1.p + node0->getWorldPosition(); + pose1.q = rot * pose0.q; } _mJoint->setLocalPose(physx::PxJointActorIndex::eACTOR1, pose1); } diff --git a/native/cocos/physics/physx/joints/PhysXSpherical.cpp b/native/cocos/physics/physx/joints/PhysXSpherical.cpp index bb664c46f7..286af8dc48 100644 --- a/native/cocos/physics/physx/joints/PhysXSpherical.cpp +++ b/native/cocos/physics/physx/joints/PhysXSpherical.cpp @@ -64,10 +64,12 @@ void PhysXSpherical::updatePose() { node1->updateWorldTransform(); pose1.p = _mPivotB * node1->getWorldScale(); } else { - pose1.p = _mPivotA * node0->getWorldScale(); - pose1.p += _mPivotB + node0->getWorldPosition(); const auto &wr = node0->getWorldRotation(); - pose1.q *= physx::PxQuat{wr.x, wr.y, wr.z, wr.w}; + auto rot = physx::PxQuat{wr.x, wr.y, wr.z, wr.w}; + pose1.p = _mPivotA * node0->getWorldScale(); + rot.rotate(pose1.p); + pose1.p = pose1.p + node0->getWorldPosition(); + pose1.q = rot; } _mJoint->setLocalPose(physx::PxJointActorIndex::eACTOR1, pose1); } From 96c4927a28f010b5a617fd3e9905b4282018a006 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Wed, 17 May 2023 15:24:39 +0800 Subject: [PATCH 04/22] add support to change connected body for joint component (#14609) * complete implement of joint.setConnectedBody * fix c++ joint issues * clean code --- .../bullet/constraints/bullet-constraint.ts | 36 +++++++++++++-- .../cannon/constraints/cannon-constraint.ts | 45 ++++++++++++++----- cocos/physics/physx/joints/physx-joint.ts | 31 ++++++++++++- cocos/physics/physx/physx-shared-body.ts | 4 +- .../cocos/physics/physx/joints/PhysXJoint.cpp | 16 +++++++ 5 files changed, 114 insertions(+), 18 deletions(-) diff --git a/cocos/physics/bullet/constraints/bullet-constraint.ts b/cocos/physics/bullet/constraints/bullet-constraint.ts index 93a59e6d98..b061ff9a2b 100644 --- a/cocos/physics/bullet/constraints/bullet-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-constraint.ts @@ -30,7 +30,33 @@ import { bt, EBulletType } from '../instantiated'; export abstract class BulletConstraint implements IBaseConstraint { setConnectedBody (v: RigidBody | null): void { - // TODO: support dynamic change connected body + if (this._connectedBody === v) return; + // clear old joint info + const oldBody2 = this._connectedBody; + if (oldBody2) { + const oldSB2 = (oldBody2.body as BulletRigidBody).sharedBody; + oldSB2.removeJoint(this, 1); + } + + const sb = (this._rigidBody.body as BulletRigidBody).sharedBody; + sb.removeJoint(this, 0); + if (this._impl) { + sb.wrappedWorld.removeConstraint(this); + bt._safe_delete(this._impl, EBulletType.EBulletTypeTypedConstraint); // delete old bullet constraint + } + + this._connectedBody = v; + const connect = this._connectedBody; + // create the new joint + this.onComponentSet(); + this.setEnableCollision(this._collided); + sb.wrappedWorld.addConstraint(this); + sb.addJoint(this, 0); + // fill new joint info + if (connect) { + const sb2 = (connect.body as BulletRigidBody).sharedBody; + sb2.addJoint(this, 1); + } } setEnableCollision (v: boolean): void { @@ -54,6 +80,7 @@ export abstract class BulletConstraint implements IBaseConstraint { protected _impl: Bullet.ptr = 0; protected _com!: Constraint; protected _rigidBody!: RigidBody; + protected _connectedBody: RigidBody | null = null; protected _collided = false; updateByReAdd () { @@ -67,8 +94,10 @@ export abstract class BulletConstraint implements IBaseConstraint { initialize (v: Constraint): void { this._com = v; this._rigidBody = v.attachedBody!; + this._connectedBody = v.connectedBody; this._collided = v.enableCollision; this.onComponentSet(); + this.setEnableCollision(this._collided); } // virtual @@ -81,7 +110,7 @@ export abstract class BulletConstraint implements IBaseConstraint { const sb = (this._rigidBody.body as BulletRigidBody).sharedBody; sb.wrappedWorld.addConstraint(this); sb.addJoint(this, 0); - const connect = this.constraint.connectedBody; + const connect = this._connectedBody; if (connect) { const sb2 = (connect.body as BulletRigidBody).sharedBody; sb2.addJoint(this, 1); @@ -92,7 +121,7 @@ export abstract class BulletConstraint implements IBaseConstraint { const sb = (this._rigidBody.body as BulletRigidBody).sharedBody; sb.wrappedWorld.removeConstraint(this); sb.removeJoint(this, 0); - const connect = this.constraint.connectedBody; + const connect = this._connectedBody; if (connect) { const sb2 = (connect.body as BulletRigidBody).sharedBody; sb2.removeJoint(this, 1); @@ -103,5 +132,6 @@ export abstract class BulletConstraint implements IBaseConstraint { bt._safe_delete(this._impl, EBulletType.EBulletTypeTypedConstraint); (this._com as any) = null; (this._rigidBody as any) = null; + (this._connectedBody as any) = null; } } diff --git a/cocos/physics/cannon/constraints/cannon-constraint.ts b/cocos/physics/cannon/constraints/cannon-constraint.ts index 4ae5d9cfa1..b3d121ebe9 100644 --- a/cocos/physics/cannon/constraints/cannon-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-constraint.ts @@ -34,18 +34,36 @@ import { CannonSharedBody } from '../cannon-shared-body'; export class CannonConstraint implements IBaseConstraint { setConnectedBody (v: RigidBody | null): void { - const oldSB = getWrap(this.impl.bodyB); - if (oldSB) oldSB.removeJoint(this, 1); + if (this._connectedBody === v) return; - if (v) { - this._impl.bodyB = (v.body as CannonRigidBody).impl; - const newSB = (v.body as CannonRigidBody).sharedBody; - newSB.addJoint(this, 1); - } else { - this._impl.bodyB = (CANNON.World as any).staticBody; + const oldBody2 = this._connectedBody; + if (oldBody2) { + const oldSB2 = (oldBody2.body as CannonRigidBody).sharedBody; + oldSB2.removeJoint(this, 1); + } + + const sb = (this._rigidBody.body as CannonRigidBody).sharedBody; + sb.removeJoint(this, 0); + if (this._impl) { + sb.wrappedWorld.removeConstraint(this); + delete (CANNON.World as any).idToConstraintMap[this._impl.id]; + (this._impl as any) = null; + } + + this._connectedBody = v; + const connect = this._connectedBody; + + this.onComponentSet(); + this.setEnableCollision(this._com.enableCollision); + (CANNON.World as any).idToConstraintMap[this._impl.id] = this._impl; + + sb.wrappedWorld.addConstraint(this); + sb.addJoint(this, 0); + + if (connect) { + const newSB2 = (connect.body as CannonRigidBody).sharedBody; + newSB2.addJoint(this, 1); } - const newBJ = this._impl.bodyB; - this._impl.equations.forEach((v: CANNON.Equation) => { v.bj = newBJ; }); } setEnableCollision (v: boolean): void { @@ -58,10 +76,12 @@ export class CannonConstraint implements IBaseConstraint { protected _impl!: CANNON.Constraint; protected _com!: Constraint; protected _rigidBody!: RigidBody; + protected _connectedBody!: RigidBody | null; initialize (v: Constraint): void { this._com = v; this._rigidBody = v.attachedBody!; + this._connectedBody = v.connectedBody; this.onComponentSet(); this.setEnableCollision(v.enableCollision); (CANNON.World as any).idToConstraintMap[this._impl.id] = this._impl; @@ -78,7 +98,7 @@ export class CannonConstraint implements IBaseConstraint { const sb = (this._rigidBody.body as CannonRigidBody).sharedBody; sb.wrappedWorld.addConstraint(this); sb.addJoint(this, 0); - const connect = this.constraint.connectedBody; + const connect = this._connectedBody; if (connect) { const sb2 = (connect.body as CannonRigidBody).sharedBody; sb2.addJoint(this, 1); @@ -89,7 +109,7 @@ export class CannonConstraint implements IBaseConstraint { const sb = (this._rigidBody.body as CannonRigidBody).sharedBody; sb.wrappedWorld.removeConstraint(this); sb.removeJoint(this, 0); - const connect = this.constraint.connectedBody; + const connect = this._connectedBody; if (connect) { const sb2 = (connect.body as CannonRigidBody).sharedBody; sb2.removeJoint(this, 1); @@ -100,6 +120,7 @@ export class CannonConstraint implements IBaseConstraint { delete (CANNON.World as any).idToConstraintMap[this._impl.id]; (this._com as any) = null; (this._rigidBody as any) = null; + (this._connectedBody as any) = null; (this._impl as any) = null; } } diff --git a/cocos/physics/physx/joints/physx-joint.ts b/cocos/physics/physx/joints/physx-joint.ts index dedff979d8..bc55b1911c 100644 --- a/cocos/physics/physx/joints/physx-joint.ts +++ b/cocos/physics/physx/joints/physx-joint.ts @@ -40,7 +40,33 @@ export class PhysXJoint implements IBaseConstraint { } setConnectedBody (v: RigidBody | null): void { - // TODO + if (this._connectedBody === v) return; + + // // unregister old + const oldBody2 = this._connectedBody; + if (oldBody2) { + const oldSB2 = (oldBody2.body as PhysXRigidBody).sharedBody; + oldSB2.removeJoint(this, 1); + } + + const sb = (this._rigidBody.body as PhysXRigidBody).sharedBody; + sb.removeJoint(this, 0); + sb.addJoint(this, 0); // add to inner body if this joint is not added to sb + if (v) { + const sb2 = (v.body as PhysXRigidBody).sharedBody; + setJointActors(this._impl, sb.impl, sb2.impl); + sb2.addJoint(this, 1); // add to new sb2 + } else { + setJointActors(this._impl, sb.impl, null); + } + + if (oldBody2) { + oldBody2.wakeUp(); // wake it up, or the old body will be sleep for a while + } + + this._connectedBody = v; + this.updateScale0(); + this.updateScale1(); } setEnableCollision (v: boolean): void { @@ -53,10 +79,12 @@ export class PhysXJoint implements IBaseConstraint { protected _impl!: any; protected _com!: Constraint; protected _rigidBody!: RigidBody; + protected _connectedBody: RigidBody | null = null; initialize (v: Constraint): void { this._com = v; this._rigidBody = v.attachedBody!; + this._connectedBody = v.connectedBody; this.onComponentSet(); this.setEnableCollision(this._com.enableCollision); if (this._impl.$$) { @@ -103,6 +131,7 @@ export class PhysXJoint implements IBaseConstraint { this._impl.release(); (this._com as any) = null; (this._rigidBody as any) = null; + (this._connectedBody as any) = null; this._impl = null; } } diff --git a/cocos/physics/physx/physx-shared-body.ts b/cocos/physics/physx/physx-shared-body.ts index 52c1fbec19..6ff9a24557 100644 --- a/cocos/physics/physx/physx-shared-body.ts +++ b/cocos/physics/physx/physx-shared-body.ts @@ -240,13 +240,13 @@ export class PhysXSharedBody { } } - setLinearDamping (linDamp:number) { + setLinearDamping (linDamp: number) { if (!this._dynamicActor) return; const dt = PhysicsSystem.instance.fixedTimeStep; this._dynamicActor.setLinearDamping((1 - (1 - linDamp) ** dt) / dt); } - setAngularDamping (angDamp:number) { + setAngularDamping (angDamp: number) { if (!this._dynamicActor) return; const dt = PhysicsSystem.instance.fixedTimeStep; this._dynamicActor.setAngularDamping((1 - (1 - angDamp) ** dt) / dt); diff --git a/native/cocos/physics/physx/joints/PhysXJoint.cpp b/native/cocos/physics/physx/joints/PhysXJoint.cpp index 460d4bfd17..aff2e264f0 100644 --- a/native/cocos/physics/physx/joints/PhysXJoint.cpp +++ b/native/cocos/physics/physx/joints/PhysXJoint.cpp @@ -69,16 +69,32 @@ void PhysXJoint::setConnectedBody(uint32_t rigidBodyID) { if (pxRigidBody == nullptr) return; + + auto *oldConnectedBody = _mConnectedBody; + if (oldConnectedBody) { + oldConnectedBody->removeJoint(*this, physx::PxJointActorIndex::eACTOR1); + } + uintptr_t nodePtr = reinterpret_cast(pxRigidBody->getSharedBody().getNode()); if (nodePtr) { auto &ins = PhysXWorld::getInstance(); _mConnectedBody = ins.getSharedBody(reinterpret_cast(nodePtr)); + _mConnectedBody->addJoint(*this, physx::PxJointActorIndex::eACTOR1); } else { _mConnectedBody = nullptr; } if (_mJoint) { _mJoint->setActors(_mSharedBody->getImpl().rigidActor, _mConnectedBody ? _mConnectedBody->getImpl().rigidActor : nullptr); } + + if (oldConnectedBody) { + if (oldConnectedBody->isDynamic()) { + oldConnectedBody->getImpl().rigidDynamic->wakeUp(); + } + } + + updateScale0(); + updateScale1(); } void PhysXJoint::setEnableCollision(const bool v) { From 43f835b7bdddddcddf4c4e11a91e157e1cbe0e2e Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Wed, 17 May 2023 15:44:53 +0800 Subject: [PATCH 05/22] fix: vb ib indirect should be shared. (#15062) --- native/cocos/core/assets/RenderingSubMesh.cpp | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/native/cocos/core/assets/RenderingSubMesh.cpp b/native/cocos/core/assets/RenderingSubMesh.cpp index e031c50ca8..363414194c 100644 --- a/native/cocos/core/assets/RenderingSubMesh.cpp +++ b/native/cocos/core/assets/RenderingSubMesh.cpp @@ -207,15 +207,9 @@ void RenderingSubMesh::enableVertexIdChannel(gfx::Device *device) { } bool RenderingSubMesh::destroy() { - for (auto *vertexBuffer : _vertexBuffers) { - vertexBuffer->destroy(); - } _vertexBuffers.clear(); - - if (_indexBuffer && _isOwnerOfIndexBuffer) { - _indexBuffer->destroy(); - _indexBuffer = nullptr; - } + _indexBuffer = nullptr; + _indirectBuffer = nullptr; if (!_jointMappedBuffers.empty() && !_jointMappedBufferIndices.empty()) { for (uint32_t index : _jointMappedBufferIndices) { @@ -224,8 +218,6 @@ bool RenderingSubMesh::destroy() { _jointMappedBuffers.clear(); _jointMappedBufferIndices.clear(); } - - CC_SAFE_DESTROY_NULL(_indirectBuffer); return true; } From 8bc85cc577aed67188edf62533e1397610ec68eb Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Wed, 17 May 2023 15:58:18 +0800 Subject: [PATCH 06/22] IPhysicsEngineId replaces ammo.js with bullet (#15070) * IPhysicsEngineId replaces ammo.js with bullet * put back "string" --- cocos/physics/framework/physics-config.ts | 2 +- cocos/physics/framework/physics-selector.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/physics/framework/physics-config.ts b/cocos/physics/framework/physics-config.ts index c570ac0fd1..746bb575c8 100644 --- a/cocos/physics/framework/physics-config.ts +++ b/cocos/physics/framework/physics-config.ts @@ -43,5 +43,5 @@ export interface IPhysicsConfig { collisionGroups?: ICollisionGroup[]; autoSimulation?: boolean; useNodeChains?: boolean; - physicsEngine?: 'builtin' | 'cannon.js' | 'ammo.js' | string; + physicsEngine?: 'builtin' | 'cannon.js' | 'bullet' | 'physx' | string; } diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index c65a8588ae..018c53e87f 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -38,7 +38,7 @@ import { errorID, IVec3Like, warn, cclegacy } from '../../core'; import { EColliderType, EConstraintType, ECharacterControllerType } from './physics-enum'; import { PhysicsMaterial } from '.'; -export type IPhysicsEngineId = 'builtin' | 'cannon.js' | 'ammo.js' | 'physx' | string; +export type IPhysicsEngineId = 'builtin' | 'cannon.js' | 'bullet' | 'physx' | string; interface IPhysicsWrapperObject { PhysicsWorld?: Constructor, From 4c2bed1c76f878c719489f31fda331183c821f53 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Wed, 17 May 2023 16:14:42 +0800 Subject: [PATCH 07/22] update shader code and i18n (#15060) --- .../chunks/builtin/uniforms/cc-local.chunk | 2 +- .../assets/chunks/common/math/transform.chunk | 14 +++++++ .../data-structures/vs-input.chunk | 2 +- .../render-planar-shadow/vs.chunk | 1 + .../default-functions/standard-fs.chunk | 4 +- .../effects/advanced/simple-skin.effect | 40 +++++++++++-------- editor/assets/effects/advanced/skin.effect | 10 +++-- .../pipeline/post-process/chunks/hbao.chunk | 36 ++++++++--------- editor/i18n/en/assets.js | 3 ++ editor/i18n/zh/assets.js | 3 ++ native/cocos/renderer/pipeline/Define.cpp | 6 +++ native/cocos/renderer/pipeline/Define.h | 2 + 12 files changed, 80 insertions(+), 43 deletions(-) diff --git a/editor/assets/chunks/builtin/uniforms/cc-local.chunk b/editor/assets/chunks/builtin/uniforms/cc-local.chunk index f554b29584..b44350d7cd 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-local.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-local.chunk @@ -5,7 +5,7 @@ layout(set = 2, binding = 0) uniform CCLocal { highp mat4 cc_matWorld; highp mat4 cc_matWorldIT; highp vec4 cc_lightingMapUVParam; - highp vec4 cc_localShadowBias; // x:shadow bias, y:shadow normal bias, z:unused, w:visibility for dirlight + highp vec4 cc_localShadowBias; // x:shadow bias, y:shadow normal bias, z: reflection probe id, w: blend reflection probe id highp vec4 cc_reflectionProbeData1; // xyzw: plane or xyz: cube center highp vec4 cc_reflectionProbeData2; // x: planar reflection depth scale or xyz: cube box half size, w: isRGBE(1000) and mipCount highp vec4 cc_reflectionProbeBlendData1; //xyz: blend cube center w:blend weight diff --git a/editor/assets/chunks/common/math/transform.chunk b/editor/assets/chunks/common/math/transform.chunk index e92675bab8..fd9c9ad985 100644 --- a/editor/assets/chunks/common/math/transform.chunk +++ b/editor/assets/chunks/common/math/transform.chunk @@ -266,3 +266,17 @@ vec3 quatToEuler(vec4 q) { } return vec3(bank, heading, attitude); } + +void departWorldMatrix(out vec3 translation, out vec3 scale, mat4 matWorld) +{ + scale = vec3(length(matWorld[0].xyz), length(matWorld[1].xyz), length(matWorld[2].xyz)); + translation = vec3(matWorld[0].w, matWorld[1].w, matWorld[2].w); +} + +void departWorldMatrix(out vec3 translation, out vec3 scale, out mat3 matRotation, mat4 matWorld) +{ + departWorldMatrix(translation, scale, matWorld); + matRotation[0] = matWorld[0].xyz / scale.x; + matRotation[1] = matWorld[1].xyz / scale.y; + matRotation[2] = matWorld[2].xyz / scale.z; +} 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 6cb6033b3b..004fdd89ed 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk +++ b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk @@ -39,7 +39,7 @@ layout(location = 2) in vec2 a_texCoord; in vec4 a_lightingMapUVParam; #endif #if CC_RECEIVE_SHADOW || CC_USE_REFLECTION_PROBE - in vec4 a_localShadowBiasAndProbeId; // x:shadow bias, y:shadow normal bias, z: reflection probe id, w: reserved for blend reflection probe id + in vec4 a_localShadowBiasAndProbeId; // x:shadow bias, y:shadow normal bias, z: reflection probe id, w: blend reflection probe id #endif #if CC_USE_REFLECTION_PROBE in vec4 a_reflectionProbeData; // x:reflection probe blend weight diff --git a/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk index 00e819f888..f2b34e3506 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk @@ -1,5 +1,6 @@ #include #include +#include #include out highp float v_dist; diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk index 545e6f8f3c..e7f3446aac 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk @@ -80,7 +80,7 @@ vec4 SurfacesFragmentModifyPBRParams() #ifndef CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_SCATTERING_PARAMS // depends on CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_SCATTERING_PARAMS -// scattering related parameters and colors +// scattering related parameters and colors, shared by transmit diffuse and specular vec4 SurfacesFragmentModifyTransmitScatteringParams() { // x: extinction coef for out/in-scattering, 0 means disable scattering, thin object needs larger value such as 100-1000 @@ -121,7 +121,7 @@ vec4 SurfacesFragmentModifyTransmitDiffuseParams() // notice: setting too small a value for thick objects, no transmit light will disappear. // y: transmit area mask, limit area to avoid shadowmap coverage precision artifacts, default 1.0 means enable full transmit, and gradient value makes transmit lighting look smoother // z: environment transmit scale, useless (env transmit is not accuracy, some material should give 0 to disable, or use area mask instead) - // w: shadowmap transmit distance scale, useless + // w: shadowmap transmit distance scale, useless (very large model is hard to control transmit lighting through extinction coef, should use small value to scale its distance) return vec4(1.0, 1.0, 1.0, 1.0); } #endif diff --git a/editor/assets/effects/advanced/simple-skin.effect b/editor/assets/effects/advanced/simple-skin.effect index a2b3799acd..de07c46a9c 100644 --- a/editor/assets/effects/advanced/simple-skin.effect +++ b/editor/assets/effects/advanced/simple-skin.effect @@ -10,7 +10,7 @@ CCEffect %{ tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } 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: { slide: true, range: [0, 1.0], step: 0.001 } } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, 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.5, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } metallic: { value: 0.0, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } @@ -30,9 +30,9 @@ CCEffect %{ sssColoration: { value: 1.0, target: dualLobeParams.z, editor: { parent: USE_PREINTEGRATED_SKIN, slide: true, range: [0, 10.0], step: 0.001 } } cavityMap: { value: white, editor: { tooltip: 'cavity map or specular map' } } maskMap: { value: black, editor: { parent: USE_BACK_LIT } } - thickness: { value: 0.0, target: scatterParams.x, editor: { parent: USE_BACK_LIT, displayName: Object Thickness, range: [0, 1000.0], tooltip: 'Object thickness (world space unit), setting a too small value will cause the scattered light to disappear' } } - extinction: { value: 0.0, target: scatterParams.y, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Extinction, slide: true, range: [0, 10.0], step: 0.001 } } - transmitColor: { value: [1.0, 0.2, 0.1, 1.0], linear: true, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Color, type: color, tooltip: 'The color of scattered lighting' } } + thickness: { value: 0.0, target: scatterParams.x, editor: { parent: USE_BACK_LIT, displayName: Object Thickness, range: [0, 1000.0], tooltip: 'i18n:ENGINE.assets.effect.propertyTips.transmitThicknessWithShadowMap' } } + extinction: { value: 0.0, target: scatterParams.y, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Extinction, slide: true, range: [0, 10.0], step: 0.001, tooltip: 'i18n:ENGINE.assets.effect.propertyTips.transmitExtinctionWithShadowMap' } } + transmitColor: { value: [1.0, 0.2, 0.1, 1.0], linear: true, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Color, type: color, tooltip: 'The color of scattered lighting, red for human skin' } } dualLobeRoughness: { value: 0.5, target: dualLobeParams.x, editor: { parent: USE_DUAL_LOBE_SPECULAR, range: [0, 1.0] } } dualLobeIntensity: { value: 0.02, target: dualLobeParams.w, editor: { parent: USE_DUAL_LOBE_SPECULAR, slide: true, range: [0, 0.1], step: 0.001 } } rasterizerState: @@ -215,22 +215,28 @@ CCProgram surface-fragment %{ return vec4(scatterParams.z, sssCurvature, dualLobeParams.z, 0.0); } - #include - - #include - #define CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA - void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData) + #define CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS + vec4 SurfacesFragmentModifyPBRParams() { - float cavity = texture(cavityMap, FSInput_texcoord).x; - surfaceData.specularIntensity *= cavity; - - // ao and metallic ignored from pbrMap - #if !USE_OCCLUSION_MAP - surfaceData.ao = 1.0; + vec4 pbr = pbrParams; + pbr.x = 1.0; + pbr.z = 0.0; + #if USE_PBR_MAP + // ao and metallic ignored from pbrMap + vec4 res = texture(pbrMap, DEFAULT_UV); + pbr.y *= res.ROUGHNESS_CHANNEL; + pbr.w *= res.SPECULAR_INTENSITY_CHANNEL; + #endif + #if USE_OCCLUSION_MAP + pbr.x = mix(1.0, texture(occlusionMap, DEFAULT_UV).OCCLUSION_CHANNEL, pbrParams.x); #endif - surfaceData.metallic = 0.0; - } + float cavity = texture(cavityMap, FSInput_texcoord).x; + pbr.w *= cavity; + return pbr; + } + + #include #include }% diff --git a/editor/assets/effects/advanced/skin.effect b/editor/assets/effects/advanced/skin.effect index f96f0e68e2..e8c98f0aca 100644 --- a/editor/assets/effects/advanced/skin.effect +++ b/editor/assets/effects/advanced/skin.effect @@ -21,16 +21,16 @@ CCEffect %{ normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } normalMap: { value: normal } - pbrMap: { value: grey } + pbrMap: { value: grey, editor: { displayName: PbrOrRoughnessMap } } occlusionMap: { value: white } emissiveMap: { value: grey } sssIntensity: { value: 1.0, target: scatterParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } sssMap: { value: black } cavityMap: { value: white, editor: { tooltip: 'cavity map or specular map' } } maskMap: { value: black, editor: { parent: USE_BACK_LIT } } - thickness: { value: 0.0, target: scatterParams.x, editor: { parent: USE_BACK_LIT, displayName: Object Thickness, range: [0, 1000.0], tooltip: 'Object thickness (world space unit), setting a too small value will cause the scattered light to disappear' } } - extinction: { value: 0.0, target: scatterParams.y, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Extinction, slide: true, range: [0, 10.0], step: 0.001 } } - transmitColor: { value: [1.0, 0.2, 0.1, 1.0], linear: true, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Color, type: color, tooltip: 'The color of scattered lighting' } } + thickness: { value: 0.0, target: scatterParams.x, editor: { parent: USE_BACK_LIT, displayName: Object Thickness, range: [0, 1000.0], tooltip: 'i18n:ENGINE.assets.effect.propertyTips.transmitThicknessWithShadowMap' } } + extinction: { value: 0.0, target: scatterParams.y, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Extinction, slide: true, range: [0, 10.0], step: 0.001, tooltip: 'i18n:ENGINE.assets.effect.propertyTips.transmitExtinctionWithShadowMap' } } + transmitColor: { value: [1.0, 0.2, 0.1, 1.0], linear: true, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Color, type: color, tooltip: 'The color of scattered lighting, red for human skin' } } dualLobeRoughness: { value: 0.5, target: dualLobeParams.x, editor: { parent: USE_DUAL_LOBE_SPECULAR, range: [0, 1.0] } } dualLobeIntensity: { value: 0.02, target: dualLobeParams.w, editor: { parent: USE_DUAL_LOBE_SPECULAR, slide: true, range: [0, 0.1], step: 0.001 } } rasterizerState: @@ -288,6 +288,7 @@ CCProgram standard-vs %{ CCProgram shadow-caster-vs %{ precision highp float; + #include #include #include #include @@ -328,6 +329,7 @@ CCProgram standard-fs %{ CCProgram shadow-caster-fs %{ precision highp float; + #include #include #include #include diff --git a/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk b/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk index 38aba02704..a3bd49d9d6 100644 --- a/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk +++ b/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk @@ -327,38 +327,38 @@ uniform sampler2D AOTexNearest; //Sample_Point_Clamp float CrossBilateralWeight(float r, float d, float d0, float blurFalloff, float blurDepthThreshold) { - return exp2(-r*r*blurFalloff) * (abs(d - d0) < blurDepthThreshold ? 1.0 : 0.0); + return exp2(-r*r*blurFalloff) * (abs(d - d0) < blurDepthThreshold ? 1.0 : 0.0); } vec2 SumWeightedAO(int i, float centerCameraDepth, vec2 centerUV, vec2 sampleDir, float blurFalloff, float blurDepthThreshold) { - // step = 2 - float r = 2.0 * float(i) + 0.5; - vec2 sampleUV = centerUV + r * sampleDir * g_InvFullResolution; - float d = GetLinearDepthBilinear(sampleUV); - float sampledAO = texture(AOTexNearest/*AOTexBilinear*/, sampleUV).x; - float w = CrossBilateralWeight(r, d, centerCameraDepth, blurFalloff, blurDepthThreshold); - return vec2(w * sampledAO, w); + // step = 2 + float r = 2.0 * float(i) + 0.5; + vec2 sampleUV = centerUV + r * sampleDir * g_InvFullResolution; + float d = GetLinearDepthBilinear(sampleUV); + float sampledAO = texture(AOTexNearest/*AOTexBilinear*/, sampleUV).x; + float w = CrossBilateralWeight(r, d, centerCameraDepth, blurFalloff, blurDepthThreshold); + return vec2(w * sampledAO, w); } float BlurCore(vec2 uv, vec2 sampleDir) { - float ao = texture(AOTexNearest, uv).x; + float ao = texture(AOTexNearest, uv).x; float weight = 1.0; - float centerCameraDepth = GetLinearDepth(uv); - for(int i = -HALF_KERNEL_RADIUS; i <= HALF_KERNEL_RADIUS; i++) - { - vec2 aoAndW = SumWeightedAO(i, centerCameraDepth, uv, sampleDir, g_BlurFallOff, g_BlurDepthThreshold); + float centerCameraDepth = GetLinearDepth(uv); + for(int i = -HALF_KERNEL_RADIUS; i <= HALF_KERNEL_RADIUS; i++) + { + vec2 aoAndW = SumWeightedAO(i, centerCameraDepth, uv, sampleDir, g_BlurFallOff, g_BlurDepthThreshold); ao += aoAndW.x; weight += aoAndW.y; - } - return ao / weight; + } + return ao / weight; } ///////////////////////////////////////Composite #define g_AOSaturation blurParam.w float Combine(vec2 uv) { - float ao = texture(AOTexNearest, uv).x; - return pow(ao, g_AOSaturation); -} \ No newline at end of file + float ao = texture(AOTexNearest, uv).x; + return g_AOSaturation > 1.0 ? pow(ao, g_AOSaturation) : mix(1.0, ao, g_AOSaturation); +} diff --git a/editor/i18n/en/assets.js b/editor/i18n/en/assets.js index 0196c2a984..e8a0287391 100644 --- a/editor/i18n/en/assets.js +++ b/editor/i18n/en/assets.js @@ -113,6 +113,9 @@ module.exports = { anisotropyMapNearestFilter: 'Duplicate the Anisotropy Map and select the Nearest filter.', anisotropyMapResolutionHeight: 'The height of Anisotropy Map texture resolution.', ior: 'Relative refractive index, which can affect the refraction angle and Fresnel effect. Water is 1.33', + transmitThicknessWithShadowMap: 'Object thickness (world space unit), setting a too small value will cause the scattered light to disappear', + transmitExtinctionWithShadowMap: 'Scatter extinction coefficient for back-transmitted light (such as ears and nose), larger value cause transmitted light to become weaker, and smaller value makes bright area bigger and average lighting. caution! the larger model size needs smaller extinction value to maintain the same lighting result, or give a distance scale to TransmitDiffuseParam from model size', + transmitExtinction: 'Thin object scatter extinction coefficient for back-transmitted light (such as leaves), larger value cause transmitted light to become weaker, and smaller value makes bright area bigger and average lighting. Need specified thickness', }, }, image: { diff --git a/editor/i18n/zh/assets.js b/editor/i18n/zh/assets.js index f37fd3491a..4e1ba01a54 100644 --- a/editor/i18n/zh/assets.js +++ b/editor/i18n/zh/assets.js @@ -113,6 +113,9 @@ module.exports = { anisotropyMapNearestFilter: '将 Anisotropy Map 贴图复制出来并选择 Nearest 过滤', anisotropyMapResolutionHeight: 'Anisotropy Map 的分辨率高度', ior: '相对折射率,该值可以影响折射角度和菲涅耳效果。水是1.33', + transmitThicknessWithShadowMap: '物体厚度(世界空间单位),注意!该值过小可能导致穿透光消失', + transmitExtinctionWithShadowMap: '穿透光的散射消光系数(可影响耳朵、鼻子等的背面透光强度)。该值越大则穿透光越弱、亮区范围也会更小、厚薄感变强, 反之穿透光越强越均匀、亮区更大但厚薄感变弱。有一点需要特别注意!由于是按照世界空间单位计算散射,则模型越大,该值必须相对更小才能维持同样的光照效果,或根据模型大小给一个距离缩放值在TransmitDiffuseParam中', + transmitExtinction: '薄片穿透光的散射消光系数(可影响叶片等的背面透光强度)。该值越大则穿透光越弱、亮区范围也会更小、厚薄感变强, 反之穿透光越强越均匀、亮区更大但厚薄感变弱。同时还需要指定薄片厚度', }, }, image: { diff --git a/native/cocos/renderer/pipeline/Define.cpp b/native/cocos/renderer/pipeline/Define.cpp index b795c83cf5..483a0634a3 100644 --- a/native/cocos/renderer/pipeline/Define.cpp +++ b/native/cocos/renderer/pipeline/Define.cpp @@ -661,10 +661,16 @@ uint32_t nextPow2(uint32_t val) { bool supportsR16HalfFloatTexture(const gfx::Device* device) { return hasAllFlags(device->getFormatFeatures(gfx::Format::R16F), gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE); } +bool supportsRGBA16HalfFloatTexture(const gfx::Device* device) { + return hasAllFlags(device->getFormatFeatures(gfx::Format::RGBA16F), gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE); +} bool supportsR32FloatTexture(const gfx::Device* device) { return hasAllFlags(device->getFormatFeatures(gfx::Format::R32F), gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE); } +bool supportsRGBA32FloatTexture(const gfx::Device* device) { + return hasAllFlags(device->getFormatFeatures(gfx::Format::RGBA32F), gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE); +} static ccstd::unordered_map phases; //cjh how to clear this global variable when exiting game? static uint32_t phaseNum = 0; diff --git a/native/cocos/renderer/pipeline/Define.h b/native/cocos/renderer/pipeline/Define.h index 78e3bbf8d1..30ae82ac3e 100644 --- a/native/cocos/renderer/pipeline/Define.h +++ b/native/cocos/renderer/pipeline/Define.h @@ -557,8 +557,10 @@ const uint32_t CAMERA_DEFAULT_MASK = ~static_cast(LayerList::UI_2D) & uint32_t nextPow2(uint32_t val); bool supportsR16HalfFloatTexture(const gfx::Device *device); +bool supportsRGBA16HalfFloatTexture(const gfx::Device *device); bool supportsR32FloatTexture(const gfx::Device *device); +bool supportsRGBA32FloatTexture(const gfx::Device *device); extern CC_DLL uint32_t skyboxFlag; From 92bf626ea61e67ce73ef336b75c0df6da4ffd629 Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Wed, 17 May 2023 16:15:57 +0800 Subject: [PATCH 08/22] fix hbao in post process pipeline (#15077) --- .../rendering/post-process/components/hbao.ts | 4 ++- .../post-process/passes/hbao-pass.ts | 31 ++++++++++--------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/cocos/rendering/post-process/components/hbao.ts b/cocos/rendering/post-process/components/hbao.ts index 9329461b98..7b08e414fc 100644 --- a/cocos/rendering/post-process/components/hbao.ts +++ b/cocos/rendering/post-process/components/hbao.ts @@ -24,7 +24,7 @@ import { CCBoolean, CCFloat, CCInteger } from '../../../core'; import { ccclass, disallowMultiple, editable, executeInEditMode, menu, range, - serializable, slide, tooltip, type } from '../../../core/data/decorators'; + serializable, slide, tooltip, type, visible } from '../../../core/data/decorators'; import { PostProcessSetting } from './post-process-setting'; @ccclass('cc.HBAO') @@ -55,6 +55,7 @@ export class HBAO extends PostProcessSetting { return this._radiusScale; } + @visible(false) @slide @tooltip('i18n:hbao.angleBiasDegree') @range([0, 100, 0.1]) @@ -67,6 +68,7 @@ export class HBAO extends PostProcessSetting { return this._angleBiasDegree; } + @visible(false) @slide @tooltip('i18n:hbao.blurSharpness') @range([0, 10, 1]) diff --git a/cocos/rendering/post-process/passes/hbao-pass.ts b/cocos/rendering/post-process/passes/hbao-pass.ts index 4eea88e09c..8dfb840fcc 100644 --- a/cocos/rendering/post-process/passes/hbao-pass.ts +++ b/cocos/rendering/post-process/passes/hbao-pass.ts @@ -22,9 +22,9 @@ THE SOFTWARE. */ +import { EDITOR } from 'internal:constants'; import { cclegacy, toRadian, Vec2, Vec4 } from '../../../core'; -import { Address, ClearFlagBit, Filter, Format } from '../../../gfx'; -import { Camera } from '../../../render-scene/scene'; +import { Camera, CameraUsage } from '../../../render-scene/scene'; import { Pipeline, QueueHint } from '../../custom'; import { getCameraUniqueID } from '../../custom/define'; import { passContext } from '../utils/pass-context'; @@ -34,6 +34,7 @@ import { HBAO } from '../components'; import { Texture2D } from '../../../asset/assets/texture-2d'; import { ImageAsset } from '../../../asset/assets/image-asset'; import { DebugViewCompositeType, DebugViewSingleType } from '../../debug-view'; +import { ClearFlagBit, Format } from '../../../gfx'; const vec2 = new Vec2(); @@ -177,7 +178,8 @@ export class HBAOPass extends SettingPass { private HBAO_BLUR_X_PASS_INDEX = 1; private HBAO_BLUR_Y_PASS_INDEX = 2; private HBAO_COMBINED_PASS_INDEX = 3; - private _hbaoParams: HBAOParams; + private _hbaoParams: HBAOParams = new HBAOParams(); + private _initialize = false; get setting () { return getSetting(HBAO); } @@ -186,15 +188,11 @@ export class HBAOPass extends SettingPass { outputNames = ['hbaoRTName', 'hbaoBluredRTName'] checkEnable (camera: Camera) { - const enable = super.checkEnable(camera); - const setting = this.setting; - return enable && !!setting && setting.enabledInHierarchy; - } - - constructor () { - super(); - this._hbaoParams = new HBAOParams(); - this.material.setProperty('RandomTex', this._hbaoParams.randomTexture, 0); + let enable = super.checkEnable(camera); + if (EDITOR && camera.cameraUsage === CameraUsage.PREVIEW) { + enable = false; + } + return enable; } public render (camera: Camera, ppl: Pipeline): void { @@ -203,6 +201,10 @@ export class HBAOPass extends SettingPass { const height = passContext.passViewport.height; const setting = this.setting; + if (!this._initialize) { + passContext.material = this.material; + this.material.setProperty('RandomTex', this._hbaoParams.randomTexture, 0); + } // params const aoStrength = 1.0; @@ -232,7 +234,7 @@ export class HBAOPass extends SettingPass { } const inputRT = this.lastPass!.slotName(camera, 0); - const inputDS = passContext.forwardPass.slotName(camera, 1); + const inputDS = this.lastPass!.slotName(camera, 1); const hbaoInfo = this._renderHBAOPass(camera, inputDS); let hbaoCombinedInputRTName = hbaoInfo.rtName; if (this.setting.needBlur) { @@ -247,7 +249,6 @@ export class HBAOPass extends SettingPass { const cameraID = getCameraUniqueID(camera); const passIdx = this.HBAO_PASS_INDEX; - passContext.material = this.material; this.material.setProperty('uvDepthToEyePosParams', this._hbaoParams.uvDepthToEyePosParams, passIdx); this.material.setProperty('radiusParam', this._hbaoParams.radiusParam, passIdx); this.material.setProperty('miscParam', this._hbaoParams.miscParam, passIdx); @@ -331,7 +332,7 @@ export class HBAOPass extends SettingPass { passIdx); this.material.setProperty('blurParam', this._hbaoParams.blurParam, passIdx); - passContext.clearBlack(); + passContext.clearFlag = ClearFlagBit.NONE; const layoutName = 'combine-pass'; const passName = `CameraHBAOCombinedPass${cameraID}`; From 49f92e322558eab375e20121e7a150031914f0a4 Mon Sep 17 00:00:00 2001 From: zhakesi Date: Wed, 17 May 2023 16:17:06 +0800 Subject: [PATCH 09/22] fix spine with a mask effect not work (#15052) --- .../editor-support/spine-creator-support/SkeletonCache.cpp | 5 ----- .../spine-creator-support/SkeletonRenderer.cpp | 6 ------ 2 files changed, 11 deletions(-) diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp index b8ce41d377..703f430924 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp @@ -320,11 +320,6 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { continue; } const spine::Color &slotColor = slot->getColor(); - // Early exit if slot is invisible - if (slotColor.a == 0) { - _clipper->clipEnd(*slot); - continue; - } TwoColorTriangles trianglesTwoColor; spine::Color attachmentColor; diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp index 4af4b9f5a1..eda9442cad 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp @@ -407,12 +407,6 @@ void SkeletonRenderer::render(float /*deltaTime*/) { continue; } - // Early exit if slot is invisible - if (slot->getColor().a == 0) { - _clipper->clipEnd(*slot); - continue; - } - cc::middleware::Triangles triangles; cc::middleware::TwoColorTriangles trianglesTwoColor; From ea5eb9ae239d77ec20d30c6356da6831e91135d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 17 May 2023 16:31:57 +0800 Subject: [PATCH 10/22] Update web-interface-check.yml (#15091) --- .github/workflows/web-interface-check.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/web-interface-check.yml b/.github/workflows/web-interface-check.yml index c1cce0c4df..f6a99fc34c 100644 --- a/.github/workflows/web-interface-check.yml +++ b/.github/workflows/web-interface-check.yml @@ -48,7 +48,7 @@ jobs: name: Checkout Head Ref with: repository: ${{ github.event.pull_request.head.repo.full_name }} - ref: 'refs/pull/${{ github.event.number }}/merge' # Don't check out the head commit, checkout the "merge commit" instead + ref: 'refs/pull/${{ github.event.pull_request.number }}/merge' # Don't check out the head commit, checkout the "merge commit" instead path: './engine-HEAD' - run: | "EXT_VERSION_HEAD=$(node ./engine-HEAD/.github/workflows/get-native-external-version.js)" >> $env:GITHUB_ENV From 5b32396567ac31b2b36485dc4c7e4bc7c9a17b4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 17 May 2023 17:15:34 +0800 Subject: [PATCH 11/22] Update web-interface-check.yml (#15094) --- .github/workflows/web-interface-check.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/web-interface-check.yml b/.github/workflows/web-interface-check.yml index f6a99fc34c..25f5e3492d 100644 --- a/.github/workflows/web-interface-check.yml +++ b/.github/workflows/web-interface-check.yml @@ -47,7 +47,6 @@ jobs: - uses: actions/checkout@v3 name: Checkout Head Ref with: - repository: ${{ github.event.pull_request.head.repo.full_name }} ref: 'refs/pull/${{ github.event.pull_request.number }}/merge' # Don't check out the head commit, checkout the "merge commit" instead path: './engine-HEAD' - run: | From be5eae04f5dc4988bdc90d5b4d09cffc4793f836 Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Wed, 17 May 2023 17:36:54 +0800 Subject: [PATCH 12/22] =?UTF-8?q?Add=20=E2=80=98screen.on=E2=80=99=20inter?= =?UTF-8?q?face=20to=20listen=20to=20screen-related=20events.=20(#15080)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 1、Add ‘screen.on’ interface to listen to screen-related events. 2、Deprecate ‘setResizeCallback’ interface * Modify comment errors --- @types/pal/screen-adapter.d.ts | 5 +++-- cocos/core/platform/screen.ts | 32 ++++++++++++++++++++++++++++++-- cocos/ui/view.ts | 8 +++++--- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/@types/pal/screen-adapter.d.ts b/@types/pal/screen-adapter.d.ts index 827b199637..505e2e661f 100644 --- a/@types/pal/screen-adapter.d.ts +++ b/@types/pal/screen-adapter.d.ts @@ -117,8 +117,9 @@ declare module 'pal/screen-adapter' { */ public exitFullScreen (): Promise; - on (event: import('pal/screen-adapter/enum-type').PalScreenEvent, cb: (...args: any)=>void, target?: any); - off (event: import('pal/screen-adapter/enum-type').PalScreenEvent, cb?: (...args: any)=>void, target?: any); + on (event: import('pal/screen-adapter/enum-type').PalScreenEvent, cb: (...args: any) => void, target?: any); + once (event: import('pal/screen-adapter/enum-type').PalScreenEvent, cb: (...args: any) => void, target?: any); + off (event: import('pal/screen-adapter/enum-type').PalScreenEvent, cb?: (...args: any) => void, target?: any); } export const screenAdapter: ScreenAdapter; diff --git a/cocos/core/platform/screen.ts b/cocos/core/platform/screen.ts index a285b5ffdc..71a5e79826 100644 --- a/cocos/core/platform/screen.ts +++ b/cocos/core/platform/screen.ts @@ -30,7 +30,7 @@ import { legacyCC } from '../global-exports'; import { Size } from '../math'; import { Settings, settings } from '../settings'; import { warnID } from './debug'; - +import { PalScreenEvent } from '../../../pal/screen-adapter/enum-type'; /** * @en The screen API provides an easy way to do some screen managing stuff. * @zh screen 单例对象提供简单的方法来做屏幕管理相关的工作。 @@ -192,7 +192,35 @@ class Screen { } // TODO: to support registering fullscreen change - // TODO: to support screen resize + /** + * @en + * Register screen event callback. + * @zh + * 注册screen事件回调。 + */ + public on (type: PalScreenEvent, callback: any, target?: any) { + screenAdapter.on(type, callback, target); + } + + /** + * @en + * Register a callback of a specific screen event type once. + * @zh + * 注册单次的screen事件回调。 + */ + public once (type: PalScreenEvent, callback?: any, target?: any) { + screenAdapter.once(type, callback, target); + } + + /** + * @en + * Unregister screen event callback. + * @zh + * 取消注册screen事件回调。 + */ + public off (type: PalScreenEvent, callback?: any, target?: any) { + screenAdapter.off(type, callback, target); + } } const screen = new Screen(); diff --git a/cocos/ui/view.ts b/cocos/ui/view.ts index f6d04bd6e7..3aec7a9c07 100644 --- a/cocos/ui/view.ts +++ b/cocos/ui/view.ts @@ -139,9 +139,9 @@ export class View extends Eventify(System) { } // For now, the engine UI is adapted to resolution size, instead of window size. - screenAdapter.on('window-resize', this._updateAdaptResult, this); - screenAdapter.on('orientation-change', this._updateAdaptResult, this); - screenAdapter.on('fullscreen-change', this._updateAdaptResult, this); + screen.on('window-resize', this._updateAdaptResult, this); + screen.on('orientation-change', this._updateAdaptResult, this); + screen.on('fullscreen-change', this._updateAdaptResult, this); } /** @@ -167,6 +167,8 @@ export class View extends Eventify(System) { * 因此你可以在这个回调函数内添加任意附加改变, * 仅在 Web 平台下有效。 * @param callback - The callback function + * + * @deprecated since v3.8.0, please use [[screen.on]] to listen for events. */ public setResizeCallback (callback: (() => void) | null) { if (typeof callback === 'function' || callback == null) { From 02e092b3d949876215d14c0e71e128e37a2f7c82 Mon Sep 17 00:00:00 2001 From: zxx43 Date: Wed, 17 May 2023 17:58:02 +0800 Subject: [PATCH 13/22] add line positions type (#15089) --- cocos/particle/line.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/particle/line.ts b/cocos/particle/line.ts index 58f8ea6284..5a923161fb 100644 --- a/cocos/particle/line.ts +++ b/cocos/particle/line.ts @@ -113,7 +113,7 @@ export class Line extends ModelRenderer { } @type([Vec3]) - private _positions = []; + private _positions: Vec3[] = []; /** * @en Inflection point positions of each polyline. From 1032bd9508c7e450755d71527283431173114000 Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Wed, 17 May 2023 18:37:03 +0800 Subject: [PATCH 14/22] Sweep Test (#15068) * init # Conflicts: # cocos/physics/physx/physx-adapter.ts # Conflicts: # cocos/physics/physx/physx-adapter.ts * init sweepBoxClosest # Conflicts: # cocos/physics/physx/physx-world.ts * back * physx boxCastClosest works now. * add physx sweepAll * init bullet sweepBoxClosest. not test yet * add bullet sweepBox * bullet add internal functions: sweep/sweepClosest * init physx c++ sweepBox/sweepBoxClosest * add sweepSphere, sweepCapsule; add unit test. * add sweep api doc * revert physx asm/wasm loading func * tweaks * add error log for builtin and cannon.js * builtin and cannon.js use warnid when calling sweep * tweak api doc --- EngineErrorMap.md | 8 + cocos/physics/bullet/bullet-world.ts | 142 ++++++++++++++- cocos/physics/cannon/cannon-world.ts | 38 +++- cocos/physics/cocos/builtin-world.ts | 38 +++- cocos/physics/framework/index.ts | 3 +- cocos/physics/framework/physics-selector.ts | 6 + cocos/physics/framework/physics-system.ts | 182 +++++++++++++++++++- cocos/physics/physx/physx-adapter.ts | 63 +++++++ cocos/physics/physx/physx-instance.ts | 2 + cocos/physics/physx/physx-world.ts | 77 ++++++++- cocos/physics/spec/i-physics-world.ts | 14 +- exports/physics-framework.ts | 1 + native/cocos/core/builtin/DebugInfos.cpp | 2 + native/cocos/physics/physx/PhysXUtils.h | 5 + native/cocos/physics/physx/PhysXWorld.cpp | 107 ++++++++++++ native/cocos/physics/physx/PhysXWorld.h | 16 ++ native/cocos/physics/sdk/World.cpp | 37 ++++ native/cocos/physics/sdk/World.h | 13 ++ native/cocos/physics/spec/IWorld.h | 12 ++ platforms/native/engine/jsb-physics.js | 102 +++++++++++ tests/physics/physics.test.ts | 4 + tests/physics/raycast.ts | 4 +- tests/physics/sweep.ts | 53 ++++++ 23 files changed, 915 insertions(+), 14 deletions(-) create mode 100644 tests/physics/sweep.ts diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 44da5d2665..3a1e009966 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -3186,6 +3186,14 @@ Can't getGFXSampler with out device [Physics]: A dynamic rigid body can not have the following collider shapes: Terrain, Plane and Non-convex Mesh. Node name: %s +### 9640 + +[Physics][builtin]: sweep functions are not supported in builtin + +### 9641 + +[Physics][cannon.js]: sweep functions are not supported in cannon.js + ### 10001 The sub-mesh contains %d vertices, which beyonds the capability (%d vertices most) of renderer of your platform. diff --git a/cocos/physics/bullet/bullet-world.ts b/cocos/physics/bullet/bullet-world.ts index db32f1affd..6efd1e4fbb 100644 --- a/cocos/physics/bullet/bullet-world.ts +++ b/cocos/physics/bullet/bullet-world.ts @@ -29,10 +29,10 @@ import { BulletShape } from './shapes/bullet-shape'; import { ArrayCollisionMatrix } from '../utils/array-collision-matrix'; import { TupleDictionary } from '../utils/tuple-dictionary'; import { TriggerEventObject, CollisionEventObject, CC_V3_0, CC_V3_1, CC_V3_2, BulletCache } from './bullet-cache'; -import { bullet2CocosVec3, cocos2BulletVec3 } from './bullet-utils'; +import { bullet2CocosVec3, cocos2BulletQuat, cocos2BulletVec3 } from './bullet-utils'; import { IRaycastOptions, IPhysicsWorld } from '../spec/i-physics-world'; import { PhysicsRayResult, PhysicsMaterial, CharacterControllerContact } from '../framework'; -import { error, RecyclePool, Vec3, js, IVec3Like, geometry } from '../../core'; +import { error, RecyclePool, Vec3, js, IVec3Like, geometry, IQuatLike, Quat } from '../../core'; import { BulletContactData } from './bullet-contact-data'; import { BulletConstraint } from './constraints/bullet-constraint'; import { BulletCharacterController } from './character-controllers/bullet-character-controller'; @@ -128,6 +128,10 @@ export class BulletWorld implements IPhysicsWorld { readonly oldContactsDic = new TupleDictionary(); readonly cctShapeEventDic = new TupleDictionary(); + private static _sweepBoxGeometry: any; + private static _sweepSphereGeometry: any; + private static _sweepCapsuleGeometry: any; + constructor () { this._broadphase = bt.DbvtBroadphase_new(); this._dispatcher = bt.CollisionDispatcher_new(); @@ -236,6 +240,140 @@ export class BulletWorld implements IPhysicsWorld { return false; } + sweepBox (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + // cast shape + const hf = BulletCache.instance.BT_V3_0; + cocos2BulletVec3(hf, halfExtent); + if (!BulletWorld._sweepBoxGeometry) { + BulletWorld._sweepBoxGeometry = bt.BoxShape_new(hf); + } + bt.BoxShape_setUnscaledHalfExtents(BulletWorld._sweepBoxGeometry, hf); + + return this.sweep(worldRay, BulletWorld._sweepBoxGeometry, orientation, options, pool, results); + } + + sweepBoxClosest (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + // cast shape + const hf = BulletCache.instance.BT_V3_0; + cocos2BulletVec3(hf, halfExtent); + if (!BulletWorld._sweepBoxGeometry) { + BulletWorld._sweepBoxGeometry = bt.BoxShape_new(hf); + } + bt.BoxShape_setUnscaledHalfExtents(BulletWorld._sweepBoxGeometry, hf); + + return this.sweepClosest(worldRay, BulletWorld._sweepBoxGeometry, orientation, options, result); + } + + sweepSphere (worldRay: geometry.Ray, radius: number, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + // cast shape + if (!BulletWorld._sweepSphereGeometry) { + BulletWorld._sweepSphereGeometry = bt.SphereShape_new(radius); + } + bt.SphereShape_setUnscaledRadius(BulletWorld._sweepSphereGeometry, radius); + return this.sweep(worldRay, BulletWorld._sweepSphereGeometry, Quat.IDENTITY, options, pool, results); + } + + sweepSphereClosest (worldRay: geometry.Ray, radius: number, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + // cast shape + if (!BulletWorld._sweepSphereGeometry) { + BulletWorld._sweepSphereGeometry = bt.SphereShape_new(radius); + } + bt.SphereShape_setUnscaledRadius(BulletWorld._sweepSphereGeometry, radius); + + return this.sweepClosest(worldRay, BulletWorld._sweepSphereGeometry, Quat.IDENTITY, options, result); + } + + sweepCapsule (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + // cast shape + if (!BulletWorld._sweepCapsuleGeometry) { + BulletWorld._sweepCapsuleGeometry = bt.CapsuleShape_new(radius, height); + } + bt.CapsuleShape_updateProp(BulletWorld._sweepCapsuleGeometry, radius, height * 0.5, 1); + return this.sweep(worldRay, BulletWorld._sweepCapsuleGeometry, orientation, options, pool, results); + } + + sweepCapsuleClosest (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + // cast shape + if (!BulletWorld._sweepCapsuleGeometry) { + BulletWorld._sweepCapsuleGeometry = bt.CapsuleShape_new(radius, height); + } + bt.CapsuleShape_updateProp(BulletWorld._sweepCapsuleGeometry, radius, height * 0.5, 1); + + return this.sweepClosest(worldRay, BulletWorld._sweepCapsuleGeometry, orientation, options, result); + } + + sweep (worldRay: geometry.Ray, btShapePtr: any, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + const BT_fromTransform = BulletCache.instance.BT_TRANSFORM_0; + const BT_toTransform = BulletCache.instance.BT_TRANSFORM_1; + const BT_orientation = BulletCache.instance.BT_QUAT_0; + + // from transform + cocos2BulletVec3(bt.Transform_getOrigin(BT_fromTransform), worldRay.o); + cocos2BulletQuat(BT_orientation, orientation); + bt.Transform_setRotation(BT_fromTransform, BT_orientation); + + // to transform + worldRay.computeHit(v3_0, options.maxDistance); + cocos2BulletVec3(bt.Transform_getOrigin(BT_toTransform), v3_0); + cocos2BulletQuat(BT_orientation, orientation); + bt.Transform_setRotation(BT_toTransform, BT_orientation); + + const allHitsCB = bt.ccAllConvexCallback_static(); + bt.ccAllConvexCallback_reset(allHitsCB, BT_fromTransform, BT_toTransform, options.mask, options.queryTrigger); + bt.CollisionWorld_convexSweepTest(this._world, btShapePtr, BT_fromTransform, BT_toTransform, allHitsCB, 0); + if (bt.ConvexCallback_hasHit(allHitsCB)) { + const posArray = bt.ccAllConvexCallback_getHitPointWorld(allHitsCB); + const normalArray = bt.ccAllConvexCallback_getHitNormalWorld(allHitsCB); + const ptrArray = bt.ccAllConvexCallback_getCollisionShapePtrs(allHitsCB); + for (let i = 0, n = bt.int_array_size(ptrArray); i < n; i++) { + bullet2CocosVec3(v3_0, bt.Vec3_array_at(posArray, i)); + bullet2CocosVec3(v3_1, bt.Vec3_array_at(normalArray, i)); + const shape = BulletCache.getWrapper(bt.int_array_at(ptrArray, i), BulletShape.TYPE); + const r = pool.add(); results.push(r); + r._assign(v3_0, Vec3.distance(worldRay.o, v3_0), shape.collider, v3_1); + } + return true; + } + return false; + } + + sweepClosest (worldRay: geometry.Ray, btShapePtr: any, orientation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + const BT_fromTransform = BulletCache.instance.BT_TRANSFORM_0; + const BT_toTransform = BulletCache.instance.BT_TRANSFORM_1; + const BT_orientation = BulletCache.instance.BT_QUAT_0; + + // from transform + cocos2BulletVec3(bt.Transform_getOrigin(BT_fromTransform), worldRay.o); + cocos2BulletQuat(BT_orientation, orientation); + bt.Transform_setRotation(BT_fromTransform, BT_orientation); + + // to transform + worldRay.computeHit(v3_0, options.maxDistance); + cocos2BulletVec3(bt.Transform_getOrigin(BT_toTransform), v3_0); + cocos2BulletQuat(BT_orientation, orientation); + bt.Transform_setRotation(BT_toTransform, BT_orientation); + + const closeHitCB = bt.ccClosestConvexCallback_static(); + bt.ccClosestConvexCallback_reset(closeHitCB, BT_fromTransform, BT_toTransform, options.mask, options.queryTrigger); + bt.CollisionWorld_convexSweepTest(this._world, btShapePtr, BT_fromTransform, BT_toTransform, closeHitCB, 0); + if (bt.ConvexCallback_hasHit(closeHitCB)) { + bullet2CocosVec3(v3_0, bt.ccClosestConvexCallback_getHitPointWorld(closeHitCB)); + bullet2CocosVec3(v3_1, bt.ccClosestConvexCallback_getHitNormalWorld(closeHitCB)); + const shape = BulletCache.getWrapper(bt.ccClosestConvexCallback_getCollisionShapePtr(closeHitCB), BulletShape.TYPE); + result._assign(v3_0, Vec3.distance(worldRay.o, v3_0), shape.collider, v3_1); + return true; + } + return false; + } + getSharedBody (node: Node, wrappedBody?: BulletRigidBody) { return BulletSharedBody.getSharedBody(node, this, wrappedBody); } diff --git a/cocos/physics/cannon/cannon-world.ts b/cocos/physics/cannon/cannon-world.ts index e701baf097..3d830d56fd 100644 --- a/cocos/physics/cannon/cannon-world.ts +++ b/cocos/physics/cannon/cannon-world.ts @@ -23,7 +23,7 @@ */ import CANNON from '@cocos/cannon'; -import { Vec3, RecyclePool, error, js, geometry, IVec3Like } from '../../core'; +import { Vec3, RecyclePool, error, js, geometry, IVec3Like, IQuatLike, warnID } from '../../core'; import { fillRaycastResult, toCannonRaycastOptions } from './cannon-util'; import { CannonConstraint } from './constraints/cannon-constraint'; import { CannonShape } from './shapes/cannon-shape'; @@ -76,6 +76,42 @@ export class CannonWorld implements IPhysicsWorld { this._world.defaultContactMaterial.frictionEquationRelaxation = 3; } + sweepBox (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + warnID(9641); + return false; + } + + sweepBoxClosest (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + warnID(9641); + return false; + } + + sweepSphere (worldRay: geometry.Ray, radius: number, options: IRaycastOptions, + pool: RecyclePool, results: PhysicsRayResult[]): boolean { + warnID(9641); + return false; + } + + sweepSphereClosest (worldRay: geometry.Ray, radius: number, options: IRaycastOptions, + result: PhysicsRayResult): boolean { + warnID(9641); + return false; + } + + sweepCapsule (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + warnID(9641); + return false; + } + + sweepCapsuleClosest (worldRay: geometry.Ray, radius: number, height: number, + orientation: IQuatLike, options: IRaycastOptions, result: PhysicsRayResult): boolean { + warnID(9641); + return false; + } + destroy (): void { if (this.constraints.length || this.bodies.length) error('You should destroy all physics component first.'); (this._world.broadphase as any) = null; diff --git a/cocos/physics/cocos/builtin-world.ts b/cocos/physics/cocos/builtin-world.ts index bf9b1a119b..5433afc467 100644 --- a/cocos/physics/cocos/builtin-world.ts +++ b/cocos/physics/cocos/builtin-world.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { Vec3, RecyclePool, error, js, IVec3Like, geometry } from '../../core'; +import { Vec3, RecyclePool, error, js, IVec3Like, geometry, IQuatLike, warnID } from '../../core'; import { PhysicsRayResult } from '../framework/physics-ray-result'; import { BuiltinSharedBody } from './builtin-shared-body'; import { BuiltinShape } from './shapes/builtin-shape'; @@ -48,6 +48,42 @@ const TriggerEventObject = { * not a full physical simulator */ export class BuiltInWorld implements IPhysicsWorld { + sweepBox (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + warnID(9640); + return false; + } + + sweepBoxClosest (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + warnID(9640); + return false; + } + + sweepSphere (worldRay: geometry.Ray, radius: number, options: IRaycastOptions, + pool: RecyclePool, results: PhysicsRayResult[]): boolean { + warnID(9640); + return false; + } + + sweepSphereClosest (worldRay: geometry.Ray, radius: number, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + warnID(9640); + return false; + } + + sweepCapsule (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + warnID(9640); + return false; + } + + sweepCapsuleClosest (worldRay: geometry.Ray, radius: number, height: number, + orientation: IQuatLike, options: IRaycastOptions, result: PhysicsRayResult): boolean { + warnID(9640); + return false; + } + setGravity (v: IVec3Like) { } setAllowSleep (v: boolean) { } setDefaultMaterial (v: PhysicsMaterial) { } diff --git a/cocos/physics/framework/index.ts b/cocos/physics/framework/index.ts index 457c100f24..0b250d1f81 100644 --- a/cocos/physics/framework/index.ts +++ b/cocos/physics/framework/index.ts @@ -24,7 +24,7 @@ import { PhysicsSystem } from './physics-system'; import { PhysicsMaterial } from './assets/physics-material'; -import { PhysicsRayResult } from './physics-ray-result'; +import { PhysicsRayResult, PhysicsLineStripCastResult } from './physics-ray-result'; import { BoxCollider } from './components/colliders/box-collider'; import { Collider } from './components/colliders/collider'; import { SphereCollider } from './components/colliders/sphere-collider'; @@ -56,6 +56,7 @@ import * as utils from '../utils/util'; export { PhysicsSystem, PhysicsRayResult, + PhysicsLineStripCastResult, Collider, BoxCollider, diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 018c53e87f..cdcf982e8c 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -204,6 +204,12 @@ const ENTIRE_WORLD: IPhysicsWorld = { syncSceneToPhysics: FUNC, raycast: FUNC, raycastClosest: FUNC, + sweepBox: FUNC, + sweepBoxClosest: FUNC, + sweepSphere: FUNC, + sweepSphereClosest: FUNC, + sweepCapsule: FUNC, + sweepCapsuleClosest: FUNC, emitEvents: FUNC, destroy: FUNC, }; diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index f75cb425a8..5555504f44 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -23,7 +23,7 @@ */ import { EDITOR } from 'internal:constants'; -import { Vec3, RecyclePool, Enum, System, cclegacy, Settings, settings, geometry, warn } from '../../core'; +import { Vec3, RecyclePool, Enum, System, cclegacy, Settings, settings, geometry, warn, IQuatLike, IVec3Like } from '../../core'; import { IRaycastOptions } from '../spec/i-physics-world'; import { director, Director, game } from '../../game'; import { PhysicsMaterial } from './assets/physics-material'; @@ -33,6 +33,7 @@ import { CollisionMatrix } from './collision-matrix'; import { PhysicsGroup } from './physics-enum'; import { constructDefaultWorld, IWorldInitData, selector } from './physics-selector'; import { assetManager, builtinResMgr } from '../../asset/asset-manager'; +import { Collider } from './components/colliders/collider'; cclegacy.internal.PhysicsGroup = PhysicsGroup; @@ -211,7 +212,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 设置默认物理材质。 */ - public setDefaultPhysicsMaterial (material : PhysicsMaterial) { + public setDefaultPhysicsMaterial (material: PhysicsMaterial) { this._material = material; this.physicsWorld.setDefaultMaterial(this._material); this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this); @@ -288,6 +289,22 @@ export class PhysicsSystem extends System implements IWorldInitData { */ public lineStripCastResults: PhysicsLineStripCastResult[] = []; + /** + * @en + * Gets the sweepCastClosest test result. + * @zh + * 获取 sweepCastClosest 的检测结果。 + */ + public readonly sweepCastClosestResult = new PhysicsRayResult(); + + /** + * @en + * Gets the sweepCast test results. + * @zh + * 获取 sweepCast 的检测结果。 + */ + public readonly sweepCastResults: PhysicsRayResult[] = []; + /** * @en * Gets the collision matrix that used for initialization only. @@ -325,6 +342,7 @@ export class PhysicsSystem extends System implements IWorldInitData { } private readonly raycastResultPool = new RecyclePool(() => new PhysicsRayResult(), 1); + private readonly sweepResultPool = new RecyclePool(() => new PhysicsRayResult(), 1); private constructor () { super(); @@ -574,6 +592,166 @@ export class PhysicsSystem extends System implements IWorldInitData { return hit; } + /** + * @en + * Cast a box along a ray and record information on what was hit. + * Access the results through PhysicsSystem.Instance.sweepCastResults. + * @zh + * 将盒体沿着射线发射,记录所有被检测到的结果,通过 PhysicsSystem.instance.sweepCastResults 访问结果。 + * @param worldRay @zh 世界空间下的一条射线 @en A ray in world space + * @param halfExtent @zh 盒体的一半尺寸 @en Half extent of the box + * @param orientation @zh 盒体的方向 @en Orientation of the box + * @param mask @zh 掩码,默认为 0xffffffff @en Mask, default value is 0xffffffff + * @param maxDistance @zh 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE + * @en Maximum detection distance, default value is 10000000, do not pass Infinity or Number.MAX_VALUE for now + * @param queryTrigger @zh 是否检测触发器 @en Whether to detect triggers + * @return {boolean} @zh 表示是否有检测到碰撞 @en Indicates whether a collision has been detected + */ + sweepBox (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean { + if (!this.physicsWorld) return false; + this.sweepResultPool.reset(); + this.sweepCastResults.length = 0; + this.raycastOptions.mask = mask >>> 0; + this.raycastOptions.maxDistance = maxDistance; + this.raycastOptions.queryTrigger = queryTrigger; + return this.physicsWorld.sweepBox(worldRay, halfExtent, orientation, + this.raycastOptions, this.sweepResultPool, this.sweepCastResults); + } + + /** + * @en + * Cast a box along a ray and record information on the closest hit. + * Access the results through PhysicsSystem.Instance.sweepCastClosestResult. + * @zh + * 将盒体沿着射线发射,记录距离最近的碰撞结果,通过 PhysicsSystem.instance.sweepCastClosestResult 访问结果。 + * @param worldRay @zh 世界空间下的一条射线 @en A ray in world space + * @param halfExtent @zh 盒体的一半尺寸 @en Half extent of the box + * @param orientation @zh 盒体的方向 @en Orientation of the box + * @param mask @zh 掩码,默认为 0xffffffff @en Mask, default value is 0xffffffff + * @param maxDistance @zh 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE + * @en Maximum detection distance, default value is 10000000, do not pass Infinity or Number.MAX_VALUE for now + * @param queryTrigger @zh 是否检测触发器 @en Whether to detect triggers + * @return {boolean} @zh 表示是否有检测到碰撞 @en Indicates whether a collision has been detected + */ + sweepBoxClosest (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean { + if (!this.physicsWorld) return false; + this.raycastOptions.mask = mask >>> 0; + this.raycastOptions.maxDistance = maxDistance; + this.raycastOptions.queryTrigger = queryTrigger; + return this.physicsWorld.sweepBoxClosest(worldRay, halfExtent, orientation, + this.raycastOptions, this.sweepCastClosestResult); + } + + /** + * @en + * Cast a sphere along a ray and record information on what was hit. + * Access the results through PhysicsSystem.Instance.sweepCastResults. + * @zh + * 将球体沿着射线发射,记录所有被检测到的结果,通过 PhysicsSystem.instance.sweepCastResults 访问结果。 + * @param worldRay @zh 世界空间下的一条射线 @en A ray in world space + * @param radius @zh 球体的半径 @en Radius of the sphere + * @param mask @zh 掩码,默认为 0xffffffff @en Mask, default value is 0xffffffff + * @param maxDistance @zh 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE + * @en Maximum detection distance, default value is 10000000, do not pass Infinity or Number.MAX_VALUE for now + * @param queryTrigger @zh 是否检测触发器 @en Whether to detect triggers + * @return {boolean} @zh 表示是否有检测到碰撞 @en Indicates whether a collision has been detected + */ + sweepSphere (worldRay: geometry.Ray, radius: number, + mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean { + if (!this.physicsWorld) return false; + this.sweepResultPool.reset(); + this.sweepCastResults.length = 0; + this.raycastOptions.mask = mask >>> 0; + this.raycastOptions.maxDistance = maxDistance; + this.raycastOptions.queryTrigger = queryTrigger; + return this.physicsWorld.sweepSphere(worldRay, radius, + this.raycastOptions, this.sweepResultPool, this.sweepCastResults); + } + + /** + * @en + * Cast a sphere along a ray and record information on the closest hit. + * Access the result through PhysicsSystem.Instance.sweepCastClosestResult. + * @zh + * 将球体沿着射线发射,记录距离最近的碰撞结果,通过 PhysicsSystem.instance.sweepCastClosestResult 访问结果。 + * @param worldRay @zh 世界空间下的一条射线 @en A ray in world space + * @param radius @zh 球体的半径 @en Radius of the sphere + * @param mask @zh 掩码,默认为 0xffffffff @en Mask, default value is 0xffffffff + * @param maxDistance @zh 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE + * @en Maximum detection distance, default value is 10000000, do not pass Infinity or Number.MAX_VALUE for now + * @param queryTrigger @zh 是否检测触发器 @en Whether to detect triggers + * @return {boolean} @zh 表示是否有检测到碰撞 @en Indicates whether a collision has been detected + */ + sweepSphereClosest (worldRay: geometry.Ray, radius: number, + mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean { + if (!this.physicsWorld) return false; + this.raycastOptions.mask = mask >>> 0; + this.raycastOptions.maxDistance = maxDistance; + this.raycastOptions.queryTrigger = queryTrigger; + return this.physicsWorld.sweepSphereClosest(worldRay, radius, + this.raycastOptions, this.sweepCastClosestResult); + } + + /** + * @en + * Cast a capsule along a ray and record information on what was hit. + * Access the results through PhysicsSystem.Instance.sweepCastResults. + * Capsule's default axis is along the world space Y axis. + * @zh + * 将胶囊体沿着射线发射,记录所有被检测到的结果,通过 PhysicsSystem.instance.sweepCastResults 访问结果。 + * 胶囊体的默认朝向是世界空间下的 Y 轴。 + * @param worldRay @zh 世界空间下的一条射线 @en A ray in world space + * @param radius @zh 胶囊体的半径 @en Radius of the capsule + * @param height @zh 胶囊体末端两个半球圆心的距离 @en Distance between the two half-sphere centers of the capsule + * @param orientation @zh 胶囊体的朝向 @en Orientation of the capsule + * @param mask @zh 掩码,默认为 0xffffffff @en Mask, default value is 0xffffffff + * @param maxDistance @zh 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE + * @en Maximum detection distance, default value is 10000000, do not pass Infinity or Number.MAX_VALUE for now + * @param queryTrigger @zh 是否检测触发器 @en Whether to detect triggers + * @return {boolean} @zh 表示是否有检测到碰撞 @en Indicates whether a collision has been detected + */ + sweepCapsule (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean { + if (!this.physicsWorld) return false; + this.sweepResultPool.reset(); + this.sweepCastResults.length = 0; + this.raycastOptions.mask = mask >>> 0; + this.raycastOptions.maxDistance = maxDistance; + this.raycastOptions.queryTrigger = queryTrigger; + return this.physicsWorld.sweepCapsule(worldRay, radius, height, orientation, + this.raycastOptions, this.sweepResultPool, this.sweepCastResults); + } + + /** + * @en + * Cast a capsule along a ray and record information on the closest hit. + * Access the result through PhysicsSystem.Instance.sweepCastClosestResult. + * Capsule's default axis is along the world space Y axis. + * @zh + * 将胶囊体沿着射线发射,记录距离最近的碰撞结果,通过 PhysicsSystem.instance.sweepCastClosestResult 访问结果。 + * 胶囊体的默认朝向是世界空间下的 Y 轴。 + * @param worldRay @zh 世界空间下的一条射线 @en A ray in world space + * @param radius @zh 胶囊体的半径 @en Radius of the capsule + * @param height @zh 胶囊体末端两个半球圆心的距离 @en Distance between the two half-sphere centers of the capsule + * @param orientation @zh 胶囊体的朝向 @en Orientation of the capsule + * @param mask @zh 掩码,默认为 0xffffffff @en Mask, default value is 0xffffffff + * @param maxDistance @zh 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE + * @en Maximum detection distance, default value is 10000000, do not pass Infinity or Number.MAX_VALUE for now + * @param queryTrigger @zh 是否检测触发器 @en Whether to detect triggers + * @return {boolean} @zh 表示是否有检测到碰撞 @en Indicates whether a collision has been detected + */ + sweepCapsuleClosest (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean { + if (!this.physicsWorld) return false; + this.raycastOptions.mask = mask >>> 0; + this.raycastOptions.maxDistance = maxDistance; + this.raycastOptions.queryTrigger = queryTrigger; + return this.physicsWorld.sweepCapsuleClosest(worldRay, radius, height, orientation, + this.raycastOptions, this.sweepCastClosestResult); + } + private _updateMaterial () { if (this.physicsWorld) this.physicsWorld.setDefaultMaterial(this._material); } diff --git a/cocos/physics/physx/physx-adapter.ts b/cocos/physics/physx/physx-adapter.ts index f8b1367675..4ad47eaea1 100644 --- a/cocos/physics/physx/physx-adapter.ts +++ b/cocos/physics/physx/physx-adapter.ts @@ -592,6 +592,66 @@ export function raycastClosest (world: PhysXWorld, worldRay: geometry.Ray, optio return false; } +export function sweepAll (world: PhysXWorld, worldRay: geometry.Ray, geometry: any, geometryRotation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + const maxDistance = options.maxDistance; + const flags = PxHitFlag.ePOSITION | PxHitFlag.eNORMAL; + const word3 = EFilterDataWord3.QUERY_FILTER | (options.queryTrigger ? 0 : EFilterDataWord3.QUERY_CHECK_TRIGGER); + const queryFlags = PxQueryFlag.eSTATIC | PxQueryFlag.eDYNAMIC | PxQueryFlag.ePREFILTER | PxQueryFlag.eNO_BLOCK; + const queryfilterData = PhysXInstance.queryfilterData; + const queryFilterCB = PhysXInstance.queryFilterCB;//? + const mutipleResults = PhysXInstance.mutipleSweepResults; + const mutipleResultSize = PhysXInstance.mutipleResultSize; + + queryfilterData.setWords(options.mask >>> 0, 0); + queryfilterData.setWords(word3, 3); + queryfilterData.setFlags(queryFlags); + const blocks = mutipleResults; + const r = world.scene.sweepMultiple(geometry, getTempTransform(worldRay.o, geometryRotation), worldRay.d, maxDistance, flags, + blocks, blocks.size(), queryfilterData, queryFilterCB, null, 0); + + if (r > 0) { + for (let i = 0; i < r; i++) { + const block = blocks.get(i); + const collider = getWrapShape(block.getShape()).collider; + const result = pool.add(); + result._assign(block.position, block.distance, collider, block.normal); + results.push(result); + } + return true; + } if (r === -1) { + // eslint-disable-next-line no-console + console.error('not enough memory.'); + } + + return false; +} + +export function sweepClosest (world: PhysXWorld, worldRay: geometry.Ray, geometry: any, geometryRotation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + const maxDistance = options.maxDistance; + const flags = PxHitFlag.ePOSITION | PxHitFlag.eNORMAL; + const word3 = EFilterDataWord3.QUERY_FILTER | (options.queryTrigger ? 0 : EFilterDataWord3.QUERY_CHECK_TRIGGER) + | EFilterDataWord3.QUERY_SINGLE_HIT; + const queryFlags = PxQueryFlag.eSTATIC | PxQueryFlag.eDYNAMIC | PxQueryFlag.ePREFILTER; + const queryfilterData = PhysXInstance.queryfilterData; + queryfilterData.setWords(options.mask >>> 0, 0); + queryfilterData.setWords(word3, 3); + queryfilterData.setFlags(queryFlags); + const queryFilterCB = PhysXInstance.queryFilterCB; + + const block = PhysXInstance.singleSweepResult; + const r = world.scene.sweepSingle(geometry, getTempTransform(worldRay.o, geometryRotation), worldRay.d, maxDistance, + flags, block, queryfilterData, queryFilterCB, null, 0); + if (r) { + const collider = getWrapShape(block.getShape()).collider; + result._assign(block.position, block.distance, collider, block.normal); + return true; + } + + return false; +} + export function initializeWorld (world: any) { if (USE_BYTEDANCE) { // construct PhysX instance object only once @@ -643,6 +703,9 @@ export function initializeWorld (world: any) { PhysXInstance.queryfilterData = new PX.PxQueryFilterData(); PhysXInstance.simulationCB = PX.PxSimulationEventCallback.implement(world.callback.eventCallback); PhysXInstance.queryFilterCB = PX.PxQueryFilterCallback.implement(world.callback.queryCallback); + PhysXInstance.singleSweepResult = new PX.PxSweepHit(); + PhysXInstance.mutipleSweepResults = new PX.PxSweepHitVector(); + PhysXInstance.mutipleSweepResults.resize(PhysXInstance.mutipleResultSize, PhysXInstance.singleSweepResult); } const sceneDesc = PX.getDefaultSceneDesc(PhysXInstance.physics.getTolerancesScale(), 0, PhysXInstance.simulationCB); diff --git a/cocos/physics/physx/physx-instance.ts b/cocos/physics/physx/physx-instance.ts index 889e89b801..4ec4d141d6 100644 --- a/cocos/physics/physx/physx-instance.ts +++ b/cocos/physics/physx/physx-instance.ts @@ -38,4 +38,6 @@ export class PhysXInstance { static simulationCB: any; static queryFilterCB: any; static mutipleResultSize = 12; + static singleSweepResult: any; + static mutipleSweepResults: any; } diff --git a/cocos/physics/physx/physx-world.ts b/cocos/physics/physx/physx-world.ts index 1d72fd4542..fc080d1118 100644 --- a/cocos/physics/physx/physx-world.ts +++ b/cocos/physics/physx/physx-world.ts @@ -25,22 +25,23 @@ /* eslint-disable @typescript-eslint/no-unsafe-return */ import { IPhysicsWorld, IRaycastOptions } from '../spec/i-physics-world'; import { PhysicsMaterial, PhysicsRayResult, CollisionEventType, TriggerEventType, CharacterControllerContact } from '../framework'; -import { error, RecyclePool, js, IVec3Like, geometry, Vec3 } from '../../core'; +import { error, RecyclePool, js, IVec3Like, geometry, IQuatLike, Vec3, Quat } from '../../core'; import { IBaseConstraint } from '../spec/i-physics-constraint'; import { PhysXRigidBody } from './physx-rigid-body'; import { - addActorToScene, raycastAll, simulateScene, initializeWorld, raycastClosest, - gatherEvents, getWrapShape, PX, getContactDataOrByteOffset, + addActorToScene, raycastAll, simulateScene, initializeWorld, raycastClosest, sweepClosest, + gatherEvents, getWrapShape, PX, getContactDataOrByteOffset, sweepAll, } from './physx-adapter'; import { PhysXSharedBody } from './physx-shared-body'; import { TupleDictionary } from '../utils/tuple-dictionary'; import { PhysXContactEquation } from './physx-contact-equation'; -import { CollisionEventObject, TriggerEventObject } from '../utils/util'; +import { CollisionEventObject, TriggerEventObject, VEC3_0 } from '../utils/util'; import { PhysXShape } from './shapes/physx-shape'; import { EFilterDataWord3 } from './physx-enum'; import { PhysXInstance } from './physx-instance'; import { Node } from '../../scene-graph'; import { PhysXCharacterController } from './character-controllers/physx-character-controller'; +import { CC_QUAT_0 } from '../bullet/bullet-cache'; export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { setAllowSleep (_v: boolean): void { } @@ -59,6 +60,10 @@ export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { private _isNeedFetch = false; + private static _sweepBoxGeometry: any; + private static _sweepSphereGeometry: any; + private static _sweepCapsuleGeometry: any; + constructor () { super(); initializeWorld(this); @@ -176,6 +181,70 @@ export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { return raycastClosest(this, worldRay, options, result); } + sweepBox (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + if (!PhysXWorld._sweepBoxGeometry) { + PhysXWorld._sweepBoxGeometry = new PX.BoxGeometry(halfExtent); + } + PhysXWorld._sweepBoxGeometry.setHalfExtents(halfExtent); + return sweepAll(this, worldRay, PhysXWorld._sweepBoxGeometry, orientation, options, pool, results); + } + + sweepBoxClosest (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + if (!PhysXWorld._sweepBoxGeometry) { + PhysXWorld._sweepBoxGeometry = new PX.BoxGeometry(halfExtent); + } + PhysXWorld._sweepBoxGeometry.setHalfExtents(halfExtent); + return sweepClosest(this, worldRay, PhysXWorld._sweepBoxGeometry, orientation, options, result); + } + + sweepSphere (worldRay: geometry.Ray, radius: number, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + if (!PhysXWorld._sweepSphereGeometry) { + PhysXWorld._sweepSphereGeometry = new PX.SphereGeometry(radius); + } + PhysXWorld._sweepSphereGeometry.setRadius(radius); + return sweepAll(this, worldRay, PhysXWorld._sweepSphereGeometry, Quat.IDENTITY, options, pool, results); + } + + sweepSphereClosest (worldRay: geometry.Ray, radius: number, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + if (!PhysXWorld._sweepSphereGeometry) { + PhysXWorld._sweepSphereGeometry = new PX.SphereGeometry(radius); + } + PhysXWorld._sweepSphereGeometry.setRadius(radius); + return sweepClosest(this, worldRay, PhysXWorld._sweepSphereGeometry, Quat.IDENTITY, options, result); + } + + sweepCapsule (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + if (!PhysXWorld._sweepCapsuleGeometry) { + PhysXWorld._sweepCapsuleGeometry = new PX.CapsuleGeometry(radius, height / 2); + } + PhysXWorld._sweepCapsuleGeometry.setRadius(radius); + PhysXWorld._sweepCapsuleGeometry.setHalfHeight(height / 2); + //add an extra 90 degree rotation to PxCapsuleGeometry whose axis is originally along the X axis + const finalOrientation = CC_QUAT_0; + Quat.fromEuler(finalOrientation, 0, 0, 90); + Quat.multiply(finalOrientation, orientation, finalOrientation); + return sweepAll(this, worldRay, PhysXWorld._sweepCapsuleGeometry, finalOrientation, options, pool, results); + } + + sweepCapsuleClosest (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean { + if (!PhysXWorld._sweepCapsuleGeometry) { + PhysXWorld._sweepCapsuleGeometry = new PX.CapsuleGeometry(radius, height / 2); + } + PhysXWorld._sweepCapsuleGeometry.setRadius(radius); + PhysXWorld._sweepCapsuleGeometry.setHalfHeight(height / 2); + //add an extra 90 degree rotation to PxCapsuleGeometry whose axis is originally along the X axis + const finalOrientation = CC_QUAT_0; + Quat.fromEuler(finalOrientation, 0, 0, 90); + Quat.multiply(finalOrientation, orientation, finalOrientation); + return sweepClosest(this, worldRay, PhysXWorld._sweepCapsuleGeometry, finalOrientation, options, result); + } + emitEvents (): void { gatherEvents(this); PhysXCallback.emitTriggerEvent(); diff --git a/cocos/physics/spec/i-physics-world.ts b/cocos/physics/spec/i-physics-world.ts index 5733679a7d..170b838ecf 100644 --- a/cocos/physics/spec/i-physics-world.ts +++ b/cocos/physics/spec/i-physics-world.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { IVec3Like, RecyclePool, geometry } from '../../core'; +import { IVec3Like, RecyclePool, geometry, IQuatLike } from '../../core'; import { PhysicsRayResult } from '../framework/physics-ray-result'; import { PhysicsMaterial } from '../framework'; @@ -41,6 +41,18 @@ export interface IPhysicsWorld { step (fixedTimeStep: number, timeSinceLastCalled?: number, maxSubSteps?: number): void; raycast (worldRay: geometry.Ray, options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean raycastClosest (worldRay: geometry.Ray, options: IRaycastOptions, out: PhysicsRayResult): boolean; + sweepBox (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean; + sweepBoxClosest (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean; + sweepSphere (worldRay: geometry.Ray, radius: number, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean; + sweepSphereClosest (worldRay: geometry.Ray, radius: number, + options: IRaycastOptions, result: PhysicsRayResult): boolean; + sweepCapsule (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean; + sweepCapsuleClosest (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, + options: IRaycastOptions, result: PhysicsRayResult): boolean; emitEvents (): void; syncSceneToPhysics (): void; syncAfterEvents (): void; diff --git a/exports/physics-framework.ts b/exports/physics-framework.ts index 32851598d1..15940ccea4 100644 --- a/exports/physics-framework.ts +++ b/exports/physics-framework.ts @@ -40,6 +40,7 @@ export { ConstantForce, PhysicsMaterial, PhysicsRayResult, + PhysicsLineStripCastResult, Collider, BoxCollider, diff --git a/native/cocos/core/builtin/DebugInfos.cpp b/native/cocos/core/builtin/DebugInfos.cpp index cdb84350a0..98a9fe8ead 100644 --- a/native/cocos/core/builtin/DebugInfos.cpp +++ b/native/cocos/core/builtin/DebugInfos.cpp @@ -426,6 +426,8 @@ ccstd::unordered_map debugInfos = { { 9612, "[Physics]: builtin physics system doesn't support cylinder collider" }, { 9620, "[Physics][Ammo]: changing the mesh is not supported after the initialization is completed" }, { 9630, "[Physics]: A dynamic rigid body can not have the following collider shapes: Terrain, Plane and Non-convex Mesh. Node name: %s" }, +{ 9640, "[Physics][builtin]: sweep functions are not supported in builtin" }, +{ 9641, "[Physics][cannon.js]: sweep functions are not supported in cannon.js" }, { 10001, "The sub-mesh contains %d vertices, which beyonds the capability (%d vertices most) of renderer of your platform." }, { 10002, "Sub-mesh may include at most %d morph targets, but you specified %d." }, { 11000, "WebGL context lost." }, diff --git a/native/cocos/physics/physx/PhysXUtils.h b/native/cocos/physics/physx/PhysXUtils.h index 465e474562..46fc644457 100644 --- a/native/cocos/physics/physx/PhysXUtils.h +++ b/native/cocos/physics/physx/PhysXUtils.h @@ -148,6 +148,11 @@ inline ccstd::vector &getPxRaycastHitBuffer() { return m; } +inline ccstd::vector &getPxSweepHitBuffer() { + static ccstd::vector m{12}; + return m; +} + inline QueryFilterShader &getQueryFilterShader() { static QueryFilterShader shader; return shader; diff --git a/native/cocos/physics/physx/PhysXWorld.cpp b/native/cocos/physics/physx/PhysXWorld.cpp index 2bd576a1f8..3adedea71f 100644 --- a/native/cocos/physics/physx/PhysXWorld.cpp +++ b/native/cocos/physics/physx/PhysXWorld.cpp @@ -361,6 +361,113 @@ RaycastResult &PhysXWorld::raycastClosestResult() { return hit; } +bool PhysXWorld::sweepBox(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ) { + return sweep(opt, physx::PxBoxGeometry{ halfExtentX, halfExtentY, halfExtentZ}, + physx::PxQuat(orientationX, orientationY, orientationZ, orientationW)); +} + +bool PhysXWorld::sweepBoxClosest(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ) { + return sweepClosest(opt, physx::PxBoxGeometry{ halfExtentX, halfExtentY, halfExtentZ}, + physx::PxQuat(orientationX, orientationY, orientationZ, orientationW)); +} + +bool PhysXWorld::sweepSphere(RaycastOptions &opt, float radius) { + return sweep(opt, physx::PxSphereGeometry{ radius }, physx::PxQuat(0, 0, 0, 1)); +} + +bool PhysXWorld::sweepSphereClosest(RaycastOptions &opt, float radius) { + return sweepClosest(opt, physx::PxSphereGeometry{ radius }, physx::PxQuat(0, 0, 0, 1)); +} + +bool PhysXWorld::sweepCapsule(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) { + //add an extra 90 degree rotation to PxCapsuleGeometry whose axis is originally along the X axis + physx::PxQuat finalOrientation = physx::PxQuat(physx::PxPiDivTwo, physx::PxVec3{0.F, 0.F, 1.F}); + finalOrientation = physx::PxQuat(orientationX, orientationY, orientationZ, orientationW) * finalOrientation; + return sweep(opt, physx::PxCapsuleGeometry{ radius, height/2.f }, finalOrientation); +} + +bool PhysXWorld::sweepCapsuleClosest(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) { + //add an extra 90 degree rotation to PxCapsuleGeometry whose axis is originally along the X axis + physx::PxQuat finalOrientation = physx::PxQuat(physx::PxPiDivTwo, physx::PxVec3{0.F, 0.F, 1.F}); + finalOrientation = physx::PxQuat(orientationX, orientationY, orientationZ, orientationW) * finalOrientation; + return sweepClosest(opt, physx::PxCapsuleGeometry{ radius, height/2.f }, finalOrientation); +} + +bool PhysXWorld::sweep(RaycastOptions &opt, const physx::PxGeometry &geometry, const physx::PxQuat &orientation) { + physx::PxQueryCache *cache = nullptr; + const auto o = opt.origin; + const auto ud = opt.unitDir; + physx::PxVec3 origin{o.x, o.y, o.z}; + physx::PxVec3 unitDir{ud.x, ud.y, ud.z}; + unitDir.normalize(); + physx::PxTransform pose{origin, orientation}; + physx::PxHitFlags flags = physx::PxHitFlag::ePOSITION | physx::PxHitFlag::eNORMAL; + physx::PxSceneQueryFilterData filterData; + filterData.data.word0 = opt.mask; + filterData.data.word3 = QUERY_FILTER | (opt.queryTrigger ? 0 : QUERY_CHECK_TRIGGER); + filterData.flags = physx::PxQueryFlag::eSTATIC | physx::PxQueryFlag::eDYNAMIC | physx::PxQueryFlag::ePREFILTER; + auto &hitBuffer = getPxSweepHitBuffer(); + bool result = false; + const auto nbTouches = physx::PxSceneQueryExt::sweepMultiple( + getScene(), geometry, pose, unitDir, opt.distance, flags, hitBuffer.data(), + static_cast(hitBuffer.size()), result, filterData, &getQueryFilterShader(), cache); + if (nbTouches == 0 || nbTouches == -1) return false; + auto &r = sweepResult(); + r.resize(nbTouches); + for (physx::PxI32 i = 0; i < nbTouches; i++) { + const auto &shapeIter = getPxShapeMap().find(reinterpret_cast(hitBuffer[i].shape)); + if (shapeIter == getPxShapeMap().end()) return false; + r[i].shape = shapeIter->second; + r[i].distance = hitBuffer[i].distance; + pxSetVec3Ext(r[i].hitNormal, hitBuffer[i].normal); + pxSetVec3Ext(r[i].hitPoint, hitBuffer[i].position); + } + return true; +} + +ccstd::vector &PhysXWorld::sweepResult() { + static ccstd::vector hits; + return hits; +} + +bool PhysXWorld::sweepClosest(RaycastOptions &opt, const physx::PxGeometry &geometry, const physx::PxQuat &orientation) { + physx::PxSweepHit hit; + physx::PxQueryCache *cache = nullptr; + const auto o = opt.origin; + const auto ud = opt.unitDir; + physx::PxVec3 origin{o.x, o.y, o.z}; + physx::PxVec3 unitDir{ud.x, ud.y, ud.z}; + unitDir.normalize(); + physx::PxTransform pose{origin, orientation}; + physx::PxHitFlags flags = physx::PxHitFlag::ePOSITION | physx::PxHitFlag::eNORMAL; + physx::PxSceneQueryFilterData filterData; + filterData.data.word0 = opt.mask; + filterData.data.word3 = QUERY_FILTER | (opt.queryTrigger ? 0 : QUERY_CHECK_TRIGGER) | QUERY_SINGLE_HIT; + filterData.flags = physx::PxQueryFlag::eSTATIC | physx::PxQueryFlag::eDYNAMIC | physx::PxQueryFlag::ePREFILTER; + const auto result = physx::PxSceneQueryExt::sweepSingle( + getScene(), geometry, pose, unitDir, opt.distance, flags, + hit, filterData, &getQueryFilterShader(), cache, 0); + if (result) { + auto &r = sweepClosestResult(); + const auto &shapeIter = getPxShapeMap().find(reinterpret_cast(hit.shape)); + if (shapeIter == getPxShapeMap().end()) return false; + r.shape = shapeIter->second; + r.distance = hit.distance; + pxSetVec3Ext(r.hitPoint, hit.position); + pxSetVec3Ext(r.hitNormal, hit.normal); + } + return result; +} + +RaycastResult &PhysXWorld::sweepClosestResult() { + static RaycastResult hit; + return hit; +} + uint32_t PhysXWorld::addPXObject(uintptr_t PXObjectPtr) { uint32_t pxObjectID = _msPXObjectID; _msPXObjectID++; diff --git a/native/cocos/physics/physx/PhysXWorld.h b/native/cocos/physics/physx/PhysXWorld.h index f48adee079..b912914380 100644 --- a/native/cocos/physics/physx/PhysXWorld.h +++ b/native/cocos/physics/physx/PhysXWorld.h @@ -58,6 +58,22 @@ public: bool raycastClosest(RaycastOptions &opt) override; ccstd::vector &raycastResult() override; RaycastResult &raycastClosestResult() override; + + bool sweep(RaycastOptions &opt, const physx::PxGeometry &geometry, const physx::PxQuat &orientation); + bool sweepClosest(RaycastOptions& opt, const physx::PxGeometry& geometry, const physx::PxQuat& orientation); + bool sweepBox(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ) override; + bool sweepBoxClosest(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ) override; + bool sweepSphere(RaycastOptions &opt, float radius) override; + bool sweepSphereClosest(RaycastOptions &opt, float radius) override; + bool sweepCapsule(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) override; + bool sweepCapsuleClosest(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) override; + ccstd::vector &sweepResult() override; + RaycastResult &sweepClosestResult() override; + uint32_t createConvex(ConvexDesc &desc) override; uint32_t createTrimesh(TrimeshDesc &desc) override; uint32_t createHeightField(HeightFieldDesc &desc) override; diff --git a/native/cocos/physics/sdk/World.cpp b/native/cocos/physics/sdk/World.cpp index 8f4fd9b0ee..d16849df61 100644 --- a/native/cocos/physics/sdk/World.cpp +++ b/native/cocos/physics/sdk/World.cpp @@ -114,5 +114,42 @@ RaycastResult &World::raycastClosestResult() { return _impl->raycastClosestResult(); } +bool World::sweepBox(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ){ + return _impl->sweepBox(opt, halfExtentX, halfExtentY, halfExtentZ, orientationW, orientationX, orientationY, orientationZ); +} + +bool World::sweepBoxClosest(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ){ + return _impl->sweepBoxClosest(opt, halfExtentX, halfExtentY, halfExtentZ, orientationW, orientationX, orientationY, orientationZ); +} + +bool World::sweepSphere(RaycastOptions &opt, float radius) { + return _impl->sweepSphere(opt, radius); +} + +bool World::sweepSphereClosest(RaycastOptions &opt, float radius) { + return _impl->sweepSphereClosest(opt, radius); +} + +bool World::sweepCapsule(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) { + return _impl->sweepCapsule(opt, radius, height, orientationW, orientationX, orientationY, orientationZ); +} + +bool World::sweepCapsuleClosest(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) { + return _impl->sweepCapsuleClosest(opt, radius, height, orientationW, orientationX, orientationY, orientationZ); +} + +RaycastResult &World::sweepClosestResult() { + return _impl->sweepClosestResult(); +} + +ccstd::vector &World::sweepResult() { + return _impl->sweepResult(); +} + + } // namespace physics } // namespace cc diff --git a/native/cocos/physics/sdk/World.h b/native/cocos/physics/sdk/World.h index 01b8cb989e..accc45e888 100644 --- a/native/cocos/physics/sdk/World.h +++ b/native/cocos/physics/sdk/World.h @@ -48,6 +48,19 @@ public: bool raycastClosest(RaycastOptions &opt) override; ccstd::vector &raycastResult() override; RaycastResult &raycastClosestResult() override; + bool sweepBox(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ) override; + bool sweepBoxClosest(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ) override; + bool sweepSphere(RaycastOptions &opt, float radius) override; + bool sweepSphereClosest(RaycastOptions &opt, float radius) override; + bool sweepCapsule(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) override; + bool sweepCapsuleClosest(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) override; + RaycastResult &sweepClosestResult() override; + ccstd::vector &sweepResult() override; + uint32_t createConvex(ConvexDesc &desc) override; uint32_t createTrimesh(TrimeshDesc &desc) override; uint32_t createHeightField(HeightFieldDesc &desc) override; diff --git a/native/cocos/physics/spec/IWorld.h b/native/cocos/physics/spec/IWorld.h index ced1fd7e48..39053ab1a7 100644 --- a/native/cocos/physics/spec/IWorld.h +++ b/native/cocos/physics/spec/IWorld.h @@ -142,6 +142,18 @@ public: virtual bool raycastClosest(RaycastOptions &opt) = 0; virtual ccstd::vector &raycastResult() = 0; virtual RaycastResult &raycastClosestResult() = 0; + virtual bool sweepBox(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ) = 0; + virtual bool sweepBoxClosest(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, + float orientationW, float orientationX, float orientationY, float orientationZ) = 0; + virtual bool sweepSphere(RaycastOptions &opt, float radius) = 0; + virtual bool sweepSphereClosest(RaycastOptions &opt, float radius) = 0; + virtual bool sweepCapsule(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) = 0; + virtual bool sweepCapsuleClosest(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) = 0; + virtual RaycastResult &sweepClosestResult() = 0; + virtual ccstd::vector &sweepResult() = 0; virtual uint32_t createConvex(ConvexDesc &desc) = 0; virtual uint32_t createTrimesh(TrimeshDesc &desc) = 0; virtual uint32_t createHeightField(HeightFieldDesc &desc) = 0; diff --git a/platforms/native/engine/jsb-physics.js b/platforms/native/engine/jsb-physics.js index 7cc098d1b3..c75bf5cef9 100644 --- a/platforms/native/engine/jsb-physics.js +++ b/platforms/native/engine/jsb-physics.js @@ -202,6 +202,108 @@ class PhysicsWorld { return isHit; } + sweepBox (worldRay, halfExtent, orientation, options, pool, results) { + raycastOptions.origin = worldRay.o; + raycastOptions.unitDir = worldRay.d; + raycastOptions.mask = options.mask >>> 0; + raycastOptions.distance = options.maxDistance; + raycastOptions.queryTrigger = !!options.queryTrigger; + const isHit = this._impl.sweepBox(raycastOptions, halfExtent.x, halfExtent.y, halfExtent.z, + orientation.w, orientation.x, orientation.y, orientation.z); + if (isHit) { + const hits = this._impl.sweepResult(); + for (let i = 0; i < hits.length; i++) { + const hit = hits[i]; + const out = pool.add(); + out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal); + results.push(out); + } + } + return isHit; + } + + sweepBoxClosest (worldRay, halfExtent, orientation, options, result) { + raycastOptions.origin = worldRay.o; + raycastOptions.unitDir = worldRay.d; + raycastOptions.mask = options.mask >>> 0; + raycastOptions.distance = options.maxDistance; + raycastOptions.queryTrigger = !!options.queryTrigger; + const isHit = this._impl.sweepBoxClosest(raycastOptions, halfExtent.x, halfExtent.y, halfExtent.z, + orientation.w, orientation.x, orientation.y, orientation.z); + if (isHit) { + const hit = this._impl.sweepClosestResult(); + result._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal); + } + return isHit; + } + + sweepSphere (worldRay, radius, options, pool, results) { + raycastOptions.origin = worldRay.o; + raycastOptions.unitDir = worldRay.d; + raycastOptions.mask = options.mask >>> 0; + raycastOptions.distance = options.maxDistance; + raycastOptions.queryTrigger = !!options.queryTrigger; + const isHit = this._impl.sweepSphere(raycastOptions, radius); + if (isHit) { + const hits = this._impl.sweepResult(); + for (let i = 0; i < hits.length; i++) { + const hit = hits[i]; + const out = pool.add(); + out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal); + results.push(out); + } + } + return isHit; + } + + sweepSphereClosest (worldRay, radius, options, result) { + raycastOptions.origin = worldRay.o; + raycastOptions.unitDir = worldRay.d; + raycastOptions.mask = options.mask >>> 0; + raycastOptions.distance = options.maxDistance; + raycastOptions.queryTrigger = !!options.queryTrigger; + const isHit = this._impl.sweepSphereClosest(raycastOptions, radius); + if (isHit) { + const hit = this._impl.sweepClosestResult(); + result._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal); + } + return isHit; + } + + sweepCapsule (worldRay, radius, height, orientation, options, pool, results) { + raycastOptions.origin = worldRay.o; + raycastOptions.unitDir = worldRay.d; + raycastOptions.mask = options.mask >>> 0; + raycastOptions.distance = options.maxDistance; + raycastOptions.queryTrigger = !!options.queryTrigger; + const isHit = this._impl.sweepCapsule(raycastOptions, radius, height, orientation.w, orientation.x, orientation.y, orientation.z); + if (isHit) { + const hits = this._impl.sweepResult(); + for (let i = 0; i < hits.length; i++) { + const hit = hits[i]; + const out = pool.add(); + out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal); + results.push(out); + } + } + return isHit; + } + + sweepCapsuleClosest (worldRay, radius, height, orientation, options, result) { + raycastOptions.origin = worldRay.o; + raycastOptions.unitDir = worldRay.d; + raycastOptions.mask = options.mask >>> 0; + raycastOptions.distance = options.maxDistance; + raycastOptions.queryTrigger = !!options.queryTrigger; + const isHit = this._impl.sweepCapsuleClosest(raycastOptions, radius, height, + orientation.w, orientation.x, orientation.y, orientation.z); + if (isHit) { + const hit = this._impl.sweepClosestResult(); + result._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal); + } + return isHit; + } + emitEvents () { this.emitTriggerEvent(); this.emitCollisionEvent(); diff --git a/tests/physics/physics.test.ts b/tests/physics/physics.test.ts index e9b604f203..f376c6bbc8 100644 --- a/tests/physics/physics.test.ts +++ b/tests/physics/physics.test.ts @@ -11,6 +11,7 @@ import { InitPhysXLibs } from '../../cocos/physics/physx/physx-adapter'; InitPhysXLibs(); import EventTest from "./event"; import RaycastTest from "./raycast"; +import SweepTest from "./sweep"; import SleepTest from "./sleep"; import StableTest from "./stability"; import VolumeTest from "./volume"; @@ -51,6 +52,9 @@ for (const id in physics.selector.backend) { // test raycast RaycastTest(temp0); + // test sweep + SweepTest(temp0); + if (physics.PhysicsSystem.PHYSICS_BUILTIN) { temp0.destroy(); scene.destroy(); diff --git a/tests/physics/raycast.ts b/tests/physics/raycast.ts index 44ad2d74e3..f289061e0c 100644 --- a/tests/physics/raycast.ts +++ b/tests/physics/raycast.ts @@ -1,4 +1,4 @@ -import { geometry, Vec3 } from "../../cocos/core"; +import { geometry, Quat, Vec3 } from "../../cocos/core"; import { physics } from "../../exports/physics-framework"; import { Node } from "../../cocos/scene-graph"; import { director } from "../../cocos/game"; @@ -82,7 +82,7 @@ export default function (parent: Node) { ray_t.o.z = box.node.worldPosition.z - box.size.z / 2; expect(Vec3.equals(hitClosest.hitPoint, ray_t.o, 0.001)).toBe(true); expect(Vec3.equals(hitClosest.hitNormal, physics.PhysicsSystem.PHYSICS_BUILTIN ? Vec3.ZERO : Vec3.FORWARD)).toBe(true); - + parent.destroyAllChildren(); parent.removeAllChildren(); } \ No newline at end of file diff --git a/tests/physics/sweep.ts b/tests/physics/sweep.ts new file mode 100644 index 0000000000..7533c737a1 --- /dev/null +++ b/tests/physics/sweep.ts @@ -0,0 +1,53 @@ +import { geometry, Quat, Vec3 } from "../../cocos/core"; +import { physics } from "../../exports/physics-framework"; +import { Node } from "../../cocos/scene-graph"; +import { director } from "../../cocos/game"; + + +/** + * This function is used to test the raycast + */ +export default function (parent: Node) { + //skip builtin and cannon.js for now + if (physics.selector.id === 'builtin' || physics.selector.id === 'cannon.js') + return; + + const nodeSphere = new Node('sphere'); + const sphere = nodeSphere.addComponent(physics.SphereCollider) as physics.SphereCollider; + parent.addChild(nodeSphere); + nodeSphere.worldPosition = new Vec3(10, 0, 0); + sphere.setGroup(physics.PhysicsGroup.DEFAULT); + + const nodeBox = new Node('box'); + const box = nodeBox.addComponent(physics.BoxCollider) as physics.BoxCollider; + parent.addChild(nodeBox); + nodeBox.worldPosition = new Vec3(5, 0, 0); + box.setGroup(physics.PhysicsGroup.DEFAULT); + + let isHit = false; + const ray_t = new geometry.Ray(0,0,0,1,0,0); + + director.tick(physics.PhysicsSystem.instance.fixedTimeStep); + + // all test + { + const hits = physics.PhysicsSystem.instance.sweepCastResults; + const boxHalfExtents = new Vec3(0.5, 0.5, 0.5); + const orientation = new Quat(); + isHit = physics.PhysicsSystem.instance.sweepBox(ray_t, boxHalfExtents, orientation); + expect(isHit).toBe(true); + expect(hits.length).toBe(2); + } + + // closest test + { + const hitClosest = physics.PhysicsSystem.instance.sweepCastClosestResult; + const boxHalfExtents = new Vec3(0.5, 0.5, 0.5); + const orientation = new Quat(); + isHit = physics.PhysicsSystem.instance.sweepBoxClosest(ray_t, boxHalfExtents, orientation); + expect(isHit).toBe(true); + expect(hitClosest.collider.uuid).toBe(box.uuid); + } + parent.destroyAllChildren(); + parent.removeAllChildren(); +} \ No newline at end of file From ae724da8cf3487a69a1fa1fdc09a4974505f9b9d Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Wed, 17 May 2023 18:56:47 +0800 Subject: [PATCH 15/22] [fix] physics-enum adds doc (#15095) * [fix] physics-enum adds doc * tweaks * tweaks --- cocos/physics/framework/physics-enum.ts | 198 ++++++++++++++++++++++++ 1 file changed, 198 insertions(+) diff --git a/cocos/physics/framework/physics-enum.ts b/cocos/physics/framework/physics-enum.ts index c296a3d99f..c8d0efdf31 100644 --- a/cocos/physics/framework/physics-enum.ts +++ b/cocos/physics/framework/physics-enum.ts @@ -24,56 +24,254 @@ import { Enum } from '../../core'; +/** + * @en + * Rigid body type. + * @zh + * 刚体类型。 + */ export enum ERigidBodyType { + /** + * @en + * Dynamic type. + * @zh + * 动态刚体。 + */ DYNAMIC = 1, + /** + * @en + * Static type. + * @zh + * 静态刚体。 + */ STATIC = 2, + /** + * @en + * Kinematic type. + * @zh + * 运动学刚体。 + */ KINEMATIC = 4, } Enum(ERigidBodyType); +/** + * @en + * Axis Direction. + * @zh + * 轴方向。 + */ export enum EAxisDirection { + /** + * @en + * X axis. + * @zh + * X 轴。 + */ X_AXIS, + /** + * @en + * Y axis. + * @zh + * Y 轴。 + */ Y_AXIS, + /** + * @en + * Z axis. + * @zh + * Z 轴。 + */ Z_AXIS, } Enum(EAxisDirection); +/** + * @en + * Simplex Type. + * @zh + * 单形体类型。 + */ export enum ESimplexType { + /** + * @en + * Point. + * @zh + * 点。 + */ VERTEX = 1, + /** + * @en + * Line. + * @zh + * 线。 + */ LINE = 2, + /** + * @en + * Triangle. + * @zh + * 三角形。 + */ TRIANGLE = 3, + /** + * @en + * Tetrahedron. + * @zh + * 四面体。 + */ TETRAHEDRON = 4, } Enum(ESimplexType); +/** + * @en + * Collider Type. + * @zh + * 碰撞体类型。 + */ export enum EColliderType { + /** + * @en + * Box collider. + * @zh + * 盒子碰撞体。 + */ BOX, + /** + * @en + * Sphere collider. + * @zh + * 球碰撞体。 + */ SPHERE, + /** + * @en + * Capsule collider. + * @zh + * 胶囊碰撞体。 + */ CAPSULE, + /** + * @en + * Cylinder collider. + * @zh + * 圆柱碰撞体。 + */ CYLINDER, + /** + * @en + * Cone collider. + * @zh + * 圆锥碰撞体。 + */ CONE, + /** + * @en + * Mesh collider. + * @zh + * 网格碰撞体。 + */ MESH, + /** + * @en + * Plane collider. + * @zh + * 平面碰撞体。 + */ PLANE, + /** + * @en + * Simplex collider. + * @zh + * 单形体碰撞体。 + */ SIMPLEX, + /** + * @en + * Terrain collider. + * @zh + * 地形碰撞体。 + */ TERRAIN, } Enum(EColliderType); +/** + * @en + * Constraint Type. + * @zh + * 约束类型。 + */ export enum EConstraintType { + /** + * @en + * Point to point constraint. + * @zh + * 点对点约束。 + */ POINT_TO_POINT, + /** + * @en + * Hinge constraint. + * @zh + * 铰链约束。 + */ HINGE, + /** + * @en + * Cone twist constraint. + * @zh + * 锥形扭转约束。 + */ CONE_TWIST, + /** + * @en + * Fixed constraint. + * @zh + * 固定约束。 + */ FIXED, } Enum(EConstraintType); +/** + * @en + * Character Controller Type. + * @zh + * 角色控制器类型。 + */ export enum ECharacterControllerType { + /** + * @en + * Box Character Controller. + * @zh + * 盒体角色控制器。 + */ BOX, + /** + * @en + * Capsule Character Controller. + * @zh + * 胶囊体角色控制器。 + */ CAPSULE, } Enum(ECharacterControllerType); +/** + * @en + * Physics Group. + * @zh + * 物理分组。 + */ export enum PhysicsGroup { + /** + * @en + * Default group. + * @zh + * 默认分组。 + */ DEFAULT = 1, } Enum(PhysicsGroup); From 4bcd1795f27b302ca9090fc21c03001516d71c60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 18 May 2023 11:03:24 +0800 Subject: [PATCH 16/22] Marionette: add test in case of states of transition yielding nullish (#14733) --- tests/animation/newgenanim.test.ts | 89 +++++++++++++++++------------- 1 file changed, 51 insertions(+), 38 deletions(-) diff --git a/tests/animation/newgenanim.test.ts b/tests/animation/newgenanim.test.ts index 8131f52ab1..ea70acf2e7 100644 --- a/tests/animation/newgenanim.test.ts +++ b/tests/animation/newgenanim.test.ts @@ -5144,45 +5144,58 @@ describe('NewGen Anim', () => { expect(observer.value).toBeCloseTo(6.); }); - test(`Run into a transition, either of the source or destination state is nullish`, () => { - const fixture = { - initial_value: 6., - source_animation: new LinearRealValueAnimationFixture(1., 2., 3.), - transition_duration: 0.3, - }; + describe(`States of transition yield nullish`, () => { + test.each([ + ['Source state yields nullish', true, false], + ['Destination state yields nullish', false, true], + [`Both yields nullish`, true, true], + ] as [title: string, isSourceYieldingNullish: boolean, isDestinationYieldingNullish: boolean][] + )(`%s`, (_title, isSourceYieldingNullish, isDestinationYieldingNullish) => { + const fixture = { + initial_value: 6., + non_nullish_source_animation: new LinearRealValueAnimationFixture(1., 2., 3.), + transition_duration: 0.3, + }; + + const observer = new SingleRealValueObserver(fixture.initial_value); + const graph = new AnimationGraph(); + const layer = graph.addLayer(); + layer.additive = true; - const observer = new SingleRealValueObserver(fixture.initial_value); - const graph = new AnimationGraph(); - const layer = graph.addLayer(); - layer.additive = true; - - // Adds a motion to "hold the pose" but don't connect to it. - const holderState = layer.stateMachine.addMotion(); - holderState.motion = new ConstantRealValueAnimationFixture(2.).createMotion(observer.getCreateMotionContext()); - - const sourceState = layer.stateMachine.addMotion(); - sourceState.motion = fixture.source_animation.createMotion(observer.getCreateMotionContext()); - layer.stateMachine.connect(layer.stateMachine.entryState, sourceState); - - const nullDestinationState = layer.stateMachine.addMotion(); - - const transition = layer.stateMachine.connect(sourceState, nullDestinationState); - transition.duration = fixture.transition_duration; - transition.exitConditionEnabled = true; - transition.exitCondition = 0.0; - - const graphEval = createAnimationGraphEval(graph, observer.root); - const graphUpdater = new GraphUpdater(graphEval); - graphUpdater.step(0.2); - - expect(observer.value).toBeCloseTo(fixture.initial_value + - lerp( - fixture.source_animation.getExpectedAdditive(0.2), - 0.0, // Because destination state is nullish, it's as if it's "zero delta pose". - 0.2 / fixture.transition_duration, - ), - ); - }) + const addState = (yieldingNullish: boolean) => { + const state = layer.stateMachine.addMotion(); + if (!yieldingNullish) { + state.motion = fixture.non_nullish_source_animation.createMotion(observer.getCreateMotionContext()); + } + return state; + }; + + // Adds a motion to "hold the pose" but don't connect to it. + const holderState = layer.stateMachine.addMotion(); + holderState.motion = new ConstantRealValueAnimationFixture(2.).createMotion(observer.getCreateMotionContext()); + + const sourceState = addState(isSourceYieldingNullish); + const destinationState = addState(isDestinationYieldingNullish); + layer.stateMachine.connect(layer.stateMachine.entryState, sourceState); + + const transition = layer.stateMachine.connect(sourceState, destinationState); + transition.duration = fixture.transition_duration; + transition.exitConditionEnabled = true; + transition.exitCondition = 0.0; + + const graphEval = createAnimationGraphEval(graph, observer.root); + const graphUpdater = new GraphUpdater(graphEval); + graphUpdater.step(0.2); + + expect(observer.value).toBeCloseTo(fixture.initial_value + + lerp( + isSourceYieldingNullish ? 0.0 : fixture.non_nullish_source_animation.getExpectedAdditive(0.2), + isDestinationYieldingNullish ? 0.0 : fixture.non_nullish_source_animation.getExpectedAdditive(0.2), + 0.2 / fixture.transition_duration, + ), + ); + }); + }); }); }); From c127228f478729c851edfde7975e02ef74cff821 Mon Sep 17 00:00:00 2001 From: alpha Date: Thu, 18 May 2023 12:25:15 +0800 Subject: [PATCH 17/22] fix: download bundle may be missing error (#15075) --- cocos/asset/asset-manager/downloader.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/asset/asset-manager/downloader.ts b/cocos/asset/asset-manager/downloader.ts index abd5fb9da4..9862dbc800 100644 --- a/cocos/asset/asset-manager/downloader.ts +++ b/cocos/asset/asset-manager/downloader.ts @@ -141,7 +141,7 @@ const downloadBundle = (nameOrUrl: string, options: Record, onCompl downloadScript(jspath, options, (err) => { error = err || error; if (++count === 2) { - onComplete(err, out); + onComplete(error, out); } }); }; From 34a5022096a2a92e82feb52e5801b09a6c438e76 Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Thu, 18 May 2023 13:00:23 +0800 Subject: [PATCH 18/22] develop pipeline interface change (#15083) --- cc.config.json | 1 + cocos/asset/assets/effect-asset.ts | 1 + cocos/rendering/custom/compiler.ts | 32 +++++- cocos/rendering/custom/custom-pipeline.ts | 53 ++++++++- cocos/rendering/custom/define.ts | 50 ++++----- cocos/rendering/custom/pipeline.ts | 22 ++-- cocos/rendering/custom/types.ts | 6 ++ cocos/rendering/custom/web-pipeline.ts | 71 ++++++++---- .../post-process/utils/pass-context.ts | 4 +- .../assets/effects/pipeline/copy-pass.effect | 53 +++++++++ .../effects/pipeline/copy-pass.effect.meta | 11 ++ native/cocos/core/assets/EffectAsset.cpp | 1 + .../pipeline/custom/NativePipeline.cpp | 4 +- .../pipeline/custom/NativePipelineTypes.h | 20 ++-- .../pipeline/custom/NativeRenderGraph.cpp | 32 ++++-- .../pipeline/custom/RenderCommonJsb.cpp | 14 +++ .../custom/RenderCommonSerialization.h | 4 + .../pipeline/custom/RenderCommonTypes.cpp | 30 +++++- .../pipeline/custom/RenderCommonTypes.h | 14 ++- .../pipeline/custom/RenderInterfaceTypes.h | 101 +++++++++++------- native/tools/swig-config/render.i | 4 +- 21 files changed, 394 insertions(+), 134 deletions(-) create mode 100644 editor/assets/effects/pipeline/copy-pass.effect create mode 100644 editor/assets/effects/pipeline/copy-pass.effect.meta diff --git a/cc.config.json b/cc.config.json index de85affd09..679be7baf2 100644 --- a/cc.config.json +++ b/cc.config.json @@ -9,6 +9,7 @@ "bcd64cc6-2dd9-43f6-abbe-66318d332032", "d930590d-bb92-4cc8-8bd1-23cd027f9edf", "a3cd009f-0ab0-420d-9278-b9fdab939bbc", + "5c601d96-e4c7-4698-991b-7ee674b11079", "9361fd90-ba52-4f84-aa93-6e878fd576ca" ] }, diff --git a/cocos/asset/assets/effect-asset.ts b/cocos/asset/assets/effect-asset.ts index 8aab3bd788..53626428b8 100644 --- a/cocos/asset/assets/effect-asset.ts +++ b/cocos/asset/assets/effect-asset.ts @@ -184,6 +184,7 @@ const legacyBuiltinEffectNames = [ 'deferred-lighting', 'bloom', 'hbao', + 'copy-pass', 'post-process', 'profiler', 'splash-screen', diff --git a/cocos/rendering/custom/compiler.ts b/cocos/rendering/custom/compiler.ts index 023e9a853a..deff480045 100644 --- a/cocos/rendering/custom/compiler.ts +++ b/cocos/rendering/custom/compiler.ts @@ -104,13 +104,16 @@ class PassVisitor implements RenderGraphVisitor { // output resourcetexture id public resID = 0xFFFFFFFF; public context: CompilerContext; - private _currPass: RasterPass | null = null; + private _currPass: RasterPass | CopyPass | null = null; constructor (context: CompilerContext) { this.context = context; } protected _isRasterPass (u: number): boolean { return !!this.context.renderGraph.tryGetRasterPass(u); } + protected _isCopyPass (u: number): boolean { + return !!this.context.renderGraph.tryGetCopy(u); + } protected _isQueue (u: number): boolean { return !!this.context.renderGraph.tryGetQueue(u); } @@ -193,7 +196,7 @@ class PassVisitor implements RenderGraphVisitor { const outputId = this.resID; const outputName = this.context.resourceGraph.vertexName(outputId); const readViews: Map = new Map(); - const pass = this._currPass!; + const pass = this._currPass! as RasterPass; const validPass = rg.getValid(this.passID); for (const [readName, raster] of pass.rasterViews) { // find the pass @@ -256,7 +259,7 @@ class PassVisitor implements RenderGraphVisitor { } applyID (id: number, resId: number): void { this.resID = resId; - if (this._isRasterPass(id)) { + if (this._isRasterPass(id) || this._isCopyPass(id)) { this.passID = id; } else if (this._isQueue(id)) { this.queueID = id; @@ -275,7 +278,28 @@ class PassVisitor implements RenderGraphVisitor { rasterSubpass (value: RasterSubpass) {} computeSubpass (value: ComputeSubpass) {} compute (value: ComputePass) {} - copy (value: CopyPass) {} + copy (value: CopyPass) { + const rg = context.renderGraph; + if (rg.getValid(this.passID)) { + return; + } + const resourceGraph = this.context.resourceGraph; + this._currPass = value; + const outputId = this.resID; + const outputName = resourceGraph.vertexName(outputId); + let resVisitor; let vertID; + for (const pair of value.copyPairs) { + if (pair.target === outputName) { + rg.setValid(this.passID, true); + if (!resVisitor) resVisitor = new ResourceVisitor(this.context); + vertID = resourceGraph.find(pair.source); + if (vertID !== 0xFFFFFFFF) { + resVisitor.resID = vertID; + resourceGraph.visitVertex(resVisitor, vertID); + } + } + } + } move (value: MovePass) {} raytrace (value: RaytracePass) {} queue (value: RenderQueue) {} diff --git a/cocos/rendering/custom/custom-pipeline.ts b/cocos/rendering/custom/custom-pipeline.ts index ccf00c618f..af64c44df3 100644 --- a/cocos/rendering/custom/custom-pipeline.ts +++ b/cocos/rendering/custom/custom-pipeline.ts @@ -25,13 +25,58 @@ import { Format, LoadOp } from '../../gfx/base/define'; import { Camera, CameraUsage } from '../../render-scene/scene'; import { BasicPipeline, PipelineBuilder } from './pipeline'; -import { LightInfo, QueueHint, SceneFlags } from './types'; +import { CopyPair, LightInfo, QueueHint, ResourceResidency, SceneFlags } from './types'; import { AntiAliasing, buildBloomPass, buildForwardPass, buildFxaaPass, buildPostprocessPass, buildSSSSPass, - buildToneMappingPass, buildTransparencyPass, buildUIPass, hasSkinObject, buildHBAOPasses } from './define'; + buildToneMappingPass, buildTransparencyPass, buildUIPass, hasSkinObject, buildHBAOPasses, buildCopyPass, getRenderArea } from './define'; import { isUICamera } from './utils'; import { RenderWindow } from '../../render-scene/core/render-window'; +const copyPair = new CopyPair(); +const pairs = [copyPair]; export class CustomPipelineBuilder implements PipelineBuilder { + public setup (cameras: Camera[], ppl: BasicPipeline): void { + for (let i = 0; i < cameras.length; i++) { + const camera = cameras[i]; + if (camera.scene === null) { + continue; + } + const isGameView = camera.cameraUsage === CameraUsage.GAME + || camera.cameraUsage === CameraUsage.GAME_VIEW; + if (!isGameView) { + // forward pass + buildForwardPass(camera, ppl, isGameView); + continue; + } + // TODO: There is currently no effective way to judge the ui camera. Let’s do this first. + if (!isUICamera(camera)) { + // forward pass + const forwardInfo = buildForwardPass(camera, ppl, isGameView); + const area = getRenderArea(camera, camera.window.width, camera.window.height); + const width = area.width; + const height = area.height; + if (!ppl.containsResource('copyTexTest')) { + ppl.addRenderTarget('copyTexTest', Format.RGBA16F, width, height, ResourceResidency.PERSISTENT); + } + copyPair.source = forwardInfo.rtName; + copyPair.target = 'copyTexTest'; + buildCopyPass(ppl, pairs); + // fxaa pass + const fxaaInfo = buildFxaaPass(camera, ppl, 'copyTexTest', forwardInfo.dsName); + // bloom passes + const bloomInfo = buildBloomPass(camera, ppl, fxaaInfo.rtName); + // tone map pass + const toneMappingInfo = buildToneMappingPass(camera, ppl, bloomInfo.rtName, bloomInfo.dsName); + // Present Pass + buildPostprocessPass(camera, ppl, toneMappingInfo.rtName, AntiAliasing.NONE); + continue; + } + // render ui + buildUIPass(camera, ppl); + } + } +} + +export class SkinPipelineBuilder implements PipelineBuilder { public setup (cameras: Camera[], ppl: BasicPipeline): void { for (let i = 0; i < cameras.length; i++) { const camera = cameras[i]; @@ -150,8 +195,8 @@ export class TestPipelineBuilder implements PipelineBuilder { const scene = camera.scene; const pass = ppl.addRenderPass(width, height, 'default'); - pass.addRenderTarget(`Color${id}`, 'color', LoadOp.CLEAR); - pass.addDepthStencil(`DepthStencil${id}`, '_', LoadOp.CLEAR); + pass.addRenderTarget(`Color${id}`, LoadOp.CLEAR); + pass.addDepthStencil(`DepthStencil${id}`, LoadOp.CLEAR); if (scene) { pass.addQueue(QueueHint.RENDER_OPAQUE, 'default') diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index 930c78e271..4ac37f1948 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -28,7 +28,8 @@ import { BufferInfo, Buffer, BufferUsageBit, ClearFlagBit, Color, DescriptorSet, import { Camera, CSMLevel, DirectionalLight, Light, LightType, ReflectionProbe, ShadowType, SKYBOX_FLAG, SpotLight } from '../../render-scene/scene'; import { supportsR32FloatTexture, supportsRGBA16FloatTexture } from '../define'; import { BasicPipeline } from './pipeline'; -import { AccessType, AttachmentType, ComputeView, LightInfo, QueueHint, RasterView, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; +import { AccessType, AttachmentType, ComputeView, CopyPair, LightInfo, + QueueHint, RasterView, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; import { Vec2, Vec3, Vec4, macro, geometry, toRadian, cclegacy, assert } from '../../core'; import { ImageAsset, Material, Texture2D } from '../../asset/assets'; import { getProfilerCamera, SRGBToLinear } from '../pipeline-funcs'; @@ -211,6 +212,10 @@ class FxaaData { } } +export function buildCopyPass (ppl: BasicPipeline, inOuts: CopyPair[]) { + ppl.addCopyPass(inOuts); +} + let fxaaData: FxaaData | null = null; export function buildFxaaPass (camera: Camera, ppl: BasicPipeline, @@ -249,7 +254,7 @@ export function buildFxaaPass (camera: Camera, if (ppl.containsResource(inputRT)) { fxaaPass.addTexture(inputRT, 'sceneColorMap'); } - fxaaPass.addRenderTarget(fxaaPassRTName, '_', LoadOp.CLEAR, StoreOp.STORE, clearColor); + fxaaPass.addRenderTarget(fxaaPassRTName, LoadOp.CLEAR, StoreOp.STORE, clearColor); fxaaData.fxaaMaterial.setProperty('texSize', new Vec4(width, height, 1.0 / width, 1.0 / height), fxaaPassIdx); fxaaPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( camera, fxaaData.fxaaMaterial, fxaaPassIdx, @@ -353,7 +358,7 @@ export function buildBloomPass (camera: Camera, if (ppl.containsResource(inputRT)) { bloomPrefilterPass.addTexture(inputRT, 'outputResultMap'); } - bloomPrefilterPass.addRenderTarget(bloomPassPrefilterRTName, '_', LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); + bloomPrefilterPass.addRenderTarget(bloomPassPrefilterRTName, LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); bloomData.bloomMaterial.setProperty('texSize', new Vec4(0, 0, bloomData.threshold, 0), 0); bloomPrefilterPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( camera, bloomData.bloomMaterial, 0, @@ -380,7 +385,7 @@ export function buildBloomPass (camera: Camera, } else { bloomDownSamplePass.addTexture(`dsBloomPassDownSampleColor${cameraName}${i - 1}`, 'bloomTexture'); } - bloomDownSamplePass.addRenderTarget(bloomPassDownSampleRTName, '_', LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); + bloomDownSamplePass.addRenderTarget(bloomPassDownSampleRTName, LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); bloomData.bloomMaterial.setProperty('texSize', texSize, BLOOM_DOWNSAMPLEPASS_INDEX + i); bloomDownSamplePass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( camera, bloomData.bloomMaterial, BLOOM_DOWNSAMPLEPASS_INDEX + i, @@ -408,7 +413,7 @@ export function buildBloomPass (camera: Camera, } else { bloomUpSamplePass.addTexture(`dsBloomPassUpSampleColor${cameraName}${bloomData.iterations - i}`, 'bloomTexture'); } - bloomUpSamplePass.addRenderTarget(bloomPassUpSampleRTName, '_', LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); + bloomUpSamplePass.addRenderTarget(bloomPassUpSampleRTName, LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); bloomData.bloomMaterial.setProperty('texSize', texSize, BLOOM_UPSAMPLEPASS_INDEX + i); bloomUpSamplePass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( camera, bloomData.bloomMaterial, BLOOM_UPSAMPLEPASS_INDEX + i, @@ -432,7 +437,7 @@ export function buildBloomPass (camera: Camera, bloomCombinePass.setViewport(new Viewport(area.x, area.y, width, height)); bloomCombinePass.addTexture(inputRT, 'outputResultMap'); bloomCombinePass.addTexture(`dsBloomPassUpSampleColor${cameraName}${0}`, 'bloomTexture'); - bloomCombinePass.addRenderTarget(bloomPassCombineRTName, '_', LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); + bloomCombinePass.addRenderTarget(bloomPassCombineRTName, LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); bloomData.bloomMaterial.setProperty('texSize', new Vec4(0, 0, 0, bloomData.intensity), BLOOM_COMBINEPASS_INDEX); bloomCombinePass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( camera, bloomData.bloomMaterial, BLOOM_COMBINEPASS_INDEX, @@ -500,9 +505,9 @@ export function buildPostprocessPass (camera: Camera, postClearColor.y = camera.clearColor.y; postClearColor.z = camera.clearColor.z; } - postprocessPass.addRenderTarget(postprocessPassRTName, '_', + postprocessPass.addRenderTarget(postprocessPassRTName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, postClearColor); - postprocessPass.addDepthStencil(postprocessPassDS, '_', + postprocessPass.addDepthStencil(postprocessPassDS, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag); postprocessPass.addQueue(QueueHint.NONE).addFullscreenQuad( @@ -558,11 +563,11 @@ export function buildForwardPass (camera: Camera, forwardPass.addTexture(spotShadowName, 'cc_spotShadowMap'); } } - forwardPass.addRenderTarget(forwardPassRTName, '_', + forwardPass.addRenderTarget(forwardPassRTName, isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); - forwardPass.addDepthStencil(forwardPassDSName, '_', + forwardPass.addDepthStencil(forwardPassDSName, isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), // If the depth texture is used by subsequent passes, it must be set to store. isOffScreen ? StoreOp.DISCARD : StoreOp.STORE, @@ -610,8 +615,8 @@ export function buildShadowPass (passName: Readonly, shadowPass = ppl.addRenderPass(width, height, 'default'); shadowPass.name = passName; shadowPass.setViewport(new Viewport(0, 0, fboW, fboH)); - shadowPass.addRenderTarget(shadowMapName, '_', LoadOp.CLEAR, StoreOp.STORE, new Color(1, 1, 1, camera.clearColor.w)); - shadowPass.addDepthStencil(`${shadowMapName}Depth`, '_', LoadOp.CLEAR, StoreOp.DISCARD, + shadowPass.addRenderTarget(shadowMapName, LoadOp.CLEAR, StoreOp.STORE, new Color(1, 1, 1, camera.clearColor.w)); + shadowPass.addDepthStencil(`${shadowMapName}Depth`, LoadOp.CLEAR, StoreOp.DISCARD, camera.clearDepth, camera.clearStencil, ClearFlagBit.DEPTH_STENCIL); } const queue = shadowPass.addQueue(QueueHint.RENDER_OPAQUE); @@ -661,9 +666,9 @@ export function buildReflectionProbePass (camera: Camera, const probePass = ppl.addRenderPass(width, height, 'default'); probePass.name = `ReflectionProbePass${faceIdx}`; probePass.setViewport(new Viewport(0, 0, width, height)); - probePass.addRenderTarget(probePassRTName, '_', getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.RENDER_TARGET), + probePass.addRenderTarget(probePassRTName, getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, new Color(probeCamera.clearColor.x, probeCamera.clearColor.y, probeCamera.clearColor.z, probeCamera.clearColor.w)); - probePass.addDepthStencil(probePassDSName, '_', getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.DEPTH_STENCIL), + probePass.addDepthStencil(probePassDSName, getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.DEPTH_STENCIL), StoreOp.STORE, probeCamera.clearDepth, probeCamera.clearStencil, probeCamera.clearFlag); const passBuilder = probePass.addQueue(QueueHint.RENDER_OPAQUE); passBuilder.addSceneOfCamera(camera, new LightInfo(), SceneFlags.REFLECTION_PROBE); @@ -771,10 +776,10 @@ export function buildGBufferPass (camera: Camera, rtColor.z = camera.clearColor.z; } } - gBufferPass.addRenderTarget(gBufferPassRTName, '_', LoadOp.CLEAR, StoreOp.STORE, rtColor); - gBufferPass.addRenderTarget(gBufferPassNormal, '_', LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0)); - gBufferPass.addRenderTarget(gBufferPassEmissive, '_', LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0)); - gBufferPass.addDepthStencil(gBufferPassDSName, '_', LoadOp.CLEAR, StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag); + gBufferPass.addRenderTarget(gBufferPassRTName, LoadOp.CLEAR, StoreOp.STORE, rtColor); + gBufferPass.addRenderTarget(gBufferPassNormal, LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0)); + gBufferPass.addRenderTarget(gBufferPassEmissive, LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0)); + gBufferPass.addDepthStencil(gBufferPassDSName, LoadOp.CLEAR, StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag); gBufferPass .addQueue(QueueHint.RENDER_OPAQUE) .addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT); @@ -853,7 +858,7 @@ export function buildLightingPass (camera: Camera, ppl: BasicPipeline, gBuffer: lightingClearColor.z = camera.clearColor.z; } lightingClearColor.w = 0; - lightingPass.addRenderTarget(deferredLightingPassRTName, '_', LoadOp.CLEAR, StoreOp.STORE, lightingClearColor); + lightingPass.addRenderTarget(deferredLightingPassRTName, LoadOp.CLEAR, StoreOp.STORE, lightingClearColor); lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( camera, lightingInfo.deferredLightingMaterial, 0, SceneFlags.VOLUMETRIC_LIGHTING, @@ -904,11 +909,11 @@ export function buildUIPass (camera: Camera, const uiAndProfilerPass = ppl.addRenderPass(width, height, 'default'); uiAndProfilerPass.name = `CameraUIAndProfilerPass${cameraID}`; uiAndProfilerPass.setViewport(new Viewport(area.x, area.y, width, height)); - uiAndProfilerPass.addRenderTarget(dsUIAndProfilerPassRTName, '_', + uiAndProfilerPass.addRenderTarget(dsUIAndProfilerPassRTName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); - uiAndProfilerPass.addDepthStencil(dsUIAndProfilerPassDSName, '_', + uiAndProfilerPass.addDepthStencil(dsUIAndProfilerPassDSName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag); @@ -1967,7 +1972,6 @@ function _buildHBAOPass (camera: Camera, } hbaoPass.addRenderTarget( hbaoRTName, - '_', LoadOp.LOAD, StoreOp.STORE, hbaoClearColor, @@ -2042,7 +2046,6 @@ function _buildHBAOBlurPass (camera: Camera, } blurPass.addRenderTarget( outputRTName, - '_', LoadOp.LOAD, StoreOp.STORE, hbaoClearColor, @@ -2097,7 +2100,6 @@ function _buildHBAOCombinedPass (camera: Camera, hbaoPass.addRenderTarget( outputRTName, - '_', LoadOp.LOAD, StoreOp.STORE, hbaoClearColor, diff --git a/cocos/rendering/custom/pipeline.ts b/cocos/rendering/custom/pipeline.ts index c98ba01e32..24c8bcff91 100644 --- a/cocos/rendering/custom/pipeline.ts +++ b/cocos/rendering/custom/pipeline.ts @@ -106,9 +106,9 @@ export interface RenderQueueBuilder extends Setter { } export interface RenderSubpassBuilder extends Setter { - addRenderTarget (name: string, accessType: AccessType, slotName: string, loadOp?: LoadOp, storeOp?: StoreOp, color?: Color): void; - addDepthStencil (name: string, accessType: AccessType, slotName: string, loadOp?: LoadOp, storeOp?: StoreOp, depth?: number, stencil?: number, clearFlags?: ClearFlagBit): void; - addTexture (name: string, slotName: string, sampler?: Sampler | null): void; + addRenderTarget (name: string, accessType: AccessType, slotName?: string, loadOp?: LoadOp, storeOp?: StoreOp, color?: Color): void; + addDepthStencil (name: string, accessType: AccessType, depthSlotName?: string, stencilSlotName?: string, loadOp?: LoadOp, storeOp?: StoreOp, depth?: number, stencil?: number, clearFlags?: ClearFlagBit): void; + addTexture (name: string, slotName: string, sampler?: Sampler | null, plane?: number): void; addStorageBuffer (name: string, accessType: AccessType, slotName: string, clearType?: ClearValueType, clearValue?: ClearValue): void; addStorageImage (name: string, accessType: AccessType, slotName: string, clearType?: ClearValueType, clearValue?: ClearValue): void; /** @@ -130,7 +130,7 @@ export interface ComputeQueueBuilder extends Setter { export interface ComputeSubpassBuilder extends Setter { addRenderTarget (name: string, slotName: string): void; - addTexture (name: string, slotName: string, sampler?: Sampler | null): void; + addTexture (name: string, slotName: string, sampler?: Sampler | null, plane?: number): void; addStorageBuffer (name: string, accessType: AccessType, slotName: string, clearType?: ClearValueType, clearValue?: ClearValue): void; addStorageImage (name: string, accessType: AccessType, slotName: string, clearType?: ClearValueType, clearValue?: ClearValue): void; /** @@ -145,9 +145,9 @@ export interface ComputeSubpassBuilder extends Setter { } export interface BasicRenderPassBuilder extends Setter { - addRenderTarget (name: string, slotName: string, loadOp?: LoadOp, storeOp?: StoreOp, color?: Color): void; - addDepthStencil (name: string, slotName: string, loadOp?: LoadOp, storeOp?: StoreOp, depth?: number, stencil?: number, clearFlags?: ClearFlagBit): void; - addTexture (name: string, slotName: string, sampler?: Sampler | null): void; + addRenderTarget (name: string, loadOp?: LoadOp, storeOp?: StoreOp, color?: Color): void; + addDepthStencil (name: string, loadOp?: LoadOp, storeOp?: StoreOp, depth?: number, stencil?: number, clearFlags?: ClearFlagBit): void; + addTexture (name: string, slotName: string, sampler?: Sampler | null, plane?: number): void; /** * @deprecated method will be removed in 3.8.0 */ @@ -174,7 +174,7 @@ export interface RenderPassBuilder extends BasicRenderPassBuilder { } export interface ComputePassBuilder extends Setter { - addTexture (name: string, slotName: string, sampler?: Sampler | null): void; + addTexture (name: string, slotName: string, sampler?: Sampler | null, plane?: number): void; addStorageBuffer (name: string, accessType: AccessType, slotName: string, clearType?: ClearValueType, clearValue?: ClearValue): void; addStorageImage (name: string, accessType: AccessType, slotName: string, clearType?: ClearValueType, clearValue?: ClearValue): void; /** @@ -239,8 +239,8 @@ export class PipelineCapabilities { } export interface BasicPipeline extends PipelineRuntime { - readonly pipelineType: PipelineType; - readonly pipelineCapabilities: PipelineCapabilities; + readonly type: PipelineType; + readonly capabilities: PipelineCapabilities; beginSetup (): void; endSetup (): void; containsResource (name: string): boolean; @@ -257,7 +257,6 @@ export interface BasicPipeline extends PipelineRuntime { beginFrame (): void; endFrame (): void; addRenderPass (width: number, height: number, layoutName?: string): BasicRenderPassBuilder; - addMovePass (movePairs: MovePair[]): void; addCopyPass (copyPairs: CopyPair[]): void; getDescriptorSetLayout (shaderName: string, freq: UpdateFrequency): DescriptorSetLayout | null; } @@ -271,6 +270,7 @@ export interface Pipeline extends BasicPipeline { updateShadingRateTexture (name: string, width: number, height: number): void; addRenderPass (width: number, height: number, layoutName?: string): RenderPassBuilder; addComputePass (layoutName: string): ComputePassBuilder; + addMovePass (movePairs: MovePair[]): void; /** * @beta function signature might change */ diff --git a/cocos/rendering/custom/types.ts b/cocos/rendering/custom/types.ts index 9f793fcb8d..c41b3521eb 100644 --- a/cocos/rendering/custom/types.ts +++ b/cocos/rendering/custom/types.ts @@ -280,6 +280,7 @@ export class RasterView { this.shaderStageFlags = shaderStageFlags; } slotName: string; + slotName1 = ''; accessType: AccessType; attachmentType: AttachmentType; loadOp: LoadOp; @@ -340,6 +341,7 @@ export class ComputeView { } name: string; accessType: AccessType; + plane = 0; clearFlags: ClearFlagBit; clearValueType: ClearValueType; readonly clearValue: ClearValue; @@ -508,6 +510,7 @@ export class PipelineStatistics { export function saveRasterView (ar: OutputArchive, v: RasterView) { ar.writeString(v.slotName); + ar.writeString(v.slotName1); ar.writeNumber(v.accessType); ar.writeNumber(v.attachmentType); ar.writeNumber(v.loadOp); @@ -520,6 +523,7 @@ export function saveRasterView (ar: OutputArchive, v: RasterView) { export function loadRasterView (ar: InputArchive, v: RasterView) { v.slotName = ar.readString(); + v.slotName1 = ar.readString(); v.accessType = ar.readNumber(); v.attachmentType = ar.readNumber(); v.loadOp = ar.readNumber(); @@ -547,6 +551,7 @@ export function loadClearValue (ar: InputArchive, v: ClearValue) { export function saveComputeView (ar: OutputArchive, v: ComputeView) { ar.writeString(v.name); ar.writeNumber(v.accessType); + ar.writeNumber(v.plane); ar.writeNumber(v.clearFlags); ar.writeNumber(v.clearValueType); saveClearValue(ar, v.clearValue); @@ -556,6 +561,7 @@ export function saveComputeView (ar: OutputArchive, v: ComputeView) { export function loadComputeView (ar: InputArchive, v: ComputeView) { v.name = ar.readString(); v.accessType = ar.readNumber(); + v.plane = ar.readNumber(); v.clearFlags = ar.readNumber(); v.clearValueType = ar.readNumber(); loadClearValue(ar, v.clearValue); diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index 1d4c8f3aff..5246d352b2 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -434,8 +434,8 @@ function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'd const director = cclegacy.director; const pipeline = director.root.pipeline; const device = pipeline.device; - const scene = cclegacy.director.getScene().renderScene; - const mainLight = camera && camera.scene ? camera.scene.mainLight : scene.mainLight; + const scene = director.getScene(); + const mainLight = camera && camera.scene ? camera.scene.mainLight : scene ? scene.renderScene.mainLight : null; const sceneData = pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; const csmLayers = sceneData.csmLayers; @@ -631,7 +631,7 @@ function setCameraUBOValues (setter: WebSetter, _uboVec.set(cfg.shadingScale, cfg.shadingScale, 1.0 / cfg.shadingScale, 1.0 / cfg.shadingScale); setter.offsetVec4(_uboVec, uniformOffset); } - const mainLight = scene.mainLight; + const mainLight = scene && scene.mainLight; if (mainLight) { uniformOffset = setter.getUniformOffset('cc_mainLitDir', Type.FLOAT4); if (setter.hasUniform(uniformOffset)) { @@ -799,8 +799,9 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild RenderGraphValue.Scene, sceneData, name, '', new RenderData(), false, this._vertID, ); const layoutName = this.getLayoutName(); + const scene = cclegacy.director.getScene(); setCameraUBOValues(this, camera, this._pipeline, - camera.scene ? camera.scene : cclegacy.director.getScene().renderScene, + camera.scene ? camera.scene : scene ? scene.renderScene : null, layoutName); if (sceneFlags & SceneFlags.SHADOW_CASTER) { setShadowUBOLightView(this, camera, light.light!, light.level, layoutName); @@ -823,8 +824,9 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild name, '', new RenderData(), false, this._vertID, ); const layoutName = this.getLayoutName(); + const scene = cclegacy.director.getScene(); setCameraUBOValues(this, null, this._pipeline, - cclegacy.director.getScene().renderScene, layoutName); + scene ? scene.renderScene : null, layoutName); if (sceneFlags & SceneFlags.SHADOW_CASTER) { // setShadowUBOLightView(this, light.light!, light.level); } else { @@ -839,8 +841,9 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild 'CameraQuad', '', new RenderData(), false, this._vertID, ); const layoutName = this.getLayoutName(); + const scene = cclegacy.director.getScene(); setCameraUBOValues(this, camera, this._pipeline, - camera.scene ? camera.scene : cclegacy.director.getScene().renderScene, layoutName); + camera.scene ? camera.scene : scene ? scene.renderScene : null, layoutName); if (sceneFlags & SceneFlags.SHADOW_CASTER) { // setShadowUBOLightView(this, light.light!, light.level); } else { @@ -897,7 +900,7 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB addRenderTarget (name: string, accessType: AccessType, slotName: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()) { throw new Error('Method not implemented.'); } - addDepthStencil (name: string, accessType: AccessType, slotName: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { + addDepthStencil (name: string, accessType: AccessType, depthSlotName = '', stencilSlotName = '', loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { throw new Error('Method not implemented.'); } addTexture (name: string, slotName: string, sampler: Sampler | null = null): void { @@ -993,7 +996,7 @@ export class WebRenderPassBuilder extends WebSetter implements RenderPassBuilder set name (name: string) { this._renderGraph.setName(this._vertID, name); } - addRenderTarget (name: string, slotName: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()) { + addRenderTarget (name: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()) { if (DEBUG) { assert(name && this._resourceGraph.contains(name)); } @@ -1001,7 +1004,7 @@ export class WebRenderPassBuilder extends WebSetter implements RenderPassBuilder if (loadOp === LoadOp.LOAD) { clearFlag = ClearFlagBit.NONE; } - const view = new RasterView(slotName, + const view = new RasterView('', AccessType.WRITE, AttachmentType.RENDER_TARGET, loadOp, storeOp, @@ -1009,11 +1012,11 @@ export class WebRenderPassBuilder extends WebSetter implements RenderPassBuilder clearColor); this._pass.rasterViews.set(name, view); } - addDepthStencil (name: string, slotName: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { + addDepthStencil (name: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { if (DEBUG) { assert(name && this._resourceGraph.contains(name)); } - const view = new RasterView(slotName, + const view = new RasterView('', AccessType.WRITE, AttachmentType.DEPTH_STENCIL, loadOp, storeOp, @@ -1249,6 +1252,9 @@ export class WebCopyPassBuilder { this._vertID = vertID; this._pass = pass; } + addPair (pair: CopyPair): void { + throw new Error('Method not implemented.'); + } setCustomBehavior (name: string): void { throw new Error('Method not implemented.'); } @@ -1258,9 +1264,6 @@ export class WebCopyPassBuilder { set name (name: string) { this._renderGraph.setName(this._vertID, name); } - addPair (pair: CopyPair) { - this._pass.copyPairs.push(pair); - } private readonly _renderGraph: RenderGraph; private readonly _vertID: number; private readonly _pass: CopyPass; @@ -1275,10 +1278,10 @@ export class WebPipeline implements BasicPipeline { constructor (layoutGraph: LayoutGraphData) { this._layoutGraph = layoutGraph; } - get pipelineType () { + get type () { return PipelineType.BASIC; } - get pipelineCapabilities () { + get capabilities () { return new PipelineCapabilities(); } addCustomBuffer (name: string, info: BufferInfo, type: string): number { @@ -1375,8 +1378,29 @@ export class WebPipeline implements BasicPipeline { public addMovePass (movePairs: MovePair[]): void { throw new Error('Method not implemented.'); } - public addCopyPass (copyPairs: CopyPair[]): void { - throw new Error('Method not implemented.'); + public addCopyPass (copyPairs: CopyPair[]) { + // const renderData = new RenderData(); + // const vertID = this._renderGraph!.addVertex( + // RenderGraphValue.Copy, copyPass, 'copyPass', 'copy-pass', renderData, false, + // ); + // const copyPass = new CopyPass(); + // copyPass.copyPairs.splice(0, copyPass.copyPairs.length, ...copyPairs); + // const result = new WebCopyPassBuilder(this._renderGraph!, vertID, copyPass); + // return result; + for (const pair of copyPairs) { + const targetName = pair.target; + const tarVerId = this.resourceGraph.find(targetName); + if (DEBUG) { + const srcVerId = this.resourceGraph.find(pair.source); + assert(srcVerId !== 0xFFFFFFFF, `The resource named ${pair.source} was not found in Resource Graph.`); + assert(tarVerId !== 0xFFFFFFFF, `The resource named ${targetName} was not found in Resource Graph.`); + } + const resDesc = this.resourceGraph.getDesc(tarVerId); + const currRaster = this.addRenderPass(resDesc.width, resDesc.height, 'copy-pass'); + currRaster.addRenderTarget(targetName, LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0)); + currRaster.addTexture(pair.source, 'outputResultMap'); + currRaster.addQueue(QueueHint.NONE).addFullscreenQuad(this._copyPassMat, 0, SceneFlags.NONE); + } } protected _generateConstantMacros (clusterEnabled: boolean) { let str = ''; @@ -1421,6 +1445,15 @@ export class WebPipeline implements BasicPipeline { return this._globalDescSetData; } + private _compileMaterial () { + this._copyPassMat.initialize({ + effectName: 'pipeline/copy-pass', + }); + for (let i = 0; i < this._copyPassMat.passes.length; ++i) { + this._copyPassMat.passes[i].tryCompile(); + } + } + public activate (swapchain: Swapchain): boolean { this._device = deviceManager.gfxDevice; createGfxDescriptorSetsAndPipelines(this._device, this._layoutGraph); @@ -1431,6 +1464,7 @@ export class WebPipeline implements BasicPipeline { this._globalDescriptorSet = isEnableEffect() ? this._device.createDescriptorSet(this._globalDescriptorSetInfo) : this._globalDescSetData.descriptorSet; this._globalDSManager.globalDescriptorSet = this.globalDescriptorSet; + this._compileMaterial(); this.setMacroBool('CC_USE_HDR', this._pipelineSceneData.isHDR); this.setMacroBool('CC_USE_FLOAT_OUTPUT', macro.ENABLE_FLOAT_OUTPUT && supportsRGBA16FloatTexture(this._device)); this._generateConstantMacros(false); @@ -1822,6 +1856,7 @@ export class WebPipeline implements BasicPipeline { public static MAX_BLOOM_FILTER_PASS_NUM = 6; private _usesDeferredPipeline = false; + private _copyPassMat: Material = new Material(); private _device!: Device; private _globalDSManager!: GlobalDSManager; private _globalDescriptorSet: DescriptorSet | null = null; diff --git a/cocos/rendering/post-process/utils/pass-context.ts b/cocos/rendering/post-process/utils/pass-context.ts index dd20e64a28..1ec14d54c6 100644 --- a/cocos/rendering/post-process/utils/pass-context.ts +++ b/cocos/rendering/post-process/utils/pass-context.ts @@ -131,7 +131,7 @@ export class PassContext { loadOp = LoadOp.LOAD; } - pass.addDepthStencil(name, '_', loadOp, StoreOp.STORE, this.clearDepthColor.x, this.clearDepthColor.y, clearFlag); + pass.addDepthStencil(name, loadOp, StoreOp.STORE, this.clearDepthColor.x, this.clearDepthColor.y, clearFlag); } else { const clearColor = new Color(); clearColor.copy(this.clearColor); @@ -142,7 +142,7 @@ export class PassContext { loadOp = LoadOp.LOAD; } - pass.addRenderTarget(name, '_', loadOp, StoreOp.STORE, clearColor); + pass.addRenderTarget(name, loadOp, StoreOp.STORE, clearColor); } return this; } diff --git a/editor/assets/effects/pipeline/copy-pass.effect b/editor/assets/effects/pipeline/copy-pass.effect new file mode 100644 index 0000000000..e63a40190e --- /dev/null +++ b/editor/assets/effects/pipeline/copy-pass.effect @@ -0,0 +1,53 @@ +// Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - passes: + - vert: copy-pass-vs + frag: copy-pass-fs + pass: copy-pass + depthStencilState: + depthTest: false + depthWrite: false + rasterizerState: + cullMode: none + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendSrcAlpha: src_alpha + blendDstAlpha: one_minus_src_alpha +}% + +CCProgram copy-pass-vs %{ + precision highp float; + #include + #include + #include + + out vec2 v_uv; + + void main () { + StandardVertInput In; + CCDecode(In); + CC_HANDLE_GET_CLIP_FLIP(In.position.xy); + gl_Position = In.position; + gl_Position.y = gl_Position.y; + v_uv = a_texCoord; + } +}% + +CCProgram copy-pass-fs %{ + precision highp float; + in vec2 v_uv; + + #pragma rate outputResultMap pass + layout(binding = 0) uniform sampler2D outputResultMap; + + layout(location = 0) out vec4 fragColor; + +void main () { + fragColor = texture(outputResultMap, v_uv); + } +}% diff --git a/editor/assets/effects/pipeline/copy-pass.effect.meta b/editor/assets/effects/pipeline/copy-pass.effect.meta new file mode 100644 index 0000000000..d7d899473c --- /dev/null +++ b/editor/assets/effects/pipeline/copy-pass.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.7.0", + "importer": "effect", + "imported": true, + "uuid": "5c601d96-e4c7-4698-991b-7ee674b11079", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/native/cocos/core/assets/EffectAsset.cpp b/native/cocos/core/assets/EffectAsset.cpp index 9a74e9b171..78d4e069d7 100644 --- a/native/cocos/core/assets/EffectAsset.cpp +++ b/native/cocos/core/assets/EffectAsset.cpp @@ -139,6 +139,7 @@ EffectAsset *EffectAsset::get(const ccstd::string &name) { "skybox", "deferred-lighting", "bloom", + "copy-pass", "post-process", "profiler", "splash-screen", diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index bc1d0e8cf6..7a7187c9b0 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -90,11 +90,11 @@ gfx::Device *NativePipeline::getDevice() const { return device; } -PipelineType NativePipeline::getPipelineType() const { +PipelineType NativePipeline::getType() const { return PipelineType::STANDARD; } -PipelineCapabilities NativePipeline::getPipelineCapabilities() const { +PipelineCapabilities NativePipeline::getCapabilities() const { return PipelineCapabilities{}; } diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index 30d705d8bd..495a671a68 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -217,8 +217,8 @@ public: } void addRenderTarget(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override; - void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) override; - void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) override; + void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &depthSlotName, const ccstd::string &stencilSlotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) override; + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) override; void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) override; void addComputeView(const ccstd::string &name, const ComputeView &view) override; @@ -285,7 +285,7 @@ public: } void addRenderTarget(const ccstd::string &name, const ccstd::string &slotName) override; - void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) override; + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) override; void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) override; void addComputeView(const ccstd::string &name, const ComputeView &view) override; @@ -348,9 +348,9 @@ public: NativeSetter::setCamera(camera); } - void addRenderTarget(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override; - void addDepthStencil(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) override; - void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) override; + void addRenderTarget(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override; + void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) override; + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; void addRasterView(const ccstd::string &name, const RasterView &view) override; void addComputeView(const ccstd::string &name, const ComputeView &view) override; RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &layoutName) override; @@ -479,7 +479,7 @@ public: NativeSetter::setCamera(camera); } - void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) override; + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) override; void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) override; void addComputeView(const ccstd::string &name, const ComputeView &view) override; @@ -887,8 +887,8 @@ public: void resetRenderQueue(bool reset) override; bool isRenderQueueReset() const override; - PipelineType getPipelineType() const override; - PipelineCapabilities getPipelineCapabilities() const override; + PipelineType getType() const override; + PipelineCapabilities getCapabilities() const override; void beginSetup() override; void endSetup() override; bool containsResource(const ccstd::string &name) const override; @@ -901,7 +901,6 @@ public: void updateDepthStencil(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; void beginFrame() override; void endFrame() override; - void addMovePass(const ccstd::vector &movePairs) override; void addCopyPass(const ccstd::vector ©Pairs) override; gfx::DescriptorSetLayout *getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) override; @@ -913,6 +912,7 @@ public: void updateShadingRateTexture(const ccstd::string &name, uint32_t width, uint32_t height) override; RenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &layoutName) override; ComputePassBuilder *addComputePass(const ccstd::string &layoutName) override; + void addMovePass(const ccstd::vector &movePairs) override; uint32_t addCustomBuffer(const ccstd::string &name, const gfx::BufferInfo &info, const std::string &type) override; uint32_t addCustomTexture(const ccstd::string &name, const gfx::TextureInfo &info, const std::string &type) override; diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp index 2e2dc98fa0..5e4af82bd6 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp @@ -350,7 +350,6 @@ void addDepthStencilImpl( void NativeRenderPassBuilder::addRenderTarget( const ccstd::string &name, - const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) { @@ -358,7 +357,7 @@ void NativeRenderPassBuilder::addRenderTarget( *renderGraph, nodeID, name, - slotName, + "", AccessType::WRITE, loadOp, storeOp, @@ -367,7 +366,6 @@ void NativeRenderPassBuilder::addRenderTarget( void NativeRenderPassBuilder::addDepthStencil( const ccstd::string &name, - const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, @@ -377,7 +375,7 @@ void NativeRenderPassBuilder::addDepthStencil( *renderGraph, nodeID, name, - slotName, + "", AccessType::WRITE, loadOp, storeOp, @@ -389,13 +387,14 @@ void NativeRenderPassBuilder::addDepthStencil( // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) void NativeRenderPassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, - gfx::Sampler *sampler) { + gfx::Sampler *sampler, uint32_t plane) { std::ignore = sampler; addComputeView( name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), AccessType::READ, + plane, gfx::ClearFlagBit::NONE, ClearValueType::NONE, ClearValue{}, @@ -496,6 +495,7 @@ template void addRasterViewImpl( std::string_view name, std::string_view slotName, + std::string_view slotName1, AccessType accessType, AttachmentType attachmentType, gfx::LoadOp loadOp, @@ -520,6 +520,7 @@ void addRasterViewImpl( std::forward_as_tuple(name), std::forward_as_tuple( ccstd::pmr::string(slotName, subpassData.get_allocator()), + ccstd::pmr::string(slotName1, subpassData.get_allocator()), accessType, attachmentType, loadOp, @@ -600,11 +601,13 @@ void addComputeViewImpl( void NativeRenderSubpassBuilder::addRenderTarget( const ccstd::string &name, AccessType accessType, - const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, + const ccstd::string &slotName, + gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) { addRasterViewImpl( name, slotName, + "", accessType, AttachmentType::RENDER_TARGET, loadOp, @@ -618,11 +621,14 @@ void NativeRenderSubpassBuilder::addRenderTarget( void NativeRenderSubpassBuilder::addDepthStencil( const ccstd::string &name, AccessType accessType, - const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, + const ccstd::string &depthSlotName, + const ccstd::string &stencilSlotName, + gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) { addRasterViewImpl( name, - slotName, + depthSlotName, + stencilSlotName, accessType, AttachmentType::DEPTH_STENCIL, loadOp, @@ -636,13 +642,14 @@ void NativeRenderSubpassBuilder::addDepthStencil( // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) void NativeRenderSubpassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, - gfx::Sampler *sampler) { + gfx::Sampler *sampler, uint32_t plane) { std::ignore = sampler; addComputeView( name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), AccessType::READ, + plane, gfx::ClearFlagBit::NONE, ClearValueType::NONE, ClearValue{}, @@ -780,6 +787,7 @@ void NativeComputeSubpassBuilder::addRenderTarget(const ccstd::string &name, con addRasterViewImpl( name, slotName, + "", AccessType::READ, AttachmentType::RENDER_TARGET, gfx::LoadOp::LOAD, @@ -793,13 +801,14 @@ void NativeComputeSubpassBuilder::addRenderTarget(const ccstd::string &name, con // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) void NativeComputeSubpassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, - gfx::Sampler *sampler) { + gfx::Sampler *sampler, uint32_t plane) { std::ignore = sampler; addComputeView( name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), AccessType::READ, + plane, gfx::ClearFlagBit::NONE, ClearValueType::NONE, ClearValue{}, @@ -1464,13 +1473,14 @@ void NativeComputeQueueBuilder::addDispatch( // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) void NativeComputePassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, - gfx::Sampler *sampler) { + gfx::Sampler *sampler, uint32_t plane) { std::ignore = sampler; addComputeView( name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), AccessType::READ, + plane, gfx::ClearFlagBit::NONE, ClearValueType::NONE, ClearValue{}, diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp index c5c032142a..b2902cdc72 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp @@ -41,6 +41,9 @@ bool nativevalue_to_se(const cc::render::RasterView &from, se::Value &to, se::Ob nativevalue_to_se(from.slotName, tmp, ctx); obj->setProperty("slotName", tmp); + nativevalue_to_se(from.slotName1, tmp, ctx); + obj->setProperty("slotName1", tmp); + nativevalue_to_se(from.accessType, tmp, ctx); obj->setProperty("accessType", tmp); @@ -99,6 +102,9 @@ bool nativevalue_to_se(const cc::render::ComputeView &from, se::Value &to, se::O nativevalue_to_se(from.accessType, tmp, ctx); obj->setProperty("accessType", tmp); + nativevalue_to_se(from.plane, tmp, ctx); + obj->setProperty("plane", tmp); + nativevalue_to_se(from.clearFlags, tmp, ctx); obj->setProperty("clearFlags", tmp); @@ -267,6 +273,10 @@ bool sevalue_to_native(const se::Value &from, cc::render if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->slotName), ctx); } + obj->getProperty("slotName1", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->slotName1), ctx); + } obj->getProperty("accessType", &field, true); if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->accessType), ctx); @@ -343,6 +353,10 @@ bool sevalue_to_native(const se::Value &from, cc::rende if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->accessType), ctx); } + obj->getProperty("plane", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->plane), ctx); + } obj->getProperty("clearFlags", &field, true); if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->clearFlags), ctx); diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h index 2f0b3af3b6..ddfe0aa1f2 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h @@ -39,6 +39,7 @@ namespace render { inline void save(OutputArchive& ar, const RasterView& v) { save(ar, v.slotName); + save(ar, v.slotName1); save(ar, v.accessType); save(ar, v.attachmentType); save(ar, v.loadOp); @@ -51,6 +52,7 @@ inline void save(OutputArchive& ar, const RasterView& v) { inline void load(InputArchive& ar, RasterView& v) { load(ar, v.slotName); + load(ar, v.slotName1); load(ar, v.accessType); load(ar, v.attachmentType); load(ar, v.loadOp); @@ -78,6 +80,7 @@ inline void load(InputArchive& ar, ClearValue& v) { inline void save(OutputArchive& ar, const ComputeView& v) { save(ar, v.name); save(ar, v.accessType); + save(ar, v.plane); save(ar, v.clearFlags); save(ar, v.clearValueType); save(ar, v.clearValue); @@ -87,6 +90,7 @@ inline void save(OutputArchive& ar, const ComputeView& v) { inline void load(InputArchive& ar, ComputeView& v) { load(ar, v.name); load(ar, v.accessType); + load(ar, v.plane); load(ar, v.clearFlags); load(ar, v.clearValueType); load(ar, v.clearValue); diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp index eef8aebe03..bde7078493 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.cpp @@ -35,10 +35,23 @@ namespace cc { namespace render { RasterView::RasterView(const allocator_type& alloc) noexcept -: slotName(alloc) {} +: slotName(alloc), + slotName1(alloc) {} -RasterView::RasterView(ccstd::pmr::string slotNameIn, AccessType accessTypeIn, AttachmentType attachmentTypeIn, gfx::LoadOp loadOpIn, gfx::StoreOp storeOpIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, gfx::ShaderStageFlagBit shaderStageFlagsIn, const allocator_type& alloc) noexcept +RasterView::RasterView(ccstd::pmr::string slotNameIn, AccessType accessTypeIn, AttachmentType attachmentTypeIn, gfx::LoadOp loadOpIn, gfx::StoreOp storeOpIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, gfx::ShaderStageFlagBit shaderStageFlagsIn, const allocator_type& alloc) noexcept // NOLINT : slotName(std::move(slotNameIn), alloc), + slotName1(alloc), + accessType(accessTypeIn), + attachmentType(attachmentTypeIn), + loadOp(loadOpIn), + storeOp(storeOpIn), + clearFlags(clearFlagsIn), + clearColor(clearColorIn), + shaderStageFlags(shaderStageFlagsIn) {} + +RasterView::RasterView(ccstd::pmr::string slotNameIn, ccstd::pmr::string slotName1In, AccessType accessTypeIn, AttachmentType attachmentTypeIn, gfx::LoadOp loadOpIn, gfx::StoreOp storeOpIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, gfx::ShaderStageFlagBit shaderStageFlagsIn, const allocator_type& alloc) noexcept // NOLINT +: slotName(std::move(slotNameIn), alloc), + slotName1(std::move(slotName1In), alloc), accessType(accessTypeIn), attachmentType(attachmentTypeIn), loadOp(loadOpIn), @@ -49,6 +62,7 @@ RasterView::RasterView(ccstd::pmr::string slotNameIn, AccessType accessTypeIn, A RasterView::RasterView(RasterView&& rhs, const allocator_type& alloc) : slotName(std::move(rhs.slotName), alloc), + slotName1(std::move(rhs.slotName1), alloc), accessType(rhs.accessType), attachmentType(rhs.attachmentType), loadOp(rhs.loadOp), @@ -60,6 +74,7 @@ RasterView::RasterView(RasterView&& rhs, const allocator_type& alloc) RasterView::RasterView(RasterView const& rhs, const allocator_type& alloc) : slotName(rhs.slotName, alloc), + slotName1(rhs.slotName1, alloc), accessType(rhs.accessType), attachmentType(rhs.attachmentType), loadOp(rhs.loadOp), @@ -80,9 +95,19 @@ ComputeView::ComputeView(ccstd::pmr::string nameIn, AccessType accessTypeIn, gfx clearValue(clearValueIn), shaderStageFlags(shaderStageFlagsIn) {} +ComputeView::ComputeView(ccstd::pmr::string nameIn, AccessType accessTypeIn, uint32_t planeIn, gfx::ClearFlagBit clearFlagsIn, ClearValueType clearValueTypeIn, ClearValue clearValueIn, gfx::ShaderStageFlagBit shaderStageFlagsIn, const allocator_type& alloc) noexcept +: name(std::move(nameIn), alloc), + accessType(accessTypeIn), + plane(planeIn), + clearFlags(clearFlagsIn), + clearValueType(clearValueTypeIn), + clearValue(clearValueIn), + shaderStageFlags(shaderStageFlagsIn) {} + ComputeView::ComputeView(ComputeView&& rhs, const allocator_type& alloc) : name(std::move(rhs.name), alloc), accessType(rhs.accessType), + plane(rhs.plane), clearFlags(rhs.clearFlags), clearValueType(rhs.clearValueType), clearValue(rhs.clearValue), @@ -91,6 +116,7 @@ ComputeView::ComputeView(ComputeView&& rhs, const allocator_type& alloc) ComputeView::ComputeView(ComputeView const& rhs, const allocator_type& alloc) : name(rhs.name, alloc), accessType(rhs.accessType), + plane(rhs.plane), clearFlags(rhs.clearFlags), clearValueType(rhs.clearValueType), clearValue(rhs.clearValue), diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h index 3e5fe81adc..9fdedd1f89 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h @@ -201,6 +201,7 @@ struct RasterView { RasterView(const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; // NOLINT RasterView(ccstd::pmr::string slotNameIn, AccessType accessTypeIn, AttachmentType attachmentTypeIn, gfx::LoadOp loadOpIn, gfx::StoreOp storeOpIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, gfx::ShaderStageFlagBit shaderStageFlagsIn, const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; + RasterView(ccstd::pmr::string slotNameIn, ccstd::pmr::string slotName1In, AccessType accessTypeIn, AttachmentType attachmentTypeIn, gfx::LoadOp loadOpIn, gfx::StoreOp storeOpIn, gfx::ClearFlagBit clearFlagsIn, gfx::Color clearColorIn, gfx::ShaderStageFlagBit shaderStageFlagsIn, const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; RasterView(RasterView&& rhs, const allocator_type& alloc); RasterView(RasterView const& rhs, const allocator_type& alloc); @@ -210,6 +211,7 @@ struct RasterView { RasterView& operator=(RasterView const& rhs) = default; ccstd::pmr::string slotName; + ccstd::pmr::string slotName1; AccessType accessType{AccessType::WRITE}; AttachmentType attachmentType{AttachmentType::RENDER_TARGET}; gfx::LoadOp loadOp{gfx::LoadOp::LOAD}; @@ -221,8 +223,8 @@ struct RasterView { }; inline bool operator==(const RasterView& lhs, const RasterView& rhs) noexcept { - return std::forward_as_tuple(lhs.slotName, lhs.accessType, lhs.attachmentType, lhs.loadOp, lhs.storeOp, lhs.clearFlags, lhs.shaderStageFlags) == - std::forward_as_tuple(rhs.slotName, rhs.accessType, rhs.attachmentType, rhs.loadOp, rhs.storeOp, rhs.clearFlags, rhs.shaderStageFlags); + return std::forward_as_tuple(lhs.slotName, lhs.slotName1, lhs.accessType, lhs.attachmentType, lhs.loadOp, lhs.storeOp, lhs.clearFlags, lhs.shaderStageFlags) == + std::forward_as_tuple(rhs.slotName, rhs.slotName1, rhs.accessType, rhs.attachmentType, rhs.loadOp, rhs.storeOp, rhs.clearFlags, rhs.shaderStageFlags); } inline bool operator!=(const RasterView& lhs, const RasterView& rhs) noexcept { @@ -266,6 +268,7 @@ struct ComputeView { ComputeView(const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; // NOLINT ComputeView(ccstd::pmr::string nameIn, AccessType accessTypeIn, gfx::ClearFlagBit clearFlagsIn, ClearValueType clearValueTypeIn, ClearValue clearValueIn, gfx::ShaderStageFlagBit shaderStageFlagsIn, const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; + ComputeView(ccstd::pmr::string nameIn, AccessType accessTypeIn, uint32_t planeIn, gfx::ClearFlagBit clearFlagsIn, ClearValueType clearValueTypeIn, ClearValue clearValueIn, gfx::ShaderStageFlagBit shaderStageFlagsIn, const allocator_type& alloc = boost::container::pmr::get_default_resource()) noexcept; ComputeView(ComputeView&& rhs, const allocator_type& alloc); ComputeView(ComputeView const& rhs, const allocator_type& alloc); @@ -283,6 +286,7 @@ struct ComputeView { ccstd::pmr::string name; AccessType accessType{AccessType::READ}; + uint32_t plane{0}; gfx::ClearFlagBit clearFlags{gfx::ClearFlagBit::NONE}; ClearValueType clearValueType{ClearValueType::NONE}; ClearValue clearValue; @@ -290,8 +294,8 @@ struct ComputeView { }; inline bool operator==(const ComputeView& lhs, const ComputeView& rhs) noexcept { - return std::forward_as_tuple(lhs.name, lhs.accessType, lhs.clearFlags, lhs.clearValueType, lhs.shaderStageFlags) == - std::forward_as_tuple(rhs.name, rhs.accessType, rhs.clearFlags, rhs.clearValueType, rhs.shaderStageFlags); + return std::forward_as_tuple(lhs.name, lhs.accessType, lhs.plane, lhs.clearFlags, lhs.clearValueType, lhs.shaderStageFlags) == + std::forward_as_tuple(rhs.name, rhs.accessType, rhs.plane, rhs.clearFlags, rhs.clearValueType, rhs.shaderStageFlags); } inline bool operator!=(const ComputeView& lhs, const ComputeView& rhs) noexcept { @@ -440,6 +444,7 @@ namespace ccstd { inline hash_t hash::operator()(const cc::render::RasterView& val) const noexcept { hash_t seed = 0; hash_combine(seed, val.slotName); + hash_combine(seed, val.slotName1); hash_combine(seed, val.accessType); hash_combine(seed, val.attachmentType); hash_combine(seed, val.loadOp); @@ -462,6 +467,7 @@ inline hash_t hash::operator()(const cc::render::Comput hash_t seed = 0; hash_combine(seed, val.name); hash_combine(seed, val.accessType); + hash_combine(seed, val.plane); hash_combine(seed, val.clearFlags); hash_combine(seed, val.clearValueType); hash_combine(seed, val.shaderStageFlags); diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h index adb5c8e658..cc32b84765 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h @@ -182,8 +182,8 @@ public: RenderSubpassBuilder() noexcept = default; virtual void addRenderTarget(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) = 0; - virtual void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) = 0; - virtual void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) = 0; + virtual void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &depthSlotName, const ccstd::string &stencilSlotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) = 0; + virtual void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) = 0; virtual void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) = 0; virtual void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) = 0; /** @@ -198,6 +198,9 @@ public: * @beta function signature might change */ virtual void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) = 0; + void addRenderTarget(const ccstd::string &name, AccessType accessType) { + addRenderTarget(name, accessType, "", gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, {}); + } void addRenderTarget(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { addRenderTarget(name, accessType, slotName, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, {}); } @@ -207,23 +210,32 @@ public: void addRenderTarget(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp) { addRenderTarget(name, accessType, slotName, loadOp, storeOp, {}); } - void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addDepthStencil(name, accessType, slotName, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name, AccessType accessType) { + addDepthStencil(name, accessType, "", "", gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); } - void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp) { - addDepthStencil(name, accessType, slotName, loadOp, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &depthSlotName) { + addDepthStencil(name, accessType, depthSlotName, "", gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); } - void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp) { - addDepthStencil(name, accessType, slotName, loadOp, storeOp, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &depthSlotName, const ccstd::string &stencilSlotName) { + addDepthStencil(name, accessType, depthSlotName, stencilSlotName, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); } - void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth) { - addDepthStencil(name, accessType, slotName, loadOp, storeOp, depth, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &depthSlotName, const ccstd::string &stencilSlotName, gfx::LoadOp loadOp) { + addDepthStencil(name, accessType, depthSlotName, stencilSlotName, loadOp, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); } - void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil) { - addDepthStencil(name, accessType, slotName, loadOp, storeOp, depth, stencil, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &depthSlotName, const ccstd::string &stencilSlotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp) { + addDepthStencil(name, accessType, depthSlotName, stencilSlotName, loadOp, storeOp, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + } + void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &depthSlotName, const ccstd::string &stencilSlotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth) { + addDepthStencil(name, accessType, depthSlotName, stencilSlotName, loadOp, storeOp, depth, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + } + void addDepthStencil(const ccstd::string &name, AccessType accessType, const ccstd::string &depthSlotName, const ccstd::string &stencilSlotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil) { + addDepthStencil(name, accessType, depthSlotName, stencilSlotName, loadOp, storeOp, depth, stencil, gfx::ClearFlagBit::DEPTH_STENCIL); } void addTexture(const ccstd::string &name, const ccstd::string &slotName) { - addTexture(name, slotName, nullptr); + addTexture(name, slotName, nullptr, 0); + } + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) { + addTexture(name, slotName, sampler, 0); } void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { addStorageBuffer(name, accessType, slotName, ClearValueType::NONE, {}); @@ -263,7 +275,7 @@ public: ComputeSubpassBuilder() noexcept = default; virtual void addRenderTarget(const ccstd::string &name, const ccstd::string &slotName) = 0; - virtual void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) = 0; + virtual void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) = 0; virtual void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) = 0; virtual void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) = 0; /** @@ -276,7 +288,10 @@ public: */ virtual void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) = 0; void addTexture(const ccstd::string &name, const ccstd::string &slotName) { - addTexture(name, slotName, nullptr); + addTexture(name, slotName, nullptr, 0); + } + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) { + addTexture(name, slotName, sampler, 0); } void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { addStorageBuffer(name, accessType, slotName, ClearValueType::NONE, {}); @@ -299,9 +314,9 @@ class BasicRenderPassBuilder : public Setter { public: BasicRenderPassBuilder() noexcept = default; - virtual void addRenderTarget(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) = 0; - virtual void addDepthStencil(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) = 0; - virtual void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) = 0; + virtual void addRenderTarget(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) = 0; + virtual void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) = 0; + virtual void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) = 0; /** * @deprecated method will be removed in 3.8.0 */ @@ -315,32 +330,35 @@ public: virtual void setVersion(const ccstd::string &name, uint64_t version) = 0; virtual bool getShowStatistics() const = 0; virtual void setShowStatistics(bool enable) = 0; - void addRenderTarget(const ccstd::string &name, const ccstd::string &slotName) { - addRenderTarget(name, slotName, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, {}); + void addRenderTarget(const ccstd::string &name) { + addRenderTarget(name, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, {}); } - void addRenderTarget(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp) { - addRenderTarget(name, slotName, loadOp, gfx::StoreOp::STORE, {}); + void addRenderTarget(const ccstd::string &name, gfx::LoadOp loadOp) { + addRenderTarget(name, loadOp, gfx::StoreOp::STORE, {}); } - void addRenderTarget(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp) { - addRenderTarget(name, slotName, loadOp, storeOp, {}); + void addRenderTarget(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp) { + addRenderTarget(name, loadOp, storeOp, {}); } - void addDepthStencil(const ccstd::string &name, const ccstd::string &slotName) { - addDepthStencil(name, slotName, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name) { + addDepthStencil(name, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); } - void addDepthStencil(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp) { - addDepthStencil(name, slotName, loadOp, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp) { + addDepthStencil(name, loadOp, gfx::StoreOp::STORE, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); } - void addDepthStencil(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp) { - addDepthStencil(name, slotName, loadOp, storeOp, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp) { + addDepthStencil(name, loadOp, storeOp, 1, 0, gfx::ClearFlagBit::DEPTH_STENCIL); } - void addDepthStencil(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth) { - addDepthStencil(name, slotName, loadOp, storeOp, depth, 0, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth) { + addDepthStencil(name, loadOp, storeOp, depth, 0, gfx::ClearFlagBit::DEPTH_STENCIL); } - void addDepthStencil(const ccstd::string &name, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil) { - addDepthStencil(name, slotName, loadOp, storeOp, depth, stencil, gfx::ClearFlagBit::DEPTH_STENCIL); + void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil) { + addDepthStencil(name, loadOp, storeOp, depth, stencil, gfx::ClearFlagBit::DEPTH_STENCIL); } void addTexture(const ccstd::string &name, const ccstd::string &slotName) { - addTexture(name, slotName, nullptr); + addTexture(name, slotName, nullptr, 0); + } + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) { + addTexture(name, slotName, sampler, 0); } RenderQueueBuilder *addQueue() { return addQueue(QueueHint::NONE, ""); @@ -386,7 +404,7 @@ class ComputePassBuilder : public Setter { public: ComputePassBuilder() noexcept = default; - virtual void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) = 0; + virtual void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) = 0; virtual void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) = 0; virtual void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, ClearValueType clearType, const ClearValue &clearValue) = 0; /** @@ -399,7 +417,10 @@ public: */ virtual void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) = 0; void addTexture(const ccstd::string &name, const ccstd::string &slotName) { - addTexture(name, slotName, nullptr); + addTexture(name, slotName, nullptr, 0); + } + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler) { + addTexture(name, slotName, sampler, 0); } void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { addStorageBuffer(name, accessType, slotName, ClearValueType::NONE, {}); @@ -508,8 +529,8 @@ class BasicPipeline : public PipelineRuntime { public: BasicPipeline() noexcept = default; - virtual PipelineType getPipelineType() const = 0; - virtual PipelineCapabilities getPipelineCapabilities() const = 0; + virtual PipelineType getType() const = 0; + virtual PipelineCapabilities getCapabilities() const = 0; virtual void beginSetup() = 0; virtual void endSetup() = 0; virtual bool containsResource(const ccstd::string &name) const = 0; @@ -526,7 +547,6 @@ public: virtual void beginFrame() = 0; virtual void endFrame() = 0; virtual BasicRenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &layoutName) = 0; - virtual void addMovePass(const ccstd::vector &movePairs) = 0; virtual void addCopyPass(const ccstd::vector ©Pairs) = 0; virtual gfx::DescriptorSetLayout *getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) = 0; uint32_t addRenderTarget(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height) { @@ -558,6 +578,7 @@ public: virtual void updateShadingRateTexture(const ccstd::string &name, uint32_t width, uint32_t height) = 0; RenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &layoutName) override = 0 /* covariant */; virtual ComputePassBuilder *addComputePass(const ccstd::string &layoutName) = 0; + virtual void addMovePass(const ccstd::vector &movePairs) = 0; /** * @beta function signature might change */ diff --git a/native/tools/swig-config/render.i b/native/tools/swig-config/render.i index 8a92ad569d..ca0f00d3b9 100644 --- a/native/tools/swig-config/render.i +++ b/native/tools/swig-config/render.i @@ -109,8 +109,8 @@ using namespace cc::render; %attribute(cc::render::BasicRenderPassBuilder, bool, showStatistics, getShowStatistics, setShowStatistics); %attribute(cc::render::SceneVisitor, cc::pipeline::PipelineSceneData*, pipelineSceneData, getPipelineSceneData); %attribute(cc::render::SceneTask, cc::render::TaskType, taskType, getTaskType); -%attribute(cc::render::BasicPipeline, cc::render::PipelineType, pipelineType, getPipelineType); -%attribute(cc::render::BasicPipeline, cc::render::PipelineCapabilities, pipelineCapabilities, getPipelineCapabilities); +%attribute(cc::render::BasicPipeline, cc::render::PipelineType, type, getType); +%attribute(cc::render::BasicPipeline, cc::render::PipelineCapabilities, capabilities, getCapabilities); // ----- Import Section ------ // Brief: Import header files which are depended by 'Include Section' From 038f386becb6f0139007c4271d9d11a9f9794817 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 18 May 2023 13:37:54 +0800 Subject: [PATCH 19/22] Lint rule: prefer interface style type definition (#15020) * Lint rule: prefer interface style type definition * Adapt lint * Fix lint style --- .eslintrc.yaml | 3 +++ cocos/animation/marionette/graph-eval.ts | 4 ++-- cocos/animation/tracks/track.ts | 11 ++++++++--- tests/animation/animaion-clip-migration-3.x.test.ts | 4 ++-- .../utils/node-transform-value-observer.ts | 4 ++-- tests/core/algorithm/partition.test.ts | 2 +- 6 files changed, 18 insertions(+), 10 deletions(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 74f29d49ed..bb227c333e 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -140,3 +140,6 @@ rules: '@typescript-eslint/consistent-type-assertions': [error, { assertionStyle: 'as' }] + + # Prefer the interface style. + '@typescript-eslint/consistent-type-definitions': [error, interface] diff --git a/cocos/animation/marionette/graph-eval.ts b/cocos/animation/marionette/graph-eval.ts index 0844c83dcd..7c73356dbb 100644 --- a/cocos/animation/marionette/graph-eval.ts +++ b/cocos/animation/marionette/graph-eval.ts @@ -325,7 +325,7 @@ export class AnimationGraphEval { * @en * Describes how to override animation clips in an animation graph. */ -export type ReadonlyClipOverrideMap = { +export interface ReadonlyClipOverrideMap { /** * @zh * 获取指定原始动画剪辑应替换成的动画剪辑。 @@ -339,7 +339,7 @@ export type ReadonlyClipOverrideMap = { * If the original animation clip should not be overrode, `undefined` should be returned. */ get(animationClip: AnimationClip): AnimationClip | undefined; -}; +} /** * @en diff --git a/cocos/animation/tracks/track.ts b/cocos/animation/tracks/track.ts index dc3e3eacaf..13e3efb126 100644 --- a/cocos/animation/tracks/track.ts +++ b/cocos/animation/tracks/track.ts @@ -42,11 +42,11 @@ const parseTrsPathTag = Symbol('ConvertAsTrsPath'); export const trackBindingTag = Symbol('TrackBinding'); -export type RuntimeBinding = { +export interface RuntimeBinding { setValue(value: T): void; getValue?(): T; -}; +} export type Binder = (binding: TrackBinding) => undefined | RuntimeBinding; @@ -310,6 +310,11 @@ class TrackPath { private _paths: TargetPath[] = []; } +interface AnimationFunction { + getValue: () => any; + setValue: (val: any) => void +} + /** * Composite of track path and value proxy. * Not exposed to external. If there is any reason it should be exposed, @@ -324,7 +329,7 @@ export class TrackBinding { @serializable public proxy: IValueProxyFactory | undefined; - private static _animationFunctions = new WeakMap any, setValue: (val: any) => void}>>(); + private static _animationFunctions = new WeakMap>(); public parseTrsPath () { if (this.proxy) { diff --git a/tests/animation/animaion-clip-migration-3.x.test.ts b/tests/animation/animaion-clip-migration-3.x.test.ts index aaa05d5dbf..5435fe58e1 100644 --- a/tests/animation/animaion-clip-migration-3.x.test.ts +++ b/tests/animation/animaion-clip-migration-3.x.test.ts @@ -566,13 +566,13 @@ describe('Animation Clip Migration 3.x', () => { bezierPoints: [.04,.94,.53,.63], }); - type TimeBezierTestCase = { + interface TimeBezierTestCase { t0: number; t1: number; v0: number; v1: number; bezierPoints: BezierControlPoints; - }; + } function testTimeBezierCurveConversion (testCase: TimeBezierTestCase) { const curve = new RealCurve(); diff --git a/tests/animation/new-gen-anim/utils/node-transform-value-observer.ts b/tests/animation/new-gen-anim/utils/node-transform-value-observer.ts index 3d2c44d22d..6011af9504 100644 --- a/tests/animation/new-gen-anim/utils/node-transform-value-observer.ts +++ b/tests/animation/new-gen-anim/utils/node-transform-value-observer.ts @@ -136,10 +136,10 @@ export class NodeTransformValueObserver { } namespace NodeTransformValueObserver { - export type Value = { + export interface Value { position: number; rotation: number; scale: number; eulerAngles: number; - }; + } } \ No newline at end of file diff --git a/tests/core/algorithm/partition.test.ts b/tests/core/algorithm/partition.test.ts index d24978dcfd..e9a6632f28 100644 --- a/tests/core/algorithm/partition.test.ts +++ b/tests/core/algorithm/partition.test.ts @@ -1,7 +1,7 @@ import { partition } from "../../../cocos/core/algorithm/partition"; test(`Partition algorithm`, () => { - type Element = { /** The value. */ v: number, /** Result of the predicate function. */ p: boolean }; + interface Element { /** The value. */ v: number, /** Result of the predicate function. */ p: boolean } const p = (array: Element[]) => { const nFirstGroup = partition(array, (element) => element.p); From 3d80581e582d51ce0a16f72e9d7802cc2714c671 Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Thu, 18 May 2023 13:53:59 +0800 Subject: [PATCH 20/22] =?UTF-8?q?[Refactor]=20inspector=20=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E6=96=B0=E7=9A=84=20undo=20=E6=8E=A5=E5=8F=A3=20(#149?= =?UTF-8?q?42)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/batched-skinning-model.js | 7 +- .../components/light-probe-group-footer.js | 3 +- .../inspector/components/lod-group/index.js | 13 +- .../components/particle-system-2d.js | 8 +- .../inspector/components/polygon-collider.js | 6 +- editor/inspector/components/terrain.js | 10 +- editor/inspector/components/widget.js | 3 +- editor/inspector/contributions/node.js | 242 +++++++++++------- 8 files changed, 172 insertions(+), 120 deletions(-) diff --git a/editor/inspector/components/batched-skinning-model.js b/editor/inspector/components/batched-skinning-model.js index d30ef5ee07..03324f3b02 100644 --- a/editor/inspector/components/batched-skinning-model.js +++ b/editor/inspector/components/batched-skinning-model.js @@ -20,10 +20,8 @@ exports.ready = function() { $prop.appendChild($button); $button.addEventListener('confirm', async () => { - Editor.Message.send('scene', 'snapshot'); - const uuids = this.dump.value.uuid.values || [this.dump.value.uuid.value]; - + const undoID = await Editor.Message.request('scene', 'begin-recording', uuids); for (const uuid of uuids) { await Editor.Message.request('scene', 'execute-component-method', { uuid: uuid, @@ -39,7 +37,6 @@ exports.ready = function() { args: [], }); } - - Editor.Message.send('scene', 'snapshot'); + await Editor.Message.request('scene', 'end-recording', undoID); }); }; diff --git a/editor/inspector/components/light-probe-group-footer.js b/editor/inspector/components/light-probe-group-footer.js index 0536fd9441..6ebcc7e25d 100644 --- a/editor/inspector/components/light-probe-group-footer.js +++ b/editor/inspector/components/light-probe-group-footer.js @@ -66,6 +66,7 @@ exports.ready = function() { const uuidObject = panel.dump.value.uuid; const uuids = uuidObject.values ? uuidObject.values : [uuidObject.value]; + const undoID = await Editor.Message.request('scene', 'begin-recording', uuids); for (const uuid of uuids) { Editor.Message.send('scene', 'execute-component-method', { uuid: uuid, @@ -76,7 +77,7 @@ exports.ready = function() { trackEventWithTimer('bakingSystem', 'A100006'); - Editor.Message.send('scene', 'snapshot'); + await Editor.Message.request('scene', 'end-recording', undoID); } }); diff --git a/editor/inspector/components/lod-group/index.js b/editor/inspector/components/lod-group/index.js index 32c869cdaa..3fab395def 100644 --- a/editor/inspector/components/lod-group/index.js +++ b/editor/inspector/components/lod-group/index.js @@ -252,9 +252,10 @@ exports.ready = function() { }); trackEventWithTimer('LOD', 'A100003'); }, - updateLODs(operator, index) { + async updateLODs(operator, index) { const that = this; const LODs = that.dump.value.LODs.value; + const uuid = that.dump.value.uuid.value; if (operator === 'insert') { // insert after if (LODs.length >= 8) { @@ -263,17 +264,21 @@ exports.ready = function() { } const preValue = LODs[index].value.screenUsagePercentage.value; const nextValue = LODs[index + 1] ? LODs[index + 1].value.screenUsagePercentage.value : 0; - Editor.Message.request('scene', 'lod-insert', that.dump.value.uuid.value, index + 1, (preValue + nextValue) / 2, null); + const undoID = await Editor.Message.request('scene', 'begin-recording', uuid); + await Editor.Message.request('scene', 'lod-insert', uuid, index + 1, (preValue + nextValue) / 2, null); + await Editor.Message.request('scene', 'end-recording', undoID); trackEventWithTimer('LOD', 'A100005'); } else if (operator === 'delete') { if (LODs.length === 1) { console.warn('At least one LOD, Can\'t delete any more'); return; } - Editor.Message.request('scene', 'lod-erase', that.dump.value.uuid.value, index); + const undoID = await Editor.Message.request('scene', 'begin-recording', uuid); + await Editor.Message.request('scene', 'lod-erase', uuid, index); + await Editor.Message.request('scene', 'end-recording', undoID); trackEventWithTimer('LOD', 'A100006'); } - Editor.Message.send('scene', 'snapshot'); + // Editor.Message.send('scene', 'snapshot'); }, }, }); diff --git a/editor/inspector/components/particle-system-2d.js b/editor/inspector/components/particle-system-2d.js index 401cb73686..198c1945e8 100644 --- a/editor/inspector/components/particle-system-2d.js +++ b/editor/inspector/components/particle-system-2d.js @@ -50,7 +50,6 @@ exports.ready = function() { // Hack: ui-button has extra events that are passed up to ui-prop ; $sync.addEventListener('change', (event) => { event.stopPropagation(); - Editor.Message.send('scene', 'snapshot'); }); $sync.addEventListener('confirm', async (event) => { @@ -90,9 +89,8 @@ exports.ready = function() { } this.$this.dispatch('change-dump'); + this.$this.dispatch('confirm-dump'); } - - Editor.Message.send('scene', 'snapshot'); }); const $export = document.createElement('ui-button'); @@ -106,7 +104,6 @@ exports.ready = function() { $export.addEventListener('change', (event) => { event.stopPropagation(); - Editor.Message.send('scene', 'snapshot'); }); $export.addEventListener('confirm', async (event) => { @@ -129,9 +126,8 @@ exports.ready = function() { } this.$this.dispatch('change-dump'); + this.$this.dispatch('confirm-dump'); } - - Editor.Message.send('scene', 'snapshot'); }); this.$.syncButton = $sync; diff --git a/editor/inspector/components/polygon-collider.js b/editor/inspector/components/polygon-collider.js index b217d462f5..5fa16fa159 100644 --- a/editor/inspector/components/polygon-collider.js +++ b/editor/inspector/components/polygon-collider.js @@ -20,18 +20,20 @@ exports.ready = function() { $button.addEventListener('change', (event) => { event.stopPropagation(); - Editor.Message.send('scene', 'snapshot'); + // Editor.Message.send('scene', 'snapshot'); }); $button.addEventListener('confirm', async (event) => { event.stopPropagation(); const uuids = this.dump.value.uuid.values || [this.dump.value.uuid.value]; + const undoID = await Editor.Message.request('scene', 'begin-recording', uuids); for (const uuid of uuids) { await Editor.Message.request('scene', 'regenerate-polygon-2d-points', uuid); } + await Editor.Message.request('scene', 'end-recording', undoID); - Editor.Message.send('scene', 'snapshot'); + // Editor.Message.send('scene', 'snapshot'); }); }, }, diff --git a/editor/inspector/components/terrain.js b/editor/inspector/components/terrain.js index 91bf226f57..b7f1f40ce4 100644 --- a/editor/inspector/components/terrain.js +++ b/editor/inspector/components/terrain.js @@ -10,13 +10,17 @@ exports.ready = function() { this.elements = { _asset: { ready(element) { - element.addEventListener('change-dump', (event) => { - Editor.Message.send('scene', 'snapshot'); + element.addEventListener('change-dump', async (event) => { + // Editor.Message.send('scene', 'snapshot'); + const uuid = this.dump.value.uuid.value; + const dump = event.target.dump; + const undoID = await Editor.Message.request('scene', 'begin-recording',uuid); Editor.Message.request('scene', 'execute-component-method', { uuid: this.dump.value.uuid.value, name: 'manager.addAssetToComp', - args: [event.target.dump.value], + args: [dump.value], }); + await Editor.Message.request('scene', 'end-recording', undoID); }); }, }, diff --git a/editor/inspector/components/widget.js b/editor/inspector/components/widget.js index f8cf67e97f..72dd4917c3 100644 --- a/editor/inspector/components/widget.js +++ b/editor/inspector/components/widget.js @@ -810,7 +810,6 @@ exports.methods = { break; } - Editor.Message.send('scene', 'snapshot'); const dump = this.dump; if (horizontal) { if (dump.value.isAlignLeft.value !== horizontal.isAlignLeft.value || !this.isHorizontalAlignValid) { @@ -891,6 +890,8 @@ exports.methods = { } this.dimensionVertical = this.getDimensionVertical(); } + + this.$refs.summitProp.dispatch('confirm-dump'); }, toggleLock(direction) { diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index b806dd8e3b..84ea7b5bb6 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -6,6 +6,65 @@ const { throttle } = require('lodash'); const utils = require('./utils'); const { trackEventWithTimer } = require('../utils/metrics'); +const lockList = []; +let lockPerform = false; +let lastSnapShot = null; +async function performLock() { + if (lockPerform) return; + if (lockList.length === 0) return; + lockPerform = true; + const params = lockList.shift(); + const { snapshotLock, lock, uuids, cancel } = params; + if (snapshotLock && !lock) { + + if (lastSnapShot) { + await endRecording(lastSnapShot,cancel); + lastSnapShot = null; + } + // start snapshot + } else if(!snapshotLock && lock) { + lastSnapShot = await beginRecording(uuids); + } + lockPerform = false; + await performLock(); +} +/** + * 替换之前的snapshotLock,由于UI层的事件是同步的, + * 而新的beginRecording是异步的,所以需要使用队列来保证顺序 + * @param {*} lock + * @param {*} uuids + * @param {*} cancel + */ +function snapshotLock(panel,lock,uuids,cancel=false) { + // 保存当前状态,放到队列中 + const params = { + snapshotLock:panel.snapshotLock, + lock, + uuids, + cancel + } + lockList.push(params); + // 执行队列中的操作; + performLock(); + panel.snapshotLock = lock; +} + +// 不传options时,会自动记录到undo队列,不需要调用endRecording +async function beginRecording(uuids,options) { + if (!uuids) return; + const undoID = await Editor.Message.request('scene', 'begin-recording', uuids,options); + return undoID; +} + +async function endRecording(undoID,cancel) { + if(!undoID) return; + if(cancel){ + await Editor.Message.request('scene', 'cancel-recording', undoID); + }else{ + await Editor.Message.request('scene', 'end-recording', undoID); + } +} + exports.listeners = { async 'change-dump'(event) { const panel = this; @@ -14,10 +73,8 @@ exports.listeners = { if (!target) { return; } - if (!panel.snapshotLock) { - Editor.Message.send('scene', 'snapshot'); - panel.snapshotLock = true; + snapshotLock(panel, true, panel.uuidList); } const dump = event.target.dump; @@ -96,15 +153,16 @@ exports.listeners = { console.error(error); } finally { if (!panel.snapshotLock) { - Editor.Message.send('scene', 'snapshot'); + snapshotLock(panel,false); } panel.readyToUpdate = true; } }, 'confirm-dump'() { const panel = this; - - panel.snapshotLock = false; + snapshotLock(panel,false); + // In combination with change-dump, snapshot only generated once after ui-elements continuously changed. + // Editor.Message.send('scene', 'snapshot'); }, async 'create-dump'(event) { const panel = this; @@ -114,10 +172,10 @@ exports.listeners = { return; } - Editor.Message.send('scene', 'snapshot'); - + // Editor.Message.send('scene', 'snapshot'); + const undoID = await beginRecording(panel.uuidList); const dump = event.target.dump; - + let cancel = false; try { for (let i = 0; i < panel.uuidList.length; i++) { const uuid = panel.uuidList[i]; @@ -131,10 +189,12 @@ exports.listeners = { }); } - Editor.Message.send('scene', 'snapshot'); + // Editor.Message.send('scene', 'snapshot'); } catch (error) { + cancel = true; console.error(error); } + await endRecording(undoID,cancel); }, async 'reset-dump'(event) { const panel = this; @@ -144,11 +204,10 @@ exports.listeners = { return; } - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(panel.uuidList); const dump = event.target.dump; - try { + // Editor.Message.send('scene', 'snapshot'); for (let i = 0; i < panel.uuidList.length; i++) { const uuid = panel.uuidList[i]; if (i > 0) { @@ -160,9 +219,8 @@ exports.listeners = { path: dump.path, }); } - - Editor.Message.send('scene', 'snapshot'); } catch (error) { + await endRecording(undoID,true); console.error(error); } }, @@ -483,16 +541,14 @@ const Elements = { additional.push({ value, type }); } - Editor.Message.send('scene', 'snapshot'); - + // Todo + // await beginRecording(panel.uuidList); for (const info of additional) { const config = panel.dropConfig[info.type]; if (config) { await Editor.Message.request(config.package, config.message, info, panel.dumps, panel.uuidList); } } - - Editor.Message.send('scene', 'snapshot'); }); panel._readyToUpdate = true; @@ -575,6 +631,7 @@ const Elements = { return; } + // Editor.Message.send('scene', 'snapshot'); const role = button.getAttribute('role'); @@ -591,9 +648,9 @@ const Elements = { break; } case 'unlink': { - Editor.Message.send('scene', 'snapshot'); + const undoID = await beginRecording( prefab.rootUuid); await Editor.Message.request('scene', 'unlink-prefab', prefab.rootUuid, false); - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); break; } case 'local': { @@ -601,15 +658,14 @@ const Elements = { break; } case 'reset': { - Editor.Message.send('scene', 'snapshot'); + const undoID = await beginRecording( prefab.rootUuid); await Editor.Message.request('scene', 'restore-prefab', prefab.rootUuid, prefab.uuid); - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); break; } case 'save': { - Editor.Message.send('scene', 'snapshot'); + // apply-prefab是自定义的undo,在场景中实现了undo await Editor.Message.request('scene', 'apply-prefab', prefab.rootUuid); - Editor.Message.send('scene', 'snapshot'); break; } } @@ -1415,9 +1471,10 @@ const Elements = { ], listeners: { async confirm(detail/* info */) { - if (!detail) { return; } - Editor.Message.send('scene', 'snapshot'); + if (!detail) return; + // 批量调用request意味着编辑操作在很多帧后才会完成,所以不能自动记录undo + const undoID = await beginRecording(panel.uuidList) for (const uuid of panel.uuidList) { await Editor.Message.request('scene', 'create-component', { uuid, @@ -1427,8 +1484,7 @@ const Elements = { if (detail.info.name) { trackEventWithTimer('laber', `A100000_${detail.info.name}`); } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID) }, }, }); @@ -1610,77 +1666,78 @@ exports.methods = { { label: Editor.I18n.t('ENGINE.menu.reset_component'), async click() { - Editor.Message.send('scene', 'snapshot'); - const values = dump.value.uuid.values || [dump.value.uuid.value]; + const undoID = await beginRecording(values) for (const compUuid of values) { await Editor.Message.request('scene', 'reset-component', { uuid: compUuid, }); } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, { type: 'separator' }, { label: Editor.I18n.t('ENGINE.menu.remove_component'), async click() { - Editor.Message.send('scene', 'snapshot'); + // Editor.Message.send('scene', 'snapshot'); const values = dump.value.uuid.values || [dump.value.uuid.value]; - + // 收集待修改的uuids + const uuids = []; + const indexes = []; for (const value of values) { for (const nodeDump of nodeDumps) { const uuid = nodeDump.uuid.value; const index = nodeDump.__comps__.findIndex((dumpData) => dumpData.value.uuid.value === value); if (index !== -1) { - await Editor.Message.request('scene', 'remove-array-element', { - uuid, - path: '__comps__', - index, - }); - + uuids.push(uuid); + indexes.push(index); if (nodeDump.__comps__[index].type) { trackEventWithTimer('laber', `A100001_${nodeDump.__comps__[index].type}`); } } } } - - Editor.Message.send('scene', 'snapshot'); + if (!uuids.length > 0) return; + const undoID = await beginRecording(uuids); + for (let index = 0; index < uuids.length; index++) { + await Editor.Message.request('scene', 'remove-array-element', { + uuid: uuids[index], + path: '__comps__', + index:indexes[index], + }); + } + await endRecording(undoID); + // Editor.Message.send('scene', 'snapshot'); }, }, { label: Editor.I18n.t('ENGINE.menu.move_up_component'), enabled: !isMultiple && index !== 0, async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuid); await Editor.Message.request('scene', 'move-array-element', { uuid, path: '__comps__', target: index, offset: -1, }); - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, { label: Editor.I18n.t('ENGINE.menu.move_down_component'), enabled: !isMultiple && index !== total - 1, async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuid); await Editor.Message.request('scene', 'move-array-element', { uuid, path: '__comps__', target: index, offset: 1, }); - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, { type: 'separator' }, @@ -1700,24 +1757,31 @@ exports.methods = { label: Editor.I18n.t('ENGINE.menu.paste_component_values'), enabled: !!(clipboardComponentInfo && clipboardComponentInfo.cid === dump.cid), async click() { - Editor.Message.send('scene', 'snapshot'); - const values = dump.value.uuid.values || [dump.value.uuid.value]; + const uuids = []; + const indexes = []; for (const value of values) { for (const nodeDump of nodeDumps) { const uuid = nodeDump.uuid.value; const index = nodeDump.__comps__.findIndex((dumpData) => dumpData.value.uuid.value === value); if (index !== -1) { - await Editor.Message.request('scene', 'set-property', { - uuid, - path: nodeDump.__comps__[index].path, - dump: clipboardComponentInfo.dump, - }); + uuids.push(uuid); + indexes.push(index); } } } - - Editor.Message.send('scene', 'snapshot'); + const undoID = await beginRecording(uuids); + // 遍历uuids + for (let index = 0; index < uuids.length; index++) { + const uuid = uuids[index]; + const index = indexes[index]; + await Editor.Message.request('scene', 'set-property', { + uuid, + path: nodeDumps[index].__comps__[index].path, + dump: clipboardComponentInfo.dump, + }); + } + await endRecording(undoID); }, }, { type: 'separator' }, @@ -1726,8 +1790,7 @@ exports.methods = { label: Editor.I18n.t('ENGINE.menu.paste_component'), enabled: !!clipboardComponentInfo, async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuidList) const values = dump.value.uuid.values || [dump.value.uuid.value]; let index = 0; for (const dump of values) { @@ -1755,6 +1818,7 @@ exports.methods = { index++; } + await endRecording(undoID); }, }, ], @@ -1783,15 +1847,13 @@ exports.methods = { label: Editor.I18n.t('ENGINE.menu.reset_node'), enabled: !dump.position.readonly && !dump.rotation.readonly && !dump.scale.readonly, async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { await Editor.Message.request('scene', 'reset-node', { uuid, }); } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, { type: 'separator' }, @@ -1810,8 +1872,7 @@ exports.methods = { label: Editor.I18n.t('ENGINE.menu.paste_node_value'), enabled: !!clipboardNodeInfo, async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { for (const attr of clipboardNodeInfo.attrs) { await Editor.Message.request('scene', 'set-property', { @@ -1821,8 +1882,7 @@ exports.methods = { }); } } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, { type: 'separator' }, @@ -1847,9 +1907,8 @@ exports.methods = { label: Editor.I18n.t('ENGINE.menu.paste_node_world_transform'), enabled: !!clipboardNodeWorldTransform, async click() { - Editor.Message.send('scene', 'snapshot'); - if (clipboardNodeWorldTransform.data) { + const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { await Editor.Message.request('scene', 'execute-scene-script', { name: 'inspector', @@ -1857,8 +1916,7 @@ exports.methods = { args: [uuid, clipboardNodeWorldTransform.data], }); } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); } }, }, @@ -1867,8 +1925,7 @@ exports.methods = { label: Editor.I18n.t('ENGINE.menu.paste_component'), enabled: !!clipboardComponentInfo, async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { await Editor.Message.request('scene', 'create-component', { uuid, @@ -1891,8 +1948,7 @@ exports.methods = { } } } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, { type: 'separator' }, @@ -1900,64 +1956,56 @@ exports.methods = { label: Editor.I18n.t('ENGINE.menu.reset_node_position'), enabled: !dump.position.readonly && notEqualDefaultValueVec3('position'), async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { await Editor.Message.request('scene', 'reset-property', { uuid, path: 'position', }); } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, { label: Editor.I18n.t('ENGINE.menu.reset_node_rotation'), enabled: !dump.rotation.readonly && notEqualDefaultValueVec3('rotation'), async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { await Editor.Message.request('scene', 'reset-property', { uuid, path: 'rotation', }); } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, { label: Editor.I18n.t('ENGINE.menu.reset_node_scale'), enabled: !dump.scale.readonly && notEqualDefaultValueVec3('scale'), async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { await Editor.Message.request('scene', 'reset-property', { uuid, path: 'scale', }); } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, { label: Editor.I18n.t('ENGINE.menu.reset_node_mobility'), enabled: !dump.mobility.readonly && dump.mobility.value !== dump.mobility.default, async click() { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { await Editor.Message.request('scene', 'reset-property', { uuid, path: 'mobility', }); } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); }, }, ], @@ -1972,8 +2020,7 @@ exports.methods = { } try { - Editor.Message.send('scene', 'snapshot'); - + const undoID = await beginRecording(panel.uuidList); for (const dumpPath in materialUuids[assetUuid]) { const dumpData = materialUuids[assetUuid][dumpPath]; for (let i = 0; i < panel.uuidList.length; i++) { @@ -1988,8 +2035,7 @@ exports.methods = { }); } } - - Editor.Message.send('scene', 'snapshot'); + await endRecording(undoID); } catch (error) { console.error(error); } From 655dcb94bf799aa9c1b411d1b3747b39887fdaad Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Thu, 18 May 2023 14:03:34 +0800 Subject: [PATCH 21/22] fix: discard nestedPrefabRoot node when serialized (#15092) if component's property reference a nested prefabInstance node,the node will be save in scene file.But it's a nested prefab,so it should not be. --- cocos/scene-graph/node.ts | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index c1809c1d7a..26cf313aef 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -1789,11 +1789,25 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { // discard props disallow to synchronize const isRoot = this._prefab?.root === this; if (isRoot) { - serializationOutput.writeProperty('_objFlags', this._objFlags); - serializationOutput.writeProperty('_parent', this._parent); - serializationOutput.writeProperty('_prefab', this._prefab); - if (context.customArguments.keepNodeUuid) { - serializationOutput.writeProperty('_id', this._id); + // if B prefab is in A prefab,B can be referenced by component.We should discard it.because B is not the root of prefab + let isNestedPrefab = false; + let parent = this.getParent(); + while (parent) { + const nestedRoots = parent?._prefab?.nestedPrefabInstanceRoots; + if (nestedRoots && nestedRoots.length > 0) { + // if this node is not in nestedPrefabInstanceRoots,it means this node is not the root of prefab,so it should be discarded. + isNestedPrefab = !nestedRoots.some((root) => root === this); + break; + } + parent = parent.getParent(); + } + if (!isNestedPrefab) { + serializationOutput.writeProperty('_objFlags', this._objFlags); + serializationOutput.writeProperty('_parent', this._parent); + serializationOutput.writeProperty('_prefab', this._prefab); + if (context.customArguments.keepNodeUuid) { + serializationOutput.writeProperty('_id', this._id); + } } // TODO: editorExtrasTag may be a symbol in the future serializationOutput.writeProperty(editorExtrasTag, this[editorExtrasTag]); From 7be5ca80128679ff09580903437c72e38b923285 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Thu, 18 May 2023 14:31:59 +0800 Subject: [PATCH 22/22] calculate scene scale for hbao (#15098) --- .../post-process/passes/hbao-pass.ts | 39 ++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/cocos/rendering/post-process/passes/hbao-pass.ts b/cocos/rendering/post-process/passes/hbao-pass.ts index 8dfb840fcc..baba78c4b4 100644 --- a/cocos/rendering/post-process/passes/hbao-pass.ts +++ b/cocos/rendering/post-process/passes/hbao-pass.ts @@ -23,7 +23,7 @@ */ import { EDITOR } from 'internal:constants'; -import { cclegacy, toRadian, Vec2, Vec4 } from '../../../core'; +import { cclegacy, toRadian, Vec2, Vec4, Vec3, v3 } from '../../../core'; import { Camera, CameraUsage } from '../../../render-scene/scene'; import { Pipeline, QueueHint } from '../../custom'; import { getCameraUniqueID } from '../../custom/define'; @@ -35,6 +35,7 @@ import { Texture2D } from '../../../asset/assets/texture-2d'; import { ImageAsset } from '../../../asset/assets/image-asset'; import { DebugViewCompositeType, DebugViewSingleType } from '../../debug-view'; import { ClearFlagBit, Format } from '../../../gfx'; +import { Scene } from '../../../scene-graph/scene'; const vec2 = new Vec2(); @@ -180,6 +181,7 @@ export class HBAOPass extends SettingPass { private HBAO_COMBINED_PASS_INDEX = 3; private _hbaoParams: HBAOParams = new HBAOParams(); private _initialize = false; + private averageSceneScale = new Map(); get setting () { return getSetting(HBAO); } @@ -195,6 +197,17 @@ export class HBAOPass extends SettingPass { return enable; } + public getSceneScale (camera: Camera) { + let sceneScale = camera.nearClip; + if (!this.averageSceneScale.has(camera.node.scene)) { + this._calculateSceneScale(camera.node.scene, camera.visibility); + } + if (this.averageSceneScale.has(camera.node.scene)) { + sceneScale = this.averageSceneScale.get(camera.node.scene)!; + } + return sceneScale; + } + public render (camera: Camera, ppl: Pipeline): void { passContext.updatePassViewPort(); const width = passContext.passViewport.width; @@ -209,7 +222,7 @@ export class HBAOPass extends SettingPass { // params const aoStrength = 1.0; // todo: nearest object distance from camera - const sceneScale = camera.nearClip; + const sceneScale = this.getSceneScale(camera); // todo: Half Res Depth Tex this._hbaoParams.depthTexFullResolution = vec2.set(width, height); this._hbaoParams.depthTexResolution = vec2.set(width, height); @@ -343,6 +356,28 @@ export class HBAOPass extends SettingPass { .version(); } + private _calculateSceneScale (scene: Scene, visibility: number) { + if (!scene || !scene.renderScene) { + return; + } + const sumSize = new Vec3(0); + let modelCount = 0; + const models = scene.renderScene.models; + for (let i = 0; i < models.length; i++) { + const model = models[i]; + if (!model.node || !model.worldBounds) continue; + if (model.node.layer & visibility) { + sumSize.add(model.worldBounds.halfExtents); + modelCount++; + } + } + if (modelCount > 0) { + sumSize.divide(v3(modelCount)); + const scale = Math.min(sumSize.x, sumSize.y, sumSize.z); + this.averageSceneScale.set(scene, scale); + } + } + slotName (camera: Camera, index = 0) { return this.lastPass!.slotName(camera, index); }