示例#1
0
        public static JobHandle Schedule(CustomSystemBase system, JobHandle dependentOn, TJob jobData)
        {
            EntityQuery query = GetExistingEntityQuery(system);

            if (query == default)
            {
                ComponentType[] componentTypes;
                if (!componentTypesByJobType.TryGetValue(typeof(TJob), out componentTypes))
                {
                    componentTypes = GetIJobCustomComponentTypes();
                }

                query = system.GetEntityQueryPublic(componentTypes);

                system.RequireForUpdate(query);

                if (query.CalculateChunkCount() == 0)
                {
                    return(dependentOn);
                }
            }

            WrapperJob wrapperJob = new WrapperJob
            {
                wrappedJob = jobData,
                // foos = new NativeArray<Foo>(10, Allocator.TempJob), -- this will just leak and cause test failures. we're just testing that the Schedule() will not work in the first place
                entityType    = system.EntityManager.GetEntityTypeHandle(),
                bazType       = system.EntityManager.GetComponentTypeHandle <Baz>(false),
                t0Type        = system.EntityManager.GetBufferTypeHandle <T0>(false),
                isReadOnly_T0 = false
            };

            return(wrapperJob.ScheduleParallel(query, dependentOn));
        }
示例#2
0
    protected override void OnUpdate()
    {
        // Assign values to local variables captured in your job here, so that it has
        // everything it needs to do its work when it runs later.
        // For example,
        //     float deltaTime = Time.DeltaTime;

        // This declares a new kind of job, which is a unit of work to do.
        // The job is declared as an Entities.ForEach with the target components as parameters,
        // meaning it will process all entities in the world that have both
        // Translation and Rotation components. Change it to process the component
        // types you want.

        int Count = query.CalculateChunkCount();



        Entities
        .WithStoreEntityQueryInField(ref query)
        .ForEach((Entity e, int entityInQueryIndex, in int nativeThreadIndex, in CData75 data) => {
            UnityEngine.Debug.LogFormat("{0} {1}", entityInQueryIndex, nativeThreadIndex);
            // Implement the work to perform for each entity here.
            // You should only access data that is local or that is a
            // field on this job. Note that the 'rotation' parameter is
            // marked as 'in', which means it cannot be modified,
            // but allows this job to run in parallel with other jobs
            // that want to read Rotation component data.
            // For example,
            //     translation.Value += math.mul(rotation.Value, new float3(0, 0, 1)) * deltaTime;
        })
        .WithoutBurst()
        .WithName("OnUpdate")
        .Schedule();
    }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            if (m_passThroughQuery.CalculateChunkCount() == 0)
            {
                return(inputDeps);
            }

            if (m_StepPhysicsWorld.Simulation.Type == SimulationType.NoPhysics)
            {
                return(inputDeps);
            }

            // Add a custom callback to the simulation, which will inject our custom job after the body pairs have been created
            SimulationCallbacks.Callback callback = (ref ISimulation simulation, ref PhysicsWorld world, JobHandle inDeps) =>
            {
                inDeps.Complete(); //<todo Needed to initialize our modifier

                return(new PassThroughFilterPairsSystemJob
                {
                    Bodies = m_PhysicsWorld.PhysicsWorld.Bodies,
                    PassThroughGroup = GetComponentDataFromEntity <PassThrough>(true)
                }.Schedule(simulation, ref world, inputDeps));
            };
            m_StepPhysicsWorld.EnqueueCallback(SimulationCallbacks.Phase.PostCreateDispatchPairs, callback);

            return(inputDeps);
        }
示例#4
0
        protected override void OnUpdate()
        {
            //Create a native array to hold the intermediate sums
            int chunksInQuery = query.CalculateChunkCount();
            NativeArray <int> intermediateSums
                = new NativeArray <int>(chunksInQuery, Allocator.TempJob);

            //Schedule the first job to add all the buffer elements
            BuffersInChunks bufferJob = new BuffersInChunks();

            bufferJob.BufferType = GetArchetypeChunkBufferType <MyBufferElement>();
            bufferJob.sums       = intermediateSums;
            this.Dependency      = bufferJob.ScheduleParallel(query, this.Dependency);

            //Schedule the second job, which depends on the first
            SumResult finalSumJob = new SumResult();

            finalSumJob.sums = intermediateSums;
            NativeArray <int> finalSum = new NativeArray <int>(1, Allocator.Temp);

            finalSumJob.result = finalSum;
            this.Dependency    = finalSumJob.Schedule(this.Dependency);

            this.CompleteDependency();
            Debug.Log("Sum of all buffers: " + finalSum[0]);
            finalSum.Dispose();
        }
示例#5
0
        protected override void OnUpdate()
        {
            if (m_rlsQuery.CalculateChunkCount() > 0)
            {
                FixedString128 targetScene = new FixedString128();
                bool           isInvalid   = false;

                Entities.ForEach((ref RequestLoadScene rls) =>
                {
                    if (rls.newScene.UTF8LengthInBytes == 0)
                    {
                        return;
                    }
                    if (targetScene.Length == 0)
                    {
                        targetScene = rls.newScene;
                    }
                    else if (rls.newScene != targetScene)
                    {
                        isInvalid = true;
                    }
                }).Run();

                if (targetScene.Length > 0)
                {
                    if (isInvalid)
                    {
                        UnityEngine.Debug.LogError("Multiple scenes were requested to load during the previous frame.");
                    }
                    else
                    {
                        var curr = worldGlobalEntity.GetComponentData <CurrentScene>();
                        curr.previousScene = curr.currentScene;
                        UnityEngine.Debug.Log("Loading scene: " + targetScene);
                        SceneManager.LoadScene(targetScene.ToString());
                        latiosWorld.pauseForSceneLoad = true;
                        curr.currentScene             = targetScene;
                        curr.isSceneFirstFrame        = true;
                        worldGlobalEntity.SetComponentData(curr);
                        return;
                    }
                }
            }

            //Handle case where initial scene loads or set firstFrame to false
            var currentScene = worldGlobalEntity.GetComponentData <CurrentScene>();

            if (currentScene.currentScene.UTF8LengthInBytes == 0)
            {
                currentScene.currentScene      = SceneManager.GetActiveScene().name;
                currentScene.isSceneFirstFrame = true;
            }
            else
            {
                currentScene.isSceneFirstFrame = false;
            }
            worldGlobalEntity.SetComponentData(currentScene);
        }
        public void ApplyPatch(LiveLinkChangeSet changeSet)
        {
            var dstEntities = _DstWorld.EntityManager;
            var sceneSystem = _DstWorld.GetExistingSystem<SceneSystem>();
            Entity sectionEntity;
            var sceneEntity = sceneSystem.GetSceneEntity(changeSet.SceneGUID);

            //@TODO: Check if the scene or section is requested to be loaded
            if (sceneEntity == Entity.Null)
            {
                Debug.LogWarning($"'{changeSet.SceneName}' ({{changeSet.sceneGUID}}) was ignored in live link since it is not loaded.");
                return;
            }

            // Unload scene
            if (changeSet.UnloadAllPreviousEntities)
            {
                //@Todo: Can we try to keep scene & section entities alive? (In case user put custom data on it)
                sceneSystem.UnloadScene(sceneEntity, SceneSystem.UnloadParameters.DestroySectionProxyEntities | SceneSystem.UnloadParameters.DontRemoveRequestSceneLoaded);

                // Create section
                sectionEntity = dstEntities.CreateEntity();
                dstEntities.AddComponentData(sectionEntity, new SceneSectionStreamingSystem.StreamingState { Status = SceneSectionStreamingSystem.StreamingStatus.Loaded});
                dstEntities.AddComponentData(sectionEntity, new DisableSceneResolveAndLoad( ));

                // Configure scene
                dstEntities.AddComponentData(sceneEntity, new DisableSceneResolveAndLoad( ));
                dstEntities.AddComponentData(sceneEntity, new LiveLinkedSceneState { Scene = changeSet.SceneGUID });

                dstEntities.AddBuffer<ResolvedSectionEntity>(sceneEntity).Add(new ResolvedSectionEntity { SectionEntity = sectionEntity} );
                
#if UNITY_EDITOR
                dstEntities.SetName(sectionEntity, "SceneSection (LiveLink): " + changeSet.SceneName);
                dstEntities.SetName(sceneEntity, "Scene (LiveLink): " + changeSet.SceneName);
#endif
            }
            else
            {
                sectionEntity = dstEntities.GetBuffer<ResolvedSectionEntity>(sceneEntity)[0].SectionEntity;
            }
            
            // SceneTag.SceneEntity == Entity.Null is reserved for new entities added via live link.
            if (_AddedScenesQuery.CalculateChunkCount() != 0)
            {
                Debug.LogWarning("SceneTag.SceneEntity must not reference Entity.Null. Destroying Entities.");
                dstEntities.DestroyEntity(_AddedScenesQuery);
            }
            
            EntityPatcher.ApplyChangeSet(_DstWorld.EntityManager, changeSet.Changes);
            
            //liveLink.ConvertedShadowWorld.EntityManager.Debug.CheckInternalConsistency();

            dstEntities.SetSharedComponentData(_AddedScenesQuery, new SceneTag { SceneEntity = sectionEntity });

            EditorUpdateUtility.EditModeQueuePlayerLoopUpdate();
        }
示例#7
0
 private string GetRoonName()
 {
     if (roomNameQuery.CalculateChunkCount() > 0)
     {
         var singleton = roomNameQuery.GetSingletonEntity();
         return(entityManager.GetSharedComponentData <RoomNameComponent>(singleton).Value);
     }
     else
     {
         return("Null");
     }
 }
示例#8
0
 protected override void OnUpdate()
 {
     Dependency = new TriggerJob()
     {
         EffectBufferChunk   = GetArchetypeChunkBufferType <EFFECT_BUFFER>(true),
         SkillBufferChunk    = GetArchetypeChunkBufferType <SkillBuffer>(true),
         TargetChunk         = GetArchetypeChunkComponentType <Target>(true),
         ConsumerWriter      = _conusmerSystem.GetConsumerWriter(_query.CalculateChunkCount()),
         EffectContextWriter = GetContextWriter()
     }.ScheduleParallel(_query, Dependency);
     _conusmerSystem.RegisterTriggerDependency(Dependency);
 }
示例#9
0
 protected override JobHandle OnUpdate(JobHandle inputDeps)
 {
     inputDeps.Complete();
     SwapBuffer();
     if (holderPong.IsCreated && qWithDeferEntityID.CalculateChunkCount() > 0)
     {
         mFillCacheJob.entityTp = GetArchetypeChunkEntityType();
         mFillCacheJob.deferETp = GetArchetypeChunkComponentType <DeferEntityID>();
         mFillCacheJob.writer   = holderPong.ToParallelAccessor();
         mFillCacheJob.Schedule(qWithDeferEntityID, default).Complete();
         EntityManager.RemoveComponent <DeferEntityID>(qWithDeferEntityID);
     }
     return(default);
        protected override void OnUpdate()
        {
            if (m_rlsQuery.CalculateChunkCount() > 0)
            {
                var checkScenesJob = new CheckScenesJob
                {
                    targetScene = new NativeArray <NativeString128>(1, Allocator.TempJob),
                    isInvalid   = new NativeArray <bool>(1, Allocator.TempJob)
                };

                checkScenesJob.Run(this);

                var targetScene = checkScenesJob.targetScene[0];
                var isInvalid   = checkScenesJob.isInvalid[0];
                checkScenesJob.isInvalid.Dispose();
                checkScenesJob.targetScene.Dispose();

                if (targetScene.LengthInBytes > 0)
                {
                    if (!isInvalid)
                    {
                        UnityEngine.Debug.LogError("Multiple scenes were requested to load during the previous frame.");
                    }
                    else
                    {
                        var curr = worldGlobalEntity.GetComponentData <CurrentScene>();
                        curr.previousScene = curr.currentScene;
                        SceneManager.LoadScene(targetScene.ToString());
                        curr.currentScene      = targetScene;
                        curr.isSceneFirstFrame = true;
                        worldGlobalEntity.SetComponentData(curr);
                        return;
                    }
                }
            }

            //Handle case where initial scene loads or set firstFrame to false
            var currentScene = worldGlobalEntity.GetComponentData <CurrentScene>();

            if (currentScene.currentScene.LengthInBytes == 0)
            {
                currentScene.currentScene      = new NativeString128(SceneManager.GetActiveScene().name);
                currentScene.isSceneFirstFrame = true;
            }
            else
            {
                currentScene.isSceneFirstFrame = false;
            }
            worldGlobalEntity.SetComponentData(currentScene);
        }
    private static void AssertEntitiesCreated(EntityEventSystem system, EntityArchetype archetype, EventQueue <EcsTestData> queue, EntityQuery query, int[] entityCounts)
    {
        for (int i = 0; i < entityCounts.Length; i++)
        {
            var entities = entityCounts[i];
            for (int j = 0; j < entities; j++)
            {
                queue.Enqueue(new EcsTestData());
            }
            system.Update();

            Assert.AreEqual(entities, query.CalculateEntityCount());

            var expectedChunks = entities / archetype.ChunkCapacity + ((entities % archetype.ChunkCapacity == 0) ? 0 : 1);
            Assert.AreEqual(expectedChunks, query.CalculateChunkCount());
        }
    }
        protected override void OnUpdate()
        {
            var ecb    = ecbs.CreateCommandBuffer();
            var worked = new NativeList <int>(4, Allocator.Temp);

            Entities
            .WithAll <TextContent>()
            .WithNone <FontAssetEntityExistForThisText>()
            .ForEach((Entity e, FontAssetHolder sfah) =>
            {
                var sfa = sfah.htmFontAsset;
                ecb.SetComponent(e, sfa.fontMetrics);

                int sfaInstanceId = sfa.GetInstanceID();
                //One SPA get only one prepare, so if there are something here don't do it anymore.
                fontAssetQuery.SetSharedComponentFilter(sfah);
                if (fontAssetQuery.CalculateChunkCount() == 0 && worked.IndexOf(sfaInstanceId) == -1)
                {
                    Entity fontAssetEntity = ecb.CreateEntity(fontAssetArchetype);

                    ecb.SetSharedComponent(fontAssetEntity, sfah);
                    var buffer = ecb.SetBuffer <GlyphPrefabBuffer>(fontAssetEntity);
                    //Prepare prefabs for this asset.
                    for (int i = 0; i < sfa.characterInfos.Length; i++)
                    {
                        CharacterInfo c = sfa.characterInfos[i];
                        RegisterCharacter(sfa, c, ecb, buffer);
                    }

                    RegisterCharacter(sfa, new CharacterInfo
                    {
                        character = '\n',
                    }, ecb, buffer, new SpecialCharacter {
                        newLine = true
                    });

                    //Prevents loading the same font in the same frame since ECB target
                    //the next frame.
                    worked.Add(sfaInstanceId);
                }
            })
            .WithStoreEntityQueryInField(ref potentiallyNewSpriteFontAssetQuery)
            .WithoutBurst().Run();
            ecb.AddComponent <FontAssetEntityExistForThisText>(potentiallyNewSpriteFontAssetQuery);
            worked.Dispose();
        }
示例#13
0
        private void UpdateSceneLoading(out NativeList <SceneSection> sceneSectionsToInit)
        {
            NativeList <SceneSection> completeSceneSections = new NativeList <SceneSection>(4, Allocator.Temp);

            EntityCommandBuffer ecb = _ecbSystem.CreateCommandBuffer();

            Entities.WithNone <PersistentSceneSectionLoadComplete>().ForEach((Entity entity, ref RequestPersistentSceneSectionLoaded requestInfo, in SceneSectionData sceneSectionData) =>
            {
                if (requestInfo.CurrentLoadingStage == RequestPersistentSceneSectionLoaded.Stage.Complete)
                {
                    return;
                }

                SceneSection sceneSection = new SceneSection
                {
                    Section   = sceneSectionData.SubSectionIndex,
                    SceneGUID = sceneSectionData.SceneGUID
                };

                if (requestInfo.CurrentLoadingStage == RequestPersistentSceneSectionLoaded.Stage.InitialStage)
                {
                    ecb.AddComponent <PersistentSceneSection>(entity);
                    ecb.AddComponent(entity, new RequestSceneLoaded()
                    {
                        LoadFlags = requestInfo.LoadFlags
                    });
                    requestInfo.CurrentLoadingStage = RequestPersistentSceneSectionLoaded.Stage.WaitingForSceneLoad;
                }
                if (requestInfo.CurrentLoadingStage == RequestPersistentSceneSectionLoaded.Stage.WaitingForSceneLoad)
                {
                    // Pls make SceneSectionStreamingSystem.StreamingState public :) @unity
                    _sceneSectionLoadedCheckQuery.SetSharedComponentFilter(sceneSection);
                    if (_sceneSectionLoadedCheckQuery.CalculateChunkCount() > 0)
                    {
                        completeSceneSections.Add(sceneSection);
                        ecb.AddComponent <PersistentSceneSectionLoadComplete>(entity);
                        requestInfo.CurrentLoadingStage = RequestPersistentSceneSectionLoaded.Stage.Complete;
                    }
                }
            }).WithoutBurst().Run();

            _sceneSectionLoadedCheckQuery.ResetFilter();
            sceneSectionsToInit = completeSceneSections;
        }
        // Update is called once per frame
        protected override void OnUpdate( )
        {
            if (group_prefabs.CalculateChunkCount() == 0)
            {
                return;                                               // Early exit.
            }
            // Get prefabs.
            NativeArray <Entity> na_entities = group_prefabs.ToEntityArray(Allocator.Temp);
            Entity prefabsEntity             = na_entities [0];

            na_entities.Dispose();
            SpawnerPrefabs_FromEntityData spawner = EntityManager.GetComponentData <SpawnerPrefabs_FromEntityData> (prefabsEntity);


            // Check none active managers.
            _CheckNoneActiveMangers(this, Dependency, ref em, ref becb, ref jsonNeuralNetworkMangers, in spawner, in group_MMMamagerNotYetActive, layersNeuronCounts);

            _ExecuteActiveManager(this, Dependency, ref em, ref becb, ref eecb, ref random, ref l_managerSharedData, ref jsonNeuralNetworkMangers, in s_path, in spawner, in group_MMMamager, in group_carSpawnerPoint, in group_finishedPopulation, in group_allPopulation, in group_firstPopulation, in group_previousGeneration, in group_currentPopulation, in group_need2InitializePopulation, layersNeuronCounts);
        }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            //Create a native array to hold the intermediate sums
            int chunksInQuery = query.CalculateChunkCount();
            NativeArray <int> intermediateSums
                = new NativeArray <int>(chunksInQuery, Allocator.TempJob);

            //Schedule the first job to add all the buffer elements
            BuffersInChunks bufferJob = new BuffersInChunks();

            bufferJob.BufferType = GetArchetypeChunkBufferType <MyBufferElement>();
            bufferJob.sums       = intermediateSums;
            JobHandle intermediateJob = bufferJob.Schedule(query, inputDeps);

            //Schedule the second job, which depends on the first
            SumResult finalSumJob = new SumResult();

            finalSumJob.sums = intermediateSums;
            return(finalSumJob.Schedule(intermediateJob));
        }
        protected override void OnUpdate()
        {
            // If the consumer won't run, there is no point in tirgerring the effects...
            // This also avoid the creation of a stream that would never be disposed of.
            if (!_conusmerSystem.ShouldRunSystem())
            {
                return;
            }

            Dependency = new TriggerJob()
            {
                EffectBufferChunk   = GetArchetypeChunkBufferType <EFFECT_BUFFER>(true),
                AbilityBufferChunk  = GetArchetypeChunkBufferType <AbilityBuffer>(true),
                TargetChunk         = GetArchetypeChunkComponentType <Target>(true),
                EntityChunk         = GetArchetypeChunkEntityType(),
                ConsumerWriter      = _conusmerSystem.CreateConsumerWriter(_query.CalculateChunkCount()),
                EffectContextWriter = GetContextWriter()
            }.ScheduleParallel(_query, Dependency);

            // Tell the consumer to wait for ths trigger job to finish before starting to consume the effects.
            _conusmerSystem.RegisterTriggerDependency(Dependency);
        }
        public bool GetSceneMessage(out LiveLinkSceneMsg msg)
        {
            msg = default;

            if (_LoadedScenesQuery.CalculateChunkCount() == 0 && _UnloadedScenesQuery.CalculateChunkCount() == 0 &&
                m_PreviousScenes.Length == 0 && m_PreviousRemovedScenes.Length == 0)
            {
                return(false);
            }

            //TODO: Causes allocations in Editor
            var loadedScenes     = _LoadedScenesQuery.ToComponentDataArray <SceneReference>(Allocator.TempJob);
            var removedScenes    = _UnloadedScenesQuery.ToComponentDataArray <LiveLinkPatcher.LiveLinkedSceneState>(Allocator.TempJob);
            var newRemovedScenes = SubtractArrays(removedScenes, m_PreviousRemovedScenes);

            var noNewUnloads  = newRemovedScenes.Length == 0;
            var sameLoadState = loadedScenes.ArraysEqual(m_PreviousScenes.AsArray());

            if (noNewUnloads && sameLoadState)
            {
                loadedScenes.Dispose();
                removedScenes.Dispose();
                newRemovedScenes.Dispose();
                return(false);
            }

            msg.LoadedScenes  = loadedScenes.Reinterpret <Hash128>();
            msg.RemovedScenes = newRemovedScenes.Reinterpret <Hash128>();

            m_PreviousScenes.Clear();
            m_PreviousRemovedScenes.Clear();
            m_PreviousScenes.AddRange(loadedScenes);
            m_PreviousRemovedScenes.AddRange(removedScenes);
            removedScenes.Dispose();

            return(true);
        }
示例#18
0
        protected override void OnUpdate()
        {
            Entities.WithStructuralChanges().WithAll <FactionTag>().ForEach((Entity entity, ref Faction faction) =>
            {
                var factionMember = new FactionMember {
                    factionEntity = entity
                };
                m_aiQuery.SetSharedComponentFilter(factionMember);
                m_playerQuery.SetSharedComponentFilter(factionMember);

                if (faction.playerPrefab != Entity.Null && m_playerQuery.CalculateChunkCount() > 0)
                {
                    var newPlayerShip = EntityManager.Instantiate(faction.playerPrefab);
                    AddSharedComponentDataToLinkedGroup(newPlayerShip, factionMember);
                    SpawnPlayer(newPlayerShip);
                    faction.remainingReinforcements--;
                }

                {
                    int spawnCount    = m_aiQuery.CalculateEntityCount();
                    var newShipPrefab = EntityManager.Instantiate(faction.aiPrefab);
                    EntityManager.AddComponent <NewFleetTag>(newShipPrefab);
                    AddSharedComponentDataToLinkedGroup(newShipPrefab, factionMember);
                    var newShips = EntityManager.Instantiate(newShipPrefab, spawnCount, Allocator.TempJob);
                    EntityManager.DestroyEntity(newShipPrefab);
                    SpawnAi(newShips);
                    newShips.Dispose();
                    faction.remainingReinforcements -= spawnCount;
                }

                m_aiQuery.ResetFilter();
                m_playerQuery.ResetFilter();
            }).Run();

            EntityManager.RemoveComponent <NewFleetTag>(m_aiQuery);
        }
示例#19
0
    protected override JobHandle OnUpdate(JobHandle inputDependencies)
    {
        _lastAllocation++;
        LastJob.Complete();

        if (_batchQueue.Count > 0)
        {
            return(inputDependencies);
        }

        Profiler.BeginSample("Dependencies");
        var voxelColorType   = GetArchetypeChunkComponentType <VoxelColor>(true);
        var matrixType       = GetArchetypeChunkComponentType <LocalToWorld>(true);
        var chunks           = _query.CreateArchetypeChunkArrayAsync(Allocator.TempJob, out var chunksHandle);
        var chunkCount       = _query.CalculateChunkCount();
        var spaceRequirement = _query.CalculateEntityCount();
        var indexMappings    = new NativeArray <int>(chunkCount, Allocator.TempJob);
        var indexing         = new IndexingJob
        {
            IndexMappings  = indexMappings,
            Chunks         = chunks,
            ChunksPerBatch = chunksPerBatch
        }.Schedule(JobHandle.CombineDependencies(inputDependencies, chunksHandle));

        Profiler.EndSample();

        JobHandle deps = indexing;

        Profiler.BeginSample("Prepare Space");
        if (_lastColors.Length == spaceRequirement && _lastAllocation < 4)
        {
            var colorClear = new MemsetNativeArray <VoxelColor>
            {
                Source = _lastColors,
                Value  = default
            }.Schedule(_lastColors.Length, 256, inputDependencies);
        protected override void OnUpdate()
        {
            if (initialGenerationQuery.CalculateChunkCount() > 0 || changedRegenerationQuery.CalculateChunkCount() > 0)
            {
                var ecb = ecbs.CreateCommandBuffer();

                Entities
                .WithName("InitialMeshGeneration")
                .WithNone <GlyphSpawned>().ForEach(
                    (Entity e, in TextContent t, in TextStructure ts, in FontAssetHolder holder,
                     in DynamicBuffer <GlyphEntityGroup> leg) =>
                {
                    if (GenerateMeshes(EntityManager, fontAssetQuery, holder, t, ts, ecb, e, leg,
                                       updateMode: ts.persistentCharacterEntityMode))
                    {
                        //Only add if managed to find the prefabs, so it could retry next frame.
                        ecb.AddComponent <GlyphSpawned>(e);
                        ecb.AddComponent(e, new TextDiffer
                        {
                            previousText      = t,
                            previousStructure = ts,
                        });
                    }
                })
示例#21
0
 public override bool ShouldUpdateSystem()
 {
     return(m_anythingNeedsUpdateQuery.CalculateChunkCount() > 0);
 }
 protected override void OnUpdate()
 {
     AmountResource += m_Query.CalculateChunkCount() * 5;
 }
示例#23
0
    protected override void OnUpdate()
    {
        // Assign values to local variables captured in your job here, so that it has
        // everything it needs to do its work when it runs later.
        // For example,
        //     float deltaTime = Time.DeltaTime;

        // This declares a new kind of job, which is a unit of work to do.
        // The job is declared as an Entities.ForEach with the target components as parameters,
        // meaning it will process all entities in the world that have both
        // Translation and Rotation components. Change it to process the component
        // types you want.

        var count = query.CalculateChunkCount();

        /*
         * float sum = 0;
         *
         * Entities.WithReadOnly(typeof(CData76))
         *  .ForEach((int entityInQueryIndex, in DynamicBuffer<CData76> data) =>
         *  {
         *
         *      for (int i = 0; i < data.Length; i++)
         *      {
         *         sum += data[i].Value;
         *      }
         *      // Implement the work to perform for each entity here.
         *      // You should only access data that is local or that is a
         *      // field on this job. Note that the 'rotation' parameter is
         *      // marked as 'in', which means it cannot be modified,
         *      // but allows this job to run in parallel with other jobs
         *      // that want to read Rotation component data.
         *      // For example,
         *      //     translation.Value += math.mul(rotation.Value, new float3(0, 0, 1)) * deltaTime;
         *  }).WithName("OnUpdate")
         * .Run();
         */

        /*
         * NativeArray<float> sumArray = new NativeArray<float>(1, Allocator.TempJob);
         *
         * Entities.WithReadOnly(typeof(CData76))
         *  .ForEach((int entityInQueryIndex, in DynamicBuffer<CData76> data) => {
         *
         *      for(int i=0;i < data.Length; i++)
         *      {
         *          sumArray[0] += data[i].Value;
         *      }
         * }).WithName("OnUpdate")
         * .Schedule();
         */

        NativeArray <float> itemArray = new NativeArray <float>(10, Allocator.Persistent);

        for (int i = 0; i < 10; i++)
        {
            itemArray[i] = i;
        }

        NativeArray <float> sum = new NativeArray <float>(1, Allocator.Persistent);

        Entities
        .WithReadOnly(itemArray)                    //针对局部变量访问,通过WithReadOnly,来加速job计算
        //.WithReadOnly(sum)                       //注意:这地方开启会报错
        .WithStoreEntityQueryInField(ref query)
        .ForEach((int entityInQueryIndex, in DynamicBuffer <CData76> data) =>
        {
            for (int i = 0; i < itemArray.Length; i++)
            {
                sum[0] += itemArray[i];
            }
        }).WithName("OnUpdate")
示例#24
0
        protected override void OnUpdate()
        {
            if (query.CalculateChunkCount() == 0)
            {
                return;
            }
            var data = query.GetSingleton <Map3DData>();

            if (data.Changed == true)
            {
                terrain.gameObject.SetActive(true);
                cubeTerrain.gameObject.SetActive(false);
                data.Changed = false;
                if (data.CubeMode == false)
                {
                    var  terrainData = terrain.terrainData;
                    int2 bound       = new int2(0, 0);
                    int2 baseXY      = new int2(0, 0);
                    int  maxHeight   = 1;
                    for (int i = 0; i < heightData.Length; i++)
                    {
                        if (heightData[i].Position.X < baseXY.x)
                        {
                            baseXY.x = heightData[i].Position.X;
                        }
                        if (heightData[i].Position.Y < baseXY.y)
                        {
                            baseXY.y = heightData[i].Position.Y;
                        }
                        if (heightData[i].Position.X > bound.x)
                        {
                            bound.x = heightData[i].Position.X;
                        }
                        if (heightData[i].Position.Y > bound.y)
                        {
                            bound.y = heightData[i].Position.Y;
                        }
                        if (heightData[i].Height > maxHeight)
                        {
                            maxHeight = heightData[i].Height;
                        }
                    }
                    bound = bound - baseXY;
                    int2 size = new int2(math.min(bound.x + 1, terrainData.heightmapWidth), math.min(bound.y + 1, terrainData.heightmapHeight));
                    float[,] heights    = new float[size.x, size.y];
                    float[,,] alphaMaps = new float[size.x, size.y, 5];
                    for (int i = 0; i < heightData.Length; i++)
                    {
                        if (heightData[i].Position.X < size.x && heightData[i].Position.Y < size.y)
                        {
                            heights[heightData[i].Position.X, heightData[i].Position.Y] = (float)heightData[i].Height / maxHeight;

                            int mapType = heightData[i].Terrain;
                            for (int j = 0; j < 5; j++)
                            {
                                if (j == mapType)
                                {
                                    alphaMaps[heightData[i].Position.X, heightData[i].Position.Y, j] = 1;
                                }
                                else
                                {
                                    alphaMaps[heightData[i].Position.X, heightData[i].Position.Y, j] = 0;
                                }
                            }
                        }
                    }
                    Debug.Log(baseXY);
                    Debug.Log(bound);
                    Debug.Log(size);
                    terrain.terrainData.size = new Vector3(terrain.terrainData.size.x, (float)maxHeight / 5, terrain.terrainData.size.z);
                    terrainData.SetHeights(baseXY.x, baseXY.y, heights);
                    terrainData.SetAlphamaps(baseXY.x, baseXY.y, alphaMaps);
                    terrainData.RefreshPrototypes();
                    World.Active.EntityManager.SetComponentData(query.GetSingletonEntity(), data);
                }
                else
                {
                    terrain.gameObject.SetActive(false);
                    cubeTerrain.gameObject.SetActive(true);
                    cubeTerrain.ReFresh();
                }
            }
        }
        protected override void OnUpdate()
        {
            if (matrixChangedChunkQuery == default(EntityQuery))
            {
                matrixChangedChunkQuery = GetEntityQuery(ComponentType.ChunkComponent <SpriteMatrixChangeTag>());
            }

            EntityManager.RemoveChunkComponentData <SpriteMatrixChangeTag>(matrixChangedChunkQuery);

            for (int sheet = 0; sheet < spriteRenderingSystem.Baked; sheet++)
            {
                var filter = spriteRenderingSystem.filters[sheet];
                query.SetSharedComponentFilter(filter);
                if (query.CalculateEntityCount() == 0)
                {
                    continue;
                }
                spriteRenderingSystem.BufferStructureChanged[sheet] = true;
                var toBeBuffered = query.ToEntityArray(Allocator.TempJob);
                if (Logging)
                {
                    UnityEngine.Debug.Log(string.Format("ToBeBuffered: {0}.", toBeBuffered.Length));
                }
                BakedSpriteSheet bss = spriteRenderingSystem.bakedSpriteSheets[sheet];
                int  pooledIndexs    = spriteRenderingSystem.freeIndexs[sheet].Length;
                uint currentCap      = bss.Capacity;
                uint usedIndexRight  = bss.Users;
                if (toBeBuffered.Length <= pooledIndexs)
                {
                    for (int i = 0; i < toBeBuffered.Length; i++)
                    {
                        SpriteRenderSubject srs = EntityManager.GetComponentData <SpriteRenderSubject>(toBeBuffered[i]);
                        srs.bufferIndex = spriteRenderingSystem.freeIndexs[sheet][pooledIndexs - 1];
                        if (Logging)
                        {
                            UnityEngine.Debug.Log(string.Format("Entitiy {1} is taking pooled index {0}. (pool enough)", srs.bufferIndex, toBeBuffered[i].Index));
                        }
                        spriteRenderingSystem.freeIndexs[sheet].Resize(spriteRenderingSystem.freeIndexs[sheet].Length - 1, NativeArrayOptions.ClearMemory);
                        EntityManager.SetComponentData(toBeBuffered[i], srs);
                        EntityManager.AddComponentData(toBeBuffered[i], new BufferedRenderSubjectTag());
                        pooledIndexs--;
                    }
                    if (Logging)
                    {
                        UnityEngine.Debug.Log(string.Format("Reused {0} indexs.", toBeBuffered.Length));
                    }
                }
                else
                {
                    int needIndexs = toBeBuffered.Length - pooledIndexs;
                    if (needIndexs > currentCap - usedIndexRight) // Need to grow
                    {
                        uint properCap = currentCap;
                        while (properCap <= currentCap + needIndexs)
                        {
                            properCap *= 2;
                        }
                        spriteRenderingSystem.GrowBuffersForNewUser(sheet, (int)properCap);
                        if (Logging)
                        {
                            UnityEngine.Debug.Log(string.Format("Extended buffers' length of baked sprite sheet#{0} to {1}.", sheet, properCap));
                        }
                    }

                    uint prevIndexRight = usedIndexRight;
                    if (Logging)
                    {
                        UnityEngine.Debug.Log(string.Format("Reusing {0}/{1}.", pooledIndexs, toBeBuffered.Length));
                    }
                    for (int i = 0; i < toBeBuffered.Length; i++)
                    {
                        SpriteRenderSubject srs = EntityManager.GetComponentData <SpriteRenderSubject>(toBeBuffered[i]);
                        if (pooledIndexs > 0)
                        {
                            srs.bufferIndex = spriteRenderingSystem.freeIndexs[sheet][pooledIndexs - 1];
                            spriteRenderingSystem.freeIndexs[sheet].Resize(spriteRenderingSystem.freeIndexs[sheet].Length - 1, NativeArrayOptions.ClearMemory);
                            if (Logging)
                            {
                                UnityEngine.Debug.Log(string.Format("Entitiy {1} is taking pooled index {0}. (pool inenough)", srs.bufferIndex, toBeBuffered[i].Index));
                            }
                            pooledIndexs--;
                        }
                        else
                        {
                            srs.bufferIndex = (int)usedIndexRight;
                            if (Logging)
                            {
                                UnityEngine.Debug.Log(string.Format("Entitiy {1} is taking new index {0}.", srs.bufferIndex, toBeBuffered[i].Index));
                            }
                            usedIndexRight++;
                        }
                        EntityManager.SetComponentData(toBeBuffered[i], srs);
                        EntityManager.AddComponentData(toBeBuffered[i], new BufferedRenderSubjectTag());
                        EntityManager.AddChunkComponentData <SpriteMatrixChangeTag>(toBeBuffered[i]);
                    }
                    if (Logging)
                    {
                        UnityEngine.Debug.Log(string.Format("UsedIndex: {0} -> {1}.", prevIndexRight, usedIndexRight));
                    }
                    bss.Users = usedIndexRight;
                }
                if (Logging)
                {
                    UnityEngine.Debug.Log(string.Format("Added {0} users to the buffer of sprite sheet#{1}.", toBeBuffered.Length, sheet));
                }
                toBeBuffered.Dispose();
                if (Logging)
                {
                    UnityEngine.Debug.Log(string.Format("MatrixChangedChunks: " + matrixChangedChunkQuery.CalculateChunkCount()));
                }
            }
        }
示例#26
0
        // Update is called once per frame
        protected override void OnUpdate( )
        {
            if (Time.ElapsedTime <= i_startTime)
            {
                return;                                     // Delay startup.
            }
            EntityCommandBuffer ecb = becb.CreateCommandBuffer();

            ComponentDataFromEntity <NNManagerComponent> a_manager;


            if (group_MMMamager.CalculateChunkCount() == 0)
            {
                // Debug.LogWarning ( "There is no active managers yet." ) ;
                return;
            }


            a_manager = GetComponentDataFromEntity <NNManagerComponent> (false);
            // NNManagerComponent manager ;
            ComponentDataFromEntity <NNTimerComponent> a_managerTimer = GetComponentDataFromEntity <NNTimerComponent> (false);
            ComponentDataFromEntity <IsTimeUpTag>      a_isTimeUpTag  = GetComponentDataFromEntity <IsTimeUpTag> (true);


            int i_activeManager = 0;


            l_managerSharedData.Clear();
            EntityManager.GetAllUniqueSharedComponentData(l_managerSharedData);


            // Ignore default manager entity ( index = 0, version = 0 ), taken from prefab entity.
            for (int i = 0; i < l_managerSharedData.Count; i++)
            {
                NNManagerSharedComponent mangerSharedComponent = l_managerSharedData [i];
                Entity managerEntity = new Entity()
                {
                    Index = mangerSharedComponent.i_entityIndex, Version = mangerSharedComponent.i_entityVersion
                };

                ComponentDataFromEntity <IsAliveTag> a_isAliveTag = GetComponentDataFromEntity <IsAliveTag> (false);
// Debug.Log ( "nnManagerEntity: " + nnManagerEntity ) ;


                // Entity manager must be valid and active.
                if (ManagerMethods._SkipInvalidManager(managerEntity, ref a_isAliveTag))
                {
                    continue;
                }

                if (!a_isTimeUpTag.HasComponent(managerEntity))
                {
                    NNTimerComponent managerTimer = a_managerTimer [managerEntity];

                    NNManagerComponent manager = a_manager [managerEntity];

// Debug.Log ( "Timer" ) ;
                    group_finishedPopulation.SetSharedComponentFilter(mangerSharedComponent);

                    if (Time.ElapsedTime >= managerTimer.f || group_finishedPopulation.CalculateEntityCount() >= manager.i_populationSize)
                    {
                        managerTimer.f = (float)Time.ElapsedTime + manager.i_startLifeTime;

                        a_managerTimer [managerEntity] = managerTimer;   // Set back.

                        ecb.AddComponent <IsTimeUpTag> (managerEntity);

// Debug.LogError ( "Set" ) ;
                    }
                }
                else // if ( a_isTimeUpTag.Exists ( managerEntity ) )
                {
// Debug.LogError ( "Reset" ) ;
                    ecb.RemoveComponent <IsTimeUpTag> (managerEntity);
                }

                i_activeManager++;
            } // for

            becb.AddJobHandleForProducer(Dependency);
        }