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
use std::error;
use std::fmt::{self, Formatter, Display, Debug};
use gl::types::*;
use gl;

pub struct Error{
    gl_code: Option<GLenum>,
    description: Option<String>,
    cause: Option<Box<dyn error::Error + Send + Sync>>,
    kind: ErrorKind,
}

#[derive(Copy,Clone,Debug)]
pub enum ErrorKind{
    // Context
    ContextCreationError,

    // Buffer
    OutOfMemory,
    MapError,
    OutOfBounds,


    // Fbo
    SizeGreaterThanMaxSize, // On creation
    NoColorAttachments,
    MaxColorAttachments,

    FramebufferCreationError,


    // Program
    ProgramCreationError,
    CompileError,
    LinkError,
    UniformNotFound,

    // Texture
    ZeroWidth,
    ZeroHeight,
    ZeroDepth,
    WidthTooBig,
    HeightTooBig,
    DepthTooBig,
    // FormatNotSupported, // Can't figure out bytes per component from gl type
                           // Can't figure out components from gl format
                           // Can't figure format from internal
                           // Can't figure type from internal
    CorruptedImage,
    FormatSizeBiggerThanAllocated,
    FormatSizeBiggerThanData,
    FormatMandatoryOnCompressed, // Force on struct creation?

    // Cubemap
    FormatNotSupported,
    NotSquareImage, // FormatNotSupported?
    DifferentFormatsPerImage, // FormatNotSupported + additional description description
    DifferentDimensionsPerImage, // "

    // Vao
    VaoCreationError, // OutOfMemory?, according to docs only fails if n negative which we don't, remove check?
    AttributeNotFound,

    // Fence
    WaitFailed,
    NotReady,

}


impl Debug for Error{
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result{
        if let Some(gl_code) = self.gl_code{
            fmt.write_str(&format!("{{ kind: {:?}, gl_code: {}, description: {:?}, cause: {:?} }}", self.kind, error_to_string(gl_code), self.description, self.cause))
        }else{
            fmt.write_str(&format!("{{ kind: {:?}, description: {:?}, cause: {:?}  }}", self.kind, self.description, self.cause))
        }
    }
}

impl ErrorKind{
    pub fn as_str(self) -> &'static str{
        use ErrorKind::*;

        match self{
            FormatNotSupported => "Fromat not supported",

            // Context
            ContextCreationError => "Context creation error",

            // Buffer
            OutOfMemory => "Out of memory",
            MapError => "Buffer mapping error",
            OutOfBounds => "Out of bounds",


            // Fbo
            SizeGreaterThanMaxSize => "Size greater than maximum allowed size",
            NoColorAttachments => "No color attachments",
            MaxColorAttachments => "More than allowed maximum number of attachments",

            FramebufferCreationError => "Framebuffer creation error",


            // Program
            ProgramCreationError => "Program creation error",
            CompileError => "Compile error",
            LinkError => "Link error",
            UniformNotFound => "Uniform not found",

            // Texture
            ZeroWidth => "Zero width",  // Creation
            ZeroHeight => "Zero height",
            ZeroDepth => "Zero depth",  // Creation
            WidthTooBig => "Width greater than maximum allowed",
            HeightTooBig => "Height greater than maximum allowed",
            DepthTooBig => "Depth greater than maximum allowed",

            CorruptedImage => "Corrupted image",  // Load
            FormatSizeBiggerThanAllocated => "Format size is bigger than allocated",
            FormatSizeBiggerThanData => "Format size is bigger than passed data",
            FormatMandatoryOnCompressed => "Format has to be specified for compressed texture",

            // Cubemap
            NotSquareImage => "Image needs to have same width and height",
            DifferentFormatsPerImage => "All images need to have the same format",
            DifferentDimensionsPerImage => "All images need to have the same dimension",

            // Vao
            VaoCreationError => "Vao creation error",
            AttributeNotFound => "Attribute not found",

            // Fence
            WaitFailed => "Wait sync failed",
            NotReady => "Wait sync not ready yet",
        }
    }
}

impl Error{
    pub fn new<'a, S: Into<Option<&'a str>>>(kind: ErrorKind, desc: S) -> Error{
        Error{
            kind: kind,
            description: desc.into().map(|d| d.to_owned()),
            gl_code: None,
            cause: None,
        }
    }

    pub fn with_gl_code<'a, S: Into<Option<&'a str>>>(kind: ErrorKind, desc: S, gl_code: GLenum) -> Error{
        Error{
            kind: kind,
            description: desc.into().map(|d| d.to_owned()),
            gl_code: Some(gl_code),
            cause: None,
        }
    }

    pub fn with_cause<'a, E: error::Error + Send + Sync + 'static, S: Into<Option<&'a str>>>(kind: ErrorKind, desc: S, cause: E) -> Error{
        Error{
            kind: kind,
            description: desc.into().map(|d| d.to_owned()),
            gl_code: None,
            cause: Some(Box::new(cause) as Box<dyn error::Error + Send + Sync>)
        }
    }

    pub fn gl_code_description(&self) -> Option<&'static str>{
        self.gl_code.map(error_to_string)
    }

    pub fn kind(&self) -> ErrorKind{
        self.kind
    }
}


impl error::Error for Error{
    fn source(&self) -> Option<&(dyn error::Error + 'static)>{
        self.cause.as_ref().map(|e| &**e as &dyn error::Error)
    }
}

impl Display for Error{
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result{
        let msg = self.description.as_ref()
            .map(|d| d.as_ref())
            .unwrap_or(self.kind.as_str());
        fmt.write_str(msg)?;
        if let Some(gl_code) = self.gl_code {
            fmt.write_fmt(format_args!("\ngl_code: {}", gl_code))?;
        }
        if let Some(cause) = self.cause.as_ref(){
            fmt.write_str("\ncause: ")?;
            fmt.write_fmt(format_args!("{}", cause))?;
        }
        Ok(())
    }
}


impl From<ErrorKind> for Error{
    fn from(kind: ErrorKind) -> Error{
        Error::new(kind, "")
    }
}

#[cfg(all(not(feature = "gles"), not(feature="webgl")))]
pub fn error_to_string(err: GLenum) -> &'static str{
    match err{
        0 => "Ok",
        gl::INVALID_ENUM => "GL_INVALID_ENUM",
        gl::INVALID_VALUE => "GL_INVALID_VALUE",
        gl::INVALID_OPERATION => "GL_INVALID_OPERATION",
        gl::STACK_OVERFLOW => "GL_STACK_OVERFLOW",
        gl::STACK_UNDERFLOW => "GL_STACK_UNDERFLOW",
        gl::OUT_OF_MEMORY => "GL_OUT_OF_MEMORY",
        gl::FRAMEBUFFER_UNDEFINED => "GL_FRAMEBUFFER_UNDEFINED", // from gl::CheckFramebufferStatus, could be gl_code or cause?
        gl::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT",
        gl::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => "GL_FRAMEBUFFER_INCOMPLETE_MissingATTACHMENT",
        gl::FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER => "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER",
        gl::FRAMEBUFFER_INCOMPLETE_READ_BUFFER => "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER",
        gl::FRAMEBUFFER_UNSUPPORTED => "GL_FRAMEBUFFER_UNSUPPORTED",
        gl::FRAMEBUFFER_INCOMPLETE_MULTISAMPLE => "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE",
        gl::FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS => "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS",
        _ => "Unknown error",
    }
}

#[cfg(any(feature = "gles", feature="webgl"))]
pub fn error_to_string(err: GLenum) -> &'static str{
    match err{
        0 => "Ok",
        gl::INVALID_ENUM => "GL_INVALID_ENUM",
        gl::INVALID_VALUE => "GL_INVALID_VALUE",
        gl::INVALID_OPERATION => "GL_INVALID_OPERATION",
        gl::OUT_OF_MEMORY => "GL_OUT_OF_MEMORY",
        gl::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT",
        gl::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => "GL_FRAMEBUFFER_INCOMPLETE_MissingATTACHMENT",
        gl::FRAMEBUFFER_UNSUPPORTED => "GL_FRAMEBUFFER_UNSUPPORTED",
        _ => "Unknown error",
    }
}