summaryrefslogtreecommitdiffstats
path: root/LibOVRKernel/Src/Kernel/OVR_CallbacksInternal.h
blob: a0c0a31bb52defa60856f67180ee55ae63f93bcf (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/************************************************************************************

PublicHeader:   Kernel
Filename    :   OVR_CallbacksInternal.h
Content     :   Callback library
Created     :   Nov 11, 2014
Author      :   Chris Taylor

Copyright   :   Copyright 2014 Oculus VR, LLC All Rights reserved.

Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); 
you may not use the Oculus VR Rift SDK except in compliance with the License, 
which is provided at the time of installation or download, or which 
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-3.2 

Unless required by applicable law or agreed to in writing, the Oculus VR SDK 
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

************************************************************************************/

#ifndef OVR_CallbacksInternal_h
#define OVR_CallbacksInternal_h

#include "OVR_Atomic.h"
#include "OVR_RefCount.h"
#include "OVR_Delegates.h"
#include "OVR_Array.h"

namespace OVR {

template<class DelegateT> class FloatingCallbackEmitter; // Floating emitter object
template<class DelegateT> class CallbackEmitter;
template<class DelegateT> class FloatingCallbackListener; // Floating listener object
template<class DelegateT> class CallbackListener;


//-----------------------------------------------------------------------------
// FloatingCallbackEmitter
//
// The Call() function is not thread-safe.
// TBD: Should we add a thread-safe Call() option to constructor?

class CallbackEmitterBase
{
protected:
    static Lock EmitterLock;
};

template<class DelegateT>
class FloatingCallbackEmitter : public CallbackEmitterBase, public RefCountBase< FloatingCallbackEmitter<DelegateT> >
{
    friend class CallbackEmitter<DelegateT>;

    FloatingCallbackEmitter() :
        IsShutdown(false),
        DirtyListenersCache(0)
    {
    }

public:
    typedef Array< Ptr< FloatingCallbackListener<DelegateT> > > ListenerPtrArray;

    ~FloatingCallbackEmitter()
    {
        OVR_ASSERT(Listeners.GetSizeI() == 0);
        // ListenersCache will be emptied here.
    }

    bool AddListener(FloatingCallbackListener<DelegateT>* listener);
    void Shutdown();

    // Called from the listener object as it is transitioning to canceled state.
    // The listener's mutex is not held during this call.
    void OnListenerCancel(FloatingCallbackListener<DelegateT>* listener);

public:
    void Call();

    template<class Param1>
    void Call(Param1* p1);

    template<class Param1>
    void Call(Param1& p1);

    template<class Param1, class Param2>
    void Call(Param1* p1, Param2* p2);

    template<class Param1, class Param2>
    void Call(Param1& p1, Param2& p2);

    template<class Param1, class Param2, class Param3>
    void Call(Param1* p1, Param2* p2, Param3* p3);

    template<class Param1, class Param2, class Param3>
    void Call(Param1& p1, Param2& p2, Param3& p3);

protected:
    // Is the emitter shut down?  This prevents more listeners from being added during shutdown.
    bool IsShutdown;

    // Array of added listeners.
    ListenerPtrArray Listeners;

    // Is the cache dirty?  This avoids locking and memory allocation in steady state.
    AtomicInt<uint32_t> DirtyListenersCache;

    // Cache of listeners used by the Call() function.
    ListenerPtrArray ListenersCacheForCalls;

    // Update the ListenersCache array in response to an insertion or removal.
    // This is how AddListener() insertions get rolled into the listeners array.
    // This is how RemoveListener() removals get purged from the cache.
    void updateListenersCache()
    {
        if (DirtyListenersCache != 0)
        {
            Lock::Locker locker(&EmitterLock);

            // TBD: Should memory allocation be further reduced here?
            ListenersCacheForCalls = Listeners;
            DirtyListenersCache = 0;
        }
    }

    // Without holding a lock, find and remove the given listener from the array of listeners.
    void noLockFindAndRemoveListener(FloatingCallbackListener<DelegateT>* listener)
    {
        const int count = Listeners.GetSizeI();
        for (int i = 0; i < count; ++i)
        {
            if (Listeners[i] == listener)
            {
                Listeners.RemoveAt(i);

                // After removing it from the array, set the dirty flag.
                // Note: Because the flag is atomic, a portable memory fence is implied.
                DirtyListenersCache = 1;

                break;
            }
        }
    }
};


//-----------------------------------------------------------------------------
// FloatingCallbackListener
//
// Internal implementation class for the CallbackListener.
// This can only be associated with one CallbackListener object for its lifetime.
template<class DelegateT>
class FloatingCallbackListener : public RefCountBase< FloatingCallbackListener<DelegateT> >
{
public:
    FloatingCallbackListener(DelegateT handler);
    ~FloatingCallbackListener();

    void EnterCancelState();

    bool IsValid() const
    {
        return Handler.IsValid();
    }

    // TBD: Should these be binned to reduce the lock count?
    // Boost does not do that.  And I am worried about deadlocks when misused.
    mutable Lock ListenerLock;

    // Handler function
    DelegateT Handler;
};


//-----------------------------------------------------------------------------
// Template Implementation: FloatingCallbackEmitter

template<class DelegateT>
bool FloatingCallbackEmitter<DelegateT>::AddListener(FloatingCallbackListener<DelegateT>* listener)
{
    Lock::Locker locker(&EmitterLock);

    if (IsShutdown)
    {
        return false;
    }

    // Add the listener to our list
    Listeners.PushBack(listener);

    // After adding it to the array, set the dirty flag.
    // Note: Because the flag is atomic, a portable memory fence is implied.
    DirtyListenersCache = 1;

    return true;
}

// Called from the listener object as it is transitioning to canceled state.
// The listener's mutex is not held during this call.
template<class DelegateT>
void FloatingCallbackEmitter<DelegateT>::OnListenerCancel(FloatingCallbackListener<DelegateT>* listener)
{
    Lock::Locker emitterLocker(&EmitterLock);

    // If not shut down,
    // Note that if it is shut down then there will be no listeners in the array.
    if (!IsShutdown)
    {
        // Remove it.
        noLockFindAndRemoveListener(listener);
    }
}

template<class DelegateT>
void FloatingCallbackEmitter<DelegateT>::Shutdown()
{
    Lock::Locker locker(&EmitterLock);

    IsShutdown = true;

    Listeners.ClearAndRelease();

    // Note: Because the flag is atomic, a portable memory fence is implied.
    DirtyListenersCache = 1;
}

//-----------------------------------------------------------------------------
// Call function
//
// (1) Update the cache of listener references, if it has changed.
// (2) For each listener,
//    (a) Hold ListenerLock.
//    (b) If listener handler is valid, call the handler.
#define OVR_EMITTER_CALL_BODY(params) \
    updateListenersCache(); \
    if (IsShutdown) return; /* Pure optimization.  It is fine if this races. */ \
    const int count = ListenersCacheForCalls.GetSizeI(); \
    for (int i = 0; i < count; ++i) \
    { \
        Lock::Locker locker(&ListenersCacheForCalls[i]->ListenerLock); \
        if (ListenersCacheForCalls[i]->Handler.IsValid()) \
        { \
            ListenersCacheForCalls[i]->Handler params; /* Using a macro for this line. */ \
        } \
    }

template<class DelegateT>
void FloatingCallbackEmitter<DelegateT>::Call()
{
    OVR_EMITTER_CALL_BODY(())
}

template<class DelegateT>
template<class Param1>
void FloatingCallbackEmitter<DelegateT>::Call(Param1* p1)
{
    OVR_EMITTER_CALL_BODY((p1))
}

template<class DelegateT>
template<class Param1>
void FloatingCallbackEmitter<DelegateT>::Call(Param1& p1)
{
    OVR_EMITTER_CALL_BODY((p1))
}

template<class DelegateT>
template<class Param1, class Param2>
void FloatingCallbackEmitter<DelegateT>::Call(Param1* p1, Param2* p2)
{
    OVR_EMITTER_CALL_BODY((p1, p2))
}

template<class DelegateT>
template<class Param1, class Param2>
void FloatingCallbackEmitter<DelegateT>::Call(Param1& p1, Param2& p2)
{
    OVR_EMITTER_CALL_BODY((p1, p2))
}

template<class DelegateT>
template<class Param1, class Param2, class Param3>
void FloatingCallbackEmitter<DelegateT>::Call(Param1* p1, Param2* p2, Param3* p3)
{
    OVR_EMITTER_CALL_BODY((p1, p2, p3))
}

template<class DelegateT>
template<class Param1, class Param2, class Param3>
void FloatingCallbackEmitter<DelegateT>::Call(Param1& p1, Param2& p2, Param3& p3)
{
    OVR_EMITTER_CALL_BODY((p1, p2, p3))
}

#undef OVR_EMITTER_CALL_BODY


//-----------------------------------------------------------------------------
// Template Implementation: FloatingCallbackListener

template<class DelegateT>
FloatingCallbackListener<DelegateT>::FloatingCallbackListener(DelegateT handler) :
    Handler(handler)
{
    OVR_ASSERT(Handler.IsValid());
}

template<class DelegateT>
FloatingCallbackListener<DelegateT>::~FloatingCallbackListener()
{
    OVR_ASSERT(!Handler.IsValid());
}

template<class DelegateT>
void FloatingCallbackListener<DelegateT>::EnterCancelState()
{
    ListenerLock.DoLock();
    Handler.Invalidate();
    ListenerLock.Unlock();
}


} // namespace OVR

#endif // OVR_CallbacksInternal_h