RFC: Adopt Unity-style Collider components and hierarchical Rigidbody ownership
I maintainer di solito rispondono entro 1 giorno
Valutazione
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Idoneità per principianti
- 20/100
- Tipo di issue
- Funzionalità
- Chiarezza
- Abbastanza chiara
- Stato di attività
- Attiva
- Stack tecnologico
- typescript
- Ambito
- game-dev
Direzione di ricerca
Read the existing physics component and native lifecycle implementation, beginning with the current DynamicCollider, StaticCollider, ColliderShape, and MeshColliderShape paths, and inspect issue #3021 for the lifecycle root cause. The RFC defines the target ownership, transform, collision, migration, and rollback behavior, but spans engine, Editor, CLI/editor-api, Builder, Viewport, schemas, and documentation. Done means the coordinated migration and source migration satisfy the listed invariants and direct lifecycle and transform tests.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
RFC: Adopt Unity-style Collider components and hierarchical Rigidbody ownership
Summary
Adopt Unity's public physics object model for Galacean 2.0:
BoxCollider,SphereCollider,CapsuleCollider,MeshCollider, andPlaneColliderare Components.RigidbodyreplacesDynamicCollider.- A Collider without an attached Rigidbody is static; remove
StaticCollider. - A Rigidbody owns Colliders on its own Entity and descendant Entities, stopping at a nested Rigidbody.
- Remove the public
ColliderShapeobject model and theaddShape/removeShape/clearShapesAPI.
This is a deliberate breaking change. Do not keep a second public Shape API or compatibility wrappers after migration.
The goal is Unity-compatible ownership and call structure, not mechanically renaming every member or deleting useful Galacean extensions. Infinite planes, per-Collider local rotation, mesh cooking flags, CharacterController Box geometry, and separate render/physics layers remain supported.
Costs and expected benefits
Costs
- Every existing physics scene, prefab, script, Editor tool, and physics learning document must migrate.
- The runtime implementation is not necessarily smaller. Hierarchical Rigidbody ownership, static/dynamic transitions, transform synchronization, and transactional native-shape migration add lifecycle work.
- Engine, Editor, CLI/editor-api, Builder, Viewport, and generated tool schemas need coordinated changes.
- The current PhysX collision-layer assignment is actor-level, while Unity-style compound Colliders need well-defined per-Collider filtering. The backend mapping must change or the proposed semantics cannot be delivered.
- Existing projects cannot silently keep using
ColliderShapeserialized data. A versioned source migration is required.
Benefits
- Users can apply the familiar Unity model: geometry is a Component; adding a Rigidbody makes the hierarchy dynamic; omitting it makes Colliders static.
- Compound bodies use the Entity hierarchy rather than a second Shape-list ownership model.
- A Collider has an Entity and Engine, so material ownership no longer needs an Engine parameter at the Shape-instancing call site.
- Queries and callbacks can expose Colliders and Components directly instead of engine-owned Shape data objects.
- Native creation after final transforms, hierarchical ownership, and clone/prefab behavior can be designed together instead of patching them independently.
Alternatives considered
A. Keep Collider + ColliderShape and add Unity-like conveniences
This is smaller, but leaves the central mental-model difference unchanged. It also leaves Shape ownership, Shape-typed callbacks, and Shape-list serialization in place. Adding collider aliases beside shape would only create two names for the same fact.
C. Make Shapes Components but retain StaticCollider / DynamicCollider Shape lists
Rejected: the set of Colliders belonging to a body would then be recorded both by the hierarchy and by the Shape list. Those owners would inevitably diverge.
B. Adopt component Colliders and hierarchical Rigidbody ownership
Selected. The hierarchy is the single public source of body membership; native actor/shape ownership is derived from it.
Caller-facing example
Current API:
const body = entity.addComponent(DynamicCollider);
const box = new BoxColliderShape();
box.size.set(1, 2, 1);
box.material = new PhysicsMaterial(engine);
body.addShape(box);
Proposed API:
const body = entity.addComponent(Rigidbody);
const box = entity.addComponent(BoxCollider);
box.size.set(1, 2, 1);
box.material = new PhysicsMaterial(engine);
Hierarchical compound body:
const vehicle = scene.getRootEntity().createChild("vehicle");
vehicle.addComponent(Rigidbody);
vehicle.addComponent(BoxCollider);
const wheel = vehicle.createChild("wheel");
wheel.transform.setPosition(0, -0.4, 0.8);
wheel.addComponent(SphereCollider); // Attached to vehicle's Rigidbody.
Static geometry:
const ground = scene.getRootEntity().createChild("ground");
ground.addComponent(BoxCollider); // No Rigidbody in its ownership chain: static.
Public API mapping
| Current | Proposed |
|---|---|
DynamicCollider |
Rigidbody |
DynamicColliderConstraints |
RigidbodyConstraints |
StaticCollider |
Removed; a Collider without a Rigidbody is static |
ColliderShape |
Removed as a public data-object hierarchy |
BoxColliderShape |
BoxCollider Component |
SphereColliderShape |
SphereCollider Component |
CapsuleColliderShape |
CapsuleCollider Component |
MeshColliderShape |
MeshCollider Component |
PlaneColliderShape |
PlaneCollider Component (Galacean extension) |
collider.shapes |
Removed; body membership is derived from the Entity hierarchy |
addShape / removeShape / clearShapes |
Add/remove/enable/disable Collider components |
shape.position |
collider.center |
shape.rotation |
Preserve local Collider rotation as a Galacean extension |
shape.isConvex |
meshCollider.convex |
capsuleShape.upAxis |
capsuleCollider.direction |
shape.getInstanceMaterial(engine) |
collider.getInstanceMaterial() |
joint.connectedCollider |
`joint.connectedBody: Rigidbody |
onTriggerEnter(other: ColliderShape) |
onTriggerEnter(other: Collider, self: Collider) (same for Stay/Exit) |
Collision.shape |
Collision.collider, plus Collision.selfCollider for the receiving side |
HitResult.shape |
HitResult.collider |
overlap*All(): ColliderShape[] |
overlap*All(): Collider[] |
PhysicsMaterial remains an Engine-owned ReferResource. Keep explicit material instancing rather than Unity's hidden clone-on-read behavior. This also stays consistent with Galacean Renderer material instancing.
Existing Rigidbody properties such as linearVelocity, linearDamping, mass, center of mass, inertia, constraints, sleep, gravity, and collision-detection mode move with the rename. ForceMode, interpolation, trigger filtering, and other missing Unity features are separate follow-up contracts, not prerequisites for this object-model migration.
Ownership invariants
Rigidbody
- Owns the native dynamic/kinematic actor and all body-level properties.
- At most one Rigidbody is allowed per Entity; Engine component creation enforces this rather than relying only on Editor validation.
- Owns Colliders on its Entity and descendant Entities, stopping at the nearest nested Rigidbody.
- Has no public Shape list. Its internal native registration set is derived from active Collider components and is not an alternate authoring model.
- A Rigidbody added to an existing static hierarchy claims its Colliders. Removing the Rigidbody component makes those Colliders static.
- Disabling a Rigidbody disables its whole native body and attached Colliders; it must not reactivate them as static geometry. Removing and disabling are deliberately different operations.
- Nested Rigidbodies own their own subtrees even while disabled; a disabled nested Rigidbody must not let its Colliders fall through to an ancestor body.
Collider
- Is a Component with an Entity, Scene, and Engine.
- Owns its geometry/properties, native shape, and PhysicsMaterial reference.
- Exposes
attachedRigidbody: Rigidbody | nullas derived state; callers cannot set it directly. This ownership relation is structural and does not change when either component is disabled. - With no attached Rigidbody, owns a static native actor and its world pose while enabled in the Scene.
- A disabled Collider is excluded from native simulation and queries but retains its structural Rigidbody owner.
- Creating, removing, enabling, disabling, cloning, or reparenting components updates native registration through one reconciliation path.
PhysicsScene and native lifecycle
- JavaScript component fields are the source of truth while native objects are absent.
- Native actors/shapes are created only after the final Entity transform is available in scene lifecycle, never in component constructors.
- A batch of hierarchy/component changes resolves ownership once before simulation. Avoid transient static actors merely because component enable order put a Collider before its Rigidbody.
- Moving a native shape between static and dynamic actors is transactional from the public API. Failure restores the previous native registration and public owner state.
- Preserve the existing MeshColliderShape cooking/replacement transaction and trigger-registration continuity. Do not replace it with remove-then-add compensation.
- Disabling or leaving a Scene detaches native state without losing the authored JS fields or material references.
- Enabling a Rigidbody never silently enables an individually disabled Collider, and disabling a Rigidbody never changes the stored enabled flags of its Colliders.
This RFC explicitly includes the lifecycle root cause in #3021. If #3021 is fixed independently first, this migration must build on that lifecycle rather than reintroducing constructor-time native creation.
Collision and trigger identity
Collision.collideridentifies the other Collider;Collision.selfCollideridentifies the receiving Collider and also determines contact-normal/impulse orientation.- Trigger Enter/Stay/Exit receive
(other, self)so a Script on an Entity with multiple Colliders can distinguish the receiving geometry. Existing functions that only declare the first parameter remain valid JavaScript/TypeScript overrides. - Dispatch initially targets Scripts on each participating Collider's Entity. Do not also synthesize a second Rigidbody-event channel in this migration.
- If Rigidbody-level callback aggregation is added later, it must reuse this pair identity and deduplicate delivery rather than introduce a parallel event contract.
Transform rules
- A Rigidbody actor's world pose comes only from the Rigidbody Entity's Transform.
- An attached Collider's local native pose is derived from its Entity transform relative to the Rigidbody Entity, plus its authored center and local rotation.
- Moving a child Collider Entity does not move the parent Rigidbody actor; it changes that Collider's local pose.
- Dynamic simulation writes the actor pose back to the Rigidbody Entity. Attached child Entities follow through normal hierarchy transforms.
- A static Collider's native world pose follows its own Entity Transform.
- Same-Entity scale behavior must remain compatible. Hierarchical shape scale follows the existing absolute-value world-scale rule rather than introducing a second scale representation.
- A local native pose is TRS, not an arbitrary matrix. Shear produced by rotated, non-uniformly scaled ancestors is unsupported and must be documented and tested as such; do not add a parallel matrix/shear physics model or silently promise exact Unity behavior.
Matrix.decomposeis not a shear validator: it can return true while producing a different matrix, so rejection requires an explicit basis-orthogonality check.
These rules need direct tests for parent/child translation, rotation, scale, reparenting, and Rigidbody add/remove transitions.
Non-convex MeshCollider and PlaneCollider constraints
PhysX does not support triangle meshes (MeshCollider with convex = false) or infinite planes (PlaneCollider) on non-kinematic dynamic bodies. This rule must survive every new ownership path, split by operation kind:
-
Property setters (reject in place):
- setting
meshCollider.convex = falsewhile attached to a non-kinematic Rigidbody; - setting
rigidbody.isKinematic = falsewhile owning a non-convexMeshCollideror aPlaneCollider.
Reject the attempted setter before committing its JS/native state and log an error, leaving the previousconvex/isKinematicvalue, geometry, and native registration intact.
- setting
-
Component/hierarchy composition (exclude from simulation and queries):
- adding a non-kinematic
Rigidbodyto a hierarchy containing a non-convexMeshColliderorPlaneCollider; - adding a non-convex
MeshColliderorPlaneColliderunder a non-kinematicRigidbody; - reparenting a non-convex
MeshColliderorPlaneColliderunder a non-kinematicRigidbody.
Adding components and reparenting Entities cannot be rejected without making SceneGraph and Prefab/serialization order-dependent. Instead, keep the component and hierarchy ownership (attachedRigidbody), log an error once for that owner, and exclude the incompatible Collider from native simulation and scene queries until the Rigidbody becomes kinematic,convexbecomestrue, or ownership leaves that Rigidbody.
- adding a non-kinematic
Collision-layer ownership
Keep physics layers separate from Entity.layer, which is also used by rendering.
Collider.collisionLayer remains a single-layer value owned by each Collider. Child Colliders under one Rigidbody may therefore have different physics layers, matching the component-level authoring model.
The current PhysX backend calls setGroup on the actor, and also accepts a layer when attaching a Shape. Multiple Colliders must not independently overwrite one actor-level value.
The native prototype proved that attachShapeWithLayer already supports independent per-Shape query filtering and collision-matrix behavior on one actor. Runtime layer changes are different:
- the existing
setGroupbinding acceptsPxActor, notPxShape; - detaching and immediately reattaching a Shape with another layer updates queries, but repeats both
TriggerEnterandCollisionEnterfor an already-active pair; - filtering duplicate Trigger events alone is insufficient because Collision events have no equivalent active-pair owner, and adding a parallel JS contact table just to make reattachment appear safe is rejected.
Therefore the final implementation needs a Shape-level native filter update in physX.js (or an equivalent in-place native API), then must prove:
- two Colliders on one Rigidbody can use different layers;
- layer changes update only the intended Collider without repeated Enter/Exit events;
- static/dynamic migration preserves the Collider's layer;
- the existing
PhysicsScene.setColliderLayerCollisionmatrix keeps its semantics.
If per-Collider layers cannot be preserved, that is a public-contract exception requiring an explicit RFC decision, not an implementation-time fallback to last-writer-wins actor state.
Materials
Collider.materialretains an assigned shared material until replaced or the Collider is destroyed.- Assignment validates that the material belongs to
collider.entity.engine. collider.getInstanceMaterial()derives the Engine from the Entity, clones the shared material once, and reuses that instance until material is reset or replaced.- Collider cloning and prefab instantiation retain shared material references through the existing resource-reference owner.
- The backend-wide native default introduced in #3188 can remain an internal default; this RFC does not require another public default-material asset.
PR #3188 is therefore useful independently of this RFC. The later object-model change removes the now-unnecessary Engine argument instead of reverting material resource ownership.
CharacterController
CharacterController remains outside Rigidbody ownership and continues to own its controller actor.
Decision: Capsule is the default geometry, and the existing Box capability remains as an inline Galacean extension. The controller owns its geometry-kind choice and corresponding dimensions directly; there is no public Shape object or Shape list.
This preserves the useful Unity contract without mischaracterizing capsule-only as a technical requirement:
- Unity's Character Controller documentation presents a capsule for specialized first/third-person movement, wall sliding, stairs, and slopes, but does not give a technical reason for excluding Box.
- NVIDIA's PhysX Character Controllers guide supports both AABB/Box and Capsule controllers. It recommends Capsule as the default because its rounded bottom behaves better over small obstacles and stairs.
- The same PhysX guide states that auto-stepping was originally intended for Box controllers, whose sharp corners are more easily blocked by slight elevations. Box also has fixed orientation and independent horizontal extents, which are useful for non-humanoid or asymmetric characters.
Removing the existing Box capability would therefore be an API-narrowing compatibility decision, not a technical correction. Preserve it without reintroducing a second geometry-owner model.
Editor and serialized-data migration
Editor source-v2 currently stores Collider geometry inside a Collider component's Shape list, with $type objects and stable shapeId identity. The public tools also expose collider.addShape and colliderShape.update with componentId + shapeId.
The source migration must:
- Replace
DynamicColliderwithRigidbody, preserving all body properties. - Convert every
StaticCollider/ old body Shape entry into a geometry Collider component on the same Entity. - Preserve geometry, center/local rotation, trigger/query flags, contact offset, material reference, and collision layer.
- Preserve enabled state: old
StaticCollider.enabledapplies to every generated geometry Collider; oldDynamicCollider.enabledapplies to the generated Rigidbody and keeps the whole body disabled rather than converting it to active static Colliders. - Migrate each persistent
shapeIdto the new Collider component's persistentcomponentIdidentity. - Rewrite Prefab overrides, added/removed component records, references, and nested-instance data that target the old Shape identity. Array indices are not stable identities and must not be used for this mapping.
- Remove the old
StaticCollidercomponent after its Shapes have been materialized as components. - Migrate the existing single Box/Capsule CharacterController Shape into the controller's inline geometry choice, preserving its kind, dimensions, and local pose.
Use a versioned, deterministic source migration at the source-data boundary. Do not add a permanent runtime deserializer for both public object models.
Editor/UI/tooling changes include:
- Inspector: add/remove/configure Collider components instead of editing a nested Shape list.
- Component constraints: allow multiple geometry Colliders, at most one Rigidbody per Entity, and enforce Joint -> Rigidbody dependencies.
- Viewport wireframes/gizmos: bind to Collider components and hierarchical ownership.
- editor-api and CLI: replace Shape-specific tools with normal component create/read/update/remove tools and schemas.
- Builder/runtime scene generation: emit the new component model only.
- Agent skills, examples, tests, and documentation: use the new public entry points, not compatibility examples.
Proposed rollout
- Prototype the invariants without shipping a parallel API. Prove hierarchical ownership, static/dynamic transitions, per-Collider filtering, final-transform native creation, and transactional rollback in an isolated Engine branch.
- Land lifecycle prerequisites where useful. #3021 may be fixed independently. #3188 remains independent and should continue through its own review.
- Engine breaking change. Change core/design/physics-physx, serialization contracts, tests, declarations, and migration documentation together. Remove the old public Shape API in the same contract change.
- Editor source migration and UI. Land source-v2 migration, Prefab identity migration, Inspector, Viewport, and model projection against the new Engine contract.
- CLI/editor-api/Builder and downstream validation. Migrate public tools, generated schemas, package consumers, examples, E2E, and skills. Remove superseded Shape-specific tests rather than maintaining duplicate coverage.
- Follow-up feature parity. ForceMode, interpolation, trigger query filters,
IgnoreCollision, collision relative velocity/impulse, and controller grounding are independently reviewable additions. HingeJoint's currentuseSpringsoft-limit semantics versus Unity's target-angle spring must be fixed as its own documented behavior change.
An eval measuring how often Unity-familiar users or agents incorrectly assume component Colliders would be useful evidence, but the object-model decision is no longer blocked on running that eval.
Native prototype evidence
Branch feat/unity-physics-prototype, commit 7d607ef7e, adds tests/src/core/physics/UnityPhysicsPrototype.test.ts without changing production code.
Observed in the real Chromium/PhysX runtime:
- independent per-Shape layers on one actor work for both queries and the collision matrix;
- the actor-only
setGroupbinding rejects aPxShape; - detach/reattach layer changes repeat TriggerEnter and CollisionEnter, so that candidate is rejected;
- after a mocked target-actor attach rejection, reattaching to the source actor restores the Shape and its query result; the final public owner still needs to implement this transaction;
- hierarchical TRS round-trips correctly, while a three-level non-uniform-scale/rotation hierarchy produces genuine shear that
Matrix.decomposeaccepts with a nonzero reconstruction error; - cloned colliders synchronize to their final non-origin transforms, with no stale Shape at the origin.
The prototype suite passed 8/8 and the full physics directory passed 16 files / 469 tests. These are native-mechanism results, not proof of the final component API, scene-lifecycle reconciliation, physX.js runtime update, or Editor migration. The shear fixture was corrected to recompute the current inverse and use a three-level hierarchy before the final run.
Acceptance matrix
Engine behavior tests must enter through public APIs and cover at least:
- same-Entity multiple Colliders and parent/child compound bodies;
- nested Rigidbody ownership boundaries;
- adding/removing Rigidbody on an existing static hierarchy;
- adding/removing/enabling/disabling Collider and Rigidbody components, including proof that a disabled Rigidbody does not produce active static Colliders or fall through to an ancestor body;
- reparenting, activation/deactivation, Scene changes, and destruction;
- clone and Prefab instantiation at non-origin transforms, including external material references;
- static/dynamic migration preserving world pose, local pose, layer, material, enabled state, and native registration;
- non-convex
MeshColliderandPlaneColliderenforcement across every path listed above: in-place setter rejection (convex = false,isKinematic = false) with unchanged JS/native state, and simulation/query exclusion on composition/reparenting with automatic re-inclusion once kinematic or detached; - same-Entity scale compatibility and explicitly unsupported hierarchical shear cases;
- rollback after native attach failure and Mesh cooking/replacement failure;
- per-Collider layers on one Rigidbody and layer changes after migration;
- callbacks and raycast/overlap results exposing the correct Collider, including child Colliders;
- self/other Collider identity and contact orientation when one Entity has multiple Colliders, with no duplicate or stale delivery;
- material reference counts and GC across Collider replacement, clone, disable, destroy, and Engine teardown.
Editor acceptance must additionally cover source migration, Prefab override identity, nested Prefabs, undo/redo, Inspector CRUD, Viewport rendering, CLI create/read/update/remove, build output, and reload. Browser E2E should use the standard UI/tool drivers and observable state, not direct internal method invocation.
Non-goals
- Exact Unity naming for every member or automatic Unity script compatibility.
- Merging render and physics layers.
- Replacing PhysX or changing fixed-step policy (#3012 is separate).
- Wheel/Terrain colliders, CharacterJoint/ConfigurableJoint, or full Unity feature parity in this migration.
- Permanent aliases or wrappers for
ColliderShape,StaticCollider, orDynamicCollider. - Hidden material cloning or a second default-material lifecycle.
Evidence in current code
The current model and migration surface were checked against Engine PR #3188 head 5f76e3cb4 and Editor dev/2.0:
packages/core/src/physics/Collider.ts: public Shape list and actor-levelcollisionLayer.packages/core/src/physics/DynamicCollider.ts: body properties and constructor-created native actor.packages/core/src/physics/shape/: parameterless geometry objects with no Entity owner.packages/core/src/physics/PhysicsScene.ts: Shape-typed query results and event dispatch.packages/physics-physx/src/PhysXCollider.ts: actorsetGroupand per-Shape attach layer.- Editor
packages/model/src/headless/collider-shape.ts: persistentshapeIdauthoring identity. - Editor
packages/editor-api/src/tools/component/: Shape-specific public tool contracts and source-v2 serialization tests. - Editor
plugins/main/src/components/physics/: Inspector/projection ownership.
Related: #3021 (native creation after final transforms), #3012 (independent fixed-step policy), and PR #3188 (Engine-owned physics materials).
- Lingua principale
- TypeScript
- Stelle
- 5.9k
- Fork
- 413
- Merge medio
- 16h 17m
- PR unite (30g)
- 41
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Nessuna guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di galacean/engine
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 64/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 85/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 4/5 3-5 giorni Idoneità per principianti 52/100
I maintainer di solito rispondono entro 1 giorno
-
SkinnedMeshRenderer should derive default rootBone-space localBounds from mesh and skinForse già presa Una pull request collegata a questa issue è aperta o già unita. Apertaenhancement
Difficoltà 4/5 3-5 giorni Idoneità per principianti 42/100
I maintainer di solito rispondono entro 1 giorno
-
performance
Difficoltà 5/5 Più di una settimana Idoneità per principianti 25/100
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di galacean/engine
Issue simili
-
bug impact:low Team: SecuritySolution Team:Defend Workflows v9.6.0
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
elastic/kibana#306401 · 3 commenti ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
agentes-chat/agentes-chat#927 ·
I maintainer di solito rispondono entro 1 giorno
-
[Bug]: Webapp workspace fails to render in Safari — "Can't find variable: requestIdleCallback"Apertacomp/desktop P2 type/bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
NousResearch/hermes-agent#157702 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
I maintainer di solito rispondono entro 1 giorno
-
e2e-failure ready-to-code
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 72/100
redhat-developer/rhdh-plugin-export-overlays#4794 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno