use std::ffi::c_void;
use std::fmt;
use std::ptr;
use std::rc::Rc;
use crate::context::{GlContext, GlInner};
use crate::error::{checked_sizei, GlError, Result};
use crate::sys;
use crate::types::{
CompareFunc, InternalFormat, PixelFormat, PixelType, TextureFilter, TextureTarget, TextureWrap,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Texture2DDesc {
pub width: u32,
pub height: u32,
pub internal_format: InternalFormat,
pub pixel_format: PixelFormat,
pub pixel_type: PixelType,
pub min_filter: TextureFilter,
pub mag_filter: TextureFilter,
pub wrap_s: TextureWrap,
pub wrap_t: TextureWrap,
}
impl Texture2DDesc {
#[inline]
pub const fn rgba8(width: u32, height: u32) -> Self {
Self {
width,
height,
internal_format: InternalFormat::Rgba8,
pixel_format: PixelFormat::Rgba,
pixel_type: PixelType::U8,
min_filter: TextureFilter::Linear,
mag_filter: TextureFilter::Linear,
wrap_s: TextureWrap::ClampToEdge,
wrap_t: TextureWrap::ClampToEdge,
}
}
}
pub struct Texture {
ctx: Rc<GlInner>,
id: sys::GLuint,
target: TextureTarget,
width: u32,
height: u32,
internal_format: InternalFormat,
}
impl fmt::Debug for Texture {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Texture")
.field("id", &self.id)
.field("target", &self.target)
.field("width", &self.width)
.field("height", &self.height)
.field("internal_format", &self.internal_format)
.finish()
}
}
impl Drop for Texture {
fn drop(&mut self) {
if self.id != 0 {
unsafe { (self.ctx.fns.delete_textures)(1, &self.id) };
}
}
}
impl Texture {
pub fn new_2d(
ctx: &GlContext,
desc: &Texture2DDesc,
initial_data: Option<&[u8]>,
) -> Result<Self> {
if desc.width == 0 || desc.height == 0 {
return Err(GlError::InvalidParameter {
parameter: "dimensions",
reason: "texture width and height must be non-zero",
});
}
if !desc.mag_filter.is_valid_mag_filter() {
return Err(GlError::InvalidParameter {
parameter: "mag_filter",
reason: "magnification filter must be Nearest or Linear",
});
}
let w = checked_sizei(desc.width as usize, "Texture::new_2d width")?;
let h = checked_sizei(desc.height as usize, "Texture::new_2d height")?;
if let Some(bytes) = initial_data {
let expected = expected_pixel_bytes(
desc.width,
desc.height,
desc.pixel_format,
desc.pixel_type,
)?;
if bytes.len() < expected {
return Err(GlError::BufferSizeMismatch {
expected,
actual: bytes.len(),
});
}
}
let mut id: sys::GLuint = 0;
unsafe { (ctx.inner.fns.gen_textures)(1, &mut id) };
if id == 0 {
return Err(GlError::ObjectCreationFailed { object: "Texture" });
}
let tex = Self {
ctx: Rc::clone(&ctx.inner),
id,
target: TextureTarget::Texture2D,
width: desc.width,
height: desc.height,
internal_format: desc.internal_format,
};
let ptr = initial_data.map_or(ptr::null(), |b| b.as_ptr().cast::<c_void>());
unsafe {
(tex.ctx.fns.bind_texture)(sys::GL_TEXTURE_2D, tex.id);
(tex.ctx.fns.pixel_storei)(sys::GL_UNPACK_ALIGNMENT, 1);
(tex.ctx.fns.tex_image_2d)(
sys::GL_TEXTURE_2D,
0,
desc.internal_format as sys::GLint,
w,
h,
0,
desc.pixel_format as sys::GLenum,
desc.pixel_type as sys::GLenum,
ptr,
);
(tex.ctx.fns.tex_parameteri)(
sys::GL_TEXTURE_2D,
sys::GL_TEXTURE_MIN_FILTER,
desc.min_filter as sys::GLint,
);
(tex.ctx.fns.tex_parameteri)(
sys::GL_TEXTURE_2D,
sys::GL_TEXTURE_MAG_FILTER,
desc.mag_filter as sys::GLint,
);
(tex.ctx.fns.tex_parameteri)(
sys::GL_TEXTURE_2D,
sys::GL_TEXTURE_WRAP_S,
desc.wrap_s as sys::GLint,
);
(tex.ctx.fns.tex_parameteri)(
sys::GL_TEXTURE_2D,
sys::GL_TEXTURE_WRAP_T,
desc.wrap_t as sys::GLint,
);
}
tex.ctx.check_gl_error("glTexImage2D")?;
Ok(tex)
}
#[inline]
pub const fn raw_id(&self) -> u32 {
self.id
}
#[inline]
pub const fn target(&self) -> TextureTarget {
self.target
}
#[inline]
pub const fn width(&self) -> u32 {
self.width
}
#[inline]
pub const fn height(&self) -> u32 {
self.height
}
#[inline]
pub const fn internal_format(&self) -> InternalFormat {
self.internal_format
}
pub fn bind_unit(&self, unit: u32) -> Result<()> {
if unit >= 32 {
return Err(GlError::OutOfBounds {
context: "Texture::bind_unit",
requested: unit as usize,
available: 32,
});
}
unsafe {
(self.ctx.fns.active_texture)(sys::GL_TEXTURE0 + unit);
(self.ctx.fns.bind_texture)(self.target as sys::GLenum, self.id);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn upload_sub_2d(
&self,
x: u32,
y: u32,
width: u32,
height: u32,
pixel_format: PixelFormat,
pixel_type: PixelType,
data: &[u8],
) -> Result<()> {
let x_end = x.checked_add(width).ok_or(GlError::IntegerOverflow {
context: "Texture::upload_sub_2d x_end",
})?;
let y_end = y.checked_add(height).ok_or(GlError::IntegerOverflow {
context: "Texture::upload_sub_2d y_end",
})?;
if x_end > self.width {
return Err(GlError::OutOfBounds {
context: "Texture::upload_sub_2d x",
requested: x_end as usize,
available: self.width as usize,
});
}
if y_end > self.height {
return Err(GlError::OutOfBounds {
context: "Texture::upload_sub_2d y",
requested: y_end as usize,
available: self.height as usize,
});
}
let expected = expected_pixel_bytes(width, height, pixel_format, pixel_type)?;
if data.len() < expected {
return Err(GlError::BufferSizeMismatch {
expected,
actual: data.len(),
});
}
let gx = checked_sizei(x as usize, "Texture::upload_sub_2d x")?;
let gy = checked_sizei(y as usize, "Texture::upload_sub_2d y")?;
let gw = checked_sizei(width as usize, "Texture::upload_sub_2d width")?;
let gh = checked_sizei(height as usize, "Texture::upload_sub_2d height")?;
unsafe {
(self.ctx.fns.bind_texture)(sys::GL_TEXTURE_2D, self.id);
(self.ctx.fns.pixel_storei)(sys::GL_UNPACK_ALIGNMENT, 1);
(self.ctx.fns.tex_sub_image_2d)(
sys::GL_TEXTURE_2D,
0,
gx,
gy,
gw,
gh,
pixel_format as sys::GLenum,
pixel_type as sys::GLenum,
data.as_ptr().cast(),
);
}
self.ctx.check_gl_error("glTexSubImage2D")
}
pub fn generate_mipmaps(&self) -> Result<()> {
unsafe {
(self.ctx.fns.bind_texture)(self.target as sys::GLenum, self.id);
(self.ctx.fns.generate_mipmap)(self.target as sys::GLenum);
}
self.ctx.check_gl_error("glGenerateMipmap")
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SamplerDesc {
pub min_filter: TextureFilter,
pub mag_filter: TextureFilter,
pub wrap_s: TextureWrap,
pub wrap_t: TextureWrap,
pub wrap_r: TextureWrap,
pub compare_func: Option<CompareFunc>,
pub min_lod: f32,
pub max_lod: f32,
}
impl Default for SamplerDesc {
fn default() -> Self {
Self {
min_filter: TextureFilter::LinearMipmapLinear,
mag_filter: TextureFilter::Linear,
wrap_s: TextureWrap::Repeat,
wrap_t: TextureWrap::Repeat,
wrap_r: TextureWrap::Repeat,
compare_func: None,
min_lod: -1000.0,
max_lod: 1000.0,
}
}
}
pub struct Sampler {
ctx: Rc<GlInner>,
id: sys::GLuint,
}
impl fmt::Debug for Sampler {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Sampler").field("id", &self.id).finish()
}
}
impl Drop for Sampler {
fn drop(&mut self) {
if self.id != 0 {
unsafe { (self.ctx.fns.delete_samplers)(1, &self.id) };
}
}
}
impl Sampler {
pub fn new(ctx: &GlContext, desc: &SamplerDesc) -> Result<Self> {
if !desc.mag_filter.is_valid_mag_filter() {
return Err(GlError::InvalidParameter {
parameter: "mag_filter",
reason: "magnification filter must be Nearest or Linear",
});
}
if !desc.min_lod.is_finite() || !desc.max_lod.is_finite() {
return Err(GlError::InvalidParameter {
parameter: "lod",
reason: "min_lod and max_lod must be finite",
});
}
let mut id: sys::GLuint = 0;
unsafe { (ctx.inner.fns.gen_samplers)(1, &mut id) };
if id == 0 {
return Err(GlError::ObjectCreationFailed { object: "Sampler" });
}
let sampler = Self {
ctx: Rc::clone(&ctx.inner),
id,
};
unsafe {
(sampler.ctx.fns.sampler_parameteri)(
sampler.id,
sys::GL_TEXTURE_MIN_FILTER,
desc.min_filter as sys::GLint,
);
(sampler.ctx.fns.sampler_parameteri)(
sampler.id,
sys::GL_TEXTURE_MAG_FILTER,
desc.mag_filter as sys::GLint,
);
(sampler.ctx.fns.sampler_parameteri)(
sampler.id,
sys::GL_TEXTURE_WRAP_S,
desc.wrap_s as sys::GLint,
);
(sampler.ctx.fns.sampler_parameteri)(
sampler.id,
sys::GL_TEXTURE_WRAP_T,
desc.wrap_t as sys::GLint,
);
(sampler.ctx.fns.sampler_parameteri)(
sampler.id,
sys::GL_TEXTURE_WRAP_R,
desc.wrap_r as sys::GLint,
);
(sampler.ctx.fns.sampler_parameterf)(
sampler.id,
sys::GL_TEXTURE_MIN_LOD,
desc.min_lod,
);
(sampler.ctx.fns.sampler_parameterf)(
sampler.id,
sys::GL_TEXTURE_MAX_LOD,
desc.max_lod,
);
if let Some(cmp) = desc.compare_func {
(sampler.ctx.fns.sampler_parameteri)(
sampler.id,
sys::GL_TEXTURE_COMPARE_MODE,
sys::GL_COMPARE_REF_TO_TEXTURE as sys::GLint,
);
(sampler.ctx.fns.sampler_parameteri)(
sampler.id,
sys::GL_TEXTURE_COMPARE_FUNC,
cmp as sys::GLint,
);
} else {
(sampler.ctx.fns.sampler_parameteri)(
sampler.id,
sys::GL_TEXTURE_COMPARE_MODE,
sys::GL_NONE as sys::GLint,
);
}
}
sampler.ctx.check_gl_error("Sampler::new")?;
Ok(sampler)
}
#[inline]
pub const fn raw_id(&self) -> u32 {
self.id
}
pub fn bind_unit(&self, unit: u32) -> Result<()> {
if unit >= 32 {
return Err(GlError::OutOfBounds {
context: "Sampler::bind_unit",
requested: unit as usize,
available: 32,
});
}
unsafe { (self.ctx.fns.bind_sampler)(unit, self.id) };
Ok(())
}
pub fn unbind_unit(ctx: &GlContext, unit: u32) -> Result<()> {
if unit >= 32 {
return Err(GlError::OutOfBounds {
context: "Sampler::unbind_unit",
requested: unit as usize,
available: 32,
});
}
unsafe { (ctx.inner.fns.bind_sampler)(unit, 0) };
Ok(())
}
}
pub(crate) fn expected_pixel_bytes(
width: u32,
height: u32,
format: PixelFormat,
pixel_type: PixelType,
) -> Result<usize> {
(width as usize)
.checked_mul(height as usize)
.and_then(|px| px.checked_mul(format.channel_count()))
.and_then(|ch| ch.checked_mul(pixel_type.component_bytes()))
.ok_or(GlError::IntegerOverflow {
context: "pixel buffer byte size",
})
}