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
/*!

Without bindless textures, using a texture in a shader requires binding the texture to a specific
bind point before drawing. This not only slows down rendering, but may also prevent you from
grouping multiple draw calls into one because of the limitation to the number of available
texture units.

Instead, bindless textures allow you to manually manipulate pointers to textures in video memory.
You can use thousands of textures if you want.

# Initialization

Before using a bindless texture, you must turn it into a `ResidentTexture`. This is done by
calling `resident` on the texture you want.

Bindless textures are a very recent feature that is supported only by recent hardware and
drivers. `resident` will return an `Err` if this feature is not supported.

```no_run
# let display: glium::Display = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
# let texture: glium::texture::Texture2d = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
let texture = texture.resident().unwrap();
```

In a real application, you will likely manage a `Vec<ResidentTexture>`.

# Usage

You can then use a `TextureHandle` as if it was a pointer to a texture. A `TextureHandle` can be
built from a `&ResidentTexture` and can't outlive it.

```no_run
#[macro_use]
extern crate glium;

# fn main() {
#[derive(Copy, Clone)]
struct UniformBuffer<'a> {
    texture: glium::texture::TextureHandle<'a>,
    some_value: f32,
}

implement_uniform_block!(UniformBuffer<'a>, texture, some_value);

# let display: glium::Display = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
# let texture: glium::texture::bindless::ResidentTexture = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
let uniform_buffer = glium::uniforms::UniformBuffer::new(&display, UniformBuffer {
    texture: glium::texture::TextureHandle::new(&texture, &Default::default()),
    some_value: 5.0,
});
# }
```

Inside your shader, you can refer to the texture with a traditional `sampler*` variable. Glium
currently doesn't check whether the type of your texture matches the expected type (but it may
do in the future). Binding the wrong type of texture may lead to undefined values when sampling
the texture.

*/
use texture::any::TextureAny;
use TextureExt;
use GlObject;

use ContextExt;
use gl;

use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};

use program::BlockLayout;
use uniforms::AsUniformValue;
use uniforms::LayoutMismatchError;
use uniforms::UniformBlock;
use uniforms::UniformValue;
use uniforms::UniformType;
use uniforms::SamplerBehavior;

/// A texture that is resident in video memory. This allows you to use bindless textures in your
/// shaders.
pub struct ResidentTexture {
    texture: Option<TextureAny>,
    handle: gl::types::GLuint64,
}

impl ResidentTexture {
    /// Takes ownership of the given texture and makes it resident.
    // TODO: sampler
    pub fn new(texture: TextureAny) -> Result<ResidentTexture, BindlessTexturesNotSupportedError> {
        let handle = {
            let mut ctxt = texture.get_context().make_current();

            if !ctxt.extensions.gl_arb_bindless_texture {
                return Err(BindlessTexturesNotSupportedError);
            }

            let handle = unsafe { ctxt.gl.GetTextureHandleARB(texture.get_id()) };
            unsafe { ctxt.gl.MakeTextureHandleResidentARB(handle) };
            ctxt.resident_texture_handles.push(handle);
            handle
        };

        // store the handle in the context
        Ok(ResidentTexture {
            texture: Some(texture),
            handle: handle,
        })
    }

    /// Unwraps the texture and restores it.
    #[inline]
    pub fn into_inner(mut self) -> TextureAny {
        self.into_inner_impl()
    }

    /// Implementation of `into_inner`. Also called by the destructor.
    fn into_inner_impl(&mut self) -> TextureAny {
        let texture = self.texture.take().unwrap();

        {
            let mut ctxt = texture.get_context().make_current();
            unsafe { ctxt.gl.MakeTextureHandleNonResidentARB(self.handle) };
            ctxt.resident_texture_handles.retain(|&t| t != self.handle);
        }

        texture
    }
}

impl Deref for ResidentTexture {
    type Target = TextureAny;

    #[inline]
    fn deref(&self) -> &TextureAny {
        self.texture.as_ref().unwrap()
    }
}

impl DerefMut for ResidentTexture {
    #[inline]
    fn deref_mut(&mut self) -> &mut TextureAny {
        self.texture.as_mut().unwrap()
    }
}

impl Drop for ResidentTexture {
    #[inline]
    fn drop(&mut self) {
        self.into_inner_impl();
    }
}

/// Represents a handle to a texture. Contains a raw pointer to a texture that is hidden from you.
#[derive(Copy, Clone)]
pub struct TextureHandle<'a> {
    value: gl::types::GLuint64,
    marker: PhantomData<&'a ResidentTexture>,
}

impl<'a> TextureHandle<'a> {
    /// Builds a new handle.
    #[inline]
    pub fn new(texture: &'a ResidentTexture, _: &SamplerBehavior) -> TextureHandle<'a> {
        // FIXME: take sampler into account
        TextureHandle {
            value: texture.handle,
            marker: PhantomData,
        }
    }

    /// Sets the value to the given texture.
    #[inline]
    pub fn set(&mut self, texture: &'a ResidentTexture, _: &SamplerBehavior) {
        // FIXME: take sampler into account
        self.value = texture.handle;
    }
}

impl<'a> AsUniformValue for TextureHandle<'a> {
    #[inline]
    fn as_uniform_value(&self) -> UniformValue {
        // TODO: u64
        unimplemented!();
    }
}

impl<'a> UniformBlock for TextureHandle<'a> {
    fn matches(layout: &BlockLayout, base_offset: usize)
               -> Result<(), LayoutMismatchError>
    {
        if let &BlockLayout::BasicType { ty, offset_in_buffer } = layout {
            // TODO: unfortunately we have no idea what the exact type of this handle is
            //       strong typing should be considered
            //
            //       however there is no safety problem here ; the worse that can happen in case of
            //       wrong type is zeroes or undefined data being returned when sampling
            match ty {
                UniformType::Sampler1d => (),
                UniformType::ISampler1d => (),
                UniformType::USampler1d => (),
                UniformType::Sampler2d => (),
                UniformType::ISampler2d => (),
                UniformType::USampler2d => (),
                UniformType::Sampler3d => (),
                UniformType::ISampler3d => (),
                UniformType::USampler3d => (),
                UniformType::Sampler1dArray => (),
                UniformType::ISampler1dArray => (),
                UniformType::USampler1dArray => (),
                UniformType::Sampler2dArray => (),
                UniformType::ISampler2dArray => (),
                UniformType::USampler2dArray => (),
                UniformType::SamplerCube => (),
                UniformType::ISamplerCube => (),
                UniformType::USamplerCube => (),
                UniformType::Sampler2dRect => (),
                UniformType::ISampler2dRect => (),
                UniformType::USampler2dRect => (),
                UniformType::Sampler2dRectShadow => (),
                UniformType::SamplerCubeArray => (),
                UniformType::ISamplerCubeArray => (),
                UniformType::USamplerCubeArray => (),
                UniformType::SamplerBuffer => (),
                UniformType::ISamplerBuffer => (),
                UniformType::USamplerBuffer => (),
                UniformType::Sampler2dMultisample => (),
                UniformType::ISampler2dMultisample => (),
                UniformType::USampler2dMultisample => (),
                UniformType::Sampler2dMultisampleArray => (),
                UniformType::ISampler2dMultisampleArray => (),
                UniformType::USampler2dMultisampleArray => (),
                UniformType::Sampler1dShadow => (),
                UniformType::Sampler2dShadow => (),
                UniformType::SamplerCubeShadow => (),
                UniformType::Sampler1dArrayShadow => (),
                UniformType::Sampler2dArrayShadow => (),
                UniformType::SamplerCubeArrayShadow => (),

                _ => return Err(LayoutMismatchError::TypeMismatch {
                    expected: ty,
                    obtained: UniformType::Sampler2d,       // TODO: wrong
                })
            }

            if offset_in_buffer != base_offset {
                return Err(LayoutMismatchError::OffsetMismatch {
                    expected: offset_in_buffer,
                    obtained: base_offset,
                });
            }

            Ok(())

        } else if let &BlockLayout::Struct { ref members } = layout {
            if members.len() == 1 {
                <TextureHandle as UniformBlock>::matches(&members[0].1, base_offset)

            } else {
                Err(LayoutMismatchError::LayoutMismatch {
                    expected: layout.clone(),
                    obtained: BlockLayout::BasicType {
                        ty: UniformType::Sampler2d,       // TODO: wrong
                        offset_in_buffer: base_offset,
                    }
                })
            }

        } else {
            Err(LayoutMismatchError::LayoutMismatch {
                expected: layout.clone(),
                obtained: BlockLayout::BasicType {
                    ty: UniformType::Sampler2d,       // TODO: wrong
                    offset_in_buffer: base_offset,
                }
            })
        }
    }

    #[inline]
    fn build_layout(base_offset: usize) -> BlockLayout {
        BlockLayout::BasicType {
            ty: UniformType::Sampler2d,       // TODO: wrong
            offset_in_buffer: base_offset,
        }
    }
}

// TODO: implement `vertex::Attribute` on `TextureHandle`

/// Bindless textures are not supported.
#[derive(Debug, Copy, Clone)]
pub struct BindlessTexturesNotSupportedError;

#[cfg(test)]
mod test {
    use std::mem;
    use super::TextureHandle;

    #[test]
    fn texture_handle_size() {
        assert_eq!(mem::size_of::<TextureHandle>(), 8);
    }
}