diff options
Diffstat (limited to 'engine/src/opengl')
-rw-r--r-- | engine/src/opengl/buffer.rs | 51 | ||||
-rw-r--r-- | engine/src/opengl/glsl.rs | 616 | ||||
-rw-r--r-- | engine/src/opengl/mod.rs | 23 | ||||
-rw-r--r-- | engine/src/opengl/shader.rs | 118 | ||||
-rw-r--r-- | engine/src/opengl/texture.rs | 97 | ||||
-rw-r--r-- | engine/src/opengl/vertex_array.rs | 31 |
6 files changed, 758 insertions, 178 deletions
diff --git a/engine/src/opengl/buffer.rs b/engine/src/opengl/buffer.rs index 2be7f12..eded553 100644 --- a/engine/src/opengl/buffer.rs +++ b/engine/src/opengl/buffer.rs @@ -1,5 +1,6 @@ use std::marker::PhantomData; use std::mem::size_of_val; +use std::ptr::null; #[derive(Debug)] pub struct Buffer<Item> @@ -35,32 +36,40 @@ impl<Item> Buffer<Item> } } - pub fn object(&self) -> gl::types::GLuint + pub fn store_mapped<Value>( + &mut self, + values: &[Value], + usage: Usage, + mut map_func: impl FnMut(&Value) -> Item, + ) { - self.buf - } + unsafe { + #[allow(clippy::cast_possible_wrap)] + gl::NamedBufferData( + self.buf, + (size_of::<Item>() * values.len()) as gl::types::GLsizeiptr, + null(), + usage.into_gl(), + ); + } - /// Does a weak clone of this buffer. The buffer itself is NOT copied in any way this - /// function only copies the internal buffer ID. - /// - /// # Safety - /// The returned `Buffer` must not be dropped if another `Buffer` referencing the - /// same buffer ID is used later or if a [`VertexArray`] is used later. - /// - /// [`VertexArray`]: crate::opengl::vertex_array::VertexArray - pub unsafe fn clone_weak(&self) -> Self - { - Self { buf: self.buf, _pd: PhantomData } + for (index, value) in values.iter().enumerate() { + let item = map_func(value); + + unsafe { + gl::NamedBufferSubData( + self.buf, + (index * size_of::<Item>()) as gl::types::GLintptr, + size_of::<Item>() as gl::types::GLsizeiptr, + (&raw const item).cast(), + ); + } + } } -} -impl<Item> Drop for Buffer<Item> -{ - fn drop(&mut self) + pub fn object(&self) -> gl::types::GLuint { - unsafe { - gl::DeleteBuffers(1, &self.buf); - } + self.buf } } diff --git a/engine/src/opengl/glsl.rs b/engine/src/opengl/glsl.rs new file mode 100644 index 0000000..6fd5638 --- /dev/null +++ b/engine/src/opengl/glsl.rs @@ -0,0 +1,616 @@ +use std::borrow::Cow; +use std::fmt::{Display, Formatter}; +use std::path::{Path, PathBuf}; +use std::string::FromUtf8Error; + +const PREINCLUDE_DIRECTIVE: &str = "#preinclude"; + +pub fn preprocess<'content>( + shader_content: impl Into<Cow<'content, str>>, + read_file: &impl Fn(&Path) -> Result<Vec<u8>, std::io::Error>, +) -> Result<Cow<'content, str>, PreprocessingError> +{ + do_preprocess(shader_content, SpanPath::Original, read_file) +} + +fn do_preprocess<'content>( + shader_content: impl Into<Cow<'content, str>>, + shader_path: SpanPath<'_>, + read_file: &impl Fn(&Path) -> Result<Vec<u8>, std::io::Error>, +) -> Result<Cow<'content, str>, PreprocessingError> +{ + let shader_content = shader_content.into(); + + let mut preincludes = shader_content + .match_indices(PREINCLUDE_DIRECTIVE) + .peekable(); + + if preincludes.peek().is_none() { + // Shader content contains no preincludes + return Ok(shader_content.into()); + }; + + let mut preprocessed = shader_content.to_string(); + + let mut curr = shader_content.find(PREINCLUDE_DIRECTIVE); + + let mut last_start = 0; + let mut span_line_offset = 0; + + while let Some(preinclude_start) = curr { + let replacement_job = handle_preinclude( + &preprocessed, + &shader_path, + preinclude_start, + span_line_offset, + )?; + + let path = replacement_job.path.clone(); + + let mut included = + String::from_utf8(read_file(&replacement_job.path).map_err(|err| { + PreprocessingError::ReadIncludedShaderFailed { + source: err, + path: replacement_job.path.clone(), + } + })?) + .map_err(|err| { + PreprocessingError::IncludedShaderInvalidUtf8 { + source: err, + path: path.clone(), + } + })?; + + if let Some(first_line) = included.lines().next() { + if first_line.starts_with("#version") { + included = included + .chars() + .skip_while(|character| *character != '\n') + .collect(); + } + } + + let included_preprocessed = do_preprocess( + &included, + SpanPath::Path(replacement_job.path.as_path().into()), + read_file, + )?; + + let start = replacement_job.start_index; + let end = replacement_job.end_index; + + preprocessed.replace_range(start..end, &included_preprocessed); + + curr = preprocessed[last_start + 1..] + .find(PREINCLUDE_DIRECTIVE) + .map(|index| index + 1); + + last_start = preinclude_start + included_preprocessed.len(); + + span_line_offset += included_preprocessed.lines().count(); + } + + Ok(preprocessed.into()) +} + +fn handle_preinclude( + shader_content: &str, + shader_path: &SpanPath<'_>, + preinclude_start_index: usize, + span_line_offset: usize, +) -> Result<ReplacementJob, PreprocessingError> +{ + let expect_token = |token: char, index: usize| { + let token_found = shader_content.chars().nth(index).ok_or_else(|| { + PreprocessingError::ExpectedToken { + expected: token, + span: Span::new( + shader_content, + shader_path.to_owned(), + index, + span_line_offset, + preinclude_start_index, + ), + } + })?; + + if token_found != token { + return Err(PreprocessingError::InvalidToken { + expected: token, + found: token_found, + span: Span::new( + shader_content, + shader_path.to_owned(), + index, + span_line_offset, + preinclude_start_index, + ), + }); + } + + Ok(()) + }; + + let space_index = preinclude_start_index + PREINCLUDE_DIRECTIVE.len(); + let quote_open_index = space_index + 1; + + expect_token(' ', space_index)?; + expect_token('"', quote_open_index)?; + + let buf = shader_content[quote_open_index + 1..] + .chars() + .take_while(|character| *character != '"') + .map(|character| character as u8) + .collect::<Vec<_>>(); + + if buf.is_empty() { + return Err(PreprocessingError::ExpectedToken { + expected: '"', + span: Span::new( + shader_content, + shader_path.to_owned(), + shader_content.len() - 1, + span_line_offset, + preinclude_start_index, + ), + }); + } + + let path_len = buf.len(); + + let path = PathBuf::from(String::from_utf8(buf).map_err(|err| { + PreprocessingError::PreincludePathInvalidUtf8 { + source: err, + span: Span::new( + shader_content, + shader_path.to_owned(), + quote_open_index + 1, + span_line_offset, + preinclude_start_index, + ), + } + })?); + + Ok(ReplacementJob { + start_index: preinclude_start_index, + end_index: quote_open_index + 1 + path_len + 1, + path, + }) +} + +struct ReplacementJob +{ + start_index: usize, + end_index: usize, + path: PathBuf, +} + +#[derive(Debug, thiserror::Error)] +pub enum PreprocessingError +{ + #[error( + "Invalid token at line {}, column {} of {}. Expected '{}', found '{}'", + span.line, + span.column, + span.path, + expected, + found + )] + InvalidToken + { + expected: char, + found: char, + span: Span, + }, + + #[error( + "Expected token '{}' at line {}, column {} of {}. Found eof", + expected, + span.line, + span.column, + span.path + )] + ExpectedToken + { + expected: char, span: Span + }, + + #[error( + "Preinclude path at line {}, column {} of {} is invalid UTF-8", + span.line, + span.column, + span.path + )] + PreincludePathInvalidUtf8 + { + #[source] + source: FromUtf8Error, + span: Span, + }, + + #[error("Failed to read included shader")] + ReadIncludedShaderFailed + { + #[source] + source: std::io::Error, + path: PathBuf, + }, + + #[error("Included shader is not valid UTF-8")] + IncludedShaderInvalidUtf8 + { + #[source] + source: FromUtf8Error, + path: PathBuf, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Span +{ + pub line: usize, + pub column: usize, + pub path: SpanPath<'static>, +} + +impl Span +{ + fn new( + file_content: &str, + path: SpanPath<'static>, + char_index: usize, + line_offset: usize, + line_start_index: usize, + ) -> Self + { + let line = find_line_of_index(file_content, char_index) + 1 + - line_offset.saturating_sub(1); + + Self { + line, + column: char_index - line_start_index + 1, + path, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SpanPath<'a> +{ + Original, + Path(Cow<'a, Path>), +} + +impl<'a> SpanPath<'a> +{ + fn to_owned(&self) -> SpanPath<'static> + { + match self { + Self::Original => SpanPath::Original, + Self::Path(path) => SpanPath::Path(Cow::Owned(path.to_path_buf().into())), + } + } +} + +impl<'a> Display for SpanPath<'a> +{ + fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result + { + match self { + Self::Original => write!(formatter, "original file"), + Self::Path(path) => write!(formatter, "file {}", path.display()), + } + } +} + +impl<'a, PathLike> PartialEq<PathLike> for SpanPath<'a> +where + PathLike: AsRef<Path>, +{ + fn eq(&self, other: &PathLike) -> bool + { + match self { + Self::Original => false, + Self::Path(path) => path == other.as_ref(), + } + } +} + +fn find_line_of_index(text: &str, index: usize) -> usize +{ + text.chars() + .take(index + 1) + .enumerate() + .filter(|(_, character)| *character == '\n') + .count() +} + +#[cfg(test)] +mod tests +{ + use std::ffi::OsStr; + use std::path::Path; + + use super::{preprocess, PreprocessingError}; + use crate::opengl::glsl::SpanPath; + + #[test] + fn preprocess_no_directives_is_same() + { + assert_eq!( + preprocess("#version 330 core\n", &|_| { unreachable!() }).unwrap(), + "#version 330 core\n" + ); + } + + #[test] + fn preprocess_with_directives_works() + { + assert_eq!( + preprocess( + concat!( + "#version 330 core\n", + "\n", + "#preinclude \"foo.glsl\"\n", + "\n", + "void main() {}", + ), + &|_| { Ok(b"out vec4 FragColor;".to_vec()) } + ) + .unwrap(), + concat!( + "#version 330 core\n", + "\n", + "out vec4 FragColor;\n", + "\n", + "void main() {}", + ) + ); + + assert_eq!( + preprocess( + concat!( + "#version 330 core\n", + "\n", + "#preinclude \"bar.glsl\"\n", + "\n", + "in vec3 in_frag_color;\n", + "\n", + "void main() {}", + ), + &|_| { Ok(b"out vec4 FragColor;".to_vec()) } + ) + .unwrap(), + concat!( + "#version 330 core\n", + "\n", + "out vec4 FragColor;\n", + "\n", + "in vec3 in_frag_color;\n", + "\n", + "void main() {}", + ) + ); + + assert_eq!( + preprocess( + concat!( + "#version 330 core\n", + "\n", + "#preinclude \"bar.glsl\"\n", + "\n", + "in vec3 in_frag_color;\n", + "\n", + "#preinclude \"foo.glsl\"\n", + "\n", + "void main() {}", + ), + &|path| { + if path == OsStr::new("bar.glsl") { + Ok(b"out vec4 FragColor;".to_vec()) + } else { + Ok(concat!( + "uniform sampler2D input_texture;\n", + "in vec2 in_texture_coords;" + ) + .as_bytes() + .to_vec()) + } + }, + ) + .unwrap(), + concat!( + "#version 330 core\n", + "\n", + "out vec4 FragColor;\n", + "\n", + "in vec3 in_frag_color;\n", + "\n", + "uniform sampler2D input_texture;\n", + "in vec2 in_texture_coords;\n", + "\n", + "void main() {}", + ) + ); + } + + #[test] + fn preprocess_invalid_directive_does_not_work() + { + let res = preprocess( + concat!( + "#version 330 core\n", + "\n", + // Missing " + "#preinclude foo.glsl\"\n", + "\n", + "void main() {}", + ), + &|_| Ok(b"out vec4 FragColor;".to_vec()), + ); + + let Err(PreprocessingError::InvalidToken { expected, found, span }) = res else { + panic!( + "Expected result to be Err(Error::InvalidToken {{ ... }}), is {res:?}" + ); + }; + + assert_eq!(expected, '"'); + assert_eq!(found, 'f'); + assert_eq!(span.line, 3); + assert_eq!(span.column, 13); + assert_eq!(span.path, SpanPath::Original); + } + + #[test] + fn preprocess_error_has_correct_span() + { + let res = preprocess( + concat!( + "#version 330 core\n", + "\n", + "#preinclude \"bar.glsl\"\n", + "\n", + "#preinclude \"foo.glsl\"\n", + "\n", + "in vec3 in_frag_color;\n", + "\n", + "void main() {}", + ), + &|path| { + if path == OsStr::new("bar.glsl") { + Ok(concat!( + "out vec4 FragColor;\n", + "in vec2 in_texture_coords;\n", + "in float foo;" + ) + .as_bytes() + .to_vec()) + } else if path == OsStr::new("foo.glsl") { + Ok(concat!( + "uniform sampler2D input_texture;\n", + "\n", + // Missing space before first " + "#preinclude\"shared_types.glsl\"\n", + ) + .as_bytes() + .to_vec()) + } else { + panic!(concat!( + "Expected read function to be called with ", + "either path bar.glsl or foo.glsl" + )); + } + }, + ); + + let Err(PreprocessingError::InvalidToken { expected, found, span }) = res else { + panic!( + "Expected result to be Err(Error::InvalidToken {{ ... }}), is {res:?}" + ); + }; + + assert_eq!(expected, ' '); + assert_eq!(found, '"'); + assert_eq!(span.line, 3); + assert_eq!(span.column, 12); + assert_eq!(span.path, SpanPath::Path(Path::new("foo.glsl").into())); + } + + #[test] + fn preprocess_included_shader_with_include_works() + { + assert_eq!( + preprocess( + concat!( + "#version 330 core\n", + "\n", + "#preinclude \"bar.glsl\"\n", + "\n", + "in vec3 in_frag_color;\n", + "\n", + "void main() {}", + ), + &|path| { + if path == OsStr::new("bar.glsl") { + Ok(concat!( + "#preinclude \"foo.glsl\"\n", + "\n", + "out vec4 FragColor;" + ) + .as_bytes() + .to_vec()) + } else { + Ok(concat!( + "uniform sampler2D input_texture;\n", + "in vec2 in_texture_coords;" + ) + .as_bytes() + .to_vec()) + } + } + ) + .unwrap(), + concat!( + "#version 330 core\n", + "\n", + "uniform sampler2D input_texture;\n", + "in vec2 in_texture_coords;\n", + "\n", + "out vec4 FragColor;\n", + "\n", + "in vec3 in_frag_color;\n", + "\n", + "void main() {}", + ) + ); + } + + #[test] + fn preprocess_included_shader_with_include_error_span_is_correct() + { + let res = preprocess( + concat!( + "#version 330 core\n", + "\n", + "#preinclude \"bar.glsl\"\n", + "\n", + "in vec3 in_frag_color;\n", + "\n", + "void main() {}", + ), + &|path| { + if path == OsStr::new("bar.glsl") { + Ok(concat!( + // ' instead of " + "#preinclude 'foo.glsl\"\n", + "\n", + "out vec4 FragColor;" + ) + .as_bytes() + .to_vec()) + } else { + Ok(concat!( + "uniform sampler2D input_texture;\n", + "in vec2 in_texture_coords;" + ) + .as_bytes() + .to_vec()) + } + }, + ); + + let Err(PreprocessingError::InvalidToken { expected, found, span }) = res else { + panic!( + "Expected result to be Err(Error::InvalidToken {{ ... }}), is {res:?}" + ); + }; + + assert_eq!(expected, '"'); + assert_eq!(found, '\''); + assert_eq!(span.line, 1); + assert_eq!(span.column, 13); + assert_eq!(span.path, Path::new("bar.glsl")); + } +} diff --git a/engine/src/opengl/mod.rs b/engine/src/opengl/mod.rs index 0b1bb8a..53e0120 100644 --- a/engine/src/opengl/mod.rs +++ b/engine/src/opengl/mod.rs @@ -1,16 +1,17 @@ use bitflags::bitflags; +use gl::types::GLint; use crate::data_types::dimens::Dimens; use crate::vector::Vec2; pub mod buffer; +pub mod glsl; pub mod shader; pub mod texture; pub mod vertex_array; mod util; -#[cfg(feature = "debug")] pub mod debug; pub fn set_viewport(position: Vec2<u32>, size: Dimens<u32>) @@ -47,6 +48,17 @@ pub fn enable(capacity: Capability) } } +pub fn get_context_flags() -> ContextFlags +{ + let mut context_flags: GLint = 0; + + unsafe { + gl::GetIntegerv(gl::CONTEXT_FLAGS as u32, &mut context_flags); + } + + ContextFlags::from_bits_truncate(context_flags as u32) +} + bitflags! { #[derive(Debug, Clone, Copy)] pub struct BufferClearMask: u32 { @@ -105,3 +117,12 @@ impl From<crate::draw_flags::PolygonModeFace> for PolygonModeFace } } } + +bitflags! { +#[derive(Debug, Clone, Copy)] +pub struct ContextFlags: u32 { + const FORWARD_COMPATIBLE = gl::CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT; + const DEBUG = gl::CONTEXT_FLAG_DEBUG_BIT; + const ROBUST_ACCESS = gl::CONTEXT_FLAG_ROBUST_ACCESS_BIT; +} +} diff --git a/engine/src/opengl/shader.rs b/engine/src/opengl/shader.rs index 070897e..a626fc7 100644 --- a/engine/src/opengl/shader.rs +++ b/engine/src/opengl/shader.rs @@ -2,7 +2,6 @@ use std::ffi::CStr; use std::ptr::null_mut; use crate::matrix::Matrix; -use crate::shader::Kind; use crate::vector::Vec3; #[derive(Debug)] @@ -20,7 +19,7 @@ impl Shader Self { shader } } - pub fn set_source(&self, source: &str) -> Result<(), Error> + pub fn set_source(&mut self, source: &str) -> Result<(), Error> { if !source.is_ascii() { return Err(Error::SourceNotAscii); @@ -39,7 +38,7 @@ impl Shader Ok(()) } - pub fn compile(&self) -> Result<(), Error> + pub fn compile(&mut self) -> Result<(), Error> { unsafe { gl::CompileShader(self.shader); @@ -90,6 +89,14 @@ impl Drop for Shader } } +/// Shader kind. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Kind +{ + Vertex, + Fragment, +} + impl Kind { fn into_gl(self) -> gl::types::GLenum @@ -117,14 +124,14 @@ impl Program Self { program } } - pub fn attach(&self, shader: &Shader) + pub fn attach(&mut self, shader: &Shader) { unsafe { gl::AttachShader(self.program, shader.shader); } } - pub fn link(&self) -> Result<(), Error> + pub fn link(&mut self) -> Result<(), Error> { unsafe { gl::LinkProgram(self.program); @@ -152,82 +159,105 @@ impl Program } } - pub fn set_uniform_matrix_4fv(&mut self, name: &CStr, matrix: &Matrix<f32, 4, 4>) + pub fn set_uniform(&mut self, name: &CStr, var: &impl UniformVariable) { - let uniform_location = - unsafe { gl::GetUniformLocation(self.program, name.as_ptr().cast()) }; + let location = UniformLocation(unsafe { + gl::GetUniformLocation(self.program, name.as_ptr().cast()) + }); + + var.set(self, location); + } + + fn get_info_log(&self) -> String + { + let mut buf = vec![gl::types::GLchar::default(); 512]; unsafe { - gl::ProgramUniformMatrix4fv( + #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)] + gl::GetProgramInfoLog( self.program, - uniform_location, - 1, - gl::FALSE, - matrix.as_ptr(), + buf.len() as gl::types::GLsizei, + null_mut(), + buf.as_mut_ptr(), ); } + + let info_log = unsafe { CStr::from_ptr(buf.as_ptr()) }; + + unsafe { String::from_utf8_unchecked(info_log.to_bytes().to_vec()) } } +} - pub fn set_uniform_vec_3fv(&mut self, name: &CStr, vec: &Vec3<f32>) +impl Drop for Program +{ + fn drop(&mut self) { - let uniform_location = - unsafe { gl::GetUniformLocation(self.program, name.as_ptr().cast()) }; - unsafe { - gl::ProgramUniform3fv(self.program, uniform_location, 1, vec.as_ptr()); + gl::DeleteProgram(self.program); } } +} - pub fn set_uniform_1fv(&mut self, name: &CStr, num: f32) - { - let uniform_location = - unsafe { gl::GetUniformLocation(self.program, name.as_ptr().cast()) }; +pub trait UniformVariable +{ + fn set(&self, program: &mut Program, uniform_location: UniformLocation); +} +impl UniformVariable for f32 +{ + fn set(&self, program: &mut Program, uniform_location: UniformLocation) + { unsafe { - gl::ProgramUniform1fv(self.program, uniform_location, 1, &num); + gl::ProgramUniform1f(program.program, uniform_location.0, *self); } } +} - pub fn set_uniform_1i(&mut self, name: &CStr, num: i32) +impl UniformVariable for i32 +{ + fn set(&self, program: &mut Program, uniform_location: UniformLocation) { - let uniform_location = - unsafe { gl::GetUniformLocation(self.program, name.as_ptr().cast()) }; - unsafe { - gl::ProgramUniform1i(self.program, uniform_location, num); + gl::ProgramUniform1i(program.program, uniform_location.0, *self); } } +} - fn get_info_log(&self) -> String +impl UniformVariable for Vec3<f32> +{ + fn set(&self, program: &mut Program, uniform_location: UniformLocation) { - let mut buf = vec![gl::types::GLchar::default(); 512]; - unsafe { - #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)] - gl::GetProgramInfoLog( - self.program, - buf.len() as gl::types::GLsizei, - null_mut(), - buf.as_mut_ptr(), + gl::ProgramUniform3f( + program.program, + uniform_location.0, + self.x, + self.y, + self.z, ); } - - let info_log = unsafe { CStr::from_ptr(buf.as_ptr()) }; - - unsafe { String::from_utf8_unchecked(info_log.to_bytes().to_vec()) } } } -impl Drop for Program +impl UniformVariable for Matrix<f32, 4, 4> { - fn drop(&mut self) + fn set(&self, program: &mut Program, uniform_location: UniformLocation) { unsafe { - gl::DeleteProgram(self.program); + gl::ProgramUniformMatrix4fv( + program.program, + uniform_location.0, + 1, + gl::FALSE, + self.as_ptr(), + ); } } } +#[derive(Debug)] +pub struct UniformLocation(gl::types::GLint); + /// Shader error. #[derive(Debug, thiserror::Error)] pub enum Error diff --git a/engine/src/opengl/texture.rs b/engine/src/opengl/texture.rs index 074ade7..80a5f37 100644 --- a/engine/src/opengl/texture.rs +++ b/engine/src/opengl/texture.rs @@ -1,5 +1,4 @@ use crate::data_types::dimens::Dimens; -use crate::texture::{Id, Properties}; #[derive(Debug)] pub struct Texture @@ -20,10 +19,10 @@ impl Texture Self { texture } } - pub fn bind(&self) + pub fn bind_to_texture_unit(&self, texture_unit: u32) { unsafe { - gl::BindTexture(gl::TEXTURE_2D, self.texture); + gl::BindTextureUnit(texture_unit, self.texture); } } @@ -41,16 +40,9 @@ impl Texture } } - pub fn apply_properties(&mut self, properties: &Properties) - { - self.set_wrap(properties.wrap); - self.set_magnifying_filter(properties.magnifying_filter); - self.set_minifying_filter(properties.minifying_filter); - } - pub fn set_wrap(&mut self, wrapping: Wrapping) { - let wrapping_gl = wrapping.to_gl(); + let wrapping_gl = wrapping as gl::types::GLenum; #[allow(clippy::cast_possible_wrap)] unsafe { @@ -61,7 +53,7 @@ impl Texture pub fn set_magnifying_filter(&mut self, filtering: Filtering) { - let filtering_gl = filtering.to_gl(); + let filtering_gl = filtering as gl::types::GLenum; #[allow(clippy::cast_possible_wrap)] unsafe { @@ -75,7 +67,7 @@ impl Texture pub fn set_minifying_filter(&mut self, filtering: Filtering) { - let filtering_gl = filtering.to_gl(); + let filtering_gl = filtering as gl::types::GLenum; #[allow(clippy::cast_possible_wrap)] unsafe { @@ -132,43 +124,21 @@ impl Drop for Texture /// Texture wrapping. #[derive(Debug, Clone, Copy)] +#[repr(u32)] pub enum Wrapping { - Repeat, - MirroredRepeat, - ClampToEdge, - ClampToBorder, -} - -impl Wrapping -{ - fn to_gl(self) -> gl::types::GLenum - { - match self { - Self::Repeat => gl::REPEAT, - Self::MirroredRepeat => gl::MIRRORED_REPEAT, - Self::ClampToEdge => gl::CLAMP_TO_EDGE, - Self::ClampToBorder => gl::CLAMP_TO_BORDER, - } - } + Repeat = gl::REPEAT, + MirroredRepeat = gl::MIRRORED_REPEAT, + ClampToEdge = gl::CLAMP_TO_EDGE, + ClampToBorder = gl::CLAMP_TO_BORDER, } #[derive(Debug, Clone, Copy)] +#[repr(u32)] pub enum Filtering { - Nearest, - Linear, -} - -impl Filtering -{ - fn to_gl(self) -> gl::types::GLenum - { - match self { - Self::Linear => gl::LINEAR, - Self::Nearest => gl::NEAREST, - } - } + Nearest = gl::NEAREST, + Linear = gl::LINEAR, } /// Texture pixel data format. @@ -197,44 +167,3 @@ impl PixelDataFormat } } } - -pub fn set_active_texture_unit(texture_unit: TextureUnit) -{ - unsafe { - gl::ActiveTexture(texture_unit.into_gl()); - } -} - -macro_rules! texture_unit_enum { - (cnt=$cnt: literal) => { - seq_macro::seq!(N in 0..$cnt { - #[derive(Debug, Clone, Copy)] - pub enum TextureUnit { - #( - No~N, - )* - } - - impl TextureUnit { - fn into_gl(self) -> gl::types::GLenum { - match self { - #( - Self::No~N => gl::TEXTURE~N, - )* - } - } - - pub fn from_texture_id(texture_id: Id) -> Option<Self> { - match texture_id.into_inner() { - #( - N => Some(Self::No~N), - )* - _ => None - } - } - } - }); - }; -} - -texture_unit_enum!(cnt = 31); diff --git a/engine/src/opengl/vertex_array.rs b/engine/src/opengl/vertex_array.rs index da5d91e..1f8a870 100644 --- a/engine/src/opengl/vertex_array.rs +++ b/engine/src/opengl/vertex_array.rs @@ -1,10 +1,6 @@ use std::mem::size_of; use crate::opengl::buffer::Buffer; -use crate::vertex::Vertex; - -#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] -const VERTEX_STRIDE: i32 = size_of::<Vertex>() as i32; #[derive(Debug)] pub struct VertexArray @@ -59,10 +55,10 @@ impl VertexArray } } - pub fn bind_vertex_buffer( + pub fn bind_vertex_buffer<VertexT>( &mut self, binding_index: u32, - vertex_buffer: &Buffer<Vertex>, + vertex_buffer: &Buffer<VertexT>, offset: isize, ) { @@ -72,7 +68,7 @@ impl VertexArray binding_index, vertex_buffer.object(), offset, - VERTEX_STRIDE, + size_of::<VertexT>() as i32, ); } } @@ -125,27 +121,6 @@ impl VertexArray { unsafe { gl::BindVertexArray(self.array) } } - - /// Does a weak clone of this vertex array. The vertex array itself is NOT copied in - /// any way this function only copies the internal vertex array ID. - /// - /// # Safety - /// The returned `VertexArray` must not be dropped if another `VertexArray` - /// referencing the same vertex array ID is used later. - pub unsafe fn clone_unsafe(&self) -> Self - { - Self { array: self.array } - } -} - -impl Drop for VertexArray -{ - fn drop(&mut self) - { - unsafe { - gl::DeleteVertexArrays(1, &self.array); - } - } } #[derive(Debug)] |