Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Official Unity Physics Discussion

Discussion in 'Physics for ECS' started by smcclelland, Mar 18, 2019.

Thread Status:
Not open for further replies.
  1. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    Add a PhysicsDebugDisplay to your scene and tick Draw Colliders so you can see how the points you pass to Create work. They are the endpoint sphere positions relative to the RigidBody position. It will be obvious once you visualize it how it works.
     
  2. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    So the visual debugger quickly became less then useful.

    You see from this pic the problem. That's the terrain collider, and it's rendering over everything including other colliders that should be in front.

    I thought I remembered 0.1.0 the colliders being transparent, I know I was debugging the terrain and it wasn't rendering over everything like it is now in 0.2.0. Or maybe it's some interaction with something else in the scene I can't think of.

    upload_2019-8-1_14-2-23.png
     
  3. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    I'm wondering if the physics team understands why the dependencies are problematic the way they are. The only way they work right now will limit the amount of time your own jobs have to run.
    So we added some dynamic bodies to our system so I did a bit of a refactor and have some more feedback.

    The dynamic bodies, structures, and terrain are now using default paths not custom static worlds.

    For dynamic bodies I wanted first order control, kinematic physics. So I'm using dynamic bodies but I disable StepPhysicsWorld and just move stuff via the Translation component. Not ideal but seems to work.

    Vegetation is still in a custom static world. I didn't see a straight forward way to associate our own unique id's to collider keys when looking at making this into a single compound. Another issue here is the sync point and just the time it takes to load a huge collider (which I don't know what that is yet) using the default flow. Our flow has this entire flow off the main thread. But I'm interested in at least testing it if there is a relatively straight forward way to associate our id's with collider keys.
     
  4. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    Still having issues with dependencies. The pic shows system order, my systems are in GameLogicGroup. In that group a couple are adding handles to EndFramePhysicsSystem.HandlesToWaitFor.


    In BuildPhysicsWorld.OnUpdate the first thing is to combine the EndFramePhysicsSystem.FinalJobHandle. If I call Complete on the line above all is good, if I don't it complains that handles I've added to EndFramePhysicsSystem.HandlesToWaitFor need to be completed. Specifically it's saying I'm reading from .Broadphase.m_DynamicTree.Nodes which I am.



    upload_2019-8-2_3-13-7.png
     
  5. voidwave

    voidwave

    Joined:
    Jul 16, 2012
    Posts:
    6
    i turned on the debug display, it showed me exactly what i thought. changing the center point of sphere and capsule colliders from zero makes them ignore static colliders. i just changed the pivot of the unit meshes to fix it for now.
     
  6. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    I'm trying to figure out why I'm seeing surface normals that seem to be impossible when using both distance and collider casts against mesh colliders. The source collider is a capsule, I'm testing with it on a character controller with a cast distance of 0.01.

    What I'm seeing is when I'm near an edge in the mesh collider where it hits two surfaces, one of the hit normals is often off by a large amount. Like where it should be around 20 degrees from up it's over 80. If I move the controller to where it's only picking up one of the two edges, the normals are what I would expect.

    This also happens on flat surfaces, I have a ramp I was testing against that the debugger showed a single diagonal edge on the ramp incline, and positioning the character to the cast's returned two hits and one of the normals is correct and the other is way off.

    Since it always returns one that is good it's not a blocker really, but I'm curious what might be causing this.
     
  7. Spy-Shifty

    Spy-Shifty

    Joined:
    May 5, 2011
    Posts:
    546
    Sry for the late answer. Yes this works well.
    But it's a little bit unhandy (Boilerplate code)

    Anyway thx
     
  8. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    Not just for physics but generally so you can order your stuff easily against built in systems, I highly suggest putting your own systems in their own groups, ie not just sticking them in the simulation group for example, but put your group into the simulation group.

    The following will optimize so your jobs have as much time as possible to run while correctly dealing with shared dependencies added to HandlesToWaitFor.

    Code (csharp):
    1.  
    2. [UpdateInGroup(typeof(SimulationSystemGroup))]
    3.     [UpdateAfter(typeof(Unity.Physics.Systems.BuildPhysicsWorld))]
    4.     [UpdateAfter(typeof(Unity.Physics.Systems.ExportPhysicsWorld))]
    5.     [UpdateBefore(typeof(Unity.Physics.Systems.EndFramePhysicsSystem))]
    6.     public class GameLogicGroup : ComponentSystemGroup
    7.     {
    8.     }
    9.  
    10. [UpdateInGroup(typeof(SimulationSystemGroup))]
    11.     [UpdateBefore(typeof(BuildPhysicsWorld))]
    12.     public class CompletePhysicsWorldSystem : ComponentSystem
    13.     {
    14.         private EndFramePhysicsSystem EndFramePhysicsSystem;
    15.  
    16.         protected override void OnCreate()
    17.         {
    18.             base.OnCreate();
    19.  
    20.             EndFramePhysicsSystem = World.GetOrCreateSystem<EndFramePhysicsSystem>();
    21.         }
    22.  
    23.         protected override void OnUpdate()
    24.         {
    25.             EndFramePhysicsSystem.FinalJobHandle.Complete();
    26.         }
    27.     }
    28.  
     
    Spy-Shifty likes this.
  9. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,753
    A couple of things.

    1. Any chance we can get an UpdateBefore(typeof(ConvertGameObjectToEntitySystem)) on the Authoring systems?
    It'd be nice in our own conversion scripts if we could check if a collider has been added to the entity. (I actually want to conditionally toggle a couple of layers in my conversion script depending on the state of other components during initialization.)


    -edit-

    Further discussion has made me decide to that there is an alternate way I can achieve this.

    2. Use LocalToWorld instead of Translation/Rotation for static entities
    I'm pretty sure it's been mentioned before but it's a bit annoying Translation/Rotation are added back to entities that have been static optimized. It causes the Transform system to do a lot more updating and therefore also breaks all of my chunk checks

    chunk.DidChange(this.LocalToWorldType, this.LastSystemVersion)

    That I use to early exit.

     
    Last edited: Aug 5, 2019
  10. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    4,223
    What's preventing you from doing this? The conversion systems use the same sorting and grouping system as normal systems. The groups can be found in GameObjectConversionUtility.cs right at the top.

    It has been mentioned a few times, and it was fixed with the release of Entities 0.1.0 which added change checks in the transform systems. Is this somehow breaking for you?
     
  11. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,753
    I don't want to edit the package, especially because I'm trying to write assets for others.

    I did not realize they had fixed the performance issues. to be honest i had not looked in a while and just tacked this on because i was making a post already about ordering.

    -edit-

    just to explain the first one more, this is specifically what i want to be able to do in Convert

    Code (CSharp):
    1.                         var physicsCollider = dstManager.GetComponentData<Unity.Physics.PhysicsCollider>(entity);
    2.  
    3.                         // if it's added all good we can just set the values
    4.                         var filter = physicsCollider.Value.Value.Filter;
    5.  
    6.                         if (installer.IsDynamic && observersLayerBit > 0)
    7.                         {
    8.                             if (this.isObserver)
    9.                             {
    10.                                 filter.BelongsTo |= 1u << observersLayerBit;
    11.                             }
    12.                             else
    13.                             {
    14.                                 filter.BelongsTo &= ~(1u << observersLayerBit);
    15.                             }
    16.                         }
    17.  
    18.                         if (this.isObstruction && collisionLayerBit > 0)
    19.                         {
    20.                             filter.BelongsTo |= 1u << collisionLayerBit;
    21.                         }
    22.  
    23.                         physicsCollider.Value.Value.Filter = filter;
    I'm solving it by writing an extra authoring system that runs after physics and checks for my component, but just be nice to avoid this extra overhead.

    Actually thinking about it, moving the whole conversion to it's own authoring system might make more sense for me anyway.
     
    Last edited: Aug 5, 2019
  12. Jawsarn

    Jawsarn

    Joined:
    Jan 12, 2017
    Posts:
    245
    I'm trying to spawn in the colliders of a dynamic body deferred. Having a GO parent with PhysicsBody and GO child with shape works if it's converted in the scene from start, and it seems the collider is put on the parent entitiy. But if I convert them seperately and set the parent in runtime, it seems the collider stays at the child entity and it doesn't work as expected. (doesn't collide and stuff) Anyone knows how to solve this?
     
  13. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    4,223
    Oh. I see, ConvertGameObjectToEntitySystem is not public. That's kinda dumb. But do GameObjectBeforeConversionGroup or GameObjectAfterConversionGroup not run your custom GameObjectConversionSystem when you need it?
     
  14. kstothert

    kstothert

    Joined:
    Dec 8, 2016
    Posts:
    68
    could anyone point me to an example of basic collision and trigger event detection examples (equivalent to OnCollisionEnter, exit, stay)
     
  15. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,754
    Have you seen Unity EXS samples/examples on film hub? Along więcej h hello cube, there is folder with physics samples project.
     
  16. kstothert

    kstothert

    Joined:
    Dec 8, 2016
    Posts:
    68
    yea I've seen the samples/examples. I have not found anything in there that resembles collision events like enter, exit, and stay
     
  17. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,754
    I am sure I have seen some. But I am on mobile atm, so unable to confirm/check effectively. Sorry.
     
  18. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,754
    Just as an example, I haven't study it however:
    https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/c50af1872c992c740b437c187d88054468799fd1/UnityPhysicsSamples/Assets/Demos/2. Setup/2d. Events/Scripts/CollisionEventImpulseBehaviour.cs
    Code (CSharp):
    1. // This system applies an impulse to any dynamic that collides with a Repulsor.
    2. // A Repulsor is defined by a PhysicsShape with the `Raise Collision Events` flag ticked and a
    3. // CollisionEventImpulse behaviour added.
    Code (CSharp):
    1.  
    2. using Unity.Physics;
    3. using Unity.Physics.Systems;
    4. using Unity.Collections;
    5. using Unity.Entities;
    6. using Unity.Jobs;
    7. using UnityEngine;
    8. using Collider = Unity.Physics.Collider;
    9. using Unity.Transforms;
    10. using Unity.Profiling;
    11. using Unity.Burst;
    12. using System;
    13. using UnityEditor;
    14. using Unity.Collections.LowLevel.Unsafe;
    15. using Unity.Mathematics;
    16. public struct CollisionEventImpulse : IComponentData
    17. {
    18. public float3 Impulse;
    19. }
    20. public class CollisionEventImpulseBehaviour : MonoBehaviour, IConvertGameObjectToEntity
    21. {
    22. public float Magnitude = 1.0f;
    23. public float3 Direction = math.up();
    24. void OnEnable() { }
    25. void IConvertGameObjectToEntity.Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    26. {
    27. if (enabled)
    28. {
    29. dstManager.AddComponentData(entity, new CollisionEventImpulse()
    30. {
    31. Impulse = Magnitude * Direction,
    32. });
    33. }
    34. }
    35. }
    36. // This system applies an impulse to any dynamic that collides with a Repulsor.
    37. // A Repulsor is defined by a PhysicsShape with the `Raise Collision Events` flag ticked and a
    38. // CollisionEventImpulse behaviour added.
    39. [UpdateAfter(typeof(EndFramePhysicsSystem))]
    40. unsafe public class CollisionEventImpulseSystem : JobComponentSystem
    41. {
    42. BuildPhysicsWorld m_BuildPhysicsWorldSystem;
    43. StepPhysicsWorld m_StepPhysicsWorldSystem;
    44. EntityQuery ImpulseGroup;
    45. protected override void OnCreate()
    46. {
    47. m_BuildPhysicsWorldSystem = World.GetOrCreateSystem<BuildPhysicsWorld>();
    48. m_StepPhysicsWorldSystem = World.GetOrCreateSystem<StepPhysicsWorld>();
    49. ImpulseGroup = GetEntityQuery(new EntityQueryDesc
    50. {
    51. All = new ComponentType[] { typeof(CollisionEventImpulse), }
    52. });
    53. }
    54. [BurstCompile]
    55. struct CollisionEventImpulseJob : ICollisionEventsJob
    56. {
    57. [ReadOnly] public ComponentDataFromEntity<CollisionEventImpulse> ColliderEventImpulseGroup;
    58. public ComponentDataFromEntity<PhysicsVelocity> PhysicsVelocityGroup;
    59. public void Execute(CollisionEvent collisionEvent)
    60. {
    61. Entity entityA = collisionEvent.Entities.EntityA;
    62. Entity entityB = collisionEvent.Entities.EntityB;
    63. bool isBodyADynamic = PhysicsVelocityGroup.Exists(entityA);
    64. bool isBodyBDynamic = PhysicsVelocityGroup.Exists(entityB);
    65. bool isBodyARepulser = ColliderEventImpulseGroup.Exists(entityA);
    66. bool isBodyBRepulser = ColliderEventImpulseGroup.Exists(entityB);
    67. if(isBodyARepulser && isBodyBDynamic)
    68. {
    69. var impulseComponent = ColliderEventImpulseGroup[entityA];
    70. var velocityComponent = PhysicsVelocityGroup[entityB];
    71. velocityComponent.Linear = impulseComponent.Impulse;
    72. PhysicsVelocityGroup[entityB] = velocityComponent;
    73. }
    74. if (isBodyBRepulser && isBodyADynamic)
    75. {
    76. var impulseComponent = ColliderEventImpulseGroup[entityB];
    77. var velocityComponent = PhysicsVelocityGroup[entityA];
    78. velocityComponent.Linear = impulseComponent.Impulse;
    79. PhysicsVelocityGroup[entityA] = velocityComponent;
    80. }
    81. }
    82. }
    83. protected override JobHandle OnUpdate(JobHandle inputDeps)
    84. {
    85. JobHandle jobHandle = new CollisionEventImpulseJob
    86. {
    87. ColliderEventImpulseGroup = GetComponentDataFromEntity<CollisionEventImpulse>(true),
    88. PhysicsVelocityGroup = GetComponentDataFromEntity<PhysicsVelocity>(),
    89. }.Schedule(m_StepPhysicsWorldSystem.Simulation,
    90. ref m_BuildPhysicsWorldSystem.PhysicsWorld, inputDeps);
    91. return jobHandle;
    92. }
    93. }
    94.  
     
  19. kstothert

    kstothert

    Joined:
    Dec 8, 2016
    Posts:
    68
    thanks, I've seen that too but I was expecting something different.

    I've been advocating for a while that Unity shouldn't forget that one of it's most attractive features was it's approachability. With that in mind I think it's inevitable that the performant path will sometimes diverge from the most ergonomic one. Unity has really embraced that with the entities.foreach approach which is ergonomic and expressive so I think it would be a mistake not to enable unity physics to work there as well, without jobs.

    Code (CSharp):
    1.   public class StartJumpSystem : ComponentSystem {
    2.     EntityQuery player;
    3.     EntityQuery ground;
    4.     // something like this would be great
    5.     CollisionQuery playerAndGroundCollisions;
    6.  
    7.     protected override void OnCreate () {
    8.       player = GetEntityQuery(
    9.         typeof(Player),
    10.         ComponentType.Exclude(typeof(Jumping))
    11.       );
    12.       ground = GetEntityQuery(
    13.         typeof(Ground)
    14.       )
    15.  
    16.       playerAndGroundCollisions = GetCollisionQuery(player, ground);
    17.     }
    18.  
    19.     protected override void OnUpdate () {
    20.       // iterate the collision events between player and ground using standard systems on the main thread
    21.       // I think it's important that people be able to use unity physics without jobs, it helps with the transition and softens the learning curve
    22.       Entities.With(playerAndGroundCollisions).ForEach((CollisionEvent collisionEvent) => {
    23.         Entity playerEntity = collisionEvent.Entities.EntityA;
    24.         Entity groundEntity = collisionEvent.Entities.EntityB;
    25.  
    26.         if (collisionEvent.type != CollisionType.Enter)
    27.           return;
    28.  
    29.         // do stuff
    30.       });
    31.     }
    32.   }
    I know some people may disagree but try to remember that performance IS NOT an issue for many different types of games especially 2D and some developers, whether they are just learning or trying to shave off complexity and development time, would love to have these options
     
    Last edited: Aug 6, 2019
    NotaNaN likes this.
  20. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,754
    Yep I would like to see as such.
    Yet I am not out of fate yet. In the end, Unity ECS based physics is still in nappies.
    So we may see equivalent at some point.
     
    NotaNaN likes this.
  21. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Apologies for being away so long. I double checked the performance of the Pool and Planet Gravity demos between 0.1.0 and 0.2.0 and can't see any performance regression.
    The planet gravity demo has better performance in 0.2.0 (for me).
    I tried the original 9999 bodies PlanetGravity-0.1.0 v 0.2.0-9999.png and a 99999 variant PlanetGravity-0.1.0 v 0.2.0-99999.png .
    The Pool sample is a little more tricky to compare like for like but overall 0.2.0 does seem to come out on top: PoolSample-0.1.0 v 0.2.0.png .
    One important thing is to make sure the JobsDebugger is disabled. This can seriously through out the performance numbers.

    I removed the Abacus mostly as it didn't provide any educational extras. The demo should really be using prismatic joints rather than colliding with the frame. Its also not particularly interactive as an abacus. Finally, it seemed redundant given that actual users are doing pretty incredible things themselves (
    ).... Perhaps we should add it back in the test folder as a joint explosion test.

    The continuous test demo has a bunch of increasingly faster spinning boxes, making sure they hit the pillar rather than step through it. In the Broadphase debug viewer you see the faster spinning boxes have a bigger AABB. This is because there is an expansion factor that makes the objects AABB larger based on linear and angular velocity and also a parameter called
    AngularExpansionFactor
    (see the MassProperties and PhysicsMass structs). Ultimately this expansion is used to determine how far away from a body to look for collisions.
    The extra AngularExpansionFactor is related to how rotational symmetric an object would be. For example a sphere would have an AngularExpansionFactor of zero, as it isn't any bigger in one direction compared to another. A really long stick might need an AngularExpansionFactor greater than 1.
    This is worth knowing about if you plan on having really fast spinning objects as you could meet performance issues, as potentially more and more collisions are tested for as angular velocity ramps up. At some point, swapping in a sphere collider as a simple representation of the very fast spinning irregular object becomes a simple optimization.
     

    Attached Files:

    BobFlame and Adam-Mechtley like this.
  22. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    4,223
    Thanks for looking into this. I'll try to reproduce the issue this weekend.

    I really like the idea of the random toys that you make be added to the tests folder or an "Experiments" folder. Those random toys are sometimes all that is required to unblock a team from a problem no one anticipated.

    I knew that the motion expansion was expanding the AABB in the broadphase. What I haven't figured out yet is what the narrow phase is doing with it. I'm trying to understand its characteristics with respect to other continuous collision detection techniques such as sweep-tests and speculative contacts.
     
    steveeHavok likes this.
  23. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Apologies for the delay. I'm not seeing exactly the same as yourself but there does seem to be an issue here. The timestep is large but the 'w' should have a softer collision rather jitter, and/or fall through the floor. I've logged the details and we'll look into the issue.

    EDIT: can I ask why you need the timestep so large?
     
    Last edited: Aug 6, 2019
  24. linfuqing

    linfuqing

    Joined:
    May 11, 2015
    Posts:
    166
    My game is MMO with lockstep sync.I need to get the same results from server and client.The update time must be fixed and a large timestep can save bandwidth.
    And I have 60K rigidbodies and a 7km2 mesh collider in server.For the performance larger timestep is the better.

    I make a package with repo in video here.(need to set fixedtime=0.2)
     

    Attached Files:

  25. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,753
    Somewhat unrelated, but how can an MMO with lockstep possibly work? It's really not a network architecture that scales.
     
  26. linfuqing

    linfuqing

    Joined:
    May 11, 2015
    Posts:
    166
    Actually it's the Time Wrap Sync same as OverWatch.It save some snapshots and rollback when commands out of sync.
    The rollback process is similar with lockstep.
     
  27. TheOtherMonarch

    TheOtherMonarch

    Joined:
    Jul 28, 2012
    Posts:
    862
    Lockstep can scale better if you have a server. Send all inputs to the server and package them up and return to the clients. Even P2P lockstep can support 32+ players.

    If deterministic floats ever comes out I plan to switch from client-server with rollback to, server moderated lock-step with deterministic client-side prediction using physics. Will require less bandwidth and give better results but will require 50 times the CPU resources.
     
    Last edited: Aug 7, 2019
  28. thelebaron

    thelebaron

    Joined:
    Jun 2, 2013
    Posts:
    851
    Are there plans to better support conversion within a hybrid context, ie for setting up a ragdoll for a skinned render mesh setup? Currently colliders get merged into a mega collider which is pretty much incompatible with this setup. Now I have gone and sort of done this via code



    but its rather difficult for me to understand the joint limits/transformations etc without working with this kind of stuff visually. I would love it if the conversion system allowed you to setup this stuff in the editor.

    Sidenote observation:
    In the Joints parade scene, if you select inject instead of destroy for the parent(static) object, the joint seems to not really work properly, as if the child object is just fused in place. Seems to happen for all the examples in the scene. Not sure if this is a bug or not.
     
    steveeHavok and florianhanke like this.
  29. Buretto

    Buretto

    Joined:
    Mar 23, 2015
    Posts:
    49
    Sorry if this is a stupid question, but could someone explain what
    public static float GetEffectiveMass(this in PhysicsWorld world, int rigidBodyIndex, float3 impulse, float3 point)
    gets/returns? Is the effective mass here the same as the wikipedia definition? https://en.wikipedia.org/wiki/Effective_mass_(solid-state_physics) I took my best guess and assumed they aren't the same thing, but really I might just be too stupid to understand this stuff :(. I've been looking at it's usage in the vehicle example, and was also doing my own tests but ended up clueless haha.
     
  30. Adam-Mechtley

    Adam-Mechtley

    Administrator

    Joined:
    Feb 5, 2007
    Posts:
    290
    Of course! It's just a matter of getting all the work done. The first step is going to be just creating fully-featured authoring components for joints (similar to PhysicsShape/PhysicsBody, something that lives outside the samples project and is properly part of the package), then adding visualizations for them all. At some later point we will add workflows specifically tailored to ragdoll setup. Unfortunately no hard dates yet.
     
    SamOld and thelebaron like this.
  31. linfuqing

    linfuqing

    Joined:
    May 11, 2015
    Posts:
    166
    I have a question about BuildPhysicsWorld:
    Code (CSharp):
    1.             inputDeps = JobHandle.CombineDependencies(inputDeps, m_EndFramePhysicsSystem.FinalJobHandle);
    2.  
    3.             // Extract types used by initialize jobs
    4.             var entityType = GetArchetypeChunkEntityType();
    5.             var positionType = GetArchetypeChunkComponentType<Translation>(true);
    6.             var rotationType = GetArchetypeChunkComponentType<Rotation>(true);
    7.             var physicsColliderType = GetArchetypeChunkComponentType<PhysicsCollider>(true);
    8.             var physicsVelocityType = GetArchetypeChunkComponentType<PhysicsVelocity>(true);
    9.             var physicsMassType = GetArchetypeChunkComponentType<PhysicsMass>(true);
    10.             var physicsDampingType = GetArchetypeChunkComponentType<PhysicsDamping>(true);
    11.             var physicsGravityFactorType = GetArchetypeChunkComponentType<PhysicsGravityFactor>(true);
    12.             var physicsCustomTagsType = GetArchetypeChunkComponentType<PhysicsCustomTags>(true);
    13.             var physicsJointType = GetArchetypeChunkComponentType<PhysicsJoint>(true);
    14.  
    15.             int numDynamicBodies = DynamicEntityGroup.CalculateLength();
    16.             int numStaticBodies = StaticEntityGroup.CalculateLength();
    17.             int numJoints = JointEntityGroup.CalculateLength();
    18.  
    19.             m_StaticLayerChangeInfo.NumStaticBodies = numStaticBodies + 1;
    20.             m_StaticLayerChangeInfo.HaveStaticBodiesChanged = 0;
    21.  
    22.             if (numStaticBodies != (PhysicsWorld.StaticBodies.Length - 1)) //-1 for fake static body we add
    23.             {
    24.                 // Quick test if number of bodies changed
    25.                 m_StaticLayerChangeInfo.HaveStaticBodiesChanged = 1;
    26.             }
    27.             else
    28.             {
    29.                 // Make a job to test for changes
    30.                 int numChunks; // There has to be a better way of doing this...
    31.                 using (NativeArray<ArchetypeChunk> chunks = StaticEntityGroup.CreateArchetypeChunkArray(Allocator.TempJob))
    32.                 {
    33.                     numChunks = chunks.Length;
    34.                 }
    35.  
    36.                 var chunksHaveChanges = new NativeArray<int>(numChunks, Allocator.TempJob);
    37.  
    38.                 inputDeps = new Jobs.CheckStaticBodyChangesJob
    39.                 {
    40.                     PositionType = positionType,
    41.                     RotationType = rotationType,
    42.                     PhysicsColliderType = physicsColliderType,
    43.                     ChunkHasChangesOutput = chunksHaveChanges,
    44.                     m_LastSystemVersion = LastSystemVersion
    45.                 }.Schedule(StaticEntityGroup, inputDeps);
    46.  
    47.                 inputDeps = new Jobs.CheckStaticBodyChangesReduceJob
    48.                 {
    49.                     ChunkHasChangesOutput = chunksHaveChanges,
    50.                     HaveStaticBodiesChanged = m_StaticLayerChangeInfo.HaveStaticBodiesChangedArray,
    51.                     NumStaticBodies = m_StaticLayerChangeInfo.NumStaticBodiesArray
    52.                 }.Schedule(inputDeps);
    53.             }
    54.  
    55.             // Resize the world's native arrays
    56.             PhysicsWorld.Reset(
    57.                 numStaticBodies: numStaticBodies + 1,   // +1 for the default static body
    58.                 numDynamicBodies: numDynamicBodies,
    59.                 numJoints: numJoints);
    When call "PhysicsWorld.Reset", has the "inputDeps" be completed?
     
  32. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    The correct answer is maybe. Because at that point inputDeps has been combined with EndFramePhysicsSystem.FinalJobHandle. which is not automatically completed you have to do that yourself if you have added to EndFramePhysicsSystem.HandlesToWaitFor.

    Or if you didn't add anything to HandlesToWaitFor but are accessing bodies and haven't complete the jobs that access said bodies, that will make this fail also.

    The Combine at the top of BuildPhysics world serves no purpose I can see, and the comment is well unfortunate. The only possible outcome of that Combine is for code later down the path here to fail if you had added handles to HandlesToWaitFor that you have not completed by the time BuildPhysicsWorld runs. But if you didn't add your handles to HandlesToWaitFor, it would also still fail. So it seems to be a rather pointless Combine.
     
  33. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    I can't replicate this. I am getting collisions ok with your code sample. That said the collider is offset from the display shape so it does look like the collisions are missing collisions. This is want I see: upload_2019-8-8_13-1-41.png
    The capsule on the right has the bottom vert at 0,0.5,0. Note the pink interia tensor is still showing the center of mass around the original display capsule, while the green line between the collider verts is shifted up. Hence, the collider is sitting on the dynamic box but the display capsule is 'offset' into the box.
    Just moving the capsule verts will also mess with the center of mass (i.e. the center of the pink box), so you should also shift the PhysicsMass.CenterOfMass property to move the COM over the collider:
    Code (CSharp):
    1.         var mass = dstManager.GetComponentData<PhysicsMass>(entity);
    2.         mass.CenterOfMass = mass.CenterOfMass + new float3(0, 1.0f, 0);
    3.         dstManager.SetComponentData(entity, mass);
    upload_2019-8-8_13-19-41.png
    This still leaves the collider being offset from the entities transform. If you want the collider to match then you should leave the COM but create a compound collider with the capsule collider as an offset child.
    Code (CSharp):
    1.  
    2.         var collider = dstManager.GetComponentData<PhysicsCollider>(entity);
    3.         {
    4.             var children = new NativeArray<CompoundCollider.ColliderBlobInstance>(1, Allocator.Temp)
    5.             {
    6.                 [0] = new CompoundCollider.ColliderBlobInstance
    7.                 {
    8.                     CompoundFromChild = new RigidTransform(quaternion.identity, new float3(0, -1, 0)),
    9.                     Collider = tweakedCapsuleCollider,
    10.                 },
    11.             };
    12.             tweakedCapsuleCollider = CompoundCollider.Create(children);
    13.             children.Dispose();
    14.         }
    15.         collider.Value = tweakedCapsuleCollider;
    16.         dstManager.SetComponentData(entity, collider);
    17.  
    Does any of this match with what you are seeing?

    It would be great if you could post a screen shot of this. The Debug Display isn't z-sorting as @snacktime found. We'll have to look into this. One hack is to at least draw all the static objects first by tweaking com.unity.physics\Unity.Physics.Hybrid\Utilities\DebugDisplay\DisplayCollidersSystem.cs
    Code (CSharp):
    1.          
    2.             public void OnDrawGizmos()
    3.             {
    4.                 // reverse draw order (statics first)
    5.                 for (int b = Bodies.Length-1; b >= 0; b--)
    6.                 {
    7.                     ...
    8.  
     
  34. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Would you be able to throw up a visual representation of what you are seeing or even better a simple repo?
    upload_2019-8-8_15-37-55.png
    Does this image represent what you are seeing? The white lines are the surface normals from the DistanceHit on the two long triangle the purple capsule is standing on. The smaller white surface normal on the left matches the face normal. The longer white triangle on the right is the surface normal on the hit but the character is hitting of the edge of the triangle and not the face. As the character moves right, over the lip the surface normal on the right would change until the capsule is fully standing on the face of the triangle. Is this what you are seeing?
     
  35. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Would you be able to put togther a small sample scene showing the problem and we call look at it in more detail?
     
  36. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Thanks. This is good to know.
    So there are two issues. They are still there in a small timestep but the larger timestep magnifies the problem.
    First the 'W' has 2 coplanar faces in the convex hull that alternately act as the supporting surface. For me this causes an extreme jitter, sometimes rotating the body through the floor when a mesh. We have improvements to the convex hull generator coming in the next release that look for this sort of thing so the large flat side of the 'W' becomes a single face and hence no jitter in the current latest branch we are working on.
    Second problem is then when a face has a lot of vertices, so the 'O' shows this problem. Again, depending on the order the contact points are solved then similar jitter can occur, though to a lesser degree. The 'O' will shuffer across the floor rather than go through.
    We have a working fix for this at the minute, looping over the contact points in a less linear way to mix up the solve order and remove the jitter. We are still testing this but hopefully it will get in the next release as well.
     
  37. RBogdy

    RBogdy

    Joined:
    Mar 6, 2019
    Posts:
    65
    I posted this in the Entity Debugger thread as well, however I will signal it here too.
    Entities with Physics Components are no longer visible in Inspector from Entity Debugger.
    Inspector.JPG

    Error:

    Code (CSharp):
    1. InvalidCastException: Specified cast is not valid.
    2. Unity.Properties.Reflection.ReflectedMemberProperty`2[TContainer,TValue].GetValue (TContainer& container) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/Reflection/Properties/ReflectedMemberProperty.cs:24)
    3. Unity.Properties.PropertyVisitor.VisitProperty[TProperty,TContainer,TValue] (TProperty property, TContainer& container, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:54)
    4. Unity.Properties.Reflection.ReflectedPropertyBag`1+PropertyProxy`2[TContainer,TProperty,TValue].Accept[TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/Reflection/ReflectedPropertyBag.cs:19)
    5. Unity.Properties.Reflection.ReflectedPropertyBag`1[TContainer].Accept[TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/Reflection/ReflectedPropertyBag.cs:58)
    6. Unity.Properties.PropertyContainer.Visit[TContainer,TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyContainerVisit.cs:29)
    7. Unity.Properties.PropertyVisitor.TryVisitContainerWithAdapters[TProperty,TContainer,TValue] (TProperty property, TContainer& container, TValue& value, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:127)
    8. Unity.Properties.PropertyVisitor.VisitProperty[TProperty,TContainer,TValue] (TProperty property, TContainer& container, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:57)
    9. Unity.Properties.Reflection.ReflectedPropertyBag`1+PropertyProxy`2[TContainer,TProperty,TValue].Accept[TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/Reflection/ReflectedPropertyBag.cs:19)
    10. Unity.Properties.Reflection.ReflectedPropertyBag`1[TContainer].Accept[TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/Reflection/ReflectedPropertyBag.cs:58)
    11. Unity.Properties.PropertyContainer.Visit[TContainer,TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyContainerVisit.cs:29)
    12. Unity.Properties.PropertyVisitor.TryVisitContainerWithAdapters[TProperty,TContainer,TValue] (TProperty property, TContainer& container, TValue& value, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:127)
    13. Unity.Properties.PropertyVisitor.VisitProperty[TProperty,TContainer,TValue] (TProperty property, TContainer& container, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:57)
    14. Unity.Properties.Reflection.ReflectedPropertyBag`1+PropertyProxy`2[TContainer,TProperty,TValue].Accept[TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/Reflection/ReflectedPropertyBag.cs:19)
    15. Unity.Properties.Reflection.ReflectedPropertyBag`1[TContainer].Accept[TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/Reflection/ReflectedPropertyBag.cs:58)
    16. Unity.Properties.PropertyContainer.Visit[TContainer,TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyContainerVisit.cs:29)
    17. Unity.Properties.PropertyVisitor.TryVisitContainerWithAdapters[TProperty,TContainer,TValue] (TProperty property, TContainer& container, TValue& value, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:127)
    18. Unity.Properties.PropertyVisitor.VisitProperty[TProperty,TContainer,TValue] (TProperty property, TContainer& container, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:57)
    19. Unity.Properties.VisitCollectionElementCallback`1[TContainer].VisitProperty[TElementProperty,TElement] (TElementProperty property, TContainer& container, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:17)
    20. Unity.Entities.EntityContainerPropertyBag+ComponentsProperty+GetComponentDataCallback`1[TCallback].Invoke[TComponent] () (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities.Properties/EntityContainer.cs:65)
    21. Unity.Properties.PropertyBag`1[TContainer].Cast[TCallback] (TCallback& callback) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/IPropertyBag.cs:38)
    22. Unity.Entities.EntityContainerPropertyBag+ComponentsProperty.GetPropertyAtIndex[TGetter] (Unity.Entities.EntityContainer& container, System.Int32 index, Unity.Properties.ChangeTracker& changeTracker, TGetter getter) (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities.Properties/EntityContainer.cs:227)
    23. Unity.Properties.PropertyVisitor.TryVisitCollectionWithAdapters[TProperty,TContainer,TValue] (TProperty property, TContainer& container, TValue& value, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:159)
    24. Unity.Properties.PropertyVisitor.VisitCollectionProperty[TProperty,TContainer,TValue] (TProperty property, TContainer& container, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyVisitor.cs:87)
    25. Unity.Entities.EntityContainerPropertyBag.Accept[TVisitor] (Unity.Entities.EntityContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities.Properties/EntityContainer.cs:265)
    26. Unity.Properties.PropertyContainer.Visit[TContainer,TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.ChangeTracker& changeTracker) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyContainerVisit.cs:29)
    27. Unity.Properties.PropertyContainer.Visit[TContainer,TVisitor] (TContainer& container, TVisitor visitor, Unity.Properties.IVersionStorage versionStorage) (at Library/PackageCache/com.unity.properties@0.6.2-preview/Runtime/Unity.Properties/PropertyContainerVisit.cs:15)
    28. Unity.Entities.Editor.EntitySelectionProxyEditor.OnInspectorGUI () (at Library/PackageCache/com.unity.entities@0.1.1-preview/Unity.Entities.Editor/EntityInspector/EntitySelectionProxyEditor.cs:44)
    29. UnityEditor.UIElements.InspectorElement+<CreateIMGUIInspectorFromEditor>c__AnonStorey1.<>m__0 () (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorElement.cs:496)
    30. UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
    31.  
    Apologise if this is already known.
     
  38. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Effective Mass is the mass that would be 'seen' at particular 'point' and in the direction 'impulse'.
    Its discussed in this talk http://box2d.org/files/GDC2011/GDC2011_Catto_Erin_Soft_Constraints.pdf
    Given that the vehicle sample is really a toy, tbh the effective mass might be overkill.
     
  39. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Thanks for the headsup here. I'll ask around. For reference this is the link to your post in the other thread :https://forum.unity.com/threads/entity-debugger-feedback.522893/page-3#post-4833185
     
  40. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    For completeness, here are the fixes to the character controller for everyone to see. The zip contains the changed files; three for the character controller demo in the samples and one for the com.unity.physics package. You can replace the latter in the <YourUnityProject>\Library\PackageCache\com.unity.physics@0.2.0-preview subdirectory.
    I understand that @Knightmore got this working so I'll leave it to them to reply with results if so desired :)
     

    Attached Files:

  41. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    I was testing against relatively or completely flat surfaces. I'll try to get time to just create an isolated repro for it.
     
  42. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    In looking that the motion expansion it actually seems over aggressive so there is likely a bug there. Regarding continuous collision detection we have a pretty good set of docs describing this in the Havok Physics SDK and they cross over well to Unity Physics. So we'll see about tweaking and adding the appropriate sections into the Unity Physics documentation for subsequent releases.
     
  43. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    Even with two coplanar faces you will still be getting a normal against the edge of a face the character is moving onto. These edge normals don't generally affect the Character Controller but the ModifyNarrowphaseContacts demo illustrates this 'welding' issues for general simulation. Let me know if I'm even talking about the same thing you are experiencing.
     
  44. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356

    Ok ya that sounds like what is going on. I didn't know what to expect as far as behavior with edges but that makes sense. This is for character controller 'like' valid ground detection, so as long as there is a surface hit the edge hits would be ignored.
     
  45. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    4,223
    Sweet! I look forward to it!
     
  46. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    Minor thing but annoying to have to have our own implementation for.

    Which is Ray can't seem to decide what it is. I can't use it as either a ray or line segment in our own code, because I want those to be obvious as to what they are and have the obvious helper methods that should accompany them. I understand physics has it's own needs but rays are something consumers of physics api's are going to be using a lot. Maybe can we have a proper Ray and LineSegment both? Even if it's just a convenience layer over the current Ray.
     
  47. jacquesalbert

    jacquesalbert

    Joined:
    Jul 9, 2019
    Posts:
    10
    Is anyone else having an issue with CastRay where it seems to collide with the entity that it is running in a job for? Basically, I have an IJobForEachWithEntity that receives a CollisionWorld and at one point casts a ray. That ray almost always returns a hit of the entity itself instead of the entity it is directed toward. The ray originates inside the job entity, but even if it is forced to originate well outside the entity, this seems to occur. I'm wondering if this has something to do with being run from a job?
     
    gameDevMode likes this.
  48. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,753
    Manual says this

    So you need to exclude the origin entity from your layer filter as if it starts inside something, it will hit it.

    Not sure about this bit and it doesn't really make sense. It's not like the ray is linked to the entity. If a ray starts outside a collider, never passes through a collider it should not return a hit on that collider. If it does that'd have to be considered a bug.
     
  49. jacquesalbert

    jacquesalbert

    Joined:
    Jul 9, 2019
    Posts:
    10
    Interesting, the manual version I was looking at only said "Ray intersection starting inside spheres, capsules, box and convex shapes do not report an intersection as the ray leaves the volume." I guess I am looking at the wrong version.

    It is still odd that it happens even if I start the ray several units outside the collider, though. I will experiment some more tonight and see if the filters prevent it. Maybe my math is bad on the start position or something.

    Edit: i was, in fact, looking at the previous version's manual. Still need to figure out what is going on
     
    Last edited: Aug 13, 2019
  50. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,753
    Ah yes, you are not the first person to read the old 0.0 manual and run into this issue.
     
Thread Status:
Not open for further replies.