public void Execute()
            {
                EntityArray a_patternEntities = requestPatternSetupData.a_entities;

                // int i_spareCompositesCount = i_spareCompositesCount ;

                // Debug.Log ( "aa: " + requestPatternSetupData.Length ) ;
                // Debug.Log ( "i_spareCompositesCount: " + i_spareCompositesCount ) ;

                int i_totalRequiredCompositesCount = requestPatternSetupData.Length * Pattern.AddPatternPrefabSystem.i_compositesCountPerPatternGroup;
                int i_need2AddCompositesCount      = i_totalRequiredCompositesCount - i_spareCompositesCount;

                for (int i_newSpareCompositeIndex = 0; i_newSpareCompositeIndex < i_need2AddCompositesCount; ++i_newSpareCompositeIndex)
                {
                    _AddNewSpareComposites(commandBuffer, f_compositeScale);
                } // for

                /*
                 * for (int i_patternGroupIndex = 0; i_patternGroupIndex < requestPatternSetupData.Length; ++i_patternGroupIndex )
                 * {
                 *  Entity paternGroupEntity = requestPatternSetupData.a_entities [i_patternGroupIndex] ;
                 *  commandBuffer.RemoveComponent <Blocks.Pattern.RequestPatternSetupTag> ( paternGroupEntity ) ;
                 *  commandBuffer.RemoveComponent <Common.Components.IsNotAssignedTag> ( paternGroupEntity ) ;
                 * } // for
                 */
            }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        //Arrays de obstaculos activos y de sus posiciones
        obstaculosActivos = m_ObstaculosActivos.GetEntityArray();
        ComponentDataArray <Position> posicionesObstaculos = m_ObstaculosActivos.GetComponentDataArray <Position>();

        //Arrays de premios activos y de sus posiciones
        premiosActivos = m_PremiosActivos.GetEntityArray();
        ComponentDataArray <Position> posicionesPremios = m_PremiosActivos.GetComponentDataArray <Position>();

        var jobObs = new DesactivarObstaculo {
            Commands = _collisionBarrier.CreateCommandBuffer()
        };

        JobHandle jO = jobObs.Schedule(this, inputDeps);

        var jobPrem = new DesactivarPremio {
            Commands = _collisionBarrier.CreateCommandBuffer()
        };

        JobHandle jP = jobPrem.Schedule(this, jO); //"depende" del job anterior (espera a que termine)

        var jobPalillos = new DesactivarPalillos {
            Commands = _collisionBarrier.CreateCommandBuffer()
        };

        JobHandle jPl = jobPalillos.Schedule(this, jP); //"depende" del job anterior (espera a que termine)

        return(jPl);
    }
예제 #3
0
        public void EntityRemove_RemoveMultipleTimesInSameTick()
        {
            EntityArray entityArray = new EntityArray(3, new ComponentsDefinition());

            Assert.IsTrue(entityArray.TryCreateEntity(out Entity newEntity0));
            Assert.IsTrue(entityArray.TryCreateEntity(out Entity newEntity1));
            Assert.IsTrue(entityArray.TryCreateEntity(out Entity newEntity2));
            entityArray.RemoveEntity(newEntity0);
            entityArray.RemoveEntity(newEntity0);
            entityArray.EndUpdate();
            entityArray.RemoveEntity(newEntity2);
            entityArray.RemoveEntity(newEntity2);
            Assert.IsFalse(entityArray.TryGetEntity(0, out _));
            Assert.IsTrue(entityArray.TryGetEntity(1, out _));
            Assert.IsTrue(entityArray.TryGetEntity(2, out _));
            entityArray.EndUpdate();
            entityArray.RemoveEntity(newEntity1);
            entityArray.RemoveEntity(newEntity1);
            Assert.IsFalse(entityArray.TryGetEntity(0, out _));
            Assert.IsTrue(entityArray.TryGetEntity(1, out _));
            Assert.IsFalse(entityArray.TryGetEntity(2, out _));
            entityArray.EndUpdate();
            Assert.IsFalse(entityArray.TryGetEntity(0, out _));
            Assert.IsFalse(entityArray.TryGetEntity(1, out _));
            Assert.IsFalse(entityArray.TryGetEntity(2, out _));
        }
예제 #4
0
    private void Entities()
    {
        EntityArray entities = addedSyncEntities.entities;
        ComponentDataArray <NetworkSync>      networkSyncs      = addedSyncEntities.networkSyncComponents;
        ComponentDataArray <NetworkSyncState> networkSyncStates = addedSyncEntities.networkSyncStateComponents;

        for (int i = 0; i < entities.Length; i++)
        {
            int instanceId = networkSyncs[i].instanceId;

            Entity            entity            = entities[i];
            NetworkEntityData networkEntityData = new NetworkEntityData {
                InstanceId = networkSyncs[i].instanceId,

                NetworkSyncEntity = new NetworkSyncEntity {
                    ActorId   = networkSyncStates[i].actorId,
                    NetworkId = networkSyncStates[i].networkId,
                }
            };

            for (int j = 0; j < GetComponentDataMethods.Count; j++)
            {
                if (GetComponentDataMethods[j].Invoke(this, ref entity, out ComponentDataContainer componentData))
                {
                    networkEntityData.ComponentData.Add(componentData);
                }
            }

            networkSendMessageUtility.AddEntity(networkEntityData);
        }
    }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            JobHandle outputHandle = inputDeps;

            EntityArray destroyEntityArray = destroyEntityDataGroup.GetEntityArray();

            if (destroyEntityArray.Length > 0)
            {
                Entity destroyEntity = destroyEntityArray[0];
                ComponentDataFromEntity <DestroyEntityData> destroyEntityDataFromEntity = GetComponentDataFromEntity <DestroyEntityData>();

                DestroyEntityData destroyEntityData = destroyEntityDataFromEntity[destroyEntity];

                var outOfBoundJob = new EntityOutOfBoundJob
                {
                    outOfBoundEntityQueue           = destroyEntityData.entityOutOfBoundQueueConcurrent,
                    cameraPosition                  = MonoBehaviourECSBridge.Instance.gameCamera.transform.position,
                    halfFrustumHeightPreCalculation = Mathf.Tan(Camera.main.fieldOfView * 0.5f * Mathf.Deg2Rad),
                };

                outputHandle = outOfBoundJob.Schedule(this, inputDeps);
            }

            return(outputHandle);
        }
예제 #6
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>());
        }
    }
예제 #7
0
    protected override void OnUpdate()
    {
        //Entidades que poseen los componentes LogroComponent y ComprobarLogroComponent
        EntityArray logros = m_Logros.GetEntityArray();
        //Datos de los LogroComponent obtenidos
        var            logroComponents = m_Logros.GetComponentDataArray <LogroComponent>();
        bool           completado;
        LogroComponent componenteAux;

        for (int i = 0; i < logros.Length; i++)
        {
            componenteAux = logroComponents[i];
            completado    = ComprobarLogroCompletado(componenteAux);

            //Subir el nivel en la entidad para la ui
            if (completado)
            {
                EntityManager.SetComponentData(logros[i], new LogroComponent {
                    id             = componenteAux.id,
                    requisitoBase  = componenteAux.requisitoBase,
                    recompensaBase = componenteAux.recompensaBase,
                    nivel          = componenteAux.nivel + 1,
                    factor         = componenteAux.factor
                });

                //Mostrar el pop-up de logro completado
                LogrosManager.PopUpLogroCompletado(componenteAux.id, componenteAux.nivel, componenteAux.recompensaBase * componenteAux.nivel);
            }

            EntityManager.RemoveComponent(logros[i], typeof(ComprobarLogroComponent));
        }
    }
예제 #8
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            EntityCommandBuffer ecb        = barrier.CreateCommandBuffer();
            EntityArray         a_entities = group.GetEntityArray();

            for (int i = 0; i < a_entities.Length; ++i)
            {
                Entity entity = a_entities [i];

                // Renderer
                Common.previousMeshInstanceRenderer = entityManager.GetSharedComponentData <MeshInstanceRenderer> (entity);

                // Assign new renderrer
                Unity.Rendering.MeshInstanceRenderer renderer = Bootstrap.highlightRenderer;

                ecb.SetSharedComponent <MeshInstanceRenderer> (entity, renderer);    // replace renderer with material and mesh

                ecb.RemoveComponent <SetHighlightTag> (entity);
            }


            /*
             * JobHandle job = new Job
             * {
             *  ecb = barrier.CreateCommandBuffer (),
             *  entityManager = entityManager,
             *  a_entities = group.GetEntityArray (),
             *
             * }.Schedule (inputDeps) ;
             *
             * return job ;
             */

            return(inputDeps);
        }
    private void NetworkManager_OnDisconnect()
    {
        ComponentGroup group = GetComponentGroup(ComponentType.Create <NetworkSyncState>(), ComponentType.Create <NetworkSync>());
        ComponentDataArray <NetworkSyncState> networkSyncStateComponents = group.GetComponentDataArray <NetworkSyncState>();
        ComponentDataArray <NetworkSync>      networkSyncComponents      = group.GetComponentDataArray <NetworkSync>();
        EntityArray entities = group.GetEntityArray();

        for (int i = 0; i < entities.Length; i++)
        {
            Entity entity = entities[i];
            PostUpdateCommands.RemoveComponent <NetworkSyncState>(entity);
            if (networkSyncStateComponents[i].actorId != networkManager.LocalPlayerID && networkSyncComponents[i].authority != Authority.Scene)
            {
                PostUpdateCommands.DestroyEntity(entity);
                if (EntityManager.HasComponent <Transform>(entity))
                {
                    gameObjectsToDestroy.Add(EntityManager.GetComponentObject <Transform>(entity).gameObject);
                }
            }
            else if (EntityManager.HasComponent <NetworktAuthority>(entity))
            {
                PostUpdateCommands.RemoveComponent <NetworktAuthority>(entity);
            }
            for (int j = 0; j < RemoveComponentOnDestroyEntityMethods.Count; j++)
            {
                RemoveComponentOnDestroyEntityMethods[j].Invoke(this, entity);
            }
        }
    }
예제 #10
0
    private void RemovedEntities()
    {
        EntityArray entities = removedSyncEntities.entities;
        ComponentDataArray <NetworkSyncState> networkSyncs = removedSyncEntities.networkSyncStateComponents;

        for (int i = 0; i < entities.Length; i++)
        {
            NetworkSyncState component = new NetworkSyncState()
            {
                actorId   = networkManager.LocalPlayerID,
                networkId = networkManager.GetNetworkId(),
            };
            PostUpdateCommands.RemoveComponent <NetworkSyncState>(entities[i]);
            for (int j = 0; j < RemoveComponentOnDestroyEntityMethods.Count; j++)
            {
                RemoveComponentOnDestroyEntityMethods[j].Invoke(this, entities[i]);
            }

            NetworkSyncEntity networkSyncEntity = new NetworkSyncEntity {
                ActorId   = component.actorId,
                NetworkId = component.networkId,
            };
            ownNetworkSendMessageUtility.RemoveEntity(networkSyncEntity);
            AllNetworkSendMessageUtility.RemoveEntity(networkSyncEntity);
        }
    }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            // Debug.LogWarning ( "Col" ) ;
            Bounds checkBounds = new Bounds()
            {
                center = new float3(10, 2, 10),
                size   = new float3(1, 1, 1) * 5  // Total size of boundry
            };


            EntityArray a_entities     = group.GetEntityArray();
            Entity      rootNodeEntity = a_entities [0];

            ComponentDataArray <RootNodeData> a_rootNodeData = group.GetComponentDataArray <RootNodeData> ( );
            RootNodeData rootNodeData = a_rootNodeData [0];

            BufferFromEntity <NodeBufferElement> nodeBufferElement = GetBufferFromEntity <NodeBufferElement> ();
            DynamicBuffer <NodeBufferElement>    a_nodesBuffer     = nodeBufferElement [rootNodeEntity];



            Bounds maxBouds = _GetOctreeMaxBounds(rootNodeData, a_nodesBuffer);


            return(base.OnUpdate(inputDeps));
        }
예제 #12
0
        private void gameGroupBox_Paint(object sender, PaintEventArgs e)
        {
            ClientServerContext clientServerContext = (ClientServerContext)((Control)sender).Tag;
            int         now         = (clientServerContext == ClientServerContext.Client) ? this.gameClient.FrameTick : this.gameServer.FrameTick;
            EntityArray entityArray = (clientServerContext == ClientServerContext.Client) ? this.gameClient.RenderedSnapshot.EntityArray : this.gameServer.EntityArray;

            e.Graphics.DrawString(now.ToString(), this.Font, Brushes.Black, 10, 10);
            if (this.drawInterpolationCheckBox.Checked && clientServerContext == ClientServerContext.Client &&
                this.gameClient.InterpolationStartSnapshot.HasData && this.gameClient.InterpolationEndSnapshot.HasData)
            {
                foreach (Entity entity in this.gameClient.InterpolationStartSnapshot.EntityArray)
                {
                    if (!entity.HasComponent <PositionComponent>())
                    {
                        continue;
                    }

                    ref PositionComponent component = ref entity.GetComponent <PositionComponent>();
                    e.Graphics.FillRectangle(Brushes.Gainsboro, component.Position.X, component.Position.Y, 3, 3);
                }
                foreach (Entity entity in this.gameClient.InterpolationEndSnapshot.EntityArray)
                {
                    ref PositionComponent component = ref entity.GetComponent <PositionComponent>();
                    e.Graphics.FillRectangle(Brushes.Gainsboro, component.Position.X, component.Position.Y, 3, 3);
                }
    private void NetworkManager_OnMasterClientChanged(int oldMasterClientId, int newMasterClientId)
    {
        if (networkManager.LocalPlayerID == oldMasterClientId)
        {
            ComponentGroup group    = GetComponentGroup(ComponentType.Create <NetworkSyncState>(), ComponentType.Create <NetworkSync>(), ComponentType.Create <NetworktAuthority>());
            EntityArray    entities = group.GetEntityArray();
            ComponentDataArray <NetworkSync> networkSync = group.GetComponentDataArray <NetworkSync>();
            for (int i = 0; i < entities.Length; i++)
            {
                if (networkSync[i].authority != Authority.Client)
                {
                    PostUpdateCommands.RemoveComponent <NetworktAuthority>(entities[i]);
                }
            }
        }

        if (networkManager.LocalPlayerID == newMasterClientId)
        {
            ComponentGroup group = GetComponentGroup(ComponentType.Create <NetworkSyncState>(), ComponentType.Create <NetworkSync>(), ComponentType.Subtractive <NetworktAuthority>());
            ComponentDataArray <NetworkSync> networkSync = group.GetComponentDataArray <NetworkSync>();
            EntityArray entities = group.GetEntityArray();
            for (int i = 0; i < entities.Length; i++)
            {
                if (networkSync[i].authority != Authority.Client)
                {
                    PostUpdateCommands.AddComponent(entities[i], new NetworktAuthority());
                }
            }
        }
    }
예제 #14
0
        protected override void OnUpdate()
        {
            m_mapDataEntities = m_mapDataGroup.GetEntityArray();
            m_DataGroupIndex  = m_mapDataGroup.GetComponentDataArray <MapIndexComponent>();
            m_DataGroupData   = m_mapDataGroup.GetComponentDataArray <MapDataComponent>();

            for (int i = 0; i < 128 * 128; i++)
            {
                m_rawFloatData[m_DataGroupIndex[i].Value.x, m_DataGroupIndex[i].Value.y]    = m_DataGroupData[i].Value;
                m_entityIndexData[m_DataGroupIndex[i].Value.x, m_DataGroupIndex[i].Value.y] = i;
            }

            for (int w = 0; w < 128; w++)
            {
                for (int h = 0; h < 128; h++)
                {
                    //------ INNER LOOP ------
                    for (int wx = -1; wx <= 1; wx++)
                    {
                        for (int hx = -1; hx <= 1; hx++)
                        {
                        }
                    }
                    //------ INNER LOOP ------
                }
            }

            m_mapDataGroup.Dispose();

            Unity.Entities.World.Active.GetExistingManager <MetaDataSystem>().Enabled = false;
        }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        if (!initialized)
        {
            Initialize();
            initialized = true;
        }

        sphereRequestsGroup = GetComponentGroup(typeof(SphereRequest));
        if (sphereRequestsGroup.CalculateLength() == 0)
        {
            return(inputDeps);
        }

        ComponentDataArray <SphereRequest> sphereRequests = sphereRequestsGroup.GetComponentDataArray <SphereRequest>();
        JobHandle sgj = new SphereGenerateSystem.SphereGenerateJob {
            requests      = sphereRequests,
            commandBuffer = generateBarrier.CreateCommandBuffer().ToConcurrent(),
        }.Schedule(sphereRequests.Length, 64, inputDeps);

        EntityArray sphereRequestEntities = sphereRequestsGroup.GetEntityArray();
        JobHandle   srcj = new SphereRequestCleanupJob {
            entities      = sphereRequestEntities,
            commandBuffer = cleanupBarrier.CreateCommandBuffer().ToConcurrent(),
        }.Schedule(sphereRequestEntities.Length, 64, sgj);

        return(srcj);
    }
예제 #16
0
        public void EntityGet_NoEntityExists()
        {
            EntityArray entityArray = new EntityArray(3, new ComponentsDefinition());

            Assert.IsFalse(entityArray.TryGetEntity(0, out Entity noEntity));
            Assert.AreEqual(Entity.NoEntity, noEntity);
            Assert.AreEqual(-1, noEntity.ID);
            Assert.AreEqual(-1, Entity.NoEntity.ID);
        }
예제 #17
0
        protected override void OnUpdate()
        {
            s = m_SonidosMoneda.GetEntityArray();

            for (int i = 0; i < s.Length; i++)
            {
                Bootstrap_NV.bootstrap_NV.PlaySound(0); //reproducir sonido moneda

                EntityManager.RemoveComponent <SonidoMonedaComponent>(s[i]);
            }
        }
예제 #18
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            EntityArray boltSpawnerEntityDataArray = boltSpawnerEntityDataGroup.GetEntityArray();

            if (boltSpawnerEntityDataArray.Length == 0)
            {
                return(inputDeps);
            }

            BoltSpawnerEntityData boltSpawnerEntityData = GetComponentDataFromEntity <BoltSpawnerEntityData>()[boltSpawnerEntityDataArray[0]];

            uniqueEntityTypes.Clear();
            EntityManager.GetAllUniqueSharedComponentData(uniqueEntityTypes);

            JobHandle spawnJobHandle     = new JobHandle();
            JobHandle spawnJobDependency = inputDeps;

            for (int i = 0; i != uniqueEntityTypes.Count; i++)
            {
                EntityTypeData entityTypeData = uniqueEntityTypes[i];
                if (entityTypeData.entityType == EntityTypeData.EntityType.EnemyShip ||
                    entityTypeData.entityType == EntityTypeData.EntityType.AllyShip)
                {
                    aiSpawnBoltDataGroup.SetFilter(uniqueEntityTypes[i]);

                    NativeQueue <Entity> .Concurrent spawnBoltEntityQueueToUse = boltSpawnerEntityData.enemyBoltSpawnQueueConcurrent;
                    if (entityTypeData.entityType == EntityTypeData.EntityType.AllyShip)
                    {
                        spawnBoltEntityQueueToUse = boltSpawnerEntityData.allyBoltSpawnQueueConcurrent;
                    }


                    AISpawnBoltJob aiSpawnBoltJob = new AISpawnBoltJob
                    {
                        entityArray          = aiSpawnBoltDataGroup.GetEntityArray(),
                        aiPositionArray      = aiSpawnBoltDataGroup.GetComponentDataArray <Position>(),
                        aiRotationArray      = aiSpawnBoltDataGroup.GetComponentDataArray <Rotation>(),
                        aiSpawnBoltDataArray = aiSpawnBoltDataGroup.GetComponentDataArray <AISpawnBoltData>(),
                        spawnBoltEntityQueue = spawnBoltEntityQueueToUse,
                        deltaTime            = Time.deltaTime
                    };

                    JobHandle tmpJobHandle = aiSpawnBoltJob.Schedule(aiSpawnBoltJob.aiSpawnBoltDataArray.Length,
                                                                     MonoBehaviourECSBridge.Instance.GetJobBatchCount(aiSpawnBoltJob.aiSpawnBoltDataArray.Length),
                                                                     spawnJobDependency);

                    spawnJobHandle     = JobHandle.CombineDependencies(spawnJobHandle, tmpJobHandle);
                    spawnJobDependency = JobHandle.CombineDependencies(spawnJobDependency, tmpJobHandle);
                }
            }
            aiSpawnBoltDataGroup.ResetFilter();

            return(spawnJobHandle);
        }
예제 #19
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            EntityArray a_entities = group.GetEntityArray();

            Entity entity = a_entities [0];

            EntityManager.RemoveComponent(entity, typeof(ForceCollisionCheckTag));


            return(base.OnUpdate(inputDeps));
        }
예제 #20
0
 /// <summary>
 /// If you just loop and destroy each one in EntityArray without a command buffer, it will cause problems mid-loop!
 /// </summary>
 public static void DestroyAllInEntityArray(this EntityManager em, EntityArray ea)
 {
     using (var na = new NativeArray <Entity>(ea.Length, Allocator.Temp))
     {
         ea.CopyTo(na, 0);
         for (int i = 0; i < na.Length; i++)
         {
             em.DestroyEntity(na[i]);
         }
     }
 }
예제 #21
0
 public SetTargetJob(float dt, float time, EntityCommandBuffer buffer, NativeQueue <DamageInfo> .Concurrent sendDamage, NativeQueue <PathfindingInfo> .Concurrent needsPathfinding, EntityArray entities, ComponentDataArray <NavAgent> agents, ComponentDataArray <AnimatedState> animations, ComponentDataArray <Position> positions, ComponentDataArray <Unit> units)
 {
     this.dt               = dt;
     this.animations       = animations;
     this.entities         = entities;
     this.agents           = agents;
     this.positions        = positions;
     this.units            = units;
     this.sendDamage       = sendDamage;
     this.needsPathfinding = needsPathfinding;
     this.buffer           = buffer;
     this.time             = time;
 }
예제 #22
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            EntityArray boltSpawnerEntityDataArray = boltSpawnerEntityDataGroup.GetEntityArray();

            if (boltSpawnerEntityDataArray.Length == 0)
            {
                return(inputDeps);
            }

            BoltSpawnerEntityData boltSpawnerEntityData = GetComponentDataFromEntity <BoltSpawnerEntityData>()[boltSpawnerEntityDataArray[0]];

            ArchetypeChunkEntityType entityTypeRO = GetArchetypeChunkEntityType();
            ArchetypeChunkComponentType <PlayerInputData>     playerInputDataRO     = GetArchetypeChunkComponentType <PlayerInputData>(true);
            ArchetypeChunkComponentType <PlayerMoveData>      playerMoveDataRO      = GetArchetypeChunkComponentType <PlayerMoveData>(true);
            ArchetypeChunkComponentType <Position>            positionRO            = GetArchetypeChunkComponentType <Position>(true);
            ArchetypeChunkComponentType <PlayerSpawnBoltData> playerSpawnBoltDataRW = GetArchetypeChunkComponentType <PlayerSpawnBoltData>(false);


            //CreateArchetypeChunkArray runs inside a job, we can use a job handle to make dependency on that job
            //A NativeArray<ArchetypeChunk> is allocated with the correct size on the main thread and that's what is returned, we are responsible for de-allocating it (In this case using [DeallocateOnJobCompletion] in the move job)
            //The job scheduled by CreateArchetypeChunkArray fill that array with correct chunk information
            JobHandle createChunckArrayJobHandle = new JobHandle();
            NativeArray <ArchetypeChunk> playerSpawnBoltDataChunks = playerSpawnBoltDataGroup.CreateArchetypeChunkArray(Allocator.TempJob, out createChunckArrayJobHandle);

            //Special case when our query return no chunk at all
            if (playerSpawnBoltDataChunks.Length == 0)
            {
                createChunckArrayJobHandle.Complete();
                playerSpawnBoltDataChunks.Dispose();
                return(inputDeps);
            }

            //Make sure our movejob is dependent on the job filling the array has completed
            JobHandle spawnJobDependency = JobHandle.CombineDependencies(inputDeps, createChunckArrayJobHandle);

            PlayerSpawnBoltJob playerSpawnBoltJob = new PlayerSpawnBoltJob
            {
                chunks                = playerSpawnBoltDataChunks,
                entityTypeRO          = entityTypeRO,
                playerInputDataRO     = playerInputDataRO,
                playerMoveDataRO      = playerMoveDataRO,
                positionRO            = positionRO,
                playerSpawnBoltDataRW = playerSpawnBoltDataRW,
                spawnBoltEntityQueue  = boltSpawnerEntityData.playerBoltSpawnQueueConcurrent,
                currentTime           = Time.time,
            };

            return(playerSpawnBoltJob.Schedule(playerSpawnBoltDataChunks.Length,
                                               MonoBehaviourECSBridge.Instance.GetJobBatchCount(playerSpawnBoltDataChunks.Length),
                                               spawnJobDependency));
        }
예제 #23
0
    protected override void OnUpdate()
    {
        EntityArray entities       = RoleGroup.GetEntityArray();
        var         roleStateArray = RoleGroup.GetComponentArray <RoleState>();
        var         mainRoleGOE    = RoleMgr.GetInstance().GetMainRole();
        float3      mainRolePos    = float3.zero;

        if (mainRoleGOE != null)
        {
            mainRolePos = m_world.GetEntityManager().GetComponentData <Position>(mainRoleGOE.Entity).Value;
        }
        for (int i = 0; i < roleStateArray.Length; i++)
        {
            var  roleState          = roleStateArray[i];
            var  entity             = entities[i];
            bool isNeedReqLooksInfo = false;
            bool isNeedHideLooks    = false;

            //其它玩家离主角近时就要请求该玩家的角色外观信息
            var   curPos   = m_world.GetEntityManager().GetComponentData <Position>(entity).Value;
            float distance = Vector3.Distance(curPos, mainRolePos);
            Debug.Log("distance : " + distance);
            if (!roleState.hasLooks)
            {
                isNeedReqLooksInfo = distance <= 400;
                // bool isMainRole = m_world.GetEntityManager().HasComponent(entity, typeof(UnityMMO.MainRoleTag));
                // if (isMainRole)
                // {
                //     isNeedReqLooksInfo = true;
                // }
                // else
                // {
                // //其它玩家离主角近时就要请求该玩家的角色外观信息
                // var curPos = m_world.GetEntityManager().GetComponentData<Position>(entity).Value;
                // float distance = Vector3.Distance(curPos, mainRolePos);
                // Debug.Log("distance : "+distance);
                // isNeedReqLooksInfo = distance <= 200;
                // }
            }
            else
            {
                isNeedHideLooks = distance >= 300;
            }
            if (isNeedReqLooksInfo)
            {
                roleState.hasLooks = true;
                RoleLooksNetRequest.Create(PostUpdateCommands, roleState.roleUid, entity);
            }
        }
    }
예제 #24
0
        public void EntityCreate()
        {
            EntityArray entityArray = new EntityArray(3, new ComponentsDefinition());

            Assert.IsTrue(entityArray.TryCreateEntity(out Entity newEntity));
            Assert.AreEqual(0, newEntity.ID);
            Assert.IsFalse(entityArray.TryGetEntity(0, out _));
            Assert.IsFalse(entityArray.TryGetEntity(1, out _));
            Assert.IsFalse(entityArray.TryGetEntity(2, out _));
            entityArray.EndUpdate();
            Assert.IsTrue(entityArray.TryGetEntity(0, out Entity fetchedEntity));
            Assert.AreEqual(newEntity, fetchedEntity);
            Assert.IsFalse(entityArray.TryGetEntity(1, out _));
            Assert.IsFalse(entityArray.TryGetEntity(2, out _));
        }
        static public void _DebugRays(EntityArray a_collisionChecksEntities, ComponentDataFromEntity <RayData> a_rayData, ComponentDataFromEntity <RayMaxDistanceData> a_rayMaxDistanceData, ComponentDataFromEntity <IsCollidingData> a_isCollidingData, ComponentDataFromEntity <RayEntityPair4CollisionData> a_rayEntityPair4CollisionData, bool canDebugAllChecks, bool canDebugAllrays)
        {
            // Debug all, or only one check
            int i_debugCollisionChecksCount = canDebugAllChecks ? a_collisionChecksEntities.Length : 1;


            // Debug
            // ! Ensure test this only with single, or at most few ray entiities.
            for (int i_collisionChecksIndex = 0; i_collisionChecksIndex < i_debugCollisionChecksCount; i_collisionChecksIndex++)
            {
                Entity octreeRayEntity = a_collisionChecksEntities [i_collisionChecksIndex];
                Entity octreeRayEntity2;

                if (!a_rayData.Exists(octreeRayEntity))
                {
                    RayEntityPair4CollisionData rayEntityPair4CollisionData = a_rayEntityPair4CollisionData [octreeRayEntity];
                    octreeRayEntity2 = rayEntityPair4CollisionData.ray2CheckEntity;
                }
                else
                {
                    octreeRayEntity2 = octreeRayEntity;
                }

                // Draw all available rays, or signle ray
                if (canDebugAllrays)
                {
                    RayData            rayData            = a_rayData [octreeRayEntity2];
                    RayMaxDistanceData rayMaxDistanceData = a_rayMaxDistanceData [octreeRayEntity2];

                    Debug.DrawLine(rayData.ray.origin, rayData.ray.origin + rayData.ray.direction * rayMaxDistanceData.f, Color.red);
                }
                else if (i_collisionChecksIndex == 0)
                {
                    RayData            rayData            = a_rayData [octreeRayEntity2];
                    RayMaxDistanceData rayMaxDistanceData = a_rayMaxDistanceData [octreeRayEntity2];

                    Debug.DrawLine(rayData.ray.origin, rayData.ray.origin + rayData.ray.direction * rayMaxDistanceData.f, Color.red);
                }


                IsCollidingData isCollidingData = a_isCollidingData [octreeRayEntity];

                if (isCollidingData.i_collisionsCount > 0)
                {
                    Debug.Log("Is colliding.");
                }
            }
        }
예제 #26
0
        /// <summary>
        /// Allows this system to perform any rendering.
        /// </summary>
        public void ClientRender(EntityArray entityArray, Entity commandingEntity)
        {
            if (commandingEntity.IsValid && commandingEntity.HasComponent <SpatialComponent>())
            {
                ref SpatialComponent commandingSpatialComponent = ref commandingEntity.GetComponent <SpatialComponent>();
                this.BasicEffect.View = Matrix.CreateLookAt(commandingSpatialComponent.Position, commandingSpatialComponent.Position + Vector3.Transform(Vector3.Forward, commandingSpatialComponent.Rotation), Vector3.Up);

                foreach (Entity entity in entityArray)
                {
                    if (!entity.HasComponent <SpatialComponent>())
                    {
                        continue;
                    }

                    ref SpatialComponent spatialComponent = ref entity.GetComponent <SpatialComponent>();
                    ref ColorComponent   colorComponent   = ref entity.GetComponent <ColorComponent>();
예제 #27
0
    /// <summary>
    /// same as Show but adds an extra check
    /// to see if when filtering and getting all available entities
    /// we have at least one to make available
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <param name="z"></param>
    /// <returns></returns>
    private Entity ShowResizable(float x, float y, float z)
    {
        m_Group.SetFilter(new Indexer {
            Value = groupIndex
        }, new Visible {
            Value = 0
        });

        // check if the group has any entities available
        // if not it will spawn objects
        // TODO add a extend variable to define how many will be spawned if needed
        if (!(m_Group.CalculateLength() > 0))
        {
            SpawnObjects(amount);
        }
        // put filtered entities in a EntityArray TODO find a better way ?BUFFER MAYBE
        EntityArray entityArray = m_Group.GetEntityArray();
        // the entity we are going to return will be the first in the list
        // no need to iterate all the array
        Entity entity = entityArray[0];

        // mark as visible to filter it out from the next call
        entityManager.SetSharedComponentData(entity, new Visible {
            Value = 1
        });


        //entityManager.AddComponentData(entity, new Static { });//TODO add static object option
        //entityManager.RemoveComponent(entity, typeof(Frozen)); //TODO add static object option


        // set the position of the entity
        entityManager.AddComponentData(entity, new Position {
            Value = new float3(x, y, z)
        });

        // TODO implement this later
        // normally we should calculate AABB for the object and adjust values before the call
        // at the moment we should assign the culling sphere center at where the object is
        // improves performance
        entityManager.SetComponentData(entity, new MeshRenderBounds {
            Center = new float3(x, y, z), Radius = 1.0f
        });
        // magic
        return(entity);
    }
예제 #28
0
 private bool CheckBulletCollision(Entity bullet, Position bulletPosition, Collision bulletCollision,
                                   ComponentDataArray <Position> collisionPositions,
                                   SharedComponentDataArray <Collision> collisions,
                                   EntityArray entities)
 {
     for (var i = 0; i < collisionPositions.Length; i++)
     {
         var distance = math.length(bulletPosition.Value - collisionPositions[i].Value);
         if (distance <= bulletCollision.Radius + collisions[i].Radius)
         {
             PostUpdateCommands.AddComponent(entities[i], new DestroyEntity());
             PostUpdateCommands.AddComponent(bullet, new DestroyEntity());
             return(true);
         }
     }
     return(false);
 }
예제 #29
0
        protected override void OnUpdate()
        {
            exp         = m_Explosiones.GetEntityArray();
            explosiones = m_Explosiones.GetComponentDataArray <ExplosionCMP_NV>();

            Vector3 posicion;

            for (int i = 0; i < exp.Length; i++)
            {
                posicion = explosiones[i].posicion;

                Bootstrap_NV.bootstrap_NV.Explosion(posicion);
                Bootstrap_NV.bootstrap_NV.PlaySound(1);

                EntityManager.RemoveComponent <ExplosionCMP_NV>(exp[i]);
            }
        }
예제 #30
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);
            }
        }
    }