Skip to content

Engine Core

Eddie S edited this page Sep 20, 2020 · 18 revisions

This page describes core OpenGL RAII wrapper classes that provide basic functionality.

Classes

  • ContextInitializer

  • ContextState

  • ContextEventObserver

  • Shader

  • ShaderCompiler

  • Buffer

  • VertexArray

  • Texture

  • Framebuffer

  • Uniform

  • ShaderProgram

  • ContextInitializer

    • Initializes GLFW&GLEW on first Context creation
    • Stores hardware GPU limitations (extension list, shader limits)
    • Terminates GLFW if there are no contexts anymore

    static void printExtensions() noexcept;

    Writes supported extensions to extensions.txt file.

    static bool isExtensionSupported(std::string_view name) noexcept;

    Checks if name extension is supported.

  • ContextState

    Holds every created context and its state to reduce number of state changes.

    static bool hasState(GLFWwindow* window) noexcept;

    static ContextState* getState(GLFWwindow* window) noexcept;

    Allows to get ContextState* dependent on current thread by using with glfwGetCurrentContext().

    void setViewPort(glm::uvec2 viewport_size) noexcept;

    Set the viewport.

    void clearColor(const glm::vec4& color) noexcept;

    Specify clear values for the color buffers.

    void clear(Clear bits) noexcept;

    Clear buffers to preset values.

    void disable(GLenum func) noexcept;

    void enable(GLenum func) noexcept;

    Enable or disable server-side GL capabilities.

    void setDepthFunc(DepthFunc func) noexcept;

    Specify the value used for depth buffer comparisons.

    void setDepthMask(GLboolean mask) noexcept;

    Enable or disable writing into the depth buffer.

    void setCullFace(CullFace mode) noexcept;

    Specify whether front- or back-facing facets can be culled.

    void setFrontFace(FrontFace mode) noexcept;

    Define front- and back-facing polygons.

    void setPolygonMode(FrontFace face, PolygonMode mode) noexcept;

    Select a polygon rasterization mode.

  • Context

    Creates a window and its associated context.

    Window hints:

    • Resizable - specifies whether the windowed mode window will be resizable by the user.
    • Visible - specifies whether the windowed mode window will be initially visible.
    • Decorated - specifies whether the windowed mode window will have window decorations.
    • Focused - specifies whether the windowed mode window will be given input focus when created.
    • AutoIconify - specifies whether the full screen window will automatically iconify and restore the previous video mode on input focus loss.
    • Maximized - specifies whether the windowed mode window will be maximized when created.
    • Samples - specifies the desired number of samples to use for multisampling.

    Context(std::string_view title, glm::uvec2 size, const WindowHints& hints = WindowHints{});

    Constructs window with specified window title, window size and hints described above.

    Context(std::string_view title, glm::uvec2 size, const Context& shared, const WindowHints& hints = WindowHints{});

    Constructs window with shared context resources. Used by threaded asset loader.

    void makeCurrent() const noexcept;

    Makes the context current for the current thread.

    void swapBuffers() const noexcept;

    Swaps the front and back buffers.

    void pollEvents() const noexcept;

    Processes event queue events.

    void setSwapInterval(GLuint interval) const noexcept;

    Sets the swap interval.

    void setWindowShouldClose(bool value) const noexcept;

    Sets the close flag of the specified window.

    void setWindowIcon(GLFWimage icon) const noexcept;

    Sets the icon for the specified window.

    void setCursorMode(CursorMode mode) const noexcept;

    Sets the cursor mode.

    void setCursor(GLFWimage cursor) const;

    Sets the cursor icon.

    void setWindowSize(glm::uvec2 size) noexcept;

    Resizes the window.

    void setAspectRatio(glm::uvec2 ratio) noexcept;

    Sets the aspect ratio.

    void setFullscreen(bool value) noexcept;

    Sets fullscreen.

    void setWindowPos(glm::uvec2 pos) const noexcept;

    Sets window position.

    bool shouldClose() const noexcept;

    Returns close flag of the window.

    void iconify() const noexcept;

    void restore() const noexcept;

    Iconifies/Restores the window.

    void hide() const noexcept;

    void show() const noexcept;

    Hides/Shows the window.

    void focus() const noexcept;

    Makes window focused.

    glm::uvec2 getSize() const noexcept;

    glm::vec2 getCursorPos() const noexcept;

    bool isFocused() const noexcept;

    Returns specified window parameters.

  • ContextEventObserver

    Creates a context with window event observers.

    Available event observers:

    • FramebufferObserver
    • MouseClickObserver
    • MouseMoveObserver
    • KeyObserver
    • ScrollObserver

    void registerObserver(Observer* obs);

    Registers the observer to window.

    void unregisterObserver(Observer* obs);

    Removes the observer from window observers.

    InputState getKey(int key) const noexcept;

    bool isPressed(int key) const noexcept;

    Allows to get InputState for specified key.

    MouseButton:

    • Left
    • Right
    • Middle

    InputState:

    • Released
    • Pressed
    • Repeat

    Modifier:

    • Shift
    • Control
    • Alt
    • Super
    • CapsLock
    • NumLock
  • Shader

    Class that manages GLSL code of specified shader type.

    Supports include directive in GLSL file. Usage: #include "filename" - includes text of filename file in shaders directory.

    Shader(fs::path path, Type type);

    Loads GLSL code at specified path and manipulates this. Throws shader_file_not_found exception if no such file exists. Replaces:

    • GraphicsEngine::GLSL_VERSION to version specified in ContextInitializer class.
    • GraphicsEngine::Extensions to supported and used extensions for rendering.
    • All include directives

    const auto& getId() const noexcept;

    Returns its shader id.

    void replaceKey(const std::string& key, const std::string& value) noexcept;

    Replaces all entries of key with value in shader code.

    void compile() const;

    Compiles shader. If there are any errors occured, throws shader_compilation_error exception and outputs log&sourcecode to _shader_compilation_error _file.

  • ShaderCompiler

    Compiles and links shader program from specified shaders.

    ShaderCompiler& operator<<(Shader&& shader) noexcept;

    Specifies shader that should be linked to program. Takes ownership of the shader.

    std::shared_ptr<ShaderProgram> compile();

    Attaches shaders and links program. Returns shared pointer to ShaderProgram. Throws shader_linking_error on linking errors.

    std::shared_ptr<ShaderProgram> compile(const fs::path& path, const ShaderAction& actions = ShaderAction{});

    Tries to build a whole shader program from specified path. Searches each shader type using file extensions described below:

    • ".vs" vertex shader
    • ".tcs" tesselation control shader
    • ".tes" tesselation evaluation shader
    • ".gs" geometry shader
    • ".fs" fragment shader
    • ".cs" compute shader

    In addition may execute required ShaderActions on each found shader. ShaderAction is std::function<void(Shader&)>.

  • Buffer

    OpenGL object that stores an array of unformatted memory allocated by context.

    General use: Buffer::Type

    • Array The buffer will be used as a source for vertex data.
    • Element The buffer will be used as a source for indexed rendering commands.
    • Uniform Indexed buffer. The Buffer Object will be used to store uniform data. Can be used to share uniforms between different programs, as well as quickly change between sets of uniforms for the same program object.
    • ShaderStorage Indexed buffer. A lot like Uniform buffer. Can be used to store and retrieve data. Requires GL_ARB_shader_storage_buffer_object extension.
    • AtomicCounter Indexed buffer. Storage for atomic counters. Requires ARB_shader_atomic_counters extension.
    • IndirectDraw The buffer will be used as the source for the indirect data when performing indirect rendering.
    • IndirectDispatch The buffer will be used as the source for indirect compute dispatch operations. Requires GL_ARB_compute_shader extension.

    Usage: Buffer::Usage for mutable buffer. Actually, this is just hints for server side used as coombination.

    Based on action:

    • Read
    • Draw
    • Copy

    Based on frequency:

    • Static
    • Dynamic
    • Stream

    Storage: Buffer::Storage for immutable buffer. Requires GL_ARB_buffer_storage extension. Specifies the intended usage of the buffer's data store.

    • Static No further data updates.
    • Dynamic The contents of the data store may be updated after creation.
    • Client A hint that the buffer object's data should be stored in client memory.
    • DynamicWrite The data store may be mapped for write access.
    • DynamicPersistenceWrite The pointer to the data store remains valid so long as the data store is mapped.
    • DynamicCoherentWrite Data written to the store by either the client or server will be immediately visible to the other one.

    Access for mutable buffer. Buffer::MutableAccess

    • None Access to data is not required.
    • Write Buffer will be possible to write to.
    • WriteOrphaning Buffer will be possible to write to by using orphaning method.
    • WriteUnsync Unsychronized access to write.

    Access for immutable buffer. Buffer::ImmutableAccess

    • None Access to data is not required.
    • WritePersistence Buffer may be used for persistence writes.
    • WriteCoherent Buffer may be used for coherent writes.

    There are three types of buffer that can be used:

    • StateBuffer Simple buffer that uses context state while performing buffer-commands. Requires no extensions.
    • NamedBuffer The Buffer uses DSA(Direct State Access) to perform buffer-commands, requires no state changes but GL_ARB_direct_state_access is needed.
    • TripleBuffer The buffer used for round-robin data store updates that allows to avoid sync object stalls.

    StateBuffer(Type target, size_t size, const void* data, Usage usage, MutableAccess access) noexcept;

    NamedBuffer(Type target, size_t size, const void* data, Usage usage, MutableAccess access) noexcept;

    Creates mutable buffer that stores data specified by _size _and data.

    StateBuffer(Type target, size_t size, const void* data, Storage usage, ImmutableAccess access);

    NamedBuffer(Type target, size_t size, const void* data, Storage usage, ImmutableAccess access);

    Creates immutable buffer that stores data specified by _size _and data.

    void bind() const noexcept;

    Binds the buffer to current thread context.

    void bindAs(Type target) const noexcept;

    Binds the buffer to current thread context using specified target as bind point.

    void bindBase(GLuint index) const noexcept;

    Binds the buffer to current thread context indexed binding point. Widly used by Indexed buffers.

    void bindBaseAs(Type target, GLuint index) const noexcept;

    Binds the buffer to current thread context indexed binding point using specified target.

    void bindBufferRange(GLuint index, GLintptr offset) const noexcept;

    void bindBufferRangeAs(Type target, GLuint index, GLintptr offset) const noexcept;

    As functions above, just binds only part of the buffer.

    void clearSubData(GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void* data) const noexcept;

    void clearData(GLenum internalformat, GLenum format, GLenum type, const void* data) const noexcept override;

    Clears the buffer data with fixed value.

    void bufferSubData(GLintptr offset, size_t sub_size, const void* data) const noexcept;

    Updates the buffer subset.

    void mapData(const void* data, size_t data_size);

    Updates the buffer using mapping pointer, avoids one copying.

    void fence() noexcept;

    Creates fence sync object if access is either WriteUnsync or Persistence/Coherent mapping. Indicates that previous commands are finished. Should be used with Unsync/Persistent/Coherent mapping to prevent unpredictable results.

    void waitFence() noexcept;

    Waits for sync object if it exists.

    GLuint getId() const noexcept;

    Type getType() const noexcept;

    size_t getSize() const noexcept;

    const std::variant<Usage, Storage>& getUsageFlags() const noexcept;

    const std::variant<MutableAccess, ImmutableAccess>& getAccess() const noexcept;

    Gets specified buffer parameters.

  • VertexArray

    Object that stores all of the state needed to supply vertex data.

    VertexAttribute

    Describes where an attribute gets its array data from and defines how to interpret that data.

    struct VertexAttribute {
        GLint size;
        GLenum type;
        GLboolean normalized;
        GLsizei stride;
        const GLvoid* pointer;
        Buffer& buffer;
    };
    
    • size; Specifies the number of components per vertex attribute. Must be 1, 2, 3, 4.
    • type; Specifies the data type of each component in the array.
    • normalized; Specifies whether fixed-point data values should be normalized or directly accessed.
    • stride; Specifies the byte offset between consecutive generic vertex attributes.
    • pointer; Specifies a offset of the first component of the first generic vertex attribute.
    • buffer; Specified the buffer where an attribute gets its data from.

    VertexArray& operator<<(const VertexAttribute& attribute) noexcept;

    Specifies attribute that should be at current index. Increases index by one. Default value is zero.

    VertexArray& operator<<(const Buffer& element_buffer) noexcept;

    Specifies Element Buffer that will be used as source for indexed drawing.

    void bind() const noexcept;

    Binds vertex array to current thread context.

    void enableAttribute(GLuint index) const noexcept;

    void disableAttribute(GLuint index) const noexcept;

    Enables or disables attribute at specified index.

    GLuint getId() const noexcept;

    Gets vertex array id.

  • Texture

    Object that contains one or more images that all have the same image format.

    Type

    There are a number of different types:

    • Tex2D
    • Tex3D
    • CubeMap
    • Tex2DArray
    • TexCubeMapArray
    • Tex2DMS

    InternalFormat

    • Depth
    • Depth16/32/32F
    • R/G/B
    • RGB8/16/16F/32/32F

    Format

    • DepthComponent
    • StencilIndex
    • DepthStencil
    • Red/Green/Blue
    • RG/RGB/RGBA

    DataType

    • Unsigned Byte
    • Byte
    • Unsigned short
    • Short
    • Unsigned int
    • Int
    • Float

    There are three types of texture

    • StateTexture

    StateTexture uses context state for functionality.

    • NamedTexture

    NamedTexture uses DSA(Direct State Access) for functionality. Requires GL_ARB_direct_state_access.

    • BindlessTexture

    BindlessTexture does not use context state for functionality. Requires GL_ARB_bindless_texture.

    Mutable texture creation

    StateTexture(Type target, InternalFormat internal, glm::uvec2 size, Format format, DataType data_type, const void* data);

    NamedTexture(Type target, InternalFormat internal, glm::uvec2 size, Format format, DataType data_type, const void* data);

    Creates 2D texture with specified parameters.

    StateTexture(Type target, InternalFormat internal, glm::uvec3 size, Format format, DataType data_type, const void* data);

    NamedTexture(Type target, InternalFormat internal, glm::uvec3 size, Format format, DataType data_type, const void* data);

    Creates 3D texture / 2D texture array / empty cubemap array

    StateTexture(Type target, InternalFormat internal, glm::uvec2 size, Format format, DataType data_type, const std::array<void*, 6>& data);

    NamedTexture(Type target, InternalFormat internal, glm::uvec2 size, Format format, DataType data_type, const std::array<void*, 6>& data);

    Creates cubemap texture.

    Immutable texture creation

    StateTexture(Type target, GLsizei levels, InternalFormat internal, glm::uvec2 size, Format format, DataType data_type, const void* data);

    NamedTexture(Type target, GLsizei levels, InternalFormat internal, glm::uvec2 size, Format format, DataType data_type, const void* data);

    Creates immutable 2D texture with specified number of mipmap levels.

    StateTexture(Type target, GLsizei levels, InternalFormat internal, glm::uvec3 size, Format format, DataType data_type, const void* data);

    NamedTexture(Type target, GLsizei levels, InternalFormat internal, glm::uvec3 size, Format format, DataType data_type, const void* data);

    Creates immutable 3D texture / 2D texture array / empty cubemap array with specified number of mipmap levels.

    StateTexture(Type target, GLsizei levels, InternalFormat internal, glm::uvec2 size, Format format, DataType data_type, const std::array<void*, 6>& data);

    NamedTexture(Type target, GLsizei levels, InternalFormat internal, glm::uvec2 size, Format format, DataType data_type, const std::array<void*, 6>& data);

    Creates immutable cubemap texture with specified number of mipmap levels.

    NamedTexture(Type target, uint8_t samples, InternalFormat internal, glm::uvec2 size, bool immutable = false);

    Creates multisampled 2D texture.

    void bind(GLuint index) const noexcept;

    Binds the texture to index texture unit.

    void resize(glm::uvec3 size) override;

    Resizes the texture.

    void generateMipMap() const noexcept;

    Generates mipmap levels for mutable texture.

    StateTexture& operator<<(const TexParameter<GLint>& param) noexcept;

    StateTexture& operator<<(const TexParameter<GLfloat>& param) noexcept;

    StateTexture& operator<<(const TexParameter<GLint*>& param) noexcept;

    StateTexture& operator<<(const TexParameter<GLfloat*>& param) noexcept;

    Sets the specified texture parameters.

    GLuint getId() const noexcept override;

    Type getType() const noexcept override;

    glm::uvec3 getSize() const noexcept override;

    Gets texture parameters.`

  • Framebuffer

    Framebuffer is a render target that contains images for render operations.

    FramebufferAttachment

    • Depth
    • Stencil
    • DepthStencil
    • Color0-7

    Specifies location that texture can be attached to.

    TextureAttachment

    Contains FramebufferAttachment, texture itself and optional layer-level.

    Framebuffer() noexcept;

    Creates empty framebuffer.

    Framebuffer(ContextEventObserver &context) noexcept;

    Creates empty framebuffer that automatically resizes contained texture attachments on resize callback.

    Framebuffer& operator<<(const TextureAttachment &attachment) noexcept;

    Adds texture attachment to the framebuffer.

    void checkStatus();

    Checks status of the framebuffer. If there are any errors, throws incomplete_framebuffer exception.

    void clear() noexcept;

    Clears the framebuffer.

    void bind() noexcept;

    void unbind() noexcept;

    Binds/Unbinds the framebuffer.

    void drawBuffers(const std::vector<FramebufferAttachment>& a) noexcept;

    void drawBuffer(FramebufferAttachment a) noexcept;

    Specifies buffers where the framebuffer draws to.

    const TextureAttachment& get(FramebufferAttachment attachment) const;

    Gets specified texture attachment.

    void specifyLayer(FramebufferAttachment attachment, uint32_t layer);

    Specifies texture attachment layer where the framebuffer draws to.

    static void bindDefault() noexcept;

    Binds default framebuffer.

  • Uniform

    Uniforms is a shader variables contained in shader program.

    const auto& getType() const noexcept;

    Gets UniformType. Can be Value or Sampler.

    const auto& getValueType() const noexcept;

    Gets UniformValueType contained by uniform.

    UniformValue

    UniformValue is a template class that contains value.

    UniformValue(std::string name, const T& value) noexcept;

    Creates UniformValue with shader name and value.

    const auto& getValue() const noexcept;

    void setValue(const T& val) noexcept;

    Getter/Setter for contained value.

    UniformSampler

    UniformSampler is a shader uniform that containes texture as well as its bound texture unit.

    UniformSampler(std::string name, std::shared_ptr<Texture> sampler) noexcept;

    Creates uniform sampler with name and texture.

    const auto& getSampler() const noexcept;

    void setSampler(const std::shared_ptr<Texture>& texture) noexcept;

    Getter/Setter for sampler.

Clone this wiki locally