xgl 0.3.0

Unified minimalist OpenGL 3.3 & WebGL abstractions.
Documentation
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
// Copyright (C) 2025-2026 Daniel Mueller <deso@posteo.net>
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

use std::iter::once;
use std::ops::Deref;

use anyhow::ensure;
use anyhow::Context as _;
use anyhow::Result;

use crate::sys;
use crate::sys::Gl as _;


/// Information about an image to be used as a texture.
#[derive(Clone, Copy, Debug)]
pub struct TextureInfo {
  /// The texture's width.
  pub width: u32,
  /// The texture's height.
  pub height: u32,
  /// The texture's internal format.
  pub intern_format: sys::TextureInternalFormat,
  /// The texture's pixel format.
  pub pixel_format: sys::TexturePixelFormat,
  /// The texture's color format/color channel type.
  pub color_format: sys::Type,
}

impl AsRef<Self> for TextureInfo {
  #[inline]
  fn as_ref(&self) -> &Self {
    self
  }
}


/// Populate the currently bound texture with the given image data.
fn populate_texture(
  context: &sys::Context,
  target: sys::TextureTarget,
  data: Option<&[u8]>,
  info: &TextureInfo,
) -> Result<()> {
  let () = context
    .set_texture_image_2d(
      target,
      info.intern_format,
      info.pixel_format,
      info.color_format,
      info.width,
      info.height,
      data,
    )
    .context("failed to populate texture")?;

  Ok(())
}

fn populate_3d_texture(
  context: &sys::Context,
  idx: u32,
  target: sys::TextureTarget,
  data: &[u8],
  info: &TextureInfo,
) -> Result<()> {
  let x = 0;
  let y = 0;
  let z = idx;
  let () = context
    .set_texture_sub_image_3d(
      target,
      info.pixel_format,
      info.color_format,
      x,
      y,
      z,
      info.width,
      info.height,
      data,
    )
    .with_context(|| "failed to initialize 3D texture (index = {idx})")?;
  Ok(())
}


/// Builder infrastructure for a texture.
#[derive(Debug)]
pub struct Builder<C = ()> {
  /// The GL context.
  context: C,
  /// The texture wrap setting to use.
  wrap: sys::TextureWrap,
  /// Whether or not to create mipmaps.
  mipmaps: bool,
}

impl Builder<()> {
  /// Set the wrap mode for the to-be-created texture.
  pub fn set_wrap_mode(mut self, wrap: sys::TextureWrap) -> Self {
    self.wrap = wrap;
    self
  }

  /// Set whether or not to use mipmaps for the texture.
  pub fn set_mipmaps(mut self, mipmaps: bool) -> Self {
    self.mipmaps = mipmaps;
    self
  }

  /// Set the texture's GL context.
  pub fn set_context(self, context: &sys::Context) -> Builder<sys::Context> {
    let Self {
      context: (),
      wrap,
      mipmaps,
    } = self;

    Builder {
      context: context.clone(),
      wrap,
      mipmaps,
    }
  }
}

impl Builder<sys::Context> {
  /// Apply a certain texture state to the currently bound texture
  /// before it is being populated.
  ///
  /// Note that this function modifies global state and won't reset it.
  /// The modus operandi here is for everything that is required to be
  /// set unconditionally and if everybody does that there is no need to
  /// set and restore.
  fn apply_pre_texture_state(&self, texture: &Texture) {
    let Self {
      context: _,
      wrap,
      mipmaps,
    } = self;
    let target = texture.target();
    let () = self.context.set_texture_filter(
      target,
      sys::TextureFilterType::Magnify,
      sys::TextureFilter::Linear,
    );

    let filter = if *mipmaps {
      sys::TextureFilter::LinearMipmapLinear
    } else {
      sys::TextureFilter::Linear
    };
    let () = self
      .context
      .set_texture_filter(target, sys::TextureFilterType::Minimize, filter);
    let () = self.context.set_texture_wrap(target, *wrap);

    // TODO: Probably not the full story.
    let () = self.context.set_pixel_unpack_alignment(1);
  }

  /// Apply a certain texture state to the currently bound texture
  /// after it has been populated.
  fn apply_post_texture_state(&self, texture: &Texture) {
    let Self {
      context: _,
      wrap: _,
      mipmaps,
    } = self;
    let target = texture.target();

    if *mipmaps {
      let () = self.context.generate_mipmaps(target);
    }
  }

  fn new_impl(&self, data: Option<&[u8]>, info: &TextureInfo) -> Result<Texture> {
    let target = sys::TextureTarget::Texture2D;

    let texture = Texture {
      context: self.context.clone(),
      texture: self
        .context
        .create_texture()
        .context("failed to generate texture ID")?,
      target,
    };
    let () = texture.bind();
    let () = self.apply_pre_texture_state(&texture);
    let result = populate_texture(&self.context, target, data, info);
    if let Ok(()) = result {
      let () = self.apply_post_texture_state(&texture);
    }
    let () = texture.unbind();

    let () = result?;
    Ok(texture)
  }

  /// Create a new empty 2D `Texture`.
  pub fn empty(&self, info: &TextureInfo) -> Result<Texture> {
    self.new_impl(None, info)
  }

  /// Create a new 2D `Texture` suitable for use as a depth map.
  pub fn new_depth_map(&self, width: u32, height: u32) -> Result<Texture> {
    let target = sys::TextureTarget::Texture2D;
    let texture = Texture {
      context: self.context.clone(),
      texture: self
        .context
        .create_texture()
        .context("failed to generate texture ID")?,
      target,
    };
    let info = TextureInfo {
      width,
      height,
      intern_format: sys::TextureInternalFormat::Depth,
      pixel_format: sys::TexturePixelFormat::Depth,
      color_format: sys::Type::Float,
    };
    let data = None;

    let () = texture.bind();
    let () = self.apply_pre_texture_state(&texture);

    // NB: The compare mode only applies to depth maps, so we don't need
    //     to set it for other types.
    let () = self
      .context
      .set_texture_compare_mode(target, sys::TextureCompareMode::RefToTexture);
    let () = self
      .context
      .set_texture_compare_func(target, sys::Func::Greater);

    let result = populate_texture(&self.context, target, data, &info);
    if let Ok(()) = result {
      let () = self.apply_post_texture_state(&texture);
    }
    let () = texture.unbind();

    let () = result?;
    Ok(texture)
  }

  /// Create a new 2D `Texture` from the provided image data.
  pub fn from_image(&self, data: &[u8], info: &TextureInfo) -> Result<Texture> {
    self.new_impl(Some(data), info)
  }

  /// Create a new 3D `Texture` using the provided images.
  pub fn from_images<I, D, M>(&self, width: u32, height: u32, mut images: I) -> Result<Texture>
  where
    I: ExactSizeIterator<Item = Result<(D, M)>>,
    D: AsRef<[u8]>,
    M: AsRef<TextureInfo>,
  {
    let count = images.len();
    let (image, info) = images
      .next()
      .expect("3D texture creation requires at least one image")?;
    let target = sys::TextureTarget::Texture2DArray;

    let texture = Texture {
      context: self.context.clone(),
      texture: self
        .context
        .create_texture()
        .context("failed to generate texture ID")?,
      target,
    };
    let () = texture.bind();
    let () = self.apply_pre_texture_state(&texture);
    let result = self
      .context
      .set_texture_image_3d(
        target,
        info.as_ref().intern_format,
        info.as_ref().pixel_format,
        info.as_ref().color_format,
        width,
        height,
        count as _,
        None,
      )
      .context("failed to initialize 3D texture");
    let result = result.and_then(|()| {
      once(Ok((image, info)))
        .chain(images)
        .enumerate()
        .try_for_each(|(idx, result)| {
          let (image, info) = result?;
          let image = image.as_ref();
          let info = info.as_ref();
          ensure!(
            info.width <= width && info.height <= height,
            "image {idx} is larger than maximum bounds provided"
          );

          let () = populate_3d_texture(&self.context, idx as _, target, image, info)?;
          Ok(())
        })
    });
    if let Ok(()) = result {
      let () = self.apply_post_texture_state(&texture);
    }
    let () = texture.unbind();
    let () = result?;

    Ok(texture)
  }
}

/// Instantiate a "default" [`Builder`].
///
/// The defaults are as follows:
/// - wrap mode: [`Repeat`][sys::TextureWrap::Repeat]
/// - mipmaps: `false`
impl Default for Builder<()> {
  #[inline]
  fn default() -> Self {
    Self {
      context: (),
      wrap: sys::TextureWrap::Repeat,
      mipmaps: false,
    }
  }
}


/// A texture.
#[derive(Debug)]
pub struct Texture {
  /// The GL context.
  context: sys::Context,
  /// The texture ID.
  texture: sys::Texture,
  /// The "target" to bind to.
  target: sys::TextureTarget,
}

impl Texture {
  /// Create a texture builder.
  #[inline]
  pub fn builder() -> Builder {
    Builder::default()
  }

  #[inline]
  pub fn bind(&self) {
    self.context.bind_texture(self.target, Some(&self.texture))
  }

  #[inline]
  pub fn unbind(&self) {
    self.context.bind_texture(self.target, None)
  }

  /// Retrieve the texture's "target".
  #[inline]
  pub fn target(&self) -> sys::TextureTarget {
    self.target
  }
}

impl Deref for Texture {
  type Target = sys::Texture;

  #[inline]
  fn deref(&self) -> &Self::Target {
    &self.texture
  }
}

impl Drop for Texture {
  #[inline]
  fn drop(&mut self) {
    let () = self.context.delete_texture(&self.texture);
  }
}


#[cfg(test)]
mod tests {
  use super::*;

  use test_fork::fork;

  use crate::winit::with_opengl_context;


  /// Check that we can create an empty [`Texture`] object.
  #[fork]
  #[test]
  fn texture_creation_empty() {
    with_opengl_context(|| {
      let gl_context = sys::Context::default();
      let info = TextureInfo {
        width: 32,
        height: 32,
        intern_format: sys::TextureInternalFormat::RGB8,
        pixel_format: sys::TexturePixelFormat::RGB,
        color_format: sys::Type::Float,
      };
      let _texture = Texture::builder()
        .set_context(&gl_context)
        .empty(&info)
        .unwrap();
    })
  }

  /// Check that we can create a [`Texture`] object given some dummy
  /// image data.
  #[fork]
  #[test]
  fn texture_creation_dummy() {
    with_opengl_context(|| {
      let gl_context = sys::Context::default();
      let data = [0x00; 4];
      let info = TextureInfo {
        width: 1,
        height: 1,
        intern_format: sys::TextureInternalFormat::RGBA8,
        pixel_format: sys::TexturePixelFormat::RGBA,
        color_format: sys::Type::UnsignedByte,
      };
      let _texture = Texture::builder()
        .set_context(&gl_context)
        .from_image(&data, &info)
        .unwrap();
    })
  }
}