コード例 #1
0
    private void AddedComponents <T>() where T : struct, IComponentData
    {
        ComponentType          componentType = ComponentType.Create <T>();
        ComponentGroup         group         = GetComponentGroup(ComponentType.Create <NetworkSyncState>(), componentType, ComponentType.Subtractive <NetworkComponentState <T> >(), ComponentType.Create <NetworktAuthority>());
        ComponentDataArray <T> components    = group.GetComponentDataArray <T>();
        ComponentDataArray <NetworkSyncState> networkSyncStateComponents = group.GetComponentDataArray <NetworkSyncState>();
        EntityArray entities = group.GetEntityArray();

        NetworkMemberInfo[] networkMemberInfos = reflectionUtility.GetNetworkMemberInfo(componentType);

        for (int i = 0; i < entities.Length; i++)
        {
            NetworkSyncState       networkSyncState = networkSyncStateComponents[i];
            ComponentDataContainer componentData    = new ComponentDataContainer {
                ComponentTypeId = reflectionUtility.GetComponentTypeID(componentType)
            };

            T component = components[i];
            for (int j = 0; j < networkMemberInfos.Length; j++)
            {
                componentData.MemberData.Add(new MemberDataContainer {
                    MemberId = j,
                    Data     = (networkMemberInfos[j] as NetworkMemberInfo <T>).GetValue(component),
                });
            }


            ownNetworkSendMessageUtility.AddComponent(entities[i], networkSyncState.actorId, networkSyncState.networkId, componentData);
            AllNetworkSendMessageUtility.AddComponent(entities[i], networkSyncState.actorId, networkSyncState.networkId, componentData);

            int numberOfMembers = reflectionUtility.GetNumberOfMembers(componentType.GetManagedType());
            networkFactory.CreateNetworkComponentData <T>(entities[i], numberOfMembers);
            PostUpdateCommands.AddComponent(entities[i], new NetworkComponentState <T>());
        }
    }
コード例 #2
0
    private bool GetComponentData <T>(ref Entity entity, out ComponentDataContainer componentDataContainer) where T : struct, IComponentData
    {
        componentDataContainer = null;
        if (EntityManager.HasComponent <T>(entity))
        {
            ComponentType componentType   = ComponentType.Create <T>();
            int           numberOfMembers = reflectionUtility.GetNumberOfMembers(componentType.GetManagedType());

            T component = EntityManager.GetComponentData <T>(entity);
            NetworkMemberInfo[]        networkMemberInfos   = reflectionUtility.GetNetworkMemberInfo(componentType);
            List <MemberDataContainer> memberDataContainers = new List <MemberDataContainer>();
            for (int i = 0; i < numberOfMembers; i++)
            {
                memberDataContainers.Add(new MemberDataContainer()
                {
                    MemberId = i,
                    Data     = (networkMemberInfos[i] as NetworkMemberInfo <T>).GetValue(component)
                });
            }


            componentDataContainer = new ComponentDataContainer()
            {
                ComponentTypeId = reflectionUtility.GetComponentTypeID(componentType),
                MemberData      = memberDataContainers
            };
            return(true);
        }
        return(false);
    }
コード例 #3
0
    private bool AddComponentDataOnEntityAdded <T>(ref Entity entity, out ComponentDataContainer componentDataContainer) where T : struct, IComponentData
    {
        componentDataContainer = null;
        if (EntityManager.HasComponent <T>(entity))
        {
            ComponentType     componentType     = ComponentType.Create <T>();
            int               numberOfMembers   = reflectionUtility.GetNumberOfMembers(componentType.GetManagedType());
            Entity            networkDataEntity = networkFactory.CreateNetworkComponentData <T>(entity, numberOfMembers);
            NativeArray <int> values            = networkFactory.NetworkEntityManager.GetFixedArray <int>(networkDataEntity);
            PostUpdateCommands.AddComponent(entity, new NetworkComponentState <T>());

            T component = EntityManager.GetComponentData <T>(entity);
            NetworkMemberInfo[]        networkMemberInfos   = reflectionUtility.GetNetworkMemberInfo(componentType);
            List <MemberDataContainer> memberDataContainers = new List <MemberDataContainer>();
            for (int i = 0; i < numberOfMembers; i++)
            {
                int value = (networkMemberInfos[i] as NetworkMemberInfo <T>).GetValue(component);
                memberDataContainers.Add(new MemberDataContainer()
                {
                    MemberId = i,
                    Data     = value
                });
                values[i] = value;
            }

            componentDataContainer = new ComponentDataContainer()
            {
                ComponentTypeId = reflectionUtility.GetComponentTypeID(componentType),
                MemberData      = memberDataContainers
            };
            return(true);
        }
        return(false);
    }
コード例 #4
0
 public void SetComponentData(Entity entity, int actorId, int networkId, ComponentDataContainer componentDataContainer)
 {
     if (!EntityContainerMap.TryGetValue(entity, out NetworkSyncDataEntityContainer dataContainer))
     {
         dataContainer = new NetworkSyncDataEntityContainer()
         {
             NetworkSyncEntity = new NetworkSyncEntity()
             {
                 ActorId   = actorId,
                 NetworkId = networkId,
             }
         };
         DataContainer.NetworkSyncDataEntities.Add(dataContainer);
         EntityContainerMap.Add(entity, dataContainer);
     }
     dataContainer.ComponentData.Add(componentDataContainer);
 }
コード例 #5
0
    private void UpdateDataState <T>() where T : struct, IComponentData
    {
        ComponentType  componentType = ComponentType.Create <T>();
        ComponentGroup group         = GetComponentGroup(ComponentType.Create <NetworkSyncState>(), componentType, ComponentType.Create <NetworkComponentState <T> >(), ComponentType.Create <NetworktAuthority>());
        ComponentDataArray <NetworkSyncState> networkSyncStateComponents = group.GetComponentDataArray <NetworkSyncState>();
        ComponentDataArray <T> networkComponents = group.GetComponentDataArray <T>();
        ComponentDataArray <NetworkComponentState <T> > networkComponentStates = group.GetComponentDataArray <NetworkComponentState <T> >();
        EntityArray entities = group.GetEntityArray();

        ComponentDataFromEntity <NetworkSyncState> networkSyncStateEntities = EntityManager.GetComponentDataFromEntity <NetworkSyncState>();

        NetworkMemberInfo[] networkMemberInfos = reflectionUtility.GetNetworkMemberInfo(componentType);
        for (int i = 0; i < entities.Length; i++)
        {
            DynamicBuffer <int>    values = EntityManager.GetBuffer <NetworkValue>(networkComponentStates[i].dataEntity).Reinterpret <int>();
            ComponentDataContainer componentDataContainer = new ComponentDataContainer {
                ComponentTypeId = reflectionUtility.GetComponentTypeID(componentType),
            };
            for (int j = 0; j < networkMemberInfos.Length; j++)
            {
                NetworkMemberInfo <T> networkMemberInfo = (networkMemberInfos[j] as NetworkMemberInfo <T>);
                if (networkMemberInfo.netSyncOptions.InitOnly)
                {
                    continue;
                }

                int newValue = networkMemberInfo.GetValue(networkComponents[i], networkSyncStateEntities);
                if (newValue != values[j])
                {
                    componentDataContainer.MemberData.Add(new MemberDataContainer {
                        MemberId = j,
                        Data     = newValue,
                    });
                }
                values[j] = newValue;
            }

            if (componentDataContainer.MemberData.Count != 0)
            {
                NetworkSyncState networkSyncState = networkSyncStateComponents[i];
                ownNetworkSendMessageUtility.SetComponentData(entities[i], networkSyncState.actorId, networkSyncState.networkId, componentDataContainer);
                AllNetworkSendMessageUtility.SetComponentData(entities[i], networkSyncState.actorId, networkSyncState.networkId, componentDataContainer);
            }
        }
    }
    protected override void OnUpdate()
    {
        //Get Physic World
        PhysicsWorld physicsWorld = buildPhysicsWorld.PhysicsWorld;

        //Create ECB
        var entityCommandBuffer = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent();

        //Create parallel writer
        NativeQueue <BulletInfo> .ParallelWriter events = bulletEvents.AsParallelWriter();

        //Get all enemy existing
        ComponentDataContainer <EnemyTag> enemies = new ComponentDataContainer <EnemyTag>
        {
            Components = GetComponentDataFromEntity <EnemyTag>(true)
        };
        //Get all entities with life
        ComponentDataContainer <LifeComponent> entitiesLife = new ComponentDataContainer <LifeComponent>
        {
            Components = GetComponentDataFromEntity <LifeComponent>(true)
        };
        //
        ComponentDataContainer <DropChanceComponent> dropChance = new ComponentDataContainer <DropChanceComponent>
        {
            Components = GetComponentDataFromEntity <DropChanceComponent>(true)
        };
        //Get Player entity
        Entity player = GameVariables.Player.Entity;

        JobHandle job = Entities.ForEach((Entity entity, int entityInQueryIndex, ref DamageProjectile projectile,
                                          ref Translation translation, in Rotation rotation, in BulletCollider bulletCollider,
                                          in BulletPreviousPositionData previousPosition) =>
        {
            //Create Personal Filter for each Bullet
            CollisionFilter filter = new CollisionFilter
            {
                BelongsTo    = bulletCollider.BelongsTo.Value,
                CollidesWith = bulletCollider.CollidesWith.Value,
                GroupIndex   = bulletCollider.GroupIndex
            };

            //Find direction
            float3 direction = translation.Value - previousPosition.Value;
            direction        = math.normalizesafe(direction);

            //Find Vector to add
            float3 offset   = default;
            float offsetRad = math.radians(90f);
            float cos       = math.cos(offsetRad);
            float sin       = math.sin(offsetRad);
            offset.x        = direction.x * cos - direction.z * sin;
            offset.z        = direction.x * sin + direction.z * cos;
            offset         *= projectile.Radius;

            //Create Ray Inputs
            RaycastInput middleRayCast =
                GetRayCastInput(filter, translation.Value, previousPosition.Value, float3.zero);
            RaycastInput rightRayCast =
                GetRayCastInput(filter, translation.Value, previousPosition.Value, offset);
            RaycastInput leftRayCast =
                GetRayCastInput(filter, translation.Value, previousPosition.Value,
                                -offset); //Adding a negative radius

            bool hitDetected   = false;
            Entity hitEntity   = Entity.Null;
            RaycastHit hit     = default;
            float3 hitPosition = default;

            //Try first RayCast
            if (physicsWorld.CollisionWorld.CastRay(middleRayCast, out RaycastHit middleRayCastHit))
            {
                hitDetected = true;
                hit         = middleRayCastHit;
                hitPosition = float3.zero;

                //Get Hit Entity
                hitEntity = physicsWorld.Bodies[middleRayCastHit.RigidBodyIndex].Entity;
            }
            else if (physicsWorld.CollisionWorld.CastRay(rightRayCast, out RaycastHit rightRayCastHit))
            {
                hitDetected = true;
                hit         = rightRayCastHit;
                hitPosition = -offset;

                //Get Hit Entity
                hitEntity = physicsWorld.Bodies[rightRayCastHit.RigidBodyIndex].Entity;
            }
            //Try second RayCast (Only if first one didnt hit)
            else if (physicsWorld.CollisionWorld.CastRay(leftRayCast, out RaycastHit leftRayCastHit))
            {
                hitDetected = true;
                hit         = leftRayCastHit;
                hitPosition = offset;

                //Get Hit Entity
                hitEntity = physicsWorld.Bodies[leftRayCastHit.RigidBodyIndex].Entity;
            }

            //Make sure theres a collision
            if (!hitDetected)
            {
                return;
            }
            //Make sure an Entity was found
            if (hitEntity == Entity.Null)
            {
                return;
            }

            //Make sure collision hasn't been found before
            //TODO

            //Treat Collision

            //Collision = Wall until proven opposite
            BulletInfo.BulletCollisionType collisionType = BulletInfo.BulletCollisionType.ON_WALL;

            //Look if HitEntity is Player's
            if (hitEntity == player)
            {
                collisionType = BulletInfo.BulletCollisionType.ON_PLAYER;
            }
            //Look if HitEntity is an enemy
            else if (enemies.Components.HasComponent(hitEntity))
            {
                collisionType = BulletInfo.BulletCollisionType.ON_ENEMY;
            }

            bool shouldBulletBeDestroyed = true;

            //Damage entity
            if (collisionType != BulletInfo.BulletCollisionType.ON_WALL)
            {
                //Make sure HitEntity has LifeComponent
                if (entitiesLife.Components.HasComponent(hitEntity))
                {
                    //Make sure HitEntity has LifeComponent
                    if (entitiesLife.Components.HasComponent(hitEntity))
                    {
                        //Get LifeComponent of this entity
                        LifeComponent life = entitiesLife.Components[hitEntity];

                        //Decrease life
                        if (player == hitEntity)
                        {
                            shouldBulletBeDestroyed = life.DecrementLifeWithInvincibility();
                        }
                        else if (entitiesLife.Components[hitEntity].Life.Value <= 0)
                        {
                            shouldBulletBeDestroyed = false;
                        }
                        else
                        {
                            life.DecrementLife();
                        }

                        //Set Back
                        entityCommandBuffer.SetComponent(entityInQueryIndex, hitEntity, life);
                    }
                }
            }

            //Destroy bullet
            if (shouldBulletBeDestroyed)
            {
                entityCommandBuffer.DestroyEntity(entityInQueryIndex, entity);
                events.Enqueue(new BulletInfo
                {
                    HitEntity      = hitEntity,
                    ProjectileType = projectile.Type,
                    CollisionType  = collisionType,
                    HitPosition    = hit.Position + hitPosition,
                    HitRotation    = rotation.Value
                });
            }
        }).ScheduleParallel(Dependency);
コード例 #7
0
    protected override void OnUpdate()
    {
        //Debug.Log("On StateEvent Update");

        //Create parallel writer
        NativeQueue <AnimationInfo> .ParallelWriter animationEvents = EventsHolder.AnimationEvents.AsParallelWriter();

        ComponentDataContainer <AnimationData> animatedEntities = new ComponentDataContainer <AnimationData>
        {
            Components = GetComponentDataFromEntity <AnimationData>()
        };

        ReadOnlyList <StateInfo> stateEvents = new ReadOnlyList <StateInfo>()
        {
            List = EventsHolder.StateEvents
        };

        //Should work, but might be slow because lots of foreach lolololololololol
        Entities.ForEach((Entity e, DynamicBuffer <DynamicAnimator> dynamicAnimator, ref StateComponent component, in TypeData type) =>
        {
            NativeList <StateInfo> events = new NativeList <StateInfo>(Allocator.Temp);

            //Retrieve all event corresponding to this entity
            for (var index = 0; index < stateEvents.List.Length; index++)
            {
                var info = stateEvents.List[index];
                if (info.Entity == e)
                {
                    events.Add(info);
                }
            }
            //Return if no events with this entity
            if (events.Length <= 0)
            {
                return;
            }

            // bool stateChanged = false;

            //Look for an unlock event
            for (var index = 0; index < events.Length; index++)
            {
                if (events[index].Action == StateInfo.ActionType.Unlock)
                {
                    UnLock(ref component);
                    // stateChanged = true;
                }
            }

            //Retrieve all states desired and choose the most important state
            State stateToChangeTo          = 0;
            State animationStateToChangeTo = 0;
            bool shouldStateMachineLock    = false;
            bool tryChangeEvent            = false;

            for (var index = 0; index < events.Length; index++)
            {
                var info = events[index];
                if (info.Action == StateInfo.ActionType.TryChange)
                {
                    tryChangeEvent = true;
                    if (info.DesiredState > stateToChangeTo)
                    {
                        stateToChangeTo        = info.DesiredState;
                        shouldStateMachineLock = false;
                    }
                    if (info.DesiredState > animationStateToChangeTo)
                    {
                        if (Contains(ref dynamicAnimator, info.DesiredState))
                        {
                            animationStateToChangeTo = info.DesiredState;
                        }
                    }
                }
                else if (info.Action == StateInfo.ActionType.TryChangeAndLock)
                {
                    tryChangeEvent = true;
                    if (info.DesiredState > stateToChangeTo)
                    {
                        stateToChangeTo        = info.DesiredState;
                        shouldStateMachineLock = true;
                    }
                    if (info.DesiredState > animationStateToChangeTo)
                    {
                        if (Contains(ref dynamicAnimator, info.DesiredState))
                        {
                            animationStateToChangeTo = info.DesiredState;
                        }
                    }
                }
            }
            //Change state
            if (tryChangeEvent)
            {
                if (component.CurrentState != stateToChangeTo)
                {
                    TryChangeState(ref component, stateToChangeTo, shouldStateMachineLock);
                }
            }

            //Create animation event (only if state changed)
            if (animatedEntities.Components.HasComponent(e))
            {
                //Make sure animation desired isnt already playing
                if (component.CurrentAnimationState != animationStateToChangeTo)
                {
                    component.CurrentAnimationState = animationStateToChangeTo;

                    animationEvents.Enqueue(new AnimationInfo
                    {
                        Entity   = e,
                        Type     = AnimationInfo.EventType.OnSwapAnimation,
                        NewState = animationStateToChangeTo
                    });
                }
            }
            events.Dispose();
        }).ScheduleParallel(Dependency).Complete();
    }
コード例 #8
0
    protected override void OnUpdate()
    {
        var randomArray = World.GetExistingSystem <PathFollowSystem>().RandomArray;
        ComponentDataContainer <PlayerTag> player = new ComponentDataContainer <PlayerTag>
        {
            Components = GetComponentDataFromEntity <PlayerTag>()
        };
        var    physicsWorld = buildPhysicsWorld.PhysicsWorld;
        double time         = Time.ElapsedTime;
        float  deltaTime    = Time.DeltaTime;
        float3 posPlayer    = EntityManager.GetComponentData <Translation>(GameVariables.Player.Entity).Value;
        var    level        = EventsHolder.LevelEvents.CurrentLevel;

        Entities.ForEach((int nativeThreadIndex, ref PathFollowComponent pathFollow, ref AttackRangeComponent range, ref Translation translation, ref BulletCollider filter, ref TypeData typeData) =>
        {
            //if (math.distance(posPlayer, translation.Value) > 25 && level != MapType.Level_Hell)
            //    return;
            if (pathFollow.BeginWalk)
            {
                return;
            }
            range.IsInRange = false;
            range.CanAttack = false;

            //State changer
            if (math.distancesq(translation.Value, posPlayer) <= range.AgroDistance * range.AgroDistance || level == MapType.Level_Hell)
            {
                RaycastInput raycastInput = new RaycastInput
                {
                    Start  = new float3(translation.Value.x, 0, translation.Value.z),
                    End    = new float3(posPlayer.x, 0, posPlayer.z),
                    Filter = new CollisionFilter()
                    {
                        BelongsTo    = filter.BelongsTo.Value,
                        CollidesWith = filter.CollidesWith.Value,
                        GroupIndex   = filter.GroupIndex
                    }
                };
                if (physicsWorld.CollisionWorld.CastRay(raycastInput, out var hit))
                {
                    if (player.Components.HasComponent(hit.Entity))
                    {
                        range.CanAttack       = true;
                        pathFollow.EnemyState = EnemyState.Attack;
                    }
                    else
                    {
                        if (pathFollow.EnemyState == EnemyState.Attack)
                        {
                            pathFollow.EnemyState = EnemyState.Chase;
                        }
                    }
                }
            }
            else
            {
                pathFollow.EnemyState = EnemyState.Wondering;
            }
            switch (pathFollow.EnemyState)
            {
            case EnemyState.Attack:
                AttackFollow(posPlayer, ref pathFollow, ref range, ref typeData, ref filter, ref physicsWorld, translation);
                break;

            case EnemyState.Chase:
                break;

            case EnemyState.Wondering:
                WonderingFollow(ref pathFollow, ref physicsWorld, ref randomArray, translation, deltaTime,
                                nativeThreadIndex);
                break;
            }
        }).ScheduleParallel();
    }
コード例 #9
0
    protected override void OnUpdate()
    {
        //Create parallel writer
        NativeQueue <WeaponInfo> .ParallelWriter weaponFiredEvents = weaponFired.AsParallelWriter();

        //Create ECB
        EntityCommandBuffer.Concurrent ecb = entityCommandBuffer.CreateCommandBuffer().ToConcurrent();

        //Get all StateData components
        ComponentDataContainer <StateComponent> states = new ComponentDataContainer <StateComponent>
        {
            Components = GetComponentDataFromEntity <StateComponent>()
        };
        ComponentDataContainer <Translation> parentTranslations = new ComponentDataContainer <Translation>
        {
            Components = GetComponentDataFromEntity <Translation>()
        };

        float deltaTime = Time.DeltaTime;

        int boost = GameVariables.Boost;

        JobHandle gunJob = Entities.ForEach(
            (Entity e, int entityInQueryIndex, ref GunComponent gun, in LocalToWorld transform, in Parent parent) =>
        {
            //Make sure SwapDelay < 0
            if (gun.SwapTimer > 0)
            {
                gun.SwapTimer -= deltaTime;
                return;
            }

            //Make sure gun has a parent
            if (!states.Components.HasComponent(parent.Value))
            {
                return;
            }
            //Make sure parent has a Translation
            if (!parentTranslations.Components.HasComponent(parent.Value))
            {
                return;
            }

            //Variables local to job
            StateComponent state = states.Components[parent.Value];
            Translation position = parentTranslations.Components[parent.Value];
            WeaponInfo.WeaponEventType?weaponEventType = null;

            if (gun.IsReloading)
            {
                //Decrease time
                gun.ReloadTime -= deltaTime;

                if (!gun.IsReloading)
                {
                    Reload(ref gun);
                    weaponEventType = WeaponInfo.WeaponEventType.ON_RELOAD;
                }
            }
            //Only if not reloading
            else if (gun.IsBetweenShot)
            {
                //Decrease time
                gun.BetweenShotTime -= deltaTime;
            }

            if (state.CurrentState == State.Reloading)
            {
                if (TryReload(ref gun))
                {
                    StartReload(ref gun);
                }
            }

            //Should weapon be reloading?    //Deactivate this line to block auto reload
            if (TryStartReload(ref gun))
            {
                StartReload(ref gun);
            }

            if (state.CurrentState == State.Attacking)
            {
                if (TryShoot(ref gun))
                {
                    weaponEventType = WeaponInfo.WeaponEventType.ON_SHOOT;
                    Shoot(entityInQueryIndex, ecb, ref gun, transform, position.Value, boost);
                }
            }

            //Add event to NativeQueue
            if (weaponEventType != null)
            {
                weaponFiredEvents.Enqueue(new WeaponInfo
                {
                    Parent     = parent.Value,
                    WeaponType = gun.WeaponType,
                    EventType  = (WeaponInfo.WeaponEventType)weaponEventType,
                    Position   = transform.Position,
                    Rotation   = transform.Rotation,
                    AmountBulletsInMagazine = gun.CurrentAmountBulletInMagazine
                });
            }
        }).ScheduleParallel(Dependency);