stride3d / stride

Stride (formerly Xenko), a free and open-source cross-platform C# game engine.
https://stride3d.net
MIT License
6.62k stars 957 forks source link

Can't change CharacterComponent's collider shape properties #2005

Open dawnmichal opened 1 year ago

dawnmichal commented 1 year ago

Release Type: Official Release

Version: 4.1.0.1948

Platform(s): Windows

Describe the bug

Assigning a new ColliderShape into CharacterComponent in code (when game is running) and then calling CharacterComponent.ComposeShape(); causes the application to crash.

To Reproduce

  1. Create basic character with CharacterComponent.
  2. Assign capsule collider shape using Stride Studio.
  3. Assign script which perform this code (ex. when key is pressed)

characterComponent.ColliderShapes[0] = new CapsuleColliderShapeDesc() { Length = 0.6f, LocalOffset = new Vector3(0.0f, 0.70f, 0.0f), Orientation = ShapeOrientation.UpY, Radius = 0.4f };

characterPhysics.ComposeShape();

  1. This will caus the application to crash.

Expected behavior CharacterComponent starts to use new collider shape with new property values...

Log and callstacks

Additional context

I imagine we don't properly remove some reference after the dispose frees the native handle to the bullet collider and we still attempt to use it afterwards which is what causes the crash.

manio143 commented 1 year ago

More context - in the CharacterComponent.OnAttach we create a new instance of PairCachingGhostObject from BulletSharp which is used to instantiate KinematicCharacterController from BulletSharp. We provide it a handle to the collider shape. https://github.com/stride3d/stride/blob/e200843806af650ad45595f87a78374712ecaeea/sources/engine/Stride.Physics/Elements/CharacterComponent.cs#L267-L271 When you call ComposeShape we dispose of that internal handle and cause Bullet to try to "use after free" because it's holding a disposed reference to a native object.

Potential fix - make ComposeShape virtual and add reconstruction of the character controller in the component.

Potential workaround in the meantime - remove entity with character component from the scene, call ComposeShape, re-add to the scene. This will cause the correct disposal and instantiation of the character controller.

dloe commented 2 months ago

Hi! If possible could I work on this issue? I wanted to double check first in case it was recommended to work elsewhere with the ongoing Bepu Physics integration.

Eideren commented 2 months ago

Sure, if you want to do so, go ahead !