Merge pull request #15101 from shrinktofit/marionette-next

Merge remote-tracking branch 'upstream/develop' into marionette-next
This commit is contained in:
minggo
2023-05-18 14:49:50 +08:00
committed by GitHub
106 changed files with 2264 additions and 530 deletions
+3
View File
@@ -140,3 +140,6 @@ rules:
'@typescript-eslint/consistent-type-assertions': [error, {
assertionStyle: 'as'
}]
# Prefer the interface style.
'@typescript-eslint/consistent-type-definitions': [error, interface]
+1 -2
View File
@@ -47,8 +47,7 @@ jobs:
- uses: actions/checkout@v3
name: Checkout Head Ref
with:
repository: ${{ github.event.pull_request.head.repo.full_name }}
ref: ${{ github.head_ref }}
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
+3 -2
View File
@@ -117,8 +117,9 @@ declare module 'pal/screen-adapter' {
*/
public exitFullScreen (): Promise<void>;
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;
+8
View File
@@ -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.
+1
View File
@@ -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"
]
},
@@ -6,7 +6,7 @@ import { AnimationClip } from '../animation-clip';
* @en
* Describes how to override animation clips in an animation graph.
*/
export type ReadonlyClipOverrideMap = {
export interface ReadonlyClipOverrideMap {
/**
* @zh
* 获取指定原始动画剪辑应替换成的动画剪辑。
@@ -20,4 +20,4 @@ export type ReadonlyClipOverrideMap = {
* If the original animation clip should not be overrode, `undefined` should be returned.
*/
get(animationClip: AnimationClip): AnimationClip | undefined;
};
}
@@ -12,10 +12,10 @@ export enum TCBindingValueType {
INTEGER = 3 /* VariableType.INTEGER */,
}
type TCBindingValueTypeMap = {
interface TCBindingValueTypeMap {
[TCBindingValueType.FLOAT]: number;
[TCBindingValueType.INTEGER]: number;
};
}
/**
* @zh 描述过渡条件中的值绑定,例如,二元条件的左操作数上的绑定。
+8 -3
View File
@@ -42,11 +42,11 @@ const parseTrsPathTag = Symbol('ConvertAsTrsPath');
export const trackBindingTag = Symbol('TrackBinding');
export type RuntimeBinding<T = unknown> = {
export interface RuntimeBinding<T = unknown> {
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<Constructor, Map<string | number, { getValue:() => any, setValue: (val: any) => void}>>();
private static _animationFunctions = new WeakMap<Constructor, Map<string | number, AnimationFunction>>();
public parseTrsPath () {
if (this.proxy) {
+1 -1
View File
@@ -141,7 +141,7 @@ const downloadBundle = (nameOrUrl: string, options: Record<string, any>, onCompl
downloadScript(jspath, options, (err) => {
error = err || error;
if (++count === 2) {
onComplete(err, out);
onComplete(error, out);
}
});
};
+1
View File
@@ -184,6 +184,7 @@ const legacyBuiltinEffectNames = [
'deferred-lighting',
'bloom',
'hbao',
'copy-pass',
'post-process',
'profiler',
'splash-screen',
+30 -2
View File
@@ -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();
+1 -1
View File
@@ -113,7 +113,7 @@ export class Line extends ModelRenderer {
}
@type([Vec3])
private _positions = [];
private _positions: Vec3[] = [];
/**
* @en Inflection point positions of each polyline.
+1
View File
@@ -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();
+140 -2
View File
@@ -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<PhysicsRayResult>, 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<PhysicsRayResult>, 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<PhysicsRayResult>, 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<PhysicsRayResult>, 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<BulletShape>(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<BulletShape>(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);
}
@@ -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;
}
}
@@ -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);
}
@@ -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);
}
@@ -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);
+37 -1
View File
@@ -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<PhysicsRayResult>, 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<PhysicsRayResult>, 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<PhysicsRayResult>, 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;
@@ -34,18 +34,36 @@ import { CannonSharedBody } from '../cannon-shared-body';
export class CannonConstraint implements IBaseConstraint {
setConnectedBody (v: RigidBody | null): void {
const oldSB = getWrap<CannonSharedBody>(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;
}
}
@@ -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);
}
}
@@ -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);
}
}
+37 -1
View File
@@ -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<PhysicsRayResult>, 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<PhysicsRayResult>, 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<PhysicsRayResult>, 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) { }
@@ -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;
}
+2 -1
View File
@@ -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,
+1 -1
View File
@@ -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;
}
+198
View File
@@ -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);
+7 -1
View File
@@ -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<IPhysicsWorld>,
@@ -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,
};
+180 -2
View File
@@ -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<PhysicsRayResult>(() => new PhysicsRayResult(), 1);
private readonly sweepResultPool = new RecyclePool<PhysicsRayResult>(() => 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);
}
+19 -15
View File
@@ -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 () {
+30 -1
View File
@@ -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;
}
}
@@ -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();
}
}
@@ -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));
+63
View File
@@ -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<PhysicsRayResult>, 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<PhysXShape>(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<PhysXShape>(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);
+2
View File
@@ -38,4 +38,6 @@ export class PhysXInstance {
static simulationCB: any;
static queryFilterCB: any;
static mutipleResultSize = 12;
static singleSweepResult: any;
static mutipleSweepResults: any;
}
+2 -2
View File
@@ -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);
+73 -4
View File
@@ -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<PhysicsRayResult>, 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<PhysicsRayResult>, 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<PhysicsRayResult>, 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();
+13 -1
View File
@@ -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<PhysicsRayResult>, results: PhysicsRayResult[]): boolean
raycastClosest (worldRay: geometry.Ray, options: IRaycastOptions, out: PhysicsRayResult): boolean;
sweepBox (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike,
options: IRaycastOptions, pool: RecyclePool<PhysicsRayResult>, 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<PhysicsRayResult>, 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<PhysicsRayResult>, results: PhysicsRayResult[]): boolean;
sweepCapsuleClosest (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike,
options: IRaycastOptions, result: PhysicsRayResult): boolean;
emitEvents (): void;
syncSceneToPhysics (): void;
syncAfterEvents (): void;
+28 -4
View File
@@ -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<string, RasterView> = 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) {}
+49 -4
View File
@@ -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')
+26 -24
View File
@@ -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<string>,
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,
+11 -11
View File
@@ -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
*/
+6
View File
@@ -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);
+53 -18
View File
@@ -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>(
// 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;
@@ -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])
@@ -22,9 +22,9 @@
THE SOFTWARE.
*/
import { cclegacy, toRadian, Vec2, Vec4 } from '../../../core';
import { Address, ClearFlagBit, Filter, Format } from '../../../gfx';
import { Camera } from '../../../render-scene/scene';
import { EDITOR } from 'internal:constants';
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';
import { passContext } from '../utils/pass-context';
@@ -34,6 +34,8 @@ 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';
import { Scene } from '../../../scene-graph/scene';
const vec2 = new Vec2();
@@ -177,7 +179,9 @@ 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;
private averageSceneScale = new Map<Scene, number>();
get setting () { return getSetting(HBAO); }
@@ -186,15 +190,22 @@ 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;
let enable = super.checkEnable(camera);
if (EDITOR && camera.cameraUsage === CameraUsage.PREVIEW) {
enable = false;
}
return enable;
}
constructor () {
super();
this._hbaoParams = new HBAOParams();
this.material.setProperty('RandomTex', this._hbaoParams.randomTexture, 0);
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 {
@@ -203,11 +214,15 @@ 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;
// 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);
@@ -232,7 +247,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 +262,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 +345,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}`;
@@ -342,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);
}
@@ -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;
}
+19 -5
View File
@@ -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]);
+5 -3
View File
@@ -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) {
@@ -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
@@ -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;
}
@@ -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
@@ -1,5 +1,6 @@
#include <surfaces/default-functions/common-vs>
#include <surfaces/module-functions/common-vs>
#include <common/math/number>
#include <common/lighting/functions>
out highp float v_dist;
@@ -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
@@ -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 <common-functions>
#include <surfaces/data-structures/standard>
#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 <common-functions>
#include <lighting-models/default-functions/simple-skin>
}%
+6 -4
View File
@@ -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 <macro-remapping>
#include <surfaces/effect-macros/render-to-shadowmap>
#include <surfaces/includes/common-vs>
#include <shared-ubos>
@@ -328,6 +329,7 @@ CCProgram standard-fs %{
CCProgram shadow-caster-fs %{
precision highp float;
#include <macro-remapping>
#include <surfaces/effect-macros/render-to-shadowmap>
#include <surfaces/includes/common-fs>
#include <shared-ubos>
@@ -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 <legacy/decode-standard>
#include <builtin/uniforms/cc-global>
#include <common/common-define>
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);
}
}%
@@ -0,0 +1,11 @@
{
"ver": "1.7.0",
"importer": "effect",
"imported": true,
"uuid": "5c601d96-e4c7-4698-991b-7ee674b11079",
"files": [
".json"
],
"subMetas": {},
"userData": {}
}
@@ -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);
}
float ao = texture(AOTexNearest, uv).x;
return g_AOSaturation > 1.0 ? pow(ao, g_AOSaturation) : mix(1.0, ao, g_AOSaturation);
}
+3
View File
@@ -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: {
+7
View File
@@ -1149,6 +1149,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.',
+3
View File
@@ -113,6 +113,9 @@ module.exports = {
anisotropyMapNearestFilter: '将 Anisotropy Map 贴图复制出来并选择 Nearest 过滤',
anisotropyMapResolutionHeight: 'Anisotropy Map 的分辨率高度',
ior: '相对折射率,该值可以影响折射角度和菲涅耳效果。水是1.33',
transmitThicknessWithShadowMap: '物体厚度(世界空间单位),注意!该值过小可能导致穿透光消失',
transmitExtinctionWithShadowMap: '穿透光的散射消光系数(可影响耳朵、鼻子等的背面透光强度)。该值越大则穿透光越弱、亮区范围也会更小、厚薄感变强, 反之穿透光越强越均匀、亮区更大但厚薄感变弱。有一点需要特别注意!由于是按照世界空间单位计算散射,则模型越大,该值必须相对更小才能维持同样的光照效果,或根据模型大小给一个距离缩放值在TransmitDiffuseParam中',
transmitExtinction: '薄片穿透光的散射消光系数(可影响叶片等的背面透光强度)。该值越大则穿透光越弱、亮区范围也会更小、厚薄感变强, 反之穿透光越强越均匀、亮区更大但厚薄感变弱。同时还需要指定薄片厚度',
},
},
image: {
+7
View File
@@ -1130,6 +1130,13 @@ module.exports = {
torque: '在世界坐标系中,对刚体施加的扭转力',
localTorque: '在本地坐标系中,对刚体施加的扭转力',
},
constraint: {
hinge: {
pivotA: '在自身刚体的本地坐标系中,旋转轴的锚点位置',
pivotB: '在连接刚体的本地坐标系中,旋转轴的锚点位置',
axis: '在自身刚体的本地坐标系中,旋转轴的方向',
},
},
character_controller: {
group: '碰撞分组',
minMoveDistance: '最小移动距离',
@@ -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);
});
};
@@ -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);
}
});
@@ -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');
},
},
});
@@ -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;
@@ -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');
});
},
},
+7 -3
View File
@@ -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);
});
},
},
+2 -1
View File
@@ -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) {
+144 -98
View File
@@ -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);
}
+1
View File
@@ -40,6 +40,7 @@ export {
ConstantForce,
PhysicsMaterial,
PhysicsRayResult,
PhysicsLineStripCastResult,
Collider,
BoxCollider,
+1
View File
@@ -139,6 +139,7 @@ EffectAsset *EffectAsset::get(const ccstd::string &name) {
"skybox",
"deferred-lighting",
"bloom",
"copy-pass",
"post-process",
"profiler",
"splash-screen",
+2 -10
View File
@@ -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;
}
+2
View File
@@ -426,6 +426,8 @@ ccstd::unordered_map<uint32_t, ccstd::string> 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." },
@@ -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;
@@ -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;
+5
View File
@@ -148,6 +148,11 @@ inline ccstd::vector<physx::PxRaycastHit> &getPxRaycastHitBuffer() {
return m;
}
inline ccstd::vector<physx::PxSweepHit> &getPxSweepHitBuffer() {
static ccstd::vector<physx::PxSweepHit> m{12};
return m;
}
inline QueryFilterShader &getQueryFilterShader() {
static QueryFilterShader shader;
return shader;
+107
View File
@@ -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<physx::PxU32>(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<uintptr_t>(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<RaycastResult> &PhysXWorld::sweepResult() {
static ccstd::vector<RaycastResult> 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<uintptr_t>(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++;
+16
View File
@@ -58,6 +58,22 @@ public:
bool raycastClosest(RaycastOptions &opt) override;
ccstd::vector<RaycastResult> &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<RaycastResult> &sweepResult() override;
RaycastResult &sweepClosestResult() override;
uint32_t createConvex(ConvexDesc &desc) override;
uint32_t createTrimesh(TrimeshDesc &desc) override;
uint32_t createHeightField(HeightFieldDesc &desc) override;
@@ -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<uintptr_t>(pxRigidBody->getSharedBody().getNode());
if (nodePtr) {
auto &ins = PhysXWorld::getInstance();
_mConnectedBody = ins.getSharedBody(reinterpret_cast<Node *>(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) {
@@ -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);
}
@@ -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);
}
+37
View File
@@ -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<RaycastResult> &World::sweepResult() {
return _impl->sweepResult();
}
} // namespace physics
} // namespace cc
+13
View File
@@ -48,6 +48,19 @@ public:
bool raycastClosest(RaycastOptions &opt) override;
ccstd::vector<RaycastResult> &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<RaycastResult> &sweepResult() override;
uint32_t createConvex(ConvexDesc &desc) override;
uint32_t createTrimesh(TrimeshDesc &desc) override;
uint32_t createHeightField(HeightFieldDesc &desc) override;
+12
View File
@@ -142,6 +142,18 @@ public:
virtual bool raycastClosest(RaycastOptions &opt) = 0;
virtual ccstd::vector<RaycastResult> &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<RaycastResult> &sweepResult() = 0;
virtual uint32_t createConvex(ConvexDesc &desc) = 0;
virtual uint32_t createTrimesh(TrimeshDesc &desc) = 0;
virtual uint32_t createHeightField(HeightFieldDesc &desc) = 0;
@@ -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<ccstd::string, uint32_t> phases; //cjh how to clear this global variable when exiting game?
static uint32_t phaseNum = 0;
+2
View File
@@ -557,8 +557,10 @@ const uint32_t CAMERA_DEFAULT_MASK = ~static_cast<uint32_t>(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;
@@ -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{};
}
@@ -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<MovePair> &movePairs) override;
void addCopyPass(const ccstd::vector<CopyPair> &copyPairs) 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<MovePair> &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;
@@ -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 <class Tag>
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<RasterSubpassTag>(
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<RasterSubpassTag>(
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<ComputeSubpassTag>(
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{},
@@ -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<cc::render::RasterView>(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<cc::render::ComputeView>(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);
@@ -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);
@@ -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),
@@ -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<cc::render::RasterView>::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<cc::render::ComputeView>::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);
@@ -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<MovePair> &movePairs) = 0;
virtual void addCopyPass(const ccstd::vector<CopyPair> &copyPairs) = 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<MovePair> &movePairs) = 0;
/**
* @beta function signature might change
*/
+2 -2
View File
@@ -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'
+102
View File
@@ -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();
@@ -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();
@@ -1051,7 +1051,7 @@ interface TransitionSequenceFixture {
transitions: TransitionFixture[];
}
type StateFixtureBase = { };
interface StateFixtureBase { }
type StateFixture = StateMachineEnterStateFixture | StateMachineExitStateFixture | MotionStateFixture | EmptyStateFixture;

Some files were not shown because too many files have changed in this diff Show More