1use std::fmt::Display;
2use std::convert::TryFrom;
3use web_sys::{
4 WebGlRenderingContext as Context,
5};
6use super::gl::GlError;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum DataType {
10 Boolean,
11 Float,
12 Vec2,
13 Vec3,
14 Vec4,
15 Mat2,
16 Mat3,
17 Mat4,
18 Sampler,
19}
20
21impl DataType {
22 pub(crate) fn size_in_floats(self) -> Option<usize> {
23 match self {
24 DataType::Boolean => None,
25 DataType::Float => Some(1),
26 DataType::Vec2 => Some(2),
27 DataType::Vec3 => Some(3),
28 DataType::Vec4 => Some(4),
29 DataType::Mat2 => Some(4),
30 DataType::Mat3 => Some(9),
31 DataType::Mat4 => Some(16),
32 DataType::Sampler => None,
33 }
34 }
35}
36
37impl From<DataType> for &str {
38 fn from(value: DataType) -> &'static str {
39 match value {
40 DataType::Boolean => "bool",
41 DataType::Float => "float",
42 DataType::Vec2 => "vec2",
43 DataType::Vec3 => "vec3",
44 DataType::Vec4 => "vec4",
45 DataType::Mat2 => "mat2",
46 DataType::Mat3 => "mat3",
47 DataType::Mat4 => "mat4",
48 DataType::Sampler => "sampler2D",
49 }
50 }
51}
52
53impl Display for DataType {
54 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
55 formatter.write_str((*self).into())
56 }
57}
58
59impl DataType {
60 pub fn is_numeric(self) -> bool {
61 self != DataType::Boolean && self != DataType::Sampler
62 }
63 pub fn is_vector(self) -> bool {
64 self == DataType::Vec2 || self == DataType::Vec3 || self == DataType::Vec4
65 }
66 pub fn is_matrix(self) -> bool {
67 self == DataType::Mat2 || self == DataType::Mat3 || self == DataType::Mat4
68 }
69}
70
71impl TryFrom<u32> for DataType {
72 type Error = GlError;
73 fn try_from(value: u32) -> Result<DataType, GlError> {
74 match value {
75 Context::BOOL => Ok(DataType::Boolean),
76 Context::FLOAT => Ok(DataType::Float),
77 Context::FLOAT_VEC2 => Ok(DataType::Vec2),
78 Context::FLOAT_VEC3 => Ok(DataType::Vec3),
79 Context::FLOAT_VEC4 => Ok(DataType::Vec4),
80 Context::FLOAT_MAT2 => Ok(DataType::Mat2),
81 Context::FLOAT_MAT3 => Ok(DataType::Mat3),
82 Context::FLOAT_MAT4 => Ok(DataType::Mat4),
83 Context::SAMPLER_2D => Ok(DataType::Sampler),
84 _ => Err(GlError::UnsupportedType(None))
85 }
86 }
87}
88
89impl From<DataType> for u32 {
90 fn from(data_type: DataType) -> Self {
91 match data_type {
92 DataType::Boolean => Context::BOOL,
93 DataType::Float => Context::FLOAT,
94 DataType::Vec2 => Context::FLOAT_VEC2,
95 DataType::Vec3 => Context::FLOAT_VEC3,
96 DataType::Vec4 => Context::FLOAT_VEC4,
97 DataType::Mat2 => Context::FLOAT_MAT2,
98 DataType::Mat3 => Context::FLOAT_MAT3,
99 DataType::Mat4 => Context::FLOAT_MAT4,
100 DataType::Sampler => Context::SAMPLER_2D,
101 }
102 }
103}
104
105pub trait TypeMark {
106 fn data_type() -> DataType;
107}