Esempio n. 1
0
    //private NativeReference<int> _pointsToAdd;
    //private int* p_pointsToAdd;
    //unsafe protected override void OnCreate()
    //{
    //	//_pointsToAdd = new Unity.Collections.NativeArray<int>(1, Allocator.Persistent);
    //	//p_pointsToAdd = (int*)Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.GetUnsafePtr(this._pointsToAdd);
    //	_pointsToAdd = new NativeReference<int>(Allocator.Persistent);
    //	p_pointsToAdd = (int*)_pointsToAdd.GetUnsafePtr();
    //	base.OnCreate();
    //}

    //protected override void OnDestroy()
    //{
    //	_pointsToAdd.Dispose(this.Dependency);
    //	base.OnDestroy();
    //}

    unsafe protected override void OnUpdate()
    {
        //System.GC.Collect();
        //itterate every player that has a triggerbuffer
        //look at entities in triggerbuffer, and if any have a collectable, mark the collectable to be killed

        ////single threaded
        //{
        //	var ecb = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>().CreateCommandBuffer();
        //	var pointsToAdd = 0;

        //	Entities
        //		.WithAll<Player>()
        //		.ForEach((Entity playerEntity, DynamicBuffer<TriggerBuffer> tBuffer, in Player player) =>
        //		{
        //			for (var i = 0; i < tBuffer.Length; i++)
        //			{
        //				var _tb = tBuffer[i];

        //				if (HasComponent<Collectable>(_tb.entity) && !HasComponent<Kill>(_tb.entity))
        //				{
        //					ecb.AddComponent(_tb.entity, new Kill() { timer = 0 });
        //				}

        //				if (HasComponent<Collectable>(_tb.entity) && !HasComponent<Kill>(_tb.entity))
        //				{
        //					ecb.AddComponent(_tb.entity, new Kill() { timer = 0 });
        //					var collectable = GetComponent<Collectable>(_tb.entity);
        //					pointsToAdd += collectable.points;
        //					//System.Threading.Interlocked.Add(ref pointsToAdd, collectable.points);
        //					//GameManager.instance.AddPoints(collectable.points);
        //				}

        //				if (HasComponent<PowerPill>(_tb.entity) && !HasComponent<Kill>(_tb.entity))
        //				{
        //					ecb.AddComponent(_tb.entity, new Kill() { timer = 0 });
        //					var pill = GetComponent<PowerPill>(_tb.entity);
        //					ecb.AddComponent(playerEntity, pill);
        //				}
        //			}
        //		}).WithoutBurst().Run();

        //	GameManager.instance.AddPoints(pointsToAdd);
        //}

        ////parallel using class field for accumulation
        //{
        //	var ecbSystem = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
        //	var ecb = ecbSystem.CreateCommandBuffer().AsParallelWriter();
        //	var p_pointsToAdd = this.p_pointsToAdd;

        //	Entities
        //			.WithAll<Player>()
        //			.ForEach((int entityInQueryIndex, Entity playerEntity, DynamicBuffer<TriggerBuffer> triggerBuffer, in Player player) =>
        //		{
        //			for (var i = 0; i < triggerBuffer.Length; i++)
        //			{
        //				var _tb = triggerBuffer[i];

        //				if (HasComponent<Collectable>(_tb.entity) && !HasComponent<Kill>(_tb.entity))
        //				{
        //					ecb.AddComponent(entityInQueryIndex, _tb.entity, new Kill() { timer = 0 });
        //					var collectable = GetComponent<Collectable>(_tb.entity);
        //					System.Threading.Interlocked.Add(ref *p_pointsToAdd, collectable.points);
        //				}

        //				if (HasComponent<PowerPill>(_tb.entity) && !HasComponent<Kill>(_tb.entity))
        //				{
        //					ecb.AddComponent(entityInQueryIndex, _tb.entity, new Kill() { timer = 0 });
        //					var pill = GetComponent<PowerPill>(_tb.entity);
        //					ecb.AddComponent(entityInQueryIndex, playerEntity, pill);
        //				}
        //			}
        //		})
        //			.WithNativeDisableUnsafePtrRestriction(p_pointsToAdd)
        //			.ScheduleParallel();


        //	ecbSystem.AddJobHandleForProducer(this.Dependency);

        //	if (_pointsToAdd.Value != 0)
        //	{
        //		var pointsToAdd = System.Threading.Interlocked.Exchange(ref *p_pointsToAdd, 0);
        //		GameManager.instance.AddPoints(pointsToAdd);
        //	}
        //}


        //UNSAFE parallel using only job temp variable
        //SAFE nativeQueue parallel version
        {
            var ecbSystem = World.GetOrCreateSystem <EndSimulationEntityCommandBufferSystem>();
            var ecb       = ecbSystem.CreateCommandBuffer().AsParallelWriter();
            //SAFE nativeQueue
            var EXAMPLE_SAFE_queue        = new NativeQueue <int>(Allocator.TempJob);
            var EXAMPLE_SAFE_queue_writer = EXAMPLE_SAFE_queue.AsParallelWriter();
            //UNSAFE
            var pointsToAdd   = new NativeReference <int>(Allocator.TempJob);
            var p_pointsToAdd = (int *)pointsToAdd.GetUnsafePtr();
            //SAFE nativeArray
            var EXAMPLE_SAFE_array = new NativeArray <int>(_query.CalculateEntityCount(), Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
            Entities
            .WithStoreEntityQueryInField(ref _query)
            .WithAll <Player>()
            .ForEach((int nativeThreadIndex, int entityInQueryIndex, Entity playerEntity, DynamicBuffer <TriggerBuffer> triggerBuffer, in Player player) =>
            {
                var pointsToAdd = 0;
                for (var i = 0; i < triggerBuffer.Length; i++)
                {
                    var _tb = triggerBuffer[i];

                    if (HasComponent <Collectable>(_tb.entity) && !HasComponent <Kill>(_tb.entity))
                    {
                        ecb.AddComponent(entityInQueryIndex, _tb.entity, new Kill()
                        {
                            timer = 0
                        });
                        var collectable = GetComponent <Collectable>(_tb.entity);
                        //UNSAFE
                        System.Threading.Interlocked.Add(ref *p_pointsToAdd, collectable.points);
                        //SAFE nativeQueue
                        EXAMPLE_SAFE_queue_writer.Enqueue(collectable.points);
                        //SAFE nativeArray (part 1/2)
                        pointsToAdd += collectable.points;
                    }

                    if (HasComponent <PowerPill>(_tb.entity) && !HasComponent <Kill>(_tb.entity))
                    {
                        ecb.AddComponent(entityInQueryIndex, _tb.entity, new Kill()
                        {
                            timer = 0
                        });
                        var pill = GetComponent <PowerPill>(_tb.entity);
                        ecb.AddComponent(entityInQueryIndex, playerEntity, pill);
                    }
                }
                //SAFE nativeArray (part 2/2)
                EXAMPLE_SAFE_array[entityInQueryIndex] = pointsToAdd;
            })
            .WithNativeDisableUnsafePtrRestriction(p_pointsToAdd)
            .ScheduleParallel();


            ecbSystem.AddJobHandleForProducer(this.Dependency);


            Job.WithReadOnly(pointsToAdd).WithCode(() => {
                //UNSAFE
                GameManager.instance.AddPoints(pointsToAdd.Value);
                //SAFE nativeQueue
                while (EXAMPLE_SAFE_queue.TryDequeue(out var pts))
                {
                    GameManager.instance.AddPoints(pts);
                }
                //SAFE nativeArray
                foreach (var pointsToAdd in EXAMPLE_SAFE_array)
                {
                    GameManager.instance.AddPoints(pointsToAdd);
                }
            })
            //.WithDisposeOnCompletion(pointsToAdd) //doesn't work
            .WithoutBurst()
            .Run();

            pointsToAdd.Dispose(this.Dependency);             //pointsToAdd.Dispose() would also work, as internally it finds this.Dependency
            EXAMPLE_SAFE_queue.Dispose(this.Dependency);
            EXAMPLE_SAFE_array.Dispose(this.Dependency);
        }
    }
Esempio n. 2
0
        protected override void OnCreate()
        {
            //Initialize containers first
            m_mixNodePortFreelist        = new NativeList <int>(Allocator.Persistent);
            m_mixNodePortCount           = new NativeReference <int>(Allocator.Persistent);
            m_ildNodePortCount           = new NativeReference <int>(Allocator.Persistent);
            m_packedFrameCounterBufferId = new NativeReference <long>(Allocator.Persistent);
            m_audioFrame       = new NativeReference <int>(Allocator.Persistent);
            m_lastReadBufferId = new NativeReference <int>(Allocator.Persistent);
            m_buffersInFlight  = new List <ManagedIldBuffer>();

            worldBlackboardEntity.AddComponentDataIfMissing(new AudioSettings {
                audioFramesPerUpdate = 3, audioSubframesPerFrame = 1, logWarningIfBuffersAreStarved = false
            });

            //Create graph and driver
            var format   = ChannelEnumConverter.GetSoundFormatFromSpeakerMode(UnityEngine.AudioSettings.speakerMode);
            var channels = ChannelEnumConverter.GetChannelCountFromSoundFormat(format);

            UnityEngine.AudioSettings.GetDSPBufferSize(out m_samplesPerSubframe, out _);
            m_sampleRate = UnityEngine.AudioSettings.outputSampleRate;
            m_graph      = DSPGraph.Create(format, channels, m_samplesPerSubframe, m_sampleRate);
            m_driver     = new LatiosDSPGraphDriver {
                Graph = m_graph
            };
            m_outputHandle = m_driver.AttachToDefaultOutput();

            var commandBlock = m_graph.CreateCommandBlock();

            m_mixNode = commandBlock.CreateDSPNode <MixStereoPortsNode.Parameters, MixStereoPortsNode.SampleProviders, MixStereoPortsNode>();
            commandBlock.AddOutletPort(m_mixNode, 2);
            m_mixToOutputConnection = commandBlock.Connect(m_mixNode, 0, m_graph.RootDSP, 0);
            m_ildNode = commandBlock.CreateDSPNode <ReadIldBuffersNode.Parameters, ReadIldBuffersNode.SampleProviders, ReadIldBuffersNode>();
            unsafe
            {
                commandBlock.UpdateAudioKernel <SetReadIldBuffersNodePackedFrameBufferId, ReadIldBuffersNode.Parameters, ReadIldBuffersNode.SampleProviders, ReadIldBuffersNode>(
                    new SetReadIldBuffersNodePackedFrameBufferId {
                    ptr = (long *)m_packedFrameCounterBufferId.GetUnsafePtr()
                },
                    m_ildNode);
            }
            commandBlock.Complete();

            //Create queries
            m_aliveListenersQuery = Fluent.WithAll <AudioListener>(true).Build();
            m_deadListenersQuery  = Fluent.Without <AudioListener>().WithAll <ListenerGraphState>().Build();
            m_oneshotsToDestroyWhenFinishedQuery = Fluent.WithAll <AudioSourceOneShot>().WithAll <AudioSourceDestroyOneShotWhenFinished>(true).Build();
            m_oneshotsQuery = Fluent.WithAll <AudioSourceOneShot>().Build();
            m_loopedQuery   = Fluent.WithAll <AudioSourceLooped>().Build();

            //Force initialization of Burst
            commandBlock = m_graph.CreateCommandBlock();
            var dummyNode = commandBlock.CreateDSPNode <MixPortsToStereoNode.Parameters, MixPortsToStereoNode.SampleProviders, MixPortsToStereoNode>();

            StateVariableFilterNode.Create(commandBlock, StateVariableFilterNode.FilterType.Bandpass, 0f, 0f, 0f, 1);
            commandBlock.UpdateAudioKernel <MixPortsToStereoNodeUpdate, MixPortsToStereoNode.Parameters, MixPortsToStereoNode.SampleProviders, MixPortsToStereoNode>(
                new MixPortsToStereoNodeUpdate {
                leftChannelCount = 0
            },
                dummyNode);
            commandBlock.UpdateAudioKernel <ReadIldBuffersNodeUpdate, ReadIldBuffersNode.Parameters, ReadIldBuffersNode.SampleProviders, ReadIldBuffersNode>(new ReadIldBuffersNodeUpdate
            {
                ildBuffer = new IldBuffer(),
            },
                                                                                                                                                             m_ildNode);
            commandBlock.Cancel();
        }