aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Graphics.GAL/Multithreading/Resources/ThreadedCounterEvent.cs
blob: 15db2b9fa21f6006057219ef54dfae0975734bf2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using Ryujinx.Graphics.GAL.Multithreading.Commands.CounterEvent;
using Ryujinx.Graphics.GAL.Multithreading.Model;
using System.Threading;

namespace Ryujinx.Graphics.GAL.Multithreading.Resources
{
    class ThreadedCounterEvent : ICounterEvent
    {
        private readonly ThreadedRenderer _renderer;
        public ICounterEvent Base;

        public bool Invalid { get; set; }

        public CounterType Type { get; }
        public bool ClearCounter { get; }

        private bool _reserved;
        private int _createLock;

        public ThreadedCounterEvent(ThreadedRenderer renderer, CounterType type, bool clearCounter)
        {
            _renderer = renderer;
            Type = type;
            ClearCounter = clearCounter;
        }

        private TableRef<T> Ref<T>(T reference)
        {
            return new TableRef<T>(_renderer, reference);
        }

        public void Dispose()
        {
            _renderer.New<CounterEventDisposeCommand>().Set(Ref(this));
            _renderer.QueueCommand();
        }

        public void Flush()
        {
            ThreadedHelpers.SpinUntilNonNull(ref Base);

            Base.Flush();
        }

        public bool ReserveForHostAccess()
        {
            if (Base != null)
            {
                return Base.ReserveForHostAccess();
            }
            else
            {
                bool result = true;

                // A very light lock, as this case is uncommon.
                ThreadedHelpers.SpinUntilExchange(ref _createLock, 1, 0);

                if (Base != null)
                {
                    result = Base.ReserveForHostAccess();
                }
                else
                {
                    _reserved = true;
                }

                Volatile.Write(ref _createLock, 0);

                return result;
            }
        }

        public void Create(IRenderer renderer, CounterType type, System.EventHandler<ulong> eventHandler, float divisor, bool hostReserved)
        {
            ThreadedHelpers.SpinUntilExchange(ref _createLock, 1, 0);
            Base = renderer.ReportCounter(type, eventHandler, divisor, hostReserved || _reserved);
            Volatile.Write(ref _createLock, 0);
        }
    }
}