1 #ifndef MSP_GL_BINDABLE_H_
2 #define MSP_GL_BINDABLE_H_
8 A helper class for single-point binding. Provides tracking of the currently
15 static const T *cur_obj;
18 ~Bindable() { if(cur_obj==this) T::unbind(); }
20 static bool set_current(const T *obj)
30 static const T *current() { return cur_obj; }
34 const T *Bindable<T>::cur_obj;
38 A helper class for Bindables that revert to a default object on unbind.
41 class BindableWithDefault: protected Bindable<T>
43 friend class Bindable<T>;
46 BindableWithDefault() { }
47 ~BindableWithDefault() { if(this==&default_object()) Bindable<T>::set_current(0); }
50 static const T *current()
52 if(!Bindable<T>::cur_obj)
53 Bindable<T>::cur_obj = &default_object();
54 return Bindable<T>::cur_obj;
59 if(Bindable<T>::cur_obj)
60 default_object().bind();
63 static const T &default_object()
72 RAII class for binding things. Binds the thing upon construction and unbinds
73 it upon destruction. If a null pointer is given, unbinds upon construction and
74 does nothing upon destruction.
79 typedef void CleanupFunc(int);
86 Bind(T *o) { init(o); }
89 Bind(const T *o) { init(o); }
92 Bind(const T &o) { init(&o); }
94 template<typename T, typename S>
95 Bind(T *o, S s) { init(o, s); }
97 template<typename T, typename S>
98 Bind(const T *o, S s) { init(o, s); }
100 template<typename T, typename S>
101 Bind(const T &o, S s) { init(&o, s); }
105 void init(const T *o)
107 cleanup = (o ? static_cast<CleanupFunc *>(&unbind<T>) : 0);
115 template<typename T, typename S>
116 void init(const T *o, S s)
118 cleanup = (o ? static_cast<CleanupFunc *>(&unbind_from<T, S>) : 0);
128 { if(cleanup) cleanup(slot); }
132 static void unbind(int)
135 template<typename T, typename S>
136 static void unbind_from(int s)
137 { T::unbind_from(static_cast<S>(s)); }
142 Similar to Bind, but restores previous binding upon destruction.
147 typedef void CleanupFunc(const void *, int);
151 CleanupFunc *cleanup;
155 BindRestore(T *o) { init(o); }
158 BindRestore(const T *o) { init(o); }
161 BindRestore(const T &o) { init(&o); }
163 template<typename T, typename S>
164 BindRestore(T *o, S s) { init(o, s); }
166 template<typename T, typename S>
167 BindRestore(const T *o, S s) { init(o, s); }
169 template<typename T, typename S>
170 BindRestore(const T &o, S s) { init(&o, s); }
178 cleanup = (o!=old ? static_cast<CleanupFunc *>(&restore<T>) : 0);
185 template<typename T, typename S>
190 cleanup = (o!=old ? static_cast<CleanupFunc *>(&restore_to<T, S>) : 0);
199 { if(cleanup) cleanup(old, slot); }
203 static void restore(const void *o, int)
206 reinterpret_cast<const T *>(o)->bind();
211 template<typename T, typename S>
212 static void restore_to(const void *o, int si)
214 S s = static_cast<S>(si);
216 reinterpret_cast<const T *>(o)->bind_to(s);