private static bool IsTransparent(BlobAssetReference <Collider> collider, ColliderKey key)
        {
            bool bIsTransparent = false;

            unsafe
            {
                // Only Convex Colliders have Materials associated with them. So base on CollisionType
                // we'll need to cast from the base Collider type, hence, we need the pointer.
                var c = (Collider *)collider.GetUnsafePtr();
                {
                    var cc = ((ConvexCollider *)c);

                    // We also need to check if our Collider is Composite (i.e. has children).
                    // If it is then we grab the actual leaf node hit by the ray.
                    // Checking if our collider is composite
                    if (c->CollisionType != CollisionType.Convex)
                    {
                        // If it is, get the leaf as a Convex Collider
                        c->GetLeaf(key, out ChildCollider child);
                        cc = (ConvexCollider *)child.Collider;
                    }

                    // Now we've definitely got a ConvexCollider so can check the Material.
                    bIsTransparent = (cc->Material.CustomTags & k_TransparentCustomTag) != 0;
                }
            }

            return(bIsTransparent);
        }
Example #2
0
    //
    // Object creation
    //

    private unsafe Entity CreateBody(float3 position, quaternion orientation, BlobAssetReference <Collider> collider,
                                     float3 linearVelocity, float3 angularVelocity, float mass, bool isDynamic)
    {
        EntityManager entityManager = EntityManager;

        Entity entity = entityManager.CreateEntity(new ComponentType[] { });

        entityManager.AddComponentData(entity, new LocalToWorld {
        });
        entityManager.AddComponentData(entity, new Translation {
            Value = position
        });
        entityManager.AddComponentData(entity, new Rotation {
            Value = orientation
        });
        entityManager.AddComponentData(entity, new PhysicsCollider {
            Value = collider
        });

        List <Unity.Physics.Authoring.DisplayBodyColliders.DrawComponent.DisplayResult> meshes = Unity.Physics.Authoring.DisplayBodyColliders.DrawComponent.BuildDebugDisplayMesh((Collider *)collider.GetUnsafePtr());

        CombineInstance[] instances = new CombineInstance[meshes.Count];
        for (int i = 0; i < meshes.Count; i++)
        {
            instances[i] = new CombineInstance
            {
                mesh      = meshes[i].Mesh,
                transform = Matrix4x4.TRS(meshes[i].Position, meshes[i].Orientation, meshes[i].Scale)
            };
        }
        Mesh mesh = new Mesh();

        mesh.CombineMeshes(instances);

        entityManager.AddSharedComponentData(entity, new RenderMesh
        {
            mesh     = mesh,
            material = isDynamic ? dynamicMaterial : staticMaterial
        });

        if (isDynamic)
        {
            Collider *colliderPtr = (Collider *)collider.GetUnsafePtr();
            entityManager.AddComponentData(entity, PhysicsMass.CreateDynamic(colliderPtr->MassProperties, mass));

            float3 angularVelocityLocal = math.mul(math.inverse(colliderPtr->MassProperties.MassDistribution.Transform.rot), angularVelocity);
            entityManager.AddComponentData(entity, new PhysicsVelocity()
            {
                Linear  = linearVelocity,
                Angular = angularVelocityLocal
            });
            entityManager.AddComponentData(entity, new PhysicsDamping()
            {
                Linear  = 0.01f,
                Angular = 0.05f
            });
        }

        return(entity);
    }
Example #3
0
    internal override void ConfigureInstance(Entity instance, ref SpawnExplosionSettings spawnSettings)
    {
        // Create single collider per Explosion group
        if (GroupId != spawnSettings.Id)
        {
            GroupId = spawnSettings.Id;
            spawnSettings.Source = instance;

            var collider  = EntityManager.GetComponentData <PhysicsCollider>(instance);
            var memsize   = collider.Value.Value.MemorySize;
            var oldFilter = collider.Value.Value.Filter;

            // Only one of these needed per group, since all debris within
            // a group will share a single collider
            // This will make debris within a group collide some time after the explosion happens
            EntityManager.AddComponentData(instance, new ChangeFilterCountdown
            {
                Countdown = spawnSettings.Countdown * 2,
                Filter    = oldFilter
            });

            // Make unique collider for each spawned group
            unsafe
            {
                // Create new collider for the group
                // TODO : make Collider ICloneable
                BlobAssetReference <Collider> colliderCopy = BlobAssetReference <Collider> .Create(UnsafeUtility.Malloc(memsize, 16, Allocator.Persistent), memsize);

                UnsafeUtility.MemCpy(colliderCopy.GetUnsafePtr(), collider.ColliderPtr, memsize);

                // Set the GroupIndex to GroupId, which is negative
                // This ensures that the debris within a group don't collide
                colliderCopy.Value.Filter = new CollisionFilter
                {
                    BelongsTo    = oldFilter.BelongsTo,
                    CollidesWith = oldFilter.CollidesWith,
                    GroupIndex   = GroupId,
                };
                PhysicsCollider newCollider = new PhysicsCollider
                {
                    Value = colliderCopy
                };
                GroupCollider = newCollider;
                CreatedColliders.Add(GroupCollider);
            }
        }

        EntityManager.SetComponentData(instance, GroupCollider);

        EntityManager.AddComponentData(instance, new ExplosionCountdown
        {
            Source    = spawnSettings.Source,
            Countdown = spawnSettings.Countdown,
            Center    = spawnSettings.Position,
            Force     = spawnSettings.Force
        });
    }
Example #4
0
        //Adds a dynamic box to the world
        static public unsafe void addDynamicBoxToWorld(Physics.PhysicsWorld world, int index, Vector3 pos, Quaternion orientation, Vector3 size)
        {
            Assert.IsTrue(index < world.NumDynamicBodies, "Dynamic body index is out of range in addDynamicBoxToWorld");
            Unity.Collections.NativeSlice <Physics.RigidBody> dynamicBodies = world.DynamicBodies;
            Physics.RigidBody rb = dynamicBodies[index];
            BlobAssetReference <Physics.Collider> collider = Unity.Physics.BoxCollider.Create(pos, orientation, size, .01f);

            rb.Collider          = (Collider *)collider.GetUnsafePtr();
            dynamicBodies[index] = rb;
        }
    public unsafe Unity.Entities.Entity CreateBody(float3 position, quaternion orientation,
                                                   BlobAssetReference <Unity.Physics.Collider> collider,
                                                   float3 linearVelocity, float3 angularVelocity, float mass, bool isDynamic)
    {
        ComponentType[] componentTypes = new ComponentType[isDynamic ? 7 : 3];

        componentTypes[0] = typeof(TranslationProxy);
        componentTypes[1] = typeof(RotationProxy);
        componentTypes[2] = typeof(PhysicsCollider);
        if (isDynamic)
        {
            componentTypes[3] = typeof(PhysicsVelocity);
            componentTypes[4] = typeof(PhysicsMass);
            componentTypes[5] = typeof(PhysicsDamping);
            componentTypes[6] = typeof(PhysicsGravityFactor);
        }

        Unity.Entities.Entity entity = entityManager.CreateEntity(componentTypes);

        entityManager.AddComponentData(entity, new Translation {
            Value = position
        });
        entityManager.AddComponentData(entity, new Rotation {
            Value = orientation
        });
        entityManager.SetComponentData(entity, new PhysicsCollider {
            Value = collider
        });
        if (isDynamic)
        {
            Unity.Physics.Collider *colliderPtr = (Unity.Physics.Collider *)collider.GetUnsafePtr();
            entityManager.SetComponentData(entity, PhysicsMass.CreateDynamic(colliderPtr->MassProperties, mass));

            float3 angularVelocityLocal = math.mul(math.inverse(colliderPtr->MassProperties.MassDistribution.Transform.rot), angularVelocity);
            entityManager.SetComponentData(entity, new PhysicsVelocity()
            {
                Linear  = linearVelocity,
                Angular = angularVelocityLocal
            });
            entityManager.SetComponentData(entity, new PhysicsDamping()
            {
                Linear  = 1.5f,
                Angular = 1.5f
            });

            entityManager.SetComponentData(entity, new PhysicsGravityFactor {
                Value = 0.0f
            });
        }

        return(entity);
    }
        public unsafe void RigidBodyCalculateDistanceTest()
        {
            const float size         = 1.0f;
            const float convexRadius = 0.0f;
            const float sphereRadius = 1.0f;

            var queryPos = new float3(-10, -10, -10);

            BlobAssetReference <Collider> boxCollider = BoxCollider.Create(new BoxGeometry
            {
                Center      = float3.zero,
                Orientation = quaternion.identity,
                Size        = size,
                BevelRadius = convexRadius
            });
            BlobAssetReference <Collider> sphereCollider = SphereCollider.Create(new SphereGeometry
            {
                Center = float3.zero,
                Radius = sphereRadius
            });

            var rigidBody = new Physics.RigidBody
            {
                WorldFromBody = RigidTransform.identity,
                Collider      = boxCollider
            };

            var colliderDistanceInput = new ColliderDistanceInput
            {
                Collider  = (Collider *)sphereCollider.GetUnsafePtr(),
                Transform = new RigidTransform(quaternion.identity, queryPos)
            };

            var closestHit = new DistanceHit();
            var allHits    = new NativeList <DistanceHit>(Allocator.Temp);

            // OK case : with enough max distance
            colliderDistanceInput.MaxDistance = 10000.0f;
            Assert.IsTrue(rigidBody.CalculateDistance(colliderDistanceInput));
            Assert.IsTrue(rigidBody.CalculateDistance(colliderDistanceInput, out closestHit));
            Assert.IsTrue(rigidBody.CalculateDistance(colliderDistanceInput, ref allHits));

            // Fail case : not enough max distance
            colliderDistanceInput.MaxDistance = 1;
            Assert.IsFalse(rigidBody.CalculateDistance(colliderDistanceInput));
            Assert.IsFalse(rigidBody.CalculateDistance(colliderDistanceInput, out closestHit));
            Assert.IsFalse(rigidBody.CalculateDistance(colliderDistanceInput, ref allHits));

            boxCollider.Dispose();
            sphereCollider.Dispose();
        }
Example #7
0
        public static unsafe bool BoxCast(float3 rayFrom, float3 rayTo, CollisionWorld collisionWorld, BoxGeometry boxGeometry, CollisionFilter collisionFilter)
        {
            BlobAssetReference <Collider> boxCollider = BoxCollider.Create(boxGeometry, collisionFilter);

            ColliderCastInput input = new ColliderCastInput()
            {
                Collider    = (Collider *)boxCollider.GetUnsafePtr(),
                Orientation = quaternion.identity,
                Start       = rayFrom,
                End         = rayTo
            };

            return(collisionWorld.CastCollider(input));
        }
Example #8
0
            public void Execute()
            {
                var colliderCastInput = new ColliderCastInput
                {
                    Collider    = (Collider *)collider.GetUnsafePtr(),
                    Start       = origin + new float3(0f, 1f, 0f),
                    End         = origin,
                    Orientation = quaternion.identity
                };

                if (!hits.IsCreated)
                {
                    hits = new NativeList <ColliderCastHit>(Allocator.TempJob);
                }
                hasHit = physicsWorld.CastCollider(colliderCastInput, ref hits);
            }
        //Adds a static box to the world
        static public unsafe void addStaticBoxToWorld(Physics.PhysicsWorld world, int index, Vector3 pos, Quaternion orientation, Vector3 size)
        {
            Assert.IsTrue(index < world.NumStaticBodies, "Static body index is out of range in addStaticBoxToWorld");
            Unity.Collections.NativeSlice <Physics.RigidBody> staticBodies = world.StaticBodies;
            Physics.RigidBody rb = staticBodies[index];
            BlobAssetReference <Physics.Collider> collider = Unity.Physics.BoxCollider.Create(new BoxGeometry
            {
                Center      = pos,
                Orientation = orientation,
                Size        = size,
                BevelRadius = 0.01f
            });

            rb.Collider         = (Collider *)collider.GetUnsafePtr();
            staticBodies[index] = rb;
        }
Example #10
0
        public static unsafe bool IsTrigger(BlobAssetReference <Collider> collider, ColliderKey key)
        {
            bool bIsTrigger = false;
            var  c          = (Collider *)collider.GetUnsafePtr();

            {
                var cc = ((ConvexCollider *)c);
                if (cc->CollisionType != CollisionType.Convex)
                {
                    c->GetLeaf(key, out ChildCollider child);
                    cc = (ConvexCollider *)child.Collider;
                    Assert.IsTrue(cc->CollisionType == CollisionType.Convex);
                }
                bIsTrigger = cc->Material.IsTrigger;
            }
            return(bIsTrigger);
        }
    public static unsafe void WriteBlobAsset <T>(ref BlobAssetReference <T> assetReference, string fileName) where T : struct
    {
        using (BinaryWriter writer = new BinaryWriter(File.Open(ConvertFileName(fileName), FileMode.Create)))
        {
            var assetPtr              = assetReference.GetUnsafePtr();
            BlobAssetHeader *header   = ((BlobAssetHeader *)assetPtr) - 1;
            long             dataSize = header->Length;

            var data = new byte[dataSize];
            fixed(byte *ptr = &data[0])
            {
                UnsafeUtility.MemCpy(ptr, UnsafeUtility.AddressOf(ref assetReference.Value), data.Length);
            }

            writer.Write(data);
            writer.Close();
        }
    }
        unsafe public void Execute(int index)
        {
            var center = math.lerp(upperRightPosition, lowerLeftPosition, 0.5f);
            var size   = new float3(startPosition.x - endPosition.x,
                                    startPosition.y - endPosition.y,
                                    1);
            var filter = new CollisionFilter()
            {
                BelongsTo    = ~0u,
                CollidesWith = ~0u, // all 1s, so all layers, collide with everything
                GroupIndex   = 0
            };

            BoxGeometry boxGeometry = new BoxGeometry()
            {
                Center = new float3(0, 0, 0) - new float3(startPosition.x - endPosition.x,
                                                          startPosition.y - endPosition.y,
                                                          1) / 2,
                Size        = (size * math.sign(size)) + new float3(1, 1, 1),
                Orientation = quaternion.identity,
                BevelRadius = 0,
            };
            BlobAssetReference <Unity.Physics.Collider> boxColliser = Unity.Physics.BoxCollider.Create(boxGeometry, filter);
            ColliderCastInput input = new ColliderCastInput()
            {
                Collider    = (Unity.Physics.Collider *)boxColliser.GetUnsafePtr(),
                Orientation = quaternion.identity,
                Start       = startPosition,
                End         = startPosition
            };
            NativeList <ColliderCastHit> allHits = new NativeList <ColliderCastHit> (500, Allocator.Temp);
            bool haveHit = collisionWorld.CastCollider(input, ref allHits);

            if (haveHit)
            {
                for (int i = 0; i < allHits.Length; i++)
                {
                    var    hit = allHits[i];
                    Entity e   = physicsWorld.Bodies[hit.RigidBodyIndex].Entity;
                    entityCommandBuffer.AddComponent(index, e, new SelectedTag());
                }
            }
        }
Example #13
0
    public unsafe static NativeArray <Entity> GetNearbyObjects(Entity e, float3 translation, quaternion rotation, PhysicsCollider physicsCollider, BuildPhysicsWorld physicsWorldSystem)
    {
        CollisionWorld       world = physicsWorldSystem.PhysicsWorld.CollisionWorld;;
        NativeArray <Entity> context;
        var filter = new CollisionFilter()
        {
            BelongsTo    = ~0u,
            CollidesWith = ~0u, // all 1s, so all layers, collide with everything
            GroupIndex   = 0
        };

        SphereGeometry sphereGeometry = new SphereGeometry()
        {
            Center = float3.zero, Radius = 3f
        };
        BlobAssetReference <Collider> sphereCollider = SphereCollider.Create(sphereGeometry, filter);
        NativeList <ColliderCastHit>  colliderHit    = new NativeList <ColliderCastHit>();
        ColliderCastInput             input          = new ColliderCastInput()
        {
            Collider    = (Collider *)sphereCollider.GetUnsafePtr(),
            Orientation = quaternion.identity,
            Start       = translation,
            End         = translation
        };

        if (world.CastCollider(input, ref colliderHit))
        {
            int compteur = 0;
            context = new NativeArray <Entity>(colliderHit.Length, Allocator.Temp);
            foreach (var collider in colliderHit)
            {
                context[compteur] = collider.Entity;
                compteur++;
            }
            Debug.Log(context.Length);
        }
        else
        {
            context = new NativeArray <Entity>(0, Allocator.Temp);
            Debug.Log("inhere");
        }
        return(context);
    }
Example #14
0
    internal override void OnBeforeInstantiatePrefab(ref BouncySpawnSettings spawnSettings)
    {
        base.OnBeforeInstantiatePrefab(ref spawnSettings);

        var component = EntityManager.GetComponentData <PhysicsCollider>(spawnSettings.Prefab);

        TweakedCollider = component.Value.Value.Clone();
        Assert.IsTrue(TweakedCollider.Value.CollisionType == CollisionType.Convex);
        unsafe
        {
            // TODO: remove when we have Material accessors
            unsafe
            {
                var header   = (ConvexColliderHeader *)TweakedCollider.GetUnsafePtr();
                var material = header->Material;
                material.Restitution = spawnSettings.Restitution;
                header->Material     = material;
            }
        }
    }
    public unsafe Entity SphereCast(float3 RayFrom, float3 RayTo, float radius)
    {
        var physicsWorldSystem = World.DefaultGameObjectInjectionWorld.GetExistingSystem <Unity.Physics.Systems.BuildPhysicsWorld>();
        var collisionWorld     = physicsWorldSystem.PhysicsWorld.CollisionWorld;

        var filter = new CollisionFilter()
        {
            BelongsTo    = ~0u,
            CollidesWith = ~0u, // all 1s, so all layers, collide with everything
            GroupIndex   = 0
        };

        SphereGeometry sphereGeometry = new SphereGeometry()
        {
            Center = float3.zero, Radius = radius
        };
        BlobAssetReference <Unity.Physics.Collider> sphereCollider = Unity.Physics.SphereCollider.Create(sphereGeometry, filter);

        ColliderCastInput input = new ColliderCastInput()
        {
            Collider    = (Unity.Physics.Collider *)sphereCollider.GetUnsafePtr(),
            Orientation = quaternion.identity,
            Start       = RayFrom,
            End         = RayTo
        };

        ColliderCastHit hit     = new ColliderCastHit();
        bool            haveHit = collisionWorld.CastCollider(input, out hit);

        if (haveHit)
        {
            // see hit.Position
            // see hit.SurfaceNormal
            Entity e = physicsWorldSystem.PhysicsWorld.Bodies[hit.RigidBodyIndex].Entity;
            return(e);
        }

        sphereCollider.Dispose();

        return(Entity.Null);
    }
Example #16
0
    protected unsafe override void OnUpdate()
    {
        float          time       = Time.DeltaTime;
        float          dirForward = Input.GetAxis("Vertical");
        float          dirAngle   = Input.GetAxis("Horizontal");
        CollisionWorld world      = physicsWorldSystem.PhysicsWorld.CollisionWorld;

        Entities.ForEach((Entity e, ref PhysicsVelocity physicsVelocity, ref Rotation rotation, ref Translation translation, ref PhysicsCollider physicsCollider) =>
        {
            var filter = new CollisionFilter()
            {
                BelongsTo    = ~0u,
                CollidesWith = ~0u, // all 1s, so all layers, collide with everything
                GroupIndex   = 0
            };

            SphereGeometry sphereGeometry = new SphereGeometry()
            {
                Center = translation.Value, Radius = 10f
            };
            BlobAssetReference <Collider> sphereCollider = SphereCollider.Create(sphereGeometry, filter);
            NativeList <ColliderCastHit> colliderHit     = new NativeList <ColliderCastHit>(Allocator.Temp);
            ColliderCastInput input = new ColliderCastInput()
            {
                Collider    = (Collider *)sphereCollider.GetUnsafePtr(),
                Orientation = quaternion.identity,
                Start       = translation.Value,
                End         = translation.Value
            };
            world.CastCollider(input, ref colliderHit);
            //for (int i = 0; i < colliderHit.Length; i++)
            //{
            //Debug.Log(colliderHit[i].Entity + " / " + e.Index);
            //}
            //Debug.Log(colliderHit.Length);
            colliderHit.Dispose();
            //NativeArray<Entity> context = GetNearbyObjects(e, translation.Value, rotation.Value, physicsCollider, test);
            //context.Dispose();
        }).ScheduleParallel();
    }
            public unsafe void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
            {
                var chunkTranslations = chunk.GetNativeArray(TranslationType);
                var chunkRotations    = chunk.GetNativeArray(RotationType);
                var chunkFighterSearchInputBuffers = chunk.GetBufferAccessor(FighterSearchInputBufferType);

                for (var i = 0; i < chunk.Count; ++i)
                {
                    DynamicBuffer <FighterSearchInputBuffer> buf = chunkFighterSearchInputBuffers[i];
                    for (var j = 0; j < buf.Length; ++j)
                    {
                        var orientation = math.mul(chunkRotations[i].Value, local_search_rotations_[j]);
                        buf[j] = new FighterSearchInputBuffer {
                            Value = new ColliderCastInput {
                                Collider    = (Collider *)cast_collider_.GetUnsafePtr(),
                                Orientation = orientation,
                                Start       = math.mul(orientation, new float3(0, 0, 10f)) + chunkTranslations[i].Value,
                                End         = math.mul(orientation, new float3(0, 0, 100f)) + chunkTranslations[i].Value,
                            },
                        };
                    }
                }
            }
    static public unsafe void _polygonColliderCast(CollisionFilter _filter, CollisionWorld _collisionWorld, NativeList <ColliderCastHit> _allHits,
                                                   quaternion Orientation,
                                                   float3 Start,
                                                   float3 End,
                                                   float3 vertex0, float3 vertex1, float3 vertex2, float3 vertex3)
    {
        BlobAssetReference <Unity.Physics.Collider> _polygonCollider = Unity.Physics.PolygonCollider.CreateQuad(vertex0, vertex1, vertex2, vertex3);

        Unity.Physics.ColliderCastInput colliderCastInput = new ColliderCastInput()
        {
            Collider    = (Unity.Physics.Collider *)_polygonCollider.GetUnsafePtr(),
            Orientation = ECS_RTSControls.instance._camera.transform.rotation,
            Start       = ECS_RTSControls.instance._camera.transform.position,
            End         = ECS_RTSControls.instance._camera.transform.rotation * new Vector3(100, 0, 0)
        };

        ColliderCastJob _colliderCastJob = new ColliderCastJob();

        _colliderCastJob._collisionWorld = _collisionWorld;
        _colliderCastJob._allHits        = _allHits;


        _polygonCollider.Dispose();
    }
 public unsafe void SetEntityMass(Unity.Entities.Entity _entity, BlobAssetReference <Unity.Physics.Collider> _collider, float _mass)
 {
     Unity.Physics.Collider *colliderPtr = (Unity.Physics.Collider *)_collider.GetUnsafePtr();
     entityManager.SetComponentData(_entity, PhysicsMass.CreateDynamic(colliderPtr->MassProperties, _mass));
 }
 public unsafe bool Equals(ClipFrameLookup other)
 {
     return(((ulong)clip.GetUnsafePtr()).Equals((ulong)other.clip.GetUnsafePtr()) && spawnFrameOrOffsetIndex == other.spawnFrameOrOffsetIndex);
 }
            public unsafe void Execute(int index)
            {
                Results.BeginForEachIndex(index);
                int numRows = (Request.ImageResolution + Results.ForEachCount - 1) / Results.ForEachCount;

                const float sphereRadius             = 0.005f;
                BlobAssetReference <Collider> sphere = default;

                if (Request.CastSphere)
                {
                    sphere = SphereCollider.Create(new SphereGeometry
                    {
                        Center = float3.zero,
                        Radius = sphereRadius
                    }, Request.CollisionFilter);
                }

                for (int yCoord = index * numRows; yCoord < math.min(Request.ImageResolution, (index + 1) * numRows); yCoord++)
                {
                    for (int xCoord = 0; xCoord < Request.ImageResolution; xCoord++)
                    {
                        float xFrac = 2.0f * ((xCoord / (float)Request.ImageResolution) - 0.5f);
                        float yFrac = 2.0f * ((yCoord / (float)Request.ImageResolution) - 0.5f);

                        float3 targetImagePlane = Request.ImageCenter + Request.Up * Request.PlaneHalfExtents * yFrac + Request.Right * Request.PlaneHalfExtents * xFrac;
                        float3 rayDir           = Request.RayLength * (Request.PinHole - targetImagePlane);

                        RaycastHit hit;
                        bool       hasHit;
                        if (Request.CastSphere)
                        {
                            var input = new ColliderCastInput
                            {
                                Collider    = (Collider *)sphere.GetUnsafePtr(),
                                Orientation = quaternion.identity,
                                Start       = Request.PinHole,
                                End         = Request.PinHole + rayDir
                            };
                            hasHit = World.CastCollider(input, out ColliderCastHit colliderHit);
                            hit    = new RaycastHit
                            {
                                Fraction       = colliderHit.Fraction,
                                Position       = colliderHit.Position,
                                SurfaceNormal  = colliderHit.SurfaceNormal,
                                RigidBodyIndex = colliderHit.RigidBodyIndex,
                                ColliderKey    = colliderHit.ColliderKey
                            };
                        }
                        else
                        {
                            var rayCastInput = new RaycastInput
                            {
                                Start  = Request.PinHole,
                                End    = Request.PinHole + rayDir,
                                Filter = Request.CollisionFilter
                            };
                            hasHit = World.CastRay(rayCastInput, out hit);
                        }

                        Color hitColor = Color.black;
                        if (hasHit)
                        {
                            if (hit.RigidBodyIndex < NumDynamicBodies)
                            {
                                hitColor = Color.yellow;
                            }
                            else
                            {
                                hitColor = Color.grey;
                            }

                            // Lighten alternate keys
                            if (Request.AlternateKeys && !hit.ColliderKey.Equals(ColliderKey.Empty))
                            {
                                var collider = (Collider *)World.Bodies[hit.RigidBodyIndex].Collider.GetUnsafePtr();
                                hit.ColliderKey.PopSubKey(collider->NumColliderKeyBits, out uint key);
                                if (key % 2 == 0)
                                {
                                    Color.RGBToHSV(hitColor, out float h, out float s, out float v);
                                    hitColor = Color.HSVToRGB(h, s, v + 0.25f);
                                }
                            }

                            if (Request.Shadows)
                            {
                                float3 hitPos    = Request.PinHole + rayDir * hit.Fraction + hit.SurfaceNormal * 0.001f;
                                bool   shadowHit = false;

                                if (Request.CastSphere)
                                {
                                    var start = hitPos + hit.SurfaceNormal * sphereRadius;
                                    var input = new ColliderCastInput
                                    {
                                        Collider    = (Collider *)sphere.GetUnsafePtr(),
                                        Orientation = quaternion.identity,
                                        Start       = start,
                                        End         = start + (Request.LightDir * Request.RayLength),
                                    };
                                    ColliderCastHit colliderHit;
                                    shadowHit = World.CastCollider(input, out colliderHit);
                                }
                                else
                                {
                                    var rayCastInput = new RaycastInput
                                    {
                                        Start  = hitPos,
                                        End    = hitPos + (Request.LightDir * Request.RayLength),
                                        Filter = Request.CollisionFilter
                                    };
                                    RaycastHit shadowOutput;
                                    shadowHit = World.CastRay(rayCastInput, out shadowOutput);
                                }

                                if (shadowHit)
                                {
                                    hitColor *= 0.4f;
                                }
                            }
                        }

                        float lighting = math.min(1.0f, math.max(Request.AmbientLight, Vector3.Dot(hit.SurfaceNormal, Request.LightDir)));

                        Results.Write(xCoord);
                        Results.Write(yCoord);
                        Results.Write(hitColor * lighting);
                    }
                }

                Results.EndForEachIndex();
            }
Example #22
0
        public unsafe void CreateCompound_WithRepeatedInputs_ChildrenAreInstances()
        {
            BlobAssetReference <Collider> boxBlob      = default;
            BlobAssetReference <Collider> capsuleBlob  = default;
            BlobAssetReference <Collider> sphereBlob   = default;
            BlobAssetReference <Collider> compoundBlob = default;

            try
            {
                // 3 unique instance inputs
                boxBlob = BoxCollider.Create(new BoxGeometry {
                    Orientation = quaternion.identity, Size = new float3(1)
                });
                capsuleBlob = CapsuleCollider.Create(new CapsuleGeometry {
                    Radius = 0.5f, Vertex0 = new float3(1f), Vertex1 = new float3(-1f)
                });
                sphereBlob = SphereCollider.Create(new SphereGeometry {
                    Radius = 0.5f
                });
                var children = new NativeArray <CompoundCollider.ColliderBlobInstance>(8, Allocator.Temp)
                {
                    [0] = new CompoundCollider.ColliderBlobInstance {
                        Collider = boxBlob, CompoundFromChild = new RigidTransform(quaternion.identity, new float3(0f))
                    },
                    [1] = new CompoundCollider.ColliderBlobInstance {
                        Collider = capsuleBlob, CompoundFromChild = new RigidTransform(quaternion.identity, new float3(1f))
                    },
                    [2] = new CompoundCollider.ColliderBlobInstance {
                        Collider = boxBlob, CompoundFromChild = new RigidTransform(quaternion.identity, new float3(2f))
                    },
                    [3] = new CompoundCollider.ColliderBlobInstance {
                        Collider = sphereBlob, CompoundFromChild = new RigidTransform(quaternion.identity, new float3(3f))
                    },
                    [4] = new CompoundCollider.ColliderBlobInstance {
                        Collider = boxBlob, CompoundFromChild = new RigidTransform(quaternion.identity, new float3(4f))
                    },
                    [5] = new CompoundCollider.ColliderBlobInstance {
                        Collider = capsuleBlob, CompoundFromChild = new RigidTransform(quaternion.identity, new float3(5f))
                    },
                    [6] = new CompoundCollider.ColliderBlobInstance {
                        Collider = boxBlob, CompoundFromChild = new RigidTransform(quaternion.identity, new float3(6f))
                    },
                    [7] = new CompoundCollider.ColliderBlobInstance {
                        Collider = sphereBlob, CompoundFromChild = new RigidTransform(quaternion.identity, new float3(7f))
                    }
                };

                compoundBlob = CompoundCollider.Create(children);

                var compound       = (CompoundCollider *)compoundBlob.GetUnsafePtr();
                var uniqueChildren = new HashSet <long>();
                for (var i = 0; i < compound->Children.Length; i++)
                {
                    uniqueChildren.Add((long)compound->Children[i].Collider);
                }
                Assert.That(uniqueChildren.Count, Is.EqualTo(3));
            }
            finally
            {
                boxBlob.Dispose();
                capsuleBlob.Dispose();
                sphereBlob.Dispose();
                if (compoundBlob.IsCreated)
                {
                    compoundBlob.Dispose();
                }
            }
        }
Example #23
0
        protected unsafe override void OnUpdate()
        {
            PhysicsWorld physicsWorld = _worldBuildSystem.PhysicsWorld;
            NativeMultiHashMap <Entity, HitboxCollision> collisions = _collisions;

            collisions.Clear();
            var collisionWriter = collisions.AsParallelWriter();

            Entities
            .WithName("QueryHitboxCollisons")
            .WithReadOnly(physicsWorld)
            .ForEach((Entity entity, ref Hitbox hitbox, ref HitboxState state, in LocalToWorld transform) => {
                if (!state.Enabled)
                {
                    return;
                }

                BlobAssetReference <Collider> collider =
                    SphereCollider.Create(new SphereGeometry {
                    Center = float3.zero,
                    Radius = hitbox.Radius
                }, new CollisionFilter {
                    BelongsTo    = (uint)PhysicsLayers.HITBOX,
                    CollidesWith = (uint)PhysicsLayers.HITBOX,
                });

                float3 position = math.transform(transform.Value, float3.zero);
                var hits        = new NativeList <ColliderCastHit>(Allocator.Temp);
                physicsWorld.CastCollider(new ColliderCastInput {
                    Collider    = (Collider *)collider.GetUnsafePtr(),
                    Start       = state.PreviousPosition ?? position,
                    End         = position,
                    Orientation = float4.zero
                }, ref hits);
                collider.Dispose();

                state.PreviousPosition = position;

                for (var i = 0; i < hits.Length; i++)
                {
                    var hit = hits[i];
                    if (!HasComponent <Hurtbox>(hit.Entity))
                    {
                        continue;
                    }
                    var hurtbox = GetComponent <Hurtbox>(hit.Entity);
                    if (!hurtbox.Enabled || hurtbox.Player == Entity.Null || hurtbox.Player == state.Player)
                    {
                        continue;
                    }

                    collisionWriter.Add(hurtbox.Player, new HitboxCollision {
                        OriginPlayer = entity,
                        Hitbox       = hitbox,
                        Hurtbox      = hurtbox,
                    });
                }
            }).ScheduleParallel();

            Entities
            .WithName("ApplyCollisions")
            .WithReadOnly(collisions)
            .ForEach((Entity entity, ref PlayerComponent player, in PlayerConfig config, in CharacterFrame frame) => {
                NativeArray <HitboxCollision>?playerCollisions = collisions.CopyValuesForKey(entity);
                if (playerCollisions == null)
                {
                    return;
                }

                // Sort collisions
                playerCollisions.Value.Sort();
            }).Schedule();
Example #24
0
    unsafe void Start()
    {
        em = World.Active.EntityManager;
        CreateArchetypes();
        float3[] vertices = new float3[snakeHeadMesh.vertices.Length];

        for (int i = 0; i < snakeHeadMesh.vertices.Length; i++)
        {
            vertices[i] = snakeHeadMesh.vertices[i];
        }

        float3[] bodyVertices = new float3[snakeBodyMesh.vertices.Length];

        for (int i = 0; i < snakeBodyMesh.vertices.Length; i++)
        {
            bodyVertices[i] = snakeBodyMesh.vertices[i];
        }

        var CollidesWith = ~0u;
        var belongsTo    = 1u << 1;
        BlobAssetReference <Unity.Physics.Collider> snakeHeadCollider = Unity.Physics.MeshCollider.Create(vertices, snakeHeadMesh.triangles, new CollisionFilter()
        {
            BelongsTo = belongsTo, CollidesWith = CollidesWith, GroupIndex = 0
        });
        BlobAssetReference <Unity.Physics.Collider> snakeBodyCollider = Unity.Physics.MeshCollider.Create(vertices, snakeHeadMesh.triangles, new CollisionFilter()
        {
            BelongsTo = belongsTo, CollidesWith = CollidesWith, GroupIndex = 0
        });

        float3 startPos      = transform.position;
        var    snakeEntity   = em.CreateEntity(snakeHeadArchetype);
        var    snakePos      = startPos;
        var    snakeRotation = quaternion.identity;

        em.SetComponentData(snakeEntity, new SnakeHead()
        {
            size = 1.0f
        });
        em.SetComponentData(snakeEntity, new Translation()
        {
            Value = snakePos
        });
        em.SetComponentData(snakeEntity, new Rotation()
        {
            Value = snakeRotation
        });
        em.SetComponentData(snakeEntity, new LocalToWorld()
        {
        });
        em.SetComponentData(snakeEntity, new MovementSpeed()
        {
            value = 4.0f
        });
        em.SetComponentData(snakeEntity, new PhysicsCollider()
        {
            Value = snakeBodyCollider
        });
        Unity.Physics.Collider *colliderPtr = (Unity.Physics.Collider *)snakeBodyCollider.GetUnsafePtr();
        em.SetComponentData(snakeEntity, PhysicsMass.CreateDynamic(colliderPtr->MassProperties, mass));

        float3 angularVelocityLocal = math.mul(math.inverse(colliderPtr->MassProperties.MassDistribution.Transform.rot), angularVelocity);

        em.SetComponentData(snakeEntity, new PhysicsVelocity()
        {
            Linear = linearVelocity, Angular = angularVelocityLocal
        });
        em.SetComponentData(snakeEntity, new PhysicsDamping()
        {
            Linear = linearDamping, Angular = angularDamping
        });
        em.SetSharedComponentData(snakeEntity, new RenderMesh()
        {
            mesh = snakeHeadMesh, material = snakeHeadMaterial, castShadows = UnityEngine.Rendering.ShadowCastingMode.On, receiveShadows = true
        });
        var buffer = em.AddBuffer <SnakeBodyBuffer>(snakeEntity);

        for (int i = 0; i < nSize; i++)
        {
            var snakeBodyPos      = startPos;
            var snakeBodyRotation = quaternion.identity;
            buffer.Add(new SnakeBodyBuffer()
            {
                position = snakeBodyPos, rotation = snakeBodyRotation
            });
        }

        for (int i = 0; i < nSize; i++)
        {
            var snakeBodyEntity   = em.CreateEntity(snakeBodyArchetype);
            var snakeBodyPos      = startPos;
            var snakeBodyRotation = quaternion.identity;

            em.SetComponentData(snakeBodyEntity, new SnakeBody()
            {
                index = i, entity = snakeEntity, size = 1.0f, target = snakeBodyPos
            });
            em.SetComponentData(snakeBodyEntity, new Translation()
            {
                Value = snakeBodyPos
            });
            em.SetComponentData(snakeBodyEntity, new Rotation()
            {
                Value = snakeBodyRotation
            });
            em.SetComponentData(snakeBodyEntity, new LocalToWorld()
            {
            });
            em.SetComponentData(snakeBodyEntity, new PhysicsCollider()
            {
                Value = snakeBodyCollider
            });
            Unity.Physics.Collider *colliderPtr2 = (Unity.Physics.Collider *)snakeHeadCollider.GetUnsafePtr();
            em.SetComponentData(snakeBodyEntity, PhysicsMass.CreateDynamic(colliderPtr2->MassProperties, mass));
            em.SetComponentData(snakeBodyEntity, new PhysicsVelocity()
            {
                Linear = linearVelocity, Angular = angularVelocityLocal
            });
            em.SetComponentData(snakeBodyEntity, new PhysicsDamping()
            {
                Linear = linearDamping, Angular = angularDamping
            });
            em.SetSharedComponentData(snakeBodyEntity, new RenderMesh()
            {
                mesh = snakeBodyMesh, material = snakeBodyMaterial, castShadows = UnityEngine.Rendering.ShadowCastingMode.On, receiveShadows = true
            });
        }
    }
    protected unsafe override void Start()
    {
        float3 gravity = new float3(0, -9.81f, 0);

        base.init(gravity);

        // Make heightfield data
        float *heights;
        int2   size;
        float3 scale;
        bool   simple   = false;
        bool   flat     = false;
        bool   mountain = false;

        if (simple)
        {
            size       = new int2(2, 2);
            scale      = new float3(1, 0.1f, 1);
            heights    = (float *)UnsafeUtility.Malloc(size.x * size.y * sizeof(float), 4, Allocator.Temp);
            heights[0] = 1;
            heights[1] = 0;
            heights[2] = 0;
            heights[3] = 1;
        }
        else
        {
            size  = new int2(SizeX, SizeZ);
            scale = new float3(ScaleX, ScaleY, ScaleZ);
            float period = 50.0f;
            heights = (float *)UnsafeUtility.Malloc(size.x * size.y * sizeof(float), 4, Allocator.Temp);
            for (int j = 0; j < size.y; j++)
            {
                for (int i = 0; i < size.x; i++)
                {
                    float a = (i + j) * 2.0f * (float)math.PI / period;
                    heights[i + j * size.x] = flat ? 0.0f : math.sin(a);
                    if (mountain)
                    {
                        float fractionFromCenter = 1.0f - math.min(math.length(new float2(i - size.x / 2, j - size.y / 2)) / (math.min(size.x, size.y) / 2), 1.0f);
                        float mountainHeight     = math.smoothstep(0.0f, 1, fractionFromCenter) * 25.0f;
                        heights[i + j * size.x] += mountainHeight;
                    }
                }
            }
        }

        // static terrain
        Entity staticEntity;
        {
            BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.TerrainCollider.Create(size, scale, heights, Method);

            bool convertToMesh = false;
            if (convertToMesh)
            {
#pragma warning disable 618
                var res = Unity.Physics.Authoring.DisplayBodyColliders.DrawComponent.BuildDebugDisplayMesh((Unity.Physics.Collider *)collider.GetUnsafePtr());
#pragma warning restore 618
                Vector3[] v        = res[0].Mesh.vertices;
                float3[]  vertices = new float3[v.Length];
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i] = v[i];
                }
                collider = Unity.Physics.MeshCollider.Create(vertices, res[0].Mesh.triangles);
            }

            bool compound = false;
            if (compound)
            {
                var instances = new NativeArray <CompoundCollider.ColliderBlobInstance>(4, Allocator.Temp);
                for (int i = 0; i < 4; i++)
                {
                    instances[i] = new CompoundCollider.ColliderBlobInstance
                    {
                        Collider          = collider,
                        CompoundFromChild = new RigidTransform
                        {
                            pos = new float3((i % 2) * scale.x * (size.x - 1), 0.0f, (i / 2) * scale.z * (size.y - 1)),
                            rot = quaternion.identity
                        }
                    };
                }
                collider = Unity.Physics.CompoundCollider.Create(instances);
                instances.Dispose();
            }

            float3 position = new float3(size.x - 1, 0.0f, size.y - 1) * scale * -0.5f;
            staticEntity = CreateStaticBody(position, quaternion.identity, collider);
        }

        UnsafeUtility.Free(heights, Allocator.Temp);
    }
Example #26
0
    public unsafe Entity CreateBody(EntityManager entityManager, RenderMesh displayMesh, float3 position, quaternion orientation, BlobAssetReference <Collider> spCollider, float3 linearVelocity, float3 angularVelocity, float mass, bool isDynamic)
    {
        var componentTypes = new ComponentType[_isDynamic ? 10 : 7];

        componentTypes[0] = typeof(RenderMesh);
        componentTypes[1] = typeof(RenderBounds);
        componentTypes[2] = typeof(Translation);
        componentTypes[3] = typeof(Rotation);
        componentTypes[4] = typeof(LocalToWorld);
        componentTypes[5] = typeof(PhysicsCollider);
        componentTypes[6] = typeof(DestroyEntityDelayed);
        if (_isDynamic)
        {
            componentTypes[7] = typeof(PhysicsVelocity);
            componentTypes[8] = typeof(PhysicsMass);
            componentTypes[9] = typeof(PhysicsDamping);
        }

        var entity = entityManager.CreateEntity(componentTypes);

        entityManager.SetSharedComponentData(entity, displayMesh);
        // entityManager.SetComponentData(entity, new RenderMesh { Value = displayMesh.mesh.bounds.ToAABB() });
        entityManager.SetComponentData(entity, new RenderBounds {
            Value = displayMesh.mesh.bounds.ToAABB()
        });

        entityManager.SetComponentData(entity, new Translation {
            Value = position
        });
        entityManager.SetComponentData(entity, new Rotation {
            Value = orientation
        });

        entityManager.SetComponentData(entity, new PhysicsCollider {
            Value = spCollider
        });
        entityManager.SetComponentData(entity, new DestroyEntityDelayed {
            timeLeft = UnityEngine.Random.Range(2.0f, 20.0f)
        });
        if (!_isDynamic)
        {
            return(entity);
        }

        var colliderPtr = (Collider *)spCollider.GetUnsafePtr();

        entityManager.SetComponentData(entity, PhysicsMass.CreateDynamic(colliderPtr->MassProperties, mass));

        // Calculate the angular velocity in local space from rotation and world angular velocity
        var angularVelocityLocal = math.mul(math.inverse(colliderPtr->MassProperties.MassDistribution.Transform.rot), angularVelocity);

        entityManager.SetComponentData(entity, new PhysicsVelocity()
        {
            Linear  = linearVelocity,
            Angular = angularVelocityLocal
        });
        entityManager.SetComponentData(entity, new PhysicsDamping()
        {
            Linear  = 0.01f,
            Angular = 0.05f
        });

        return(entity);
    }
Example #27
0
    protected unsafe override void OnUpdate()
    {
        var _ecb                  = m_EntityCommandBufferSystem.CreateCommandBuffer();
        var _ecbo                 = m_EntityCommandBufferSystemo.CreateCommandBuffer();
        var _ecbEndSimilation     = m_endSimulationEntityCommandBufferSystem.CreateCommandBuffer();
        var _ecbBeginPresentation = m_beginPresentationEntityCommandBufferSystem.CreateCommandBuffer();

        var            _physicsWorldSystem = World.DefaultGameObjectInjectionWorld.GetExistingSystem <Unity.Physics.Systems.BuildPhysicsWorld>();
        CollisionWorld _collisionWorld     = _physicsWorldSystem.PhysicsWorld.CollisionWorld;
        var            _physicsWorld       = _physicsWorldSystem.PhysicsWorld;

        float3 _startPosition      = ECS_RTSControls.instance._startScreenPosition;
        float3 _endPosition        = ECS_RTSControls.instance._endScreenPosition;
        float3 _lowerLeftPosition  = ECS_RTSControls.instance._lowerLeftScreenPosition;
        float3 _upperRightPosition = ECS_RTSControls.instance._upperRightScreenPosition;

        Dependency = JobHandle.CombineDependencies(Dependency, m_EndFramePhysicsSystem.GetOutputDependency());

        if (_inputReady)
        {
            if (Input_Mouse_0_Up == true && Input_Mouse_0_Up != EntityManager.HasComponent <Input_Mouse_0_Up>(_inputEntity))
            {
                Input_Mouse_0_GetDown = true;
                Input_Mouse_0_Up      = false;
            }

            if (Input_Mouse_0_Up == false && (Input_Mouse_0_Up != EntityManager.HasComponent <Input_Mouse_0_Up>(_inputEntity)))
            {
                Input_Mouse_0_GetUp = true;
                Input_Mouse_0_Up    = true;
            }

            if (Input_Mouse_1_Up == true && (Input_Mouse_1_Up != EntityManager.HasComponent <Input_Mouse_1_Up>(_inputEntity)))
            {
                Input_Mouse_1_GetDown = true;
                Input_Mouse_1_Up      = false;
            }
            if (Input_Mouse_1_Up == false && (Input_Mouse_1_Up != EntityManager.HasComponent <Input_Mouse_1_Up>(_inputEntity)))
            {
                Input_Mouse_1_GetUp = true;
                Input_Mouse_1_Up    = true;
            }
        }
        else
        {
            if (_queryInput.CalculateEntityCount() > 0)
            {
                _inputEntity     = _queryInput.GetSingletonEntity();
                _inputReady      = true;
                Input_Mouse_0_Up = EntityManager.HasComponent <Input_Mouse_0_Up>(_inputEntity);
                Input_Mouse_1_Up = EntityManager.HasComponent <Input_Mouse_1_Up>(_inputEntity);
            }
        }

        if (Time.ElapsedTime > 4)
        {
            /*this.Dependency =  Entities.WithoutBurst().ForEach((in Translation _translation, in UnitSelected _unitSelected, in Selectable _selectable, in GrisTag _grisTag, in Entity _entity) =>
             * {
             *   var e = _ecbEndSimilation.Instantiate(PrefabConvert._DalleVerte);
             *   _ecbEndSimilation.SetComponent<Translation>(e, _translation);
             *   _ecbEndSimilation.DestroyEntity(_entity);
             *   Debug.Log("Unity3d : 'va te faire foutre'");
             *
             * }).Schedule(this.Dependency);*/
        }

        if (Input_Mouse_0_GetUp == true)
        {
            bool  selectOnlyOneEntity  = false;
            float selectionAreaMinSize = 10f;
            float selectionAreaSize    = math.distance(_lowerLeftPosition, _upperRightPosition);
            if (selectionAreaSize < selectionAreaMinSize)
            {
                // Selection area too small
                _lowerLeftPosition  += new float3(-1, -1, 0) * (selectionAreaMinSize - selectionAreaSize) * .5f;
                _upperRightPosition += new float3(+1, +1, 0) * (selectionAreaMinSize - selectionAreaSize) * .5f;
                selectOnlyOneEntity  = true;
            }

            // Deselect all selected Entities
            this.Dependency = Entities.WithAll <UnitSelected>().ForEach((Entity entity) => {
                _ecb.RemoveComponent <UnitSelected>(entity);
            }).Schedule(this.Dependency);



            Unity.Physics.RaycastHit _hit1 = new Unity.Physics.RaycastHit();
            Unity.Physics.RaycastHit _hit2 = new Unity.Physics.RaycastHit();
            Unity.Physics.RaycastHit _hit3 = new Unity.Physics.RaycastHit();
            Unity.Physics.RaycastHit _hit4 = new Unity.Physics.RaycastHit();
            Unity.Physics.RaycastHit _hit5 = new Unity.Physics.RaycastHit();

            var _ray1 = ECS_RTSControls.instance._ray1;
            var _ray2 = ECS_RTSControls.instance._ray2;
            var _ray3 = ECS_RTSControls.instance._ray3;
            var _ray4 = ECS_RTSControls.instance._ray4;
            var _ray5 = ECS_RTSControls.instance._ray5;

            /*RaycastInput _inputo = new RaycastInput()
             * {
             *  Start = _ray1.origin,
             *  End = _ray1.origin + _ray1.direction * 1000,
             *  Filter = new CollisionFilter()
             *  {
             *      BelongsTo = (uint)10 << 10,
             *      CollidesWith = (uint)7 << 8,
             *      GroupIndex = 8
             *  }
             * };*/

            GetRaycastHit(_collisionWorld, _ray1, _ray2, _ray3, _ray4, _ray5, out _hit1, out _hit2, out _hit3, out _hit4, out _hit5);


            var _filter = new CollisionFilter()
            {
                BelongsTo    = ~1u,
                CollidesWith = ~1u, // all 1s, so all layers, collide with everything
                GroupIndex   = 0
            };

            NativeList <ColliderCastHit> _allHits = new NativeList <ColliderCastHit>(Allocator.TempJob);


            _polygonCollider = Unity.Physics.PolygonCollider.CreateQuad(_hit1.Position, _hit2.Position, _hit3.Position, _hit4.Position, _filter);

            /*SphereGeometry sphereGeometry = new SphereGeometry() { Center = float3.zero, Radius = 3 };
             * _sphereCollider = Unity.Physics.SphereCollider.Create(sphereGeometry, _filter);*/
            /*
             * Unity.Physics.ColliderCastInput colliderCastInput = new ColliderCastInput()
             * {
             *  Collider = (Unity.Physics.Collider*)_sphereCollider.GetUnsafePtr(),
             *  Orientation = ECS_RTSControls.instance._camera.transform.rotation,
             *  Start = ECS_RTSControls.instance._camera.transform.position,
             *  End = _ray1.origin + _ray1.direction * 1000
             * };*/
            var _moyPoly = new float3((_hit1.Position.x + _hit2.Position.x + _hit3.Position.x + _hit4.Position.x) / 4,
                                      (_hit1.Position.y + _hit2.Position.y + _hit3.Position.y + _hit4.Position.y) / 4,
                                      (_hit1.Position.z + _hit2.Position.z + _hit3.Position.z + _hit4.Position.z) / 4);



            Debug.Log(_moyPoly + "_moyPoly");

            //var  _pouitCollider = BlobAssetReference<Unity.Physics.Collider>.Create(_polygonCollider.GetUnsafePtr(), 1);

            /* this.Dependency = Job.WithoutBurst().WithCode(() =>
             * {
             *   var e = _ecb.Instantiate(PrefabConvert._CubeRouge);
             *   _ecb.SetComponent<Translation>(e, new Translation { Value = _hit1.Position + new float3(0, 5, 0) });
             *   e = _ecb.Instantiate(PrefabConvert._CubeRouge);
             *   _ecb.SetComponent<Translation>(e, new Translation { Value = _hit2.Position + new float3(0, 5, 0) });
             *   e = _ecb.Instantiate(PrefabConvert._CubeRouge);
             *   _ecb.SetComponent<Translation>(e, new Translation { Value = _hit3.Position + new float3(0, 5, 0) });
             *   e = _ecb.Instantiate(PrefabConvert._CubeRouge);
             *   _ecb.SetComponent<Translation>(e, new Translation { Value = _hit4.Position + new float3(0, 5, 0) });
             * }).Schedule(this.Dependency);
             * Debug.Log(_dalleSelectedQuery.CalculateEntityCount() + "_dalleSelectedQueryCount");
             * Debug.Log(_dalleQuery.CalculateEntityCount() + "_dalleQueryCount");
             *
             * /*Mesh _mesh = new Mesh { }
             *
             * RenderMesh huiaef = new RenderMesh { mesh = }
             *
             * this.Dependency.Complete();*/

            ColliderCastJob _colliderCastJob = new ColliderCastJob();
            _colliderCastJob.CollectAllHits   = true;
            _colliderCastJob.Collider         = (Unity.Physics.Collider *)_polygonCollider.GetUnsafePtr();
            _colliderCastJob.ColliderCastHits = _allHits;
            _colliderCastJob.End         = new float3(0, -2, 0); // _moyPoly;
            _colliderCastJob.Orientation = quaternion.identity;  //ECS_RTSControls.instance._camera.transform.rotation;
            _colliderCastJob.Start       = /*_moyPoly +*/ new float3(0, 5, 0);
            _colliderCastJob.World       = _physicsWorld;
            Dependency = _colliderCastJob.ScheduleSingle(_query, this.Dependency);

            //World.GetOrCreateSystem<StepPhysicsWorld>().FinalSimulationJobHandle.Complete();

            this.Dependency.Complete();

            /*Debug.Log(_query.CalculateEntityCount() + "_queryMovestats");
             * Debug.Log(_allHits.Length + "_allHits.Length");*/
            this.Dependency = Job.WithoutBurst().WithDisposeOnCompletion(_allHits).WithCode(() =>
            {
                for (int i = 0; i < _allHits.Length; i++)
                {
                    _ecbEndSimilation.AddComponent(_allHits[i].Entity, new UnitSelected());
                }

                Debug.Log(_allHits.Length + "entityHits");
            }).Schedule(this.Dependency);

            this.Dependency.Complete();
        }

        if (Input_Mouse_1_Up == false)
        {
            if (Time.ElapsedTime > 2)
            {
                Debug.Log("yoloZoulou");
                this.Dependency = Entities.WithoutBurst().WithAll <PlaneLayer>().WithAll <Player1>().ForEach((Entity entity) => {
                    _ecb.DestroyEntity(entity);//.RemoveComponent<UnitSelected>(entity);
                }).Schedule(this.Dependency);
            }

            //Debug.Log(Input.GetMouseButtonDown(1));
            // Right mouse button down
            float3        targetPosition   = UtilsClass.GetMouseWorldPosition();
            List <float3> movePositionList = GetPositionListAround(targetPosition, new float[] { 10f, 20f, 30f }, new int[] { 5, 10, 20 });
            int           positionIndex    = 0;
            Entities.WithAll <UnitSelected>().ForEach((Entity entity, ref MoveStats _moveStats) => {
                /*moveTo.position = movePositionList[positionIndex];
                 * positionIndex = (positionIndex + 1) % movePositionList.Count;
                 * moveTo.move = true;*/
            }).Schedule();
        }
        //m_EntityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
        World.GetOrCreateSystem <StepPhysicsWorld>().FinalSimulationJobHandle.Complete();
        this.Dependency.Complete();
        m_EntityCommandBufferSystemo.AddJobHandleForProducer(this.Dependency);
        m_endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
        m_EntityCommandBufferSystemo.AddJobHandleForProducer(this.Dependency);

        if (_polygonCollider.IsCreated)
        {
            _polygonCollider.Dispose();
        }
        if (_sphereCollider.IsCreated)
        {
            _sphereCollider.Dispose();
        }
        Input_Mouse_0_GetUp   = false;
        Input_Mouse_0_GetDown = false;
    }