Compare commits

...

8 Commits

Author SHA1 Message Date
NaifBanana
36945a8a9d Huge graphics overhaul 2026-07-18 16:38:24 -05:00
NaifBanana
73fa5efc47 Forgot to actually compile the shader :P 2026-07-18 16:38:24 -05:00
NaifBanana
e838d789e8 Change invalid buffer binding to warning instead of error 2026-07-18 16:38:24 -05:00
NaifBanana
616611a290 Added vertex buffers/data handling and shader/program handling 2026-07-18 16:38:24 -05:00
NaifBanana
6ac965ec0e Mild updates to Window and other pieces to match the rest 2026-07-18 16:38:24 -05:00
NaifBanana
596fbb64ee Make VertexAttributePointer store index instead of buffer pointer 2026-07-18 16:38:23 -05:00
NaifBanana
31f5b47df9 Made buildable now 2026-07-18 16:38:23 -05:00
NaifBanana
8187f01add Large OpenGL Object handling overhaul 2026-07-18 16:38:23 -05:00
28 changed files with 2392 additions and 1612 deletions

View File

@ -5,361 +5,213 @@
#include "GLLoad.hpp" #include "GLLoad.hpp"
#include <string> #include <string>
#include <vector>
#include <NBCore/Errors.hpp> #include <NBCore/Errors.hpp>
#include <NBCore/Types.hpp> #include <NBCore/Logger.hpp>
#include <NBCore/Utils.hpp>
#include "OGLObjects.hpp"
namespace nb { namespace nb {
typedef std::vector<unsigned char> RawVec; extern const std::unordered_map<GLenum, std::string> BufferTypes;
static uint8_t GLSLTypeSize(GLenum type) {
switch(type) {
case GL_SHORT:
case GL_UNSIGNED_SHORT:
case GL_HALF_FLOAT:
return 2;
break;
case GL_INT:
case GL_UNSIGNED_INT:
case GL_FLOAT:
return 4;
break;
case GL_DOUBLE:
return 8;
break;
default:
return 1;
break;
}
}
struct VertexAttributePointer {
GLuint buffer = 0;
int32_t offset = 0;
GLsizei stride = -1;
GLuint divisor = 0;
};
struct VertexAttribute {
GLint GLSLSize;
GLenum GLSLType;
GLboolean GLSLNormalization;
VertexAttributePointer ptr;
};
static bool isIndexInVertexAttribute(int i, const VertexAttribute& va) {
if ((i -= va.ptr.offset) < 0) { return false; }
return (i%va.ptr.stride) < GLSLTypeSize(va.GLSLType) * va.GLSLSize;
}
typedef std::vector<VertexAttribute> VertexAttributeList;
template<GLenum N>
struct GLSLEnum;
template<typename T> template<typename T>
RawVec vectorToRaw(const std::vector<T>& vec) { struct GLSLType;
unsigned int num_bytes = vec.size() * sizeof(T);
RawVec ret(num_bytes);
memcpy(ret.data(), vec.data(), num_bytes);
return ret;
}
template<typename T, typename S> #define GLSLTypeTraits(type_, size_, value_) \
RawVec concatVectorsToRaw(const std::vector<T>& vec1, const std::vector<S>& vec2) { template<>\
RawVec vec1_raw = vectorToRaw<T>(vec1); struct GLSLEnum<value_> {\
RawVec vec2_raw = vectorToRaw<S>(vec2); using type = type_;\
unsigned int vec1_raw_size = vec1_raw.size(); static constexpr size_t size = size_;\
unsigned int vec2_raw_size = vec2_raw.size(); static constexpr GLenum value=value_;\
RawVec ret(vec1_raw_size + vec2_raw_size); };\
memcpy(ret.data(), vec1_raw.data(), vec1_raw_size); template<>\
memcpy(ret.data() + vec1_raw_size, vec2_raw.data(), vec2_raw_size); struct GLSLType<type_> {\
return ret; using type = type_;\
} static constexpr size_t size = size_;\
static constexpr GLenum value=value_;\
template<typename T>
std::vector<T> rawToVector(const RawVec& vec) {
if (vec.size() % sizeof(T) != 0) {
throw std::runtime_error("Data size does not align to std::vector<" + std::string(typeid(T).name()) + ">.");
}
unsigned int num_elmts = vec.size() / sizeof(T);
std::vector<T> ret(num_elmts);
memcpy(ret.data(), vec.data(), vec.size());
return ret;
}
class BufferError : public std::runtime_error {
public:
const bool error;
BufferError(const std::string& msg, const std::string& file="", int line=-1)
: std::runtime_error(NB::formatDebugString(msg, file, line)), error(true) {}
BufferError(bool isError=true) : std::runtime_error(""), error(isError) {}
}; };
#define GLSLTypeEquivalence(original, newtype) \
template<>\
struct GLSLType<newtype> : public GLSLType<original> {};
template <typename ObjectType> GLSLTypeTraits(uint8_t, 1, GL_UNSIGNED_BYTE);
class OpenGLObject { GLSLTypeTraits(uint16_t, 2, GL_UNSIGNED_SHORT);
public: GLSLTypeTraits(uint32_t, 4, GL_UNSIGNED_INT);
OpenGLObject(OpenGLObject&&) = default; GLSLTypeTraits(int8_t, 1, GL_BYTE);
OpenGLObject& operator=(OpenGLObject&&) = default; GLSLTypeTraits(int16_t, 2, GL_SHORT);
~OpenGLObject() { remove(); } GLSLTypeTraits(int32_t, 4, GL_INT);
GLSLTypeTraits(float, 4, GL_FLOAT);
virtual void bind() const = 0; GLSLTypeTraits(double, 8, GL_DOUBLE);
virtual void unbind() const = 0;
virtual bool isInitialized() const = 0;
GLuint id() const { return _id; }
class BufferError : public Error<BufferError> {
protected: protected:
OpenGLObject() = default; using Base = Error<BufferError>;
OpenGLObject(const OpenGLObject&) = delete;
OpenGLObject& operator=(const OpenGLObject&) = delete;
virtual void remove() const = 0;
GLuint _id;
};
class VAO : public virtual OpenGLObject<VAO> {
public: public:
using Base = OpenGLObject<VAO>;
using Base::Base; using Base::Base;
enum Codes : unsigned int {
VAO() { glGenVertexArrays(1, &_id); } UNDEFINED,
DATA_OVERFLOW,
void bind() const { glBindVertexArray(_id); } DATA_ERROR
void unbind() const { glBindVertexArray(0); } };
static const std::string type;
static const ErrorCodeMap ErrorMessages;
protected:
using Base::_id;
const
void remove() { glDeleteVertexArrays(1, &_id); }
}; };
template <typename BufferType>
class Buffer : public virtual OpenGLObject<Buffer<BufferType>> {
public:
using Base = OpenGLObject<Buffer>;
using Base::Base;
Buffer(GLenum usage_ = GL_STATIC_DRAW) : usage(usage_) { glGenBuffers(1, &_id); }
void bind() const { glBindBuffer(GLTarget, _id); }
void unbind() const { glBindBuffer(GLTarget, 0); }
void data(void* data_, size_t size) const { glBufferData(GLTarget, size, data_, usage); }
void data(nb::ByteVector& data_) const { glBufferData(GLTarget, data_.size(), data_.data(), usage); }
void invalidate() const { glInvalidateBufferData(_id); }
const GLenum GLTarget = BufferType::GLTarget;
GLenum usage;
protected:
using Base::_id;
void remove() { glDeleteBuffers(1, &_id); }
};
class VertexBuffer : public virtual Buffer<VertexBuffer> {
public:
static const GLenum GLTarget = GL_ARRAY_BUFFER;
protected:
};
class ElementBuffer : public virtual Buffer<ElementBuffer> {
public:
static const GLenum GLTarget = GL_ELEMENT_ARRAY_BUFFER;
protected:
};
/*
class Buffer : public OpenGLObject { class Buffer : public OpenGLObject {
public: protected:
Buffer( using Codes = BufferError::Codes;
GLenum buffer_type, using OpenGLObject::_id;
GLenum usage=GL_STATIC_DRAW GLenum _usage = GL_STATIC_DRAW;
) : _type(buffer_type), _usage(usage) { size_t _size;
Buffer(GLenum target) : Target(target) {}
virtual GLuint declare() override {
if (!_id) {
glGenBuffers(1, &_id); glGenBuffers(1, &_id);
} }
Buffer(
const RawVec& init_data,
GLenum buffer_type,
GLenum usage=GL_STATIC_DRAW
) : _type{buffer_type}, _usage{usage} { data(init_data); }
Buffer(
unsigned int size,
GLenum buffer_type,
GLenum usage=GL_STATIC_DRAW
) : Buffer(RawVec(size), buffer_type, usage) {}
Buffer(Buffer&& rhs) { *this = std::move(rhs); }
Buffer& operator=(Buffer&& rhs) {
remove();
_usage = rhs._usage;
_id = rhs._id;
rhs._id = 0;
return *this;
}
GLenum usage() const { return _usage; }
unsigned int id() const { return _id; }
GLuint size() const { return _size; }
bool isInitialized() const override { return _id && glIsBuffer(_id) && bool(_size); }
RawVec data() const {
RawVec ret(_size);
bind(); bind();
glGetBufferSubData(_type, 0, _size, ret.data()); return _id;
return ret;
} }
void bind() const override { glBindBuffer(_type, _id); } virtual void remove() override {
void unbind() const override { glBindBuffer(_type, 0); } if (_id) {
GLenum usage(GLenum usage) {
_usage=usage;
data(data());
return _usage;
}
void data(const RawVec& set_data) {
if (!glfwGetCurrentContext()) {
THROW_BUFFER_ERROR("No OpenGL context.");
}
bind();
glBufferData(_type, set_data.size(), set_data.data(), _usage);
_size = set_data.size();
}
void data(const RawVec& newData, unsigned int offset) {
if (newData.size()+offset > _size) {
THROW_BUFFER_ERROR("Attempting to overflow buffer of capacity " + std::to_string(_size) + ".");
}
bind();
glBufferSubData(_type, offset, newData.size(), newData.data());
}
void data(void* src, unsigned int offset, unsigned int size) {
if (size+offset > _size) {
THROW_BUFFER_ERROR("Attempting to overflow buffer of capacity " + std::to_string(_size) + ".");
}
bind();
glBufferSubData(_type, offset, size, src);
}
protected:
virtual void remove() const override {
unbind(); unbind();
if (_id) { glDeleteBuffers(1, &_id); } glDeleteBuffers(1, &_id);
_id = 0;
}
} }
using OpenGLObject::_id; public:
GLenum _type; const GLenum Target;
GLenum _usage; using OpenGLObject::OpenGLObject;
unsigned int _size = 0; Buffer(Buffer&& other);
Buffer& operator=(Buffer&& rhs);
virtual void bind() const override {
if (_id) {
glBindBuffer(Target, _id);
} else {
THROW(OGLError(
OGLError::Codes::INVALID_OBJECT,
"w/ BufferType " + BufferTypes.at(Target)
));
}
}
virtual void unbind() const override { glBindBuffer(Target, 0); }
GLenum usage() const;
size_t size() const;
ByteVector data() const;
void data(const ByteVector& data, GLenum usage=GL_STATIC_DRAW);
void data(const void* data, size_t size, GLenum usage=GL_STATIC_DRAW);
void subdata(const void* data, size_t size, GLintptr offset=0);
void subdata(const ByteVector& data_, GLintptr offset=0);
// virtual void clear() const { glClearBufferData(Target, ) }
}; };
/* template <typename BufferType>
class Texture : public OpenGLObject { class ImmutableBuffer : public virtual Buffer {
public: public:
Texture(GLenum tar=GL_TEXTURE_2D) : _target(tar) { glGenTextures(1, &_id); } ImmutableBuffer() = default;
ImmutableBuffer(
Texture(Texture&& rhs) { *this=std::move(rhs); } size_t size_,
Texture& operator=(Texture&& rhs) { GLenum usage_ = GL_STATIC_DRAW,
_target = rhs._target; GLbitfield flags_=0x0
_id = rhs._id; ) : size(size_), Base::usage(usage_) {
rhs._id = 0; glBufferStorage(Target, size, nullptr, flags_);
return *this;
} }
void bind() const override { glBindTexture(_target, _id); } std::weak_ptr<void> map(GLbitfield access_) {
void unbind() const override { glBindTexture(_target, 0); } if (_map && _mapAccess != access_) { unmap(); }
bool isInitialized() const override { return _id && glIsTexture(_id); } _mapAccess = access_;
if (!_map) {
protected:
using OpenGLObject::_id;
GLenum _target;
};
class Framebuffer : public OpenGLObject {
public:
Framebuffer(GLenum tar=GL_FRAMEBUFFER) : _target(tar) { glGenFramebuffers(1, &_id); }
Framebuffer(Framebuffer&& rhs) { *this=std::move(rhs); }
Framebuffer& operator=(Framebuffer&& rhs) {
remove();
_target = rhs._target;
_id = rhs._id;
rhs._id = 0;
return *this;
}
void bind() const override { glBindFramebuffer(_target, _id); }
void unbind() const override { glBindFramebuffer(_target, 0); }
bool isInitialized() const override { return _id && glIsFramebuffer(_id); }
GLenum status() const {
bind(); bind();
return glCheckFramebufferStatus(_target); glMapBuffer(Target, _mapAccess);
} }
return _map;
protected:
virtual void remove() const override {
unbind();
if (_id) { glDeleteFramebuffers(1, &_id); }
} }
using OpenGLObject::_id; void unmap() {
GLenum _target;
};
class Renderbuffer : public OpenGLObject {
public:
Renderbuffer(unsigned int x, unsigned int y, GLenum format=GL_RGBA32F, unsigned int multi=0) : Renderbuffer() {
storage(x, y, format, multi);
}
Renderbuffer() { glGenRenderbuffers(1, &_id); }
Renderbuffer(Renderbuffer&& rhs) { *this = std::move(rhs); }
Renderbuffer& operator=(Renderbuffer&& rhs) {
_format = rhs._format;
_id = rhs._id;
rhs._id = 0;
return *this;
}
virtual void bind() const override { glBindRenderbuffer(GL_RENDERBUFFER, _id); }
virtual void unbind() const override { glBindRenderbuffer(GL_RENDERBUFFER, _id); }
virtual bool isInitialized() const override { return _id && glIsRenderbuffer(_id); }
void storage(unsigned int x, unsigned int y, GLenum format=GL_RGBA32F, unsigned int multi=0) {
_sizex = x;
_sizey = y;
_format = format;
_multisample = multi;
bind(); bind();
glRenderbufferStorageMultisample(GL_RENDERBUFFER, _multisample, _format, _sizex, _sizey); glUnmapBuffer(Target);
_map.reset();
} }
const size_t size;
protected: protected:
virtual void remove() const override { std::shared_ptr<void> _map = nullptr;
unbind(); GLbitfield _mapAccess = 0;
if (_id) { glDeleteRenderbuffers(1, &_id); }
}; */
class ArrayBuffer : public Buffer {
public:
template<typename T>
ArrayBuffer(const std::vector<T>& data, GLenum usage=GL_STATIC_DRAW)
: Buffer(GL_ARRAY_BUFFER) {
Buffer::data(vectorToBytes(data), usage);
} }
using OpenGLObject::_id;
GLenum _format;
unsigned int _sizex{0};
unsigned int _sizey{0};
unsigned int _multisample{0};
}; };
*/ class ElementBuffer : protected Buffer {
protected:
GLenum _glslType;
size_t _typeSize;
public:
using Buffer::Target;
using Buffer::bind;
using Buffer::usage;
using Buffer::unbind;
ElementBuffer();
template<typename T>
ElementBuffer(const T* const data_ptr, size_t size, GLenum usage=GL_STATIC_DRAW)
: Buffer(GL_ELEMENT_ARRAY_BUFFER) {
data(data_ptr, size, usage);
}
template<typename T>
ElementBuffer(const std::vector<T>& data_, GLenum usage_=GL_STATIC_DRAW)
: ElementBuffer(data_.data(), data_.size(), usage_) {}
size_t size() const;
size_t typeSize() const;
ByteVector data() const;
GLenum glslType() const;
template<typename T>
void data(const T* data_, size_t size_, GLenum usage_=GL_STATIC_DRAW) {
declare();
using TypeInfo = GLSLType<T>;
_typeSize = TypeInfo::size;
Buffer::data(data_, size_*_typeSize, usage_);
_glslType = TypeInfo::value;
}
template<typename T>
void data(const std::vector<T>& data_, GLenum usage_=GL_STATIC_DRAW) {
data(data_.data(), data_.size(), usage_);
}
template<typename T>
void subdata(const T* data, size_t size, size_t offset) {
using TypeInfo = GLSLType<T>;
if ( _glslType != TypeInfo::value ) {
THROW( BufferError(
Codes::DATA_ERROR,
"Check element buffer data types"
) );
}
Buffer::subdata(data, size*_typeSize, offset);
}
template<typename T>
void subdata(const std::vector<T>& data, size_t offset=0) {
subdata(data.data(), data.size(), offset);
}
};
} // namespace NB } // namespace NB
#endif // _NB_BUFFER #endif // _NB_BUFFER

View File

@ -1,26 +1,38 @@
include_directories(./.)
find_package(OpenGL) find_package(OpenGL)
add_subdirectory(${GLFW_PATH} ${GLFW_PATH}/build) add_subdirectory(${GLFW_PATH} ${GLFW_PATH}/build)
include_directories(${GLFW_PATH}/include ${GLAD_PATH}/include) include_directories(
${GLFW_PATH}/include
${GLAD_PATH}/include
${STBIMAGE_PATH}
)
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
toAbsolutePath(NB_GRAPHICS_SOURCE toAbsolutePath(NB_GRAPHICS_SOURCE
./src/Window.cpp
./src/Buffers.cpp ./src/Buffers.cpp
./src/FrameBuffers.cpp
./src/Image.cpp
./src/OGLObjects.cpp
./src/ProgramPipeline.cpp
./src/Textures.cpp
./src/VertexArray.cpp
./src/Window.cpp
) )
toAbsolutePath(NB_GRAPHICS_INCLUDE toAbsolutePath(NB_GRAPHICS_INCLUDE
./Buffers.hpp ./Buffers.hpp
./Camera.hpp ./Camera.hpp
./Draw.hpp ./Draw.hpp
./FrameBuffers.hpp
./GLLoad.hpp ./GLLoad.hpp
./shader.hpp ./Image.hpp
./VAOManager.hpp ./OGLObjects.hpp
./ProgramPipeline.hpp
./Textures.hpp
./VertexArray.hpp
./Window.hpp ./Window.hpp
) )
@ -31,4 +43,11 @@ add_library(NBGraphics
${NB_GRAPHICS_SOURCE} ${NB_GRAPHICS_SOURCE}
${GLAD_PATH}/src/glad.c ${GLAD_PATH}/src/glad.c
) )
target_link_libraries(NBGraphics glfw3) target_link_libraries(NBGraphics glfw)
target_include_directories(NBGraphics PUBLIC ./.)
if (NB_BUILD_TESTS)
add_subdirectory(./tests)
endif()

View File

@ -2,13 +2,14 @@
#ifndef _NB_CAMERA #ifndef _NB_CAMERA
#define _NB_CAMERA #define _NB_CAMERA
#include <GLLoad.h> #include "GLLoad.hpp"
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <glm/gtc/matrix_inverse.hpp> #include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp> #include <glm/gtc/type_ptr.hpp>
namespace NB { namespace nb {
class Camera { class Camera {
public: public:

View File

@ -0,0 +1,236 @@
#pragma once
#ifndef _NB_FRAMEBUFFER
#define _NB_FRAMEBUFFER
#include "GLLoad.hpp"
#include <NBCore/Errors.hpp>
#include "Image.hpp"
#include "OGLObjects.hpp"
#include "Textures.hpp"
namespace nb {
class FrameBufferError : public Error<FrameBufferError> {
protected:
using Base = Error<FrameBufferError>;
public:
using Base::Base;
enum Codes : unsigned int {
UNDEFINED, INVALID_VALUE
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
};
class RenderBuffer : public RenderTarget {
protected:
GLuint declare() override {
if (!_id) {
glRenderbufferStorage(
GL_RENDERBUFFER,
format,
width,
height
);
}
return _id;
}
void remove() override {
if (_id) {
unbind();
glDeleteRenderbuffers(1, &_id);
_id = 0;
}
}
public:
const unsigned int width;
const unsigned int height;
const GLenum format;
template<typename PixelType>
RenderBuffer(unsigned int width_, unsigned int height_) :
width(width_),
height(height_),
format(OGLPixelFormat<PixelType>::glFormat),
RenderTarget(GL_RENDERBUFFER)
{ declare(); }
RenderBuffer(RenderBuffer&& rhs) :
width(rhs.width),
height(rhs.height),
format(rhs.format),
RenderTarget(std::move(rhs))
{}
RenderBuffer& operator=(RenderBuffer&&) = delete;
void bind() const override {
if (_id) {
glBindRenderbuffer(GL_RENDERBUFFER, _id);
} else {
THROW(OGLError(
OGLError::Codes::INVALID_OBJECT,
"w/ RenderBuffer"
));
}
}
void unbind() const override {
glBindRenderbuffer(GL_RENDERBUFFER, 0);
}
};
class FrameBufferBase : public OpenGLObject {
private:
static bool texTypeIs2D(GLenum texType) {
switch(texType) {
case GL_TEXTURE_2D:
default:
return true;
break;
}
}
protected:
using AttachmentMap = std::unordered_map<GLenum, std::shared_ptr<RenderTarget>>;
AttachmentMap _attachments;
FrameBufferBase(GLenum target);
GLuint declare() override;
void remove() override;
std::shared_ptr<RenderTarget> detach(GLenum);
void attach(
GLenum attachment,
std::shared_ptr<Texture> texture,
unsigned int level=0
);
void attach(
GLenum attachment,
std::shared_ptr<Texture> texture,
unsigned int level,
unsigned int layer
);
void attach(
GLenum attachment,
std::shared_ptr<RenderBuffer> renderBuffer
) {
declare();
if (attachment == GL_NONE) {
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
"Cannot attach RenderBuffer to `GL_NONE`"
));
}
glFramebufferRenderbuffer(
Target,
attachment,
GL_RENDERBUFFER,
renderBuffer->id()
);
_attachments[attachment] = renderBuffer;
}
public:
const GLenum Target;
void bind() const override;
void unbind() const override;
GLenum status() const;
AttachmentMap getAllBuffers() const;
std::shared_ptr<RenderTarget> getBuffer(GLenum) const;
};
class ReadFrameBuffer;
class WriteFrameBuffer;
class ReadFrameBuffer : public virtual FrameBufferBase {
friend WriteFrameBuffer;
protected:
using FrameBufferBase::_attachments;
GLenum _location;
public:
using FrameBufferBase::attach;
ReadFrameBuffer();
ReadFrameBuffer& operator=(WriteFrameBuffer&&);
ReadFrameBuffer& operator=(ReadFrameBuffer&&);
std::shared_ptr<RenderTarget> getReadBuffer() const;
GLenum getReadLocation() const;
std::shared_ptr<RenderTarget> setReadBuffer(GLenum attachment);
template<typename T, typename... Args>
std::shared_ptr<RenderTarget> setReadBuffer(
GLenum attachment,
std::shared_ptr<T> target,
Args... args
) {
declare();
FrameBufferBase::attach(attachment, target, args...);
setReadBuffer(attachment);
return getReadBuffer();
}
};
class WriteFrameBuffer : public virtual FrameBufferBase {
friend ReadFrameBuffer;
protected:
using DrawTexVec = std::vector<std::shared_ptr<Texture>>;
using FrameBufferBase::_attachments;
std::vector<GLenum> _locations;
public:
WriteFrameBuffer();
WriteFrameBuffer& operator=(ReadFrameBuffer&&);
WriteFrameBuffer& operator=(WriteFrameBuffer&&);
template<typename... T>
void attach(
GLenum attachment,
std::shared_ptr<Texture> texture,
T... args
) { FrameBufferBase::attach(attachment, texture, args...); }
DrawTexVec getWriteBuffers() const;
std::vector<GLenum> getWriteLocations() const;
DrawTexVec setWriteBuffers(const std::vector<GLenum>& attachments);
std::shared_ptr<Texture> setWriteBuffer(GLenum attachment);
template<typename... T>
std::shared_ptr<Texture> setWriteBuffer(
GLenum attachment,
std::shared_ptr<Texture> texture,
T... args
) {
attach(attachment, texture, args...);
setWriteBuffer(attachment);
return std::static_pointer_cast<Texture>(_attachments.at(attachment));
}
RGBA<float> clearColorValue() const;
RGBA<float> clearColorValue(const RGBA<float>&);
RGBA<float> clearColorValue(float r, float g, float b, float a);
double clearDepthValue() const;
double clearDepthValue(double);
GLint clearStencilValue() const;
GLint clearStencilValue(GLint);
void clear(GLbitfield mask=(
GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT
)) const;
void clearColor() const;
void clearDepth() const;
void clearDepth(float) const;
void clearStencil() const;
void clearStencil(GLint) const;
void clearDepthStencil() const;
void clearDepthStencil(float, GLint) const;
};
class FrameBuffer : public ReadFrameBuffer, public WriteFrameBuffer {
protected:
using FrameBufferBase::_attachments;
using ReadFrameBuffer::_location;
using WriteFrameBuffer::_locations;
public:
FrameBuffer();
FrameBuffer& operator=(FrameBuffer&&);
FrameBuffer& operator=(ReadFrameBuffer&&);
FrameBuffer& operator=(WriteFrameBuffer&&);
};
} // namespace nb
#endif // _NB_FRAMEBUFFER

View File

@ -5,31 +5,4 @@
#include <glad/glad.h> #include <glad/glad.h>
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
#include <iostream>
#include <string>
namespace NB {
static unsigned int __NB_GL_DEBUG_ERROR_CODE__;
static std::string formatDebugString(const std::string& msg, const std::string& file="", int line=-1) {
std::string ret = "";
if (file != "") {
ret += "In file " + file;
if (line >= 0) {
ret += " at line " + std::to_string(line);
}
ret += ":\n\t";
}
return ret + msg;
}
}
#define NB_GL_DEBUG_THROW(cmd, when) while(NB::__NB_GL_DEBUG_ERROR_CODE__=glGetError()){\
std::cout << "[GL ERROR]: " << NB::__NB_GL_DEBUG_ERROR_CODE__;\
std::cout << " " << when << " " << cmd << "\n";\
}
#define NB_GL_DEBUG(cmd) NB_GL_DEBUG_THROW(#cmd, "before"); cmd; NB_GL_DEBUG_THROW(#cmd, "after");
#endif #endif

216
engine/NBGraphics/Image.hpp Normal file
View File

@ -0,0 +1,216 @@
#pragma once
#ifndef _NB_IMAGE
#define _NB_IMAGE
#include <cstring>
#include <NBCore/Errors.hpp>
namespace nb {
template<typename T>
struct Color {};
struct Red : Color<Red> {};
struct Green : Color<Green> {};
struct Blue : Color<Blue> {};
struct Alpha : Color<Alpha> {};
struct Depth;
struct Stencil;
template<typename... T>
struct PixelChannel;
template<typename T>
struct PixelChannel<T, Red> {
using type=T;
T value;
T& r=value;
};
template<typename T>
struct PixelChannel<T, Green> {
using type=T;
T value;
T& g=value;
};
template<typename T>
struct PixelChannel<T, Blue> {
using type=T;
T value;
T& b=value;
};
template<typename T>
struct PixelChannel<T, Alpha> {
using type=T;
T value;
T& a=value;
};
template<typename T>
struct PixelChannel<T, Depth> {
using type=T;
T value;
T& z=value;
};
template<>
struct PixelChannel<uint8_t, Stencil> {
using type=uint8_t;
uint8_t value;
uint8_t& u=value;
};
template<typename T, typename... Channels>
struct Pixel : public PixelChannel<T, Channels>... {
Pixel() = default;
Pixel& operator=(const Pixel& rhs) {
((
[&](const typename PixelChannel<T, Channels>::type& val){
this->PixelChannel<T, Channels>::value = val;
}(rhs.PixelChannel<T, Channels>::value)
), ...);
return *this;
}
Pixel(const Pixel& cpy)
: Pixel(cpy.PixelChannel<T, Channels>::value...) {}
Pixel(typename PixelChannel<T, Channels>::type... vals)
: PixelChannel<T, Channels>{vals}... {}
};
template<typename Ref>
struct PixelReference;
template<typename T, typename... Channels>
struct PixelReference<Pixel<T, Channels...>>
: public Pixel<T&, Channels...> {
using PixelType = Pixel<T, Channels...>;
using Base = Pixel<T&, Channels...>;
using Base::Base;
PixelReference(PixelType& pixel)
: Base(pixel.PixelChannel<T, Channels>::value...) {}
operator PixelType() {
return PixelType(this->PixelChannel<T&, Channels>::value...);
}
PixelReference& operator=(const PixelType& pixel) {
((
[&](const typename PixelChannel<T, Channels>::type& val){
this->PixelChannel<T&, Channels>::value = val;
}(pixel.PixelChannel<T, Channels>::value)
), ...);
return *this;
}
};
template <typename T>
using RGBA = Pixel<T, Red, Green, Blue, Alpha>;
template <typename T>
using RGB = Pixel<T, Red, Green, Blue>;
class ImageError : public Error<ImageError> {
protected:
using Base = Error<ImageError>;
using Base::Base;
public:
enum Codes : unsigned int {
UNDEFINED, OUT_OF_BOUNDS
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
};
template<typename T>
class Image;
template<typename T, typename... Channels>
class Image<Pixel<T, Channels...>> {
protected:
using Codes = ImageError::Codes;
T* _data;
Image(unsigned int x, unsigned int y)
: width(x), height(y), _data(nullptr) {}
public:
using PixelType = Pixel<T, Channels...>;
static constexpr size_t NumberChannels = sizeof...(Channels);
const unsigned int width;
const unsigned int height;
Image(unsigned int x, unsigned int y, const T* data)
: Image(x, y) {
size_t data_size = width*height*NumberChannels;
_data = new T[data_size];
std::memcpy(_data, data, data_size*sizeof(T));
}
Image(const Image&) = delete;
Image& operator=(const Image&) = delete;
Image& operator=(Image&&) = delete;
Image(Image&& mv)
: width(mv.width), height(mv.height), _data(mv._data) {
mv._data = nullptr;
}
~Image() {
if (_data) {
delete[] _data;
}
}
const T* data() const { return _data; }
Image&& copy() const {
return Image(width, height, _data);
}
PixelReference<PixelType> at(unsigned int x, unsigned int y) {
if (!(x<width) || !(y<height)) {
std::string note = "w/ ("+std::to_string(x);
note += ", "+std::to_string(y) + ") >= (";
note += std::to_string(width)+", "+std::to_string(height);
note += ")";
THROW(ImageError(
Codes::OUT_OF_BOUNDS,
note
));
}
auto coord = y*height+x;
return PixelReference<PixelType>(
_data[coord*NumberChannels+Find<Channels, Channels...>::value-1]...
);
}
};
template<typename... T>
class ImageReference;
template<typename T, typename... Channels>
class ImageReference<Pixel<T, Channels...>> : public Image<Pixel<T, Channels...>> {
protected:
using Base = Image<Pixel<T, Channels...>>;
using Base::_data;
public:
using Base::width;
using Base::height;
using Base::copy;
ImageReference(unsigned int x, unsigned int y, T* data)
: Base(x, y) {
_data = data;
}
~ImageReference() noexcept {
Base::_data = nullptr;
}
};
} // namespace nb
#endif // _NB_IMAGE

View File

@ -0,0 +1,48 @@
#pragma once
#ifndef _NB_OGL_OBJECTS
#define _NB_OGL_OBJECTS
#include "GLLoad.hpp"
#include <NBCore/Errors.hpp>
namespace nb {
class OGLError : public Error<OGLError> {
using Base = Error<OGLError>;
public:
using Base::Base;
enum Codes : unsigned int {
UNDEFINED, HANGING_OBJECT, INVALID_OBJECT
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
};
class OpenGLObject {
public:
OpenGLObject(const OpenGLObject&) = delete;
OpenGLObject& operator=(const OpenGLObject&) = delete;
OpenGLObject(OpenGLObject&&);
OpenGLObject& operator=(OpenGLObject&&);
virtual ~OpenGLObject() {};
virtual void bind() const = 0;
virtual void unbind() const = 0;
GLuint id() const { return _id; }
protected:
using Codes = OGLError::Codes;
OpenGLObject() = default;
virtual GLuint declare() = 0;
virtual void remove() = 0;
GLuint _id = 0;
};
} // namespace nb
#endif // _NB_OGL_OBJECTS

View File

@ -0,0 +1,141 @@
#pragma once
#ifndef _NB_SHADER
#define _NB_SHADER
#include "GLLoad.hpp"
#include <string>
#include <NBCore/Errors.hpp>
#include <NBCore/Utils.hpp>
#include "OGLObjects.hpp"
namespace nb {
class ShaderError : public Error<ShaderError> {
using Base = Error<ShaderError>;
public:
using Base::Base;
enum Codes : unsigned int {
UNDEFINED
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
};
class ProgramError : public Error<ProgramError> {
using Base = Error<ProgramError>;
public:
using Base::Base;
enum Codes : unsigned int {
UNDEFINED, LINKING_ERROR
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
};
enum OpenGLProfiles {
Core,
Compatibility,
ES
};
class Shader : public OpenGLObject {
using Base = OpenGLObject;
public:
using Base::Base;
using Base::id;
Shader(GLenum, const std::string&);
Shader(GLenum, const std::vector<std::string>&);
Shader(Shader&&);
Shader& operator=(Shader&&) = delete;
~Shader() { remove(); }
operator bool();
virtual void bind() const override { /* TODO: Some warning of some kind perhaps*/ }
virtual void unbind() const override { /* TODO: Some warning of some kind perhaps*/ }
bool success() const;
GLint status(GLenum) const;
std::string log() const;
const GLenum target;
friend Base;
protected:
using Base::_id;
GLint _success;
std::vector<std::string> _sources;
virtual void compile() {
int num_srcs = _sources.size();
std::vector<char*> src_ptrs(num_srcs);
for (int i=0; i < num_srcs; ++i) {
src_ptrs[i] = _sources[i].data();
}
glShaderSource(_id, num_srcs, src_ptrs.data(), NULL);
glCompileShader(_id);
_success = status(GL_COMPILE_STATUS);
if (!_success) {
WARN(log(), 0x0FE);
}
}
virtual GLuint declare() override {
if (!_id) {
_id = _id = glCreateShader(target);
}
return _id;
}
virtual void remove() override {
if (_id) {
glDeleteShader(_id);
}
}
};
class Program : public OpenGLObject {
using Base = OpenGLObject;
public:
using Base::Base;
using Base::id;
Program(SharedVector<Shader>);
Program(Program&&);
Program& operator=(Program&&) = delete;
operator bool();
~Program() { remove(); }
virtual void bind() const override {
glUseProgram(_id);
}
virtual void unbind() const override { /* TODO: Some warning of some kind perhaps*/ }
GLint status(GLenum) const;
std::string log() const;
friend Base;
protected:
using Base::_id;
GLint _success;
virtual GLuint declare() override {
if (!_id) {
_id = glCreateProgram();
}
return _id;
}
virtual void remove() override {
if (_id) {
glDeleteProgram(_id);
}
}
};
}
#endif

View File

@ -0,0 +1,153 @@
#pragma once
#ifndef _NB_TEXTURES
#define _NB_TEXTURES
#include "Buffers.hpp"
#include "Image.hpp"
#include "OGLObjects.hpp"
namespace nb {
class TextureBuffer : public virtual Buffer {
public:
TextureBuffer() : Buffer(GL_TEXTURE_BUFFER) {}
};
class RenderTarget : public OpenGLObject {
protected:
using Base = OpenGLObject;
using Base::_id;
RenderTarget(GLenum target) : Target(target) {}
RenderTarget(RenderTarget&& rhs)
: Target(rhs.Target), Base(std::move(rhs)) {}
public:
using Base::Base;
using Base::id;
const GLenum Target;
};
class Texture : public RenderTarget {
protected:
using Base = RenderTarget;
using Base::_id;
Texture(GLenum);
virtual GLuint declare() override {
if (!_id) {
glGenTextures(1, &_id);
}
bind();
return _id;
}
virtual void remove() override {
if (_id) {
bind();
glDeleteTextures(0, &_id);
}
}
public:
using Base::Base;
using Base::id;
using Base::Target;
virtual void bind() const override {
if (_id) {
glBindTexture(Target, _id);
} else {
THROW(OGLError(
OGLError::Codes::INVALID_OBJECT,
"w/ Texture"
));
}
}
virtual void unbind() const override {
glBindTexture(Target, 0);
}
template <typename T>
void parameter(GLenum param_, const T& val_);
void parameter(GLenum param_, const int& val_) {
declare();
glTexParameteri(_id, param_, val_);
}
void parameter(GLenum param_, const std::vector<int>& val_) {
declare();
glTexParameteriv(_id, param_, val_.data());
}
void parameter(GLenum param_, const std::vector<float>& val_) {
declare();
glTexParameterfv(_id, param_, val_.data());
}
void parameter(GLenum param_, const std::vector<unsigned int>& val_) {
declare();
glTexParameterIuiv(_id, param_, val_.data());
}
void generateMipmaps() const {
bind();
glGenerateMipmap(Target);
}
};
template<typename T>
class ImageTexture;
template<typename T>
struct OGLPixelFormat;
template<typename T, typename... Channels>
struct OGLPixelFormat<Pixel<T, Channels...>>;
template<>
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue>> {
static constexpr GLenum glFormat = GL_RGB;
static constexpr GLenum glData = GL_UNSIGNED_BYTE;
};
template<>
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue, Alpha>> {
static constexpr GLenum glFormat = GL_RGBA;
static constexpr GLenum glData = GL_UNSIGNED_BYTE;
};
template<typename T, typename... Channels>
class ImageTexture<Pixel<T, Channels...>> : public Texture {
protected:
using Texture::Texture;
using PixelType = Pixel<T, Channels...>;
public:
using Texture::generateMipmaps;
ImageTexture() : Texture(GL_TEXTURE_2D) {}
ImageTexture(ImageTexture&& cpy) {
*this = std::move(cpy);
}
ImageTexture& operator=(ImageTexture&& rhs) {
return Texture::operator=(std::move(rhs));
}
void setImage(const Image<PixelType>& img, unsigned int layer) {
using Format = OGLPixelFormat<PixelType>;
declare();
glTexImage2D(
Target,
layer,
Format::glFormat,
img.width,
img.height,
0,
Format::glFormat,
Format::glData,
img.data()
);
}
void setImage(const Image<PixelType>& img, bool generateMipmap=true) {
setImage(img, (unsigned int)0);
if (generateMipmap) { generateMipmaps(); }
}
};
} // namespace nb
#endif // _NB_TEXTURES

View File

@ -1,75 +0,0 @@
#pragma once
#ifndef _NB_VAO_MANAGER
#define _NB_VAO_MANAGER
#include <GLLoad.h>
#include <exception>
#include <memory>
#include <vector>
#include "Buffers.h"
#define THROW_VAO_ERROR(msg) throw VAOError(msg, __FILE__, __LINE__);
namespace NB {
class VAOError : public std::runtime_error {
public:
const bool error;
VAOError(const std::string& msg, const std::string& file="", int line=-1)
: std::runtime_error(NB::formatDebugString(msg, file, line)), error(true) {}
VAOError(bool isError=true) : std::runtime_error(""), error(isError) {}
};
class VAOManager : public OpenGLObject {
public:
typedef std::shared_ptr<Buffer> BufferManagerPointer;
//typedef BufferManager BufferManagerPointer;
VAOManager();
VAOManager(
std::vector<BufferManagerPointer>,
BufferManagerPointer elmt_buf = nullptr,
const VertexAttributeList& vert_attrs = {}
);
VAOManager(
BufferManagerPointer vert_bufs,
BufferManagerPointer elmt_buf = nullptr,
const VertexAttributeList& vert_attrs = {}
) : VAOManager(std::vector<BufferManagerPointer>(1, vert_bufs), elmt_buf, vert_attrs) {}
VAOManager(VAOManager&& rhs);
VAOManager& operator=(VAOManager&& rhs);
VertexAttributeList getLayout() const;
GLuint id() const;
unsigned int vertSize(GLuint) const;
std::vector<BufferManagerPointer> getVertexBuffers() const;
bool isInitialized() const override;
RawVec attributeData(unsigned int);
RawVec attributeData(unsigned int, const RawVec&);
void bind() const;
void unbind() const;
void addVBO(BufferManagerPointer);
void changeEBO(BufferManagerPointer);
VertexAttributeList addVertexAttributes(const VertexAttributeList&);
VertexAttributeList addVertexAttributes(VertexAttribute);
VertexAttributeList generate();
VertexAttributeList generate(VertexAttributeList);
VertexAttributeList changeLayout(unsigned int, VertexAttributePointer);
VAOError checkValid(const VertexAttributeList&);
private:
void remove() const override;
using OpenGLObject::_id;
std::map<GLuint, BufferManagerPointer> _vert_buffers;
BufferManagerPointer _elmt_buffer = nullptr;
VertexAttributeList _vert_attrs;
};
} // namespace NB
#endif // _NB_VAO_MANAGER

View File

@ -0,0 +1,238 @@
#pragma once
#ifndef _NB_VERTEX_ARRAY
#define _NB_VERTEX_ARRAY
#include "GLLoad.hpp"
#include <NBCore/Errors.hpp>
#include "Buffers.hpp"
#include "OGLObjects.hpp"
namespace nb {
static uint8_t GLSLTypeSize(GLenum type) {
switch(type) {
case GL_SHORT:
case GL_UNSIGNED_SHORT:
case GL_HALF_FLOAT:
return 2;
break;
case GL_INT:
case GL_UNSIGNED_INT:
case GL_FLOAT:
return 4;
break;
case GL_DOUBLE:
return 8;
break;
default:
return 1;
break;
}
}
struct VertexAttributeLayout {
int32_t offset = 0;
GLsizei stride = 0;
GLuint divisor = 0;
};
struct VertexAttribute {
GLint GLSLSize;
GLenum GLSLType;
GLboolean GLSLNormalization;
VertexAttributeLayout layout;
};
struct VertexAttributePointer {
VertexAttribute attribute;
GLuint buffer;
GLuint index;
};
static bool isIndexInVertexAttribute(int i, const VertexAttribute& va) {
if ((i -= va.layout.offset) < 0) { return false; }
return (i%va.layout.stride) < GLSLTypeSize(va.GLSLType) * va.GLSLSize;
}
typedef std::vector<VertexAttribute> VertexAttributeList;
typedef std::vector<VertexAttributePointer> VertexAttributePointerList;
class VAOError : public Error<VAOError> {
using Base = Error<VAOError>;
public:
using Base::Base;
enum Codes : unsigned int {
UNDEFINED, INVALID_ATTRIBUTE
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
};
class VAO : public OpenGLObject {
using Base = OpenGLObject;
using Codes = VAOError::Codes;
public:
using Base::Base;
VAO() = default;
VAO(const VertexAttributePointerList&);
VAO(VAO&&);
VAO& operator=(VAO&&);
virtual void bind() const override {
if(_id) {
glBindVertexArray(_id);
} else {
THROW(OGLError(
OGLError::Codes::INVALID_OBJECT,
"w/ VertexArrayObject"
));
}
}
virtual void unbind() const override { glBindVertexArray(0); }
VertexAttributePointerList attributes() const;
VertexAttributePointerList attributes(const VertexAttributePointerList&);
VertexAttributePointer attr(GLuint) const;
void enable() const;
void enable(GLuint) const;
void disable() const;
void disable(GLuint) const;
protected:
using Base::_id;
VertexAttributePointerList _attrs;
virtual void remove() override {
if(_id) {
disable();
bind();
glDeleteVertexArrays(1, &_id);
_id = 0;
}
}
virtual GLuint declare() override {
if (!_id) {
glGenVertexArrays(1, &_id);
}
bind();
return _id;
}
};
class VertexError : public Error<VertexError> {
protected:
using Base = Error<VertexError>;
public:
using Base::Base;
enum Codes : unsigned int {
UNDEFINED, MISALIGNED_DATA
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
};
using VBO = ArrayBuffer;
using VertBufVec = SharedVector<VBO>;
using EBO = ElementBuffer;
struct VertexData {
std::shared_ptr<VBO> vbo;
VertexAttributeList attrs;
};
using VertexDataVec = std::vector<VertexData>;
class VertexGroup {
protected:
using Codes = VertexError::Codes;
VertexDataVec _vertex_data;
std::shared_ptr<EBO> _ebo;
std::shared_ptr<VAO> _vao;
GLenum _primitive;
public:
GLenum primitive=GL_TRIANGLES;
VertexGroup(VertexGroup&&);
VertexGroup& operator=(VertexGroup&&);
VertexGroup(
const VertexDataVec& vertex_data,
const std::shared_ptr<EBO>& ebo
)
: _vao(std::make_shared<VAO>()), _ebo(ebo) {
setBuffers(vertex_data);
}
template<typename... T>
VertexGroup(
const VertexDataVec& vertex_data,
T... args
)
: VertexGroup(vertex_data, std::make_shared<EBO>(args...)) {
setBuffers(vertex_data);
}
template<typename... T>
VertexGroup(
const VertexData& vertex_data,
T... args
)
: VertexGroup(VertexDataVec{vertex_data}, args...) {}
template<typename... T>
VertexGroup(
const ByteVector& vertex_data,
const VertexAttributeList& vertex_specification,
T... args
) : VertexGroup({
std::make_shared<VBO>(vertex_data),
vertex_specification},
args...
) {}
void bind() const {
_vao->bind();
_ebo->bind();
}
void unbind() const {
_vao->unbind();
_ebo->unbind();
}
void draw() const;
VertexDataVec getBuffers();
VertexData getBuffers(size_t);
size_t setBuffers(const VertexDataVec&);
size_t addBuffer(const VertexData&);
size_t addBuffer(const ByteVector& data, const VertexAttributeList& attrs);
VertexDataVec dropBuffers();
VertexData dropBuffer(size_t);
VertexAttributePointer attribute(size_t) const;
void enableAttr(GLuint);
void disableAttr(GLuint);
void enableBuffer(size_t);
void disableBuffer(size_t);
void enable();
void disable();
std::shared_ptr<EBO> indices() const;
std::shared_ptr<EBO> indices(const std::vector<unsigned int>& data);
std::shared_ptr<EBO> indices(std::shared_ptr<EBO> buffer);
};
} // namespace nb
#endif // _NB_VERTEX_ARRAY

View File

@ -4,22 +4,42 @@
#include "GLLoad.hpp" #include "GLLoad.hpp"
#include <atomic>
#include <array> #include <array>
#include <map> #include <map>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <NBCore/Errors.hpp>
#include <NBCore/Utils.hpp>
namespace nb { namespace nb {
class GLError : public std::runtime_error { class OpenGLError : public Error<OpenGLError> {
using Base = Error<OpenGLError>;
public: public:
GLError(const std::string&); using Base::Base;
enum Codes : unsigned int {
UNDEFINED, INIT_FAILED, GLFW_INTIALIZED, GLAD_FAILED
}; };
class WindowError : public std::runtime_error { static const std::string type;
static const ErrorCodeMap ErrorMessages;
};
class WindowError : public Error<WindowError> {
using Base = Error<WindowError>;
public: public:
WindowError(const std::string&); using Base::Base;
enum Codes : unsigned int {
UNDEFINED, INITIALIZED_WINDOW, NO_GLFW, INIT_FAILED
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
}; };
class Window { class Window {

View File

@ -1,193 +0,0 @@
#pragma once
#ifndef _NB_SHADER
#define _NB_SHADER
#include <GLLoad.h>
#include <cctype>
#include <cstring>
#include <exception>
#include <fstream>
#include <iostream>
#include <map>
#include <regex>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// #define _PREPROC_FUNC_PARAMS_ (const ShaderPreprocessor&, ShaderUnit&, unsigned int, const std::string&, std::vector<uint8_t>&)
namespace NB {
class ShaderPreprocessorError : public std::runtime_error {
public:
enum Codes : unsigned char {
NONE,
FILE_NOT_FOUND,
BUILTIN_NOT_FOUND,
CUSTOM,
UNDEFINED
};
const Codes code;
ShaderPreprocessorError(const std::string&, const std::string& file="", int line=-1);
ShaderPreprocessorError(Codes, const std::string& arg="", const std::string& file="", int line=-1);
protected:
static std::string errorCodeParser(Codes, const std::string& arg="");
};
class ShaderError : public std::runtime_error {
public:
ShaderError(const std::string&, const char* shad=nullptr, const std::string& file="", int line=-1);
protected:
std::string formatString(const std::string&, const char* shad=nullptr, const std::string& file="", int line=-1);
};
struct File {
// typedef std::tuple<std::string, std::string, std::string> FilePath;
struct FilePath {
std::string dir;
std::string basename;
std::string ext;
};
FilePath path;
std::stringstream src;
std::map<unsigned int, std::shared_ptr<File>> include_map;
File() {}
File(const File& rhs) { *this = rhs; }
File& operator=(const File& rhs) {
path = rhs.path;
src.str("");
src << rhs.src.rdbuf();
include_map = rhs.include_map;
return *this;
}
};
// File::FilePath get_file_path(std::string);
class ShaderPreprocessor;
enum OpenGLProfiles {
Core,
Compatibility,
ES
};
struct ShaderUnit {
GLenum type = 0x0;
File file;
std::string preprocSource;
std::map<std::string, std::string> defines;
short vMajor=0, vMinor=0;
OpenGLProfiles profile = Core;
};
class ShaderPreprocessor;
class ShaderProgram {
friend ShaderPreprocessor;
public:
ShaderProgram() {}
ShaderProgram(const ShaderProgram& rhs) = delete;
ShaderProgram(ShaderProgram&& rhs);
~ShaderProgram();
ShaderProgram& operator=(const ShaderProgram& rhs) = delete;
ShaderProgram& operator=(ShaderProgram&& rhs);
std::vector<ShaderUnit> getShaders() const;
ShaderUnit getShaders(unsigned int) const;
void use() const;
unsigned int id() const;
void setBool(const std::string& name, bool value) const;
void setInt(const std::string& name, int value) const;
void setUnsigned(const std::string& name, int value) const;
void setFloat(const std::string& name, float value) const;
void setMat4(const std::string& name, glm::mat4& value) const;
static ShaderProgram CreateShaderProgram(std::vector<ShaderUnit>&);
private:
ShaderProgram(std::vector<ShaderUnit>& shaders) : _shader_units(shaders){}
std::vector<ShaderUnit> _shader_units;
unsigned int _id;
};
class ShaderPreprocessor {
public:
typedef ShaderPreprocessorError::Codes Codes;
enum TokenType {
TK,
DR,
WS,
NL,
LC,
BC
};
static std::string TokenName(const TokenType&);
std::map<std::string, GLenum> AcceptedExtensions = {
{".frag", GL_FRAGMENT_SHADER},
{".fs", GL_FRAGMENT_SHADER},
{".vert", GL_VERTEX_SHADER},
{".vs", GL_VERTEX_SHADER},
{".tess", 0x0},
{".geom", GL_GEOMETRY_SHADER},
{".comp", 0x0},
{".shad", 0x0},
{".glsl", 0x0}
};
std::map<std::string, OpenGLProfiles> AcceptedProfiles {
{"core", Core},
{"compatibility", Compatibility},
{"es", ES}
};
std::vector<std::string> Directories;
std::map<std::string, std::string> BuiltIns;
ShaderPreprocessor();
File load(const std::string, bool builtin_first=false) const;
ShaderUnit& preprocess(const std::string&, ShaderUnit&) const;
ShaderUnit preprocess(File, GLenum shader_type=0x0) const;
ShaderUnit preprocess(const std::string&, GLenum shader_type=0x0) const;
ShaderProgram ReloadFromFile(const ShaderProgram& rhs) const;
ShaderProgram CreateShaderProgram(std::vector<std::string>) const;
private:
typedef std::pair<TokenType, std::string> Token;
typedef std::vector<std::string> StringVec;
inline bool directive_dispatch(ShaderUnit&, const std::string&) const;
inline std::vector<Token> tokenize(const std::string&) const;
inline bool preprocessor_include(ShaderUnit&, const StringVec&, const std::string&) const;
inline bool preprocessor_version(ShaderUnit&, const StringVec&, const std::string&) const;
inline bool preprocessor_define(ShaderUnit&, const StringVec&, const std::string&) const;
// inline bool preprocessor_uniform(ShaderUnit&, const std::string&, const std::string&) const;
File loadFromBase(const std::string, const std::string base="") const;
File loadFromDirectories(const std::string) const;
File loadFromBuiltIn(const std::string) const;
File load_BuiltInFirst(const std::string) const;
File load_FilesFirst(const std::string) const;
};
}
#endif

View File

@ -2,4 +2,102 @@
namespace nb { namespace nb {
const std::unordered_map<GLenum, std::string> BufferTypes({
{GL_ARRAY_BUFFER, "GL_ARRAY_BUFFER"},
{GL_ELEMENT_ARRAY_BUFFER, "GL_ELEMENT_BUFFER"}
});
using BufferErrorCodes = BufferError::Codes;
const std::string BufferError::type = "nb::BufferError";
const ErrorCodeMap BufferError::ErrorMessages = {
{ BufferErrorCodes::UNDEFINED, "Error" },
{ BufferErrorCodes::DATA_OVERFLOW, "Attempting buffer overflow" },
{BufferErrorCodes::DATA_ERROR, "Invalid memory operation"}
};
Buffer::Buffer(Buffer&& rval) : Target(rval.Target) {
*this = std::move(rval);
}
Buffer& Buffer::operator=(Buffer&& rhs) {
if (Target != rhs.Target) {
auto targ_name = BufferTypes.at(Target);
THROW(OGLError(
OGLError::Codes::INVALID_OBJECT,
"w/ BufferType "+targ_name+" != BufferType "+BufferTypes.at(rhs.Target)
));
}
OpenGLObject::operator=(std::move(rhs));
_usage = rhs._usage;
_size = rhs._size;
rhs._usage = GL_STATIC_DRAW;
rhs._size = 0;
return *this;
}
GLenum Buffer::usage() const { return _usage; }
size_t Buffer::size() const { return _size; }
ByteVector Buffer::data() const {
bind();
ByteVector ret(_size);
glGetBufferSubData(Target, 0, _size, ret.data());
return ret;
}
void Buffer::data(const void* data_, size_t size_, GLenum usage_) {
declare();
glBufferData(Target, size_, data_, usage_);
_size = size_;
_usage = usage_;
}
void Buffer::data(const ByteVector& data_, GLenum usage_) {
declare();
data(data_.data(), data_.size(), usage_);
}
void Buffer::subdata(const void* data_, size_t size_, GLintptr offset_) {
bind();
if (offset_+size_ <= _size) {
THROW(BufferError(BufferError::Codes::DATA_OVERFLOW));
}
glBufferSubData(Target, offset_, size_, data_);
}
void Buffer::subdata(const ByteVector& data_, GLintptr offset_) {
bind();
size_t size_ = data_.size();
subdata(data_.data(), size_);
}
ElementBuffer::ElementBuffer() : Buffer(GL_ELEMENT_ARRAY_BUFFER) {}
ByteVector ElementBuffer::data() const {
return data();
}
size_t ElementBuffer::size() const { return _size / _typeSize; }
size_t ElementBuffer::typeSize() const { return _typeSize; }
GLenum ElementBuffer::glslType() const { return _glslType; }
template void ElementBuffer::data<uint8_t>(const std::vector<uint8_t>& data, GLenum usage);
template void ElementBuffer::data<uint16_t>(const std::vector<uint16_t>& data, GLenum usage);
template void ElementBuffer::data<uint32_t>(const std::vector<uint32_t>& data, GLenum usage);
template void ElementBuffer::data<uint8_t>(const uint8_t* const data, size_t size, GLenum usage);
template void ElementBuffer::data<uint16_t>(const uint16_t* const data, size_t size, GLenum usage);
template void ElementBuffer::data<uint32_t>(const uint32_t* const data, size_t size, GLenum usage);
template void ElementBuffer::subdata<uint8_t>(const uint8_t* const data, size_t size, size_t offset=0);
template void ElementBuffer::subdata<uint16_t>(const uint16_t* const data, size_t size, size_t offset=0);
template void ElementBuffer::subdata<uint32_t>(const uint32_t* const data, size_t size, size_t offset=0);
template void ElementBuffer::subdata<uint8_t>(const std::vector<uint8_t>& data, size_t offset=0);
template void ElementBuffer::subdata<uint16_t>(const std::vector<uint16_t>& data, size_t offset=0);
template void ElementBuffer::subdata<uint32_t>(const std::vector<uint32_t>& data, size_t offset=0);
} }

View File

@ -1,5 +1,6 @@
#include "Camera.h" #include "Camera.hpp"
namespace NB {
namespace nb {
// Camera class // Camera class
Camera::Camera(const Vec3& pos, const Vec3& tar, const Vec3& up) { Camera::Camera(const Vec3& pos, const Vec3& tar, const Vec3& up) {

View File

@ -0,0 +1,342 @@
#include "FrameBuffers.hpp"
namespace nb {
using FBOErrorCodes = FrameBufferError::Codes;
const std::string FrameBufferError::type = "nb::FrameBufferError";
const ErrorCodeMap FrameBufferError::ErrorMessages = {
{FBOErrorCodes::UNDEFINED, "Error"},
{FBOErrorCodes::INVALID_VALUE, "Invalid value"}
};
GLuint FrameBufferBase::declare() {
if (!_id) {
glGenFramebuffers(1, &_id);
}
bind();
return _id;
}
void FrameBufferBase::remove() {
if (_id) {
unbind();
glDeleteFramebuffers(1, &_id);
_id=0;
}
}
FrameBufferBase::FrameBufferBase(GLenum target) : Target(target) {}
std::shared_ptr<RenderTarget> FrameBufferBase::detach(GLenum attch_) {
bind();
auto ret = _attachments.at(attch_);
_attachments.erase(attch_);
glFramebufferTexture(Target, attch_, 0, 0);
return ret;
}
void FrameBufferBase::attach(
GLenum attachment_,
std::shared_ptr<Texture> texture_,
unsigned int level_,
unsigned int layer_
) {
declare();
if (attachment_ == GL_NONE) {
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
"Cannot attach object to `GL_NONE`"
));
}
glFramebufferTextureLayer(
Target,
attachment_,
texture_->id(),
level_,
layer_
);
_attachments[attachment_] = texture_;
}
void FrameBufferBase::attach(
GLenum attachment_,
std::shared_ptr<Texture> texture_,
unsigned int level_
) {
declare();
if (attachment_ == GL_NONE) {
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
"Cannot attach object to `GL_NONE`"
));
}
if (texTypeIs2D(texture_->Target)) {
glFramebufferTexture2D(
Target,
attachment_,
texture_->Target,
texture_->id(),
level_
);
} else {
glFramebufferTexture1D(
Target,
attachment_,
texture_->Target,
texture_->id(),
level_
);
}
_attachments[attachment_] = texture_;
}
void FrameBufferBase::bind() const {
if (_id) {
glBindFramebuffer(Target, _id);
} else {
THROW(OGLError(
OGLError::Codes::INVALID_OBJECT,
"w/ FrameBuffer"
));
}
}
void FrameBufferBase::unbind() const {
glBindFramebuffer(Target, 0);
}
GLenum FrameBufferBase::status() const {
bind();
return glCheckFramebufferStatus(Target);
}
FrameBufferBase::AttachmentMap FrameBufferBase::getAllBuffers() const {
return _attachments;
}
std::shared_ptr<RenderTarget> FrameBufferBase::getBuffer(GLenum attch_) const {
try {
return _attachments.at(attch_);
} catch (const std::out_of_range& e) {
THROW(e);
}
}
// class ReadFrameBuffer
ReadFrameBuffer::ReadFrameBuffer()
: _location(GL_NONE), FrameBufferBase(GL_READ_FRAMEBUFFER) {}
ReadFrameBuffer& ReadFrameBuffer::operator=(WriteFrameBuffer&& mv) {
if (mv.id()) {
_attachments = mv.getAllBuffers();
mv.setWriteBuffer(GL_NONE);
mv._attachments = {};
mv._locations = {};
FrameBufferBase::OpenGLObject::operator=(std::move(mv));
}
return *this;
}
ReadFrameBuffer& ReadFrameBuffer::operator=(ReadFrameBuffer&& mv) {
if (mv.id()) {
_attachments = mv._attachments;
_location = mv._location;
mv._attachments = {};
mv._location = GL_NONE;
FrameBufferBase::OpenGLObject::operator=(std::move(mv));
}
return *this;
}
std::shared_ptr<RenderTarget> ReadFrameBuffer::getReadBuffer() const {
if (_location == GL_NONE) { return nullptr; }
return getBuffer(_location);
}
GLenum ReadFrameBuffer::getReadLocation() const { return _location; }
std::shared_ptr<RenderTarget> ReadFrameBuffer::setReadBuffer(GLenum attch_) {
bind();
if (attch_!=GL_NONE) {
try {
const auto& x = _attachments.at(attch_);
} catch (const std::out_of_range& e) {
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
"No buffer set at attachment"
));
}
}
_location = attch_;
glReadBuffer(_location);
return getReadBuffer();
}
// class WriteFrameBuffer
WriteFrameBuffer::WriteFrameBuffer()
: FrameBufferBase(GL_DRAW_FRAMEBUFFER) {}
WriteFrameBuffer& WriteFrameBuffer::operator=(ReadFrameBuffer&& rhs) {
if (rhs.id()) {
_attachments = rhs._attachments;
rhs.setReadBuffer(GL_NONE);
rhs._attachments = {};
rhs._location = GL_NONE;
FrameBufferBase::OpenGLObject::operator=(std::move(rhs));
}
return *this;
}
WriteFrameBuffer& WriteFrameBuffer::operator=(WriteFrameBuffer&& rhs) {
if (rhs.id()) {
_attachments = rhs._attachments;
_locations = rhs._locations;
rhs._attachments = {};
rhs._locations = {};
FrameBufferBase::OpenGLObject::operator=(std::move(rhs));
}
return *this;
}
using fRGBA = RGBA<float>;
std::vector<std::shared_ptr<Texture>> WriteFrameBuffer::getWriteBuffers() const {
const size_t count = _locations.size();
std::vector<std::shared_ptr<Texture>> ret(count);
for (int i = 0; i < count; ++i) {
ret[i] = std::static_pointer_cast<Texture>(getBuffer(_locations[i]));
}
return ret;
}
std::vector<GLenum> WriteFrameBuffer::getWriteLocations() const {
return _locations;
}
WriteFrameBuffer::DrawTexVec WriteFrameBuffer::setWriteBuffers(const std::vector<GLenum>& attchs_) {
bind();
for (GLenum loc : attchs_) {
if (getBuffer(loc)->Target == GL_RENDERBUFFER) {
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
"Cannot write to renderbuffer [ @ Attachment = "+std::to_string(loc)+" ]"
));
}
}
_locations = attchs_;
glDrawBuffers(_locations.size(), _locations.data());
return getWriteBuffers();
}
std::shared_ptr<Texture> WriteFrameBuffer::setWriteBuffer(GLenum attch_) {
bind();
if (attch_ == GL_NONE) {
std::vector<GLenum> tmp(_locations.size(), GL_NONE);
glDrawBuffers(tmp.size(), tmp.data());
_locations = {};
return nullptr;
}
setWriteBuffers({attch_});
return std::static_pointer_cast<Texture>(getBuffer(attch_));
}
fRGBA WriteFrameBuffer::clearColorValue() const {
bind();
float rgba[4];
glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba);
return fRGBA{rgba[0], rgba[1], rgba[2], rgba[3]};
}
fRGBA WriteFrameBuffer::clearColorValue(const fRGBA& color) {
declare();
glClearColor(color.r, color.g, color.b, color.a);
return color;
}
fRGBA WriteFrameBuffer::clearColorValue(float r, float g, float b, float a) {
return clearColorValue({r, g,b , a});
}
double WriteFrameBuffer::clearDepthValue() const {
bind();
double ret;
glGetDoublev(GL_DEPTH_CLEAR_VALUE, &ret);
return ret;
}
double WriteFrameBuffer::clearDepthValue(double d_) {
declare();
glClearDepth(d_);
return d_;
}
GLint WriteFrameBuffer::clearStencilValue() const {
bind();
GLint ret;
glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &ret);
return ret;
}
GLint WriteFrameBuffer::clearStencilValue(GLint s_) {
declare();
glClearStencil(s_);
return s_;
}
void WriteFrameBuffer::clear(GLbitfield mask_) const {
bind();
glClear(mask_);
}
void WriteFrameBuffer::clearDepth() const {
clear(GL_DEPTH_BUFFER_BIT);
}
void WriteFrameBuffer::clearDepth(float val_) const {
bind();
glClearBufferfv(GL_DEPTH, 0, &val_);
}
void WriteFrameBuffer::clearStencil() const {
clear(GL_STENCIL_BUFFER_BIT);
}
void WriteFrameBuffer::clearStencil(GLint val_) const {
bind();
glClearBufferiv(GL_STENCIL, 0, &val_);
}
void WriteFrameBuffer::clearDepthStencil() const {
clear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
void WriteFrameBuffer::clearDepthStencil(float d_, GLint s_) const {
bind();
glClearBufferfi(GL_DEPTH_STENCIL, 0, d_, s_);
}
FrameBuffer::FrameBuffer()
: FrameBufferBase(GL_FRAMEBUFFER) {}
FrameBuffer& FrameBuffer::operator=(FrameBuffer&& rhs) {
if (rhs.id()) {
_attachments = rhs._attachments;
_location = rhs._location;
_locations = rhs._locations;
rhs._attachments = {};
rhs._locations = {};
rhs._location = GL_NONE;
OpenGLObject::operator=(std::move(rhs));
}
return *this;
}
FrameBuffer& FrameBuffer::operator=(ReadFrameBuffer&& rhs) {
ReadFrameBuffer::operator=(std::move(rhs));
return *this;
}
FrameBuffer& FrameBuffer::operator=(WriteFrameBuffer&& rhs) {
WriteFrameBuffer::operator=(std::move(rhs));
return *this;
}
} // namespace nb

View File

@ -0,0 +1,8 @@
#include "Image.hpp"
using ImageErrorCodes = nb::ImageError::Codes;
const std::string nb::ImageError::type = "nb::ImageError";
const nb::ErrorCodeMap nb::ImageError::ErrorMessages = {
{ ImageErrorCodes::UNDEFINED, "Error" },
{ImageErrorCodes::OUT_OF_BOUNDS, "Out of bounds"}
};

View File

@ -0,0 +1,23 @@
#include "OGLObjects.hpp"
namespace nb {
const std::string OGLError::type = "nb::OGLError";
const ErrorCodeMap OGLError::ErrorMessages = {
{ OGLError::Codes::UNDEFINED, "Error" },
{OGLError::Codes::HANGING_OBJECT, "Attempting to leave a hanging OpenGL object"},
{OGLError::Codes::INVALID_OBJECT, "Attempting operation with invalid object"}
};
OpenGLObject::OpenGLObject(OpenGLObject&& rval) {
*this = std::move(rval);
}
OpenGLObject& OpenGLObject::operator=(OpenGLObject&& rhs) {
if (_id) { THROW(OGLError(Codes::HANGING_OBJECT)); }
_id = rhs._id;
rhs._id = 0;
return *this;
}
} // namespace nb

View File

@ -0,0 +1,88 @@
#include "ProgramPipeline.hpp"
namespace nb{
using ShaderErrCodes = ShaderError::Codes;
const std::string ShaderError::type = "nb::ShaderError";
const ErrorCodeMap ShaderError::ErrorMessages = {
{ShaderErrCodes::UNDEFINED, "Error"}
};
using ProgramErrCodes = ProgramError::Codes;
const std::string ProgramError::type = "nb::ProgramError";
const ErrorCodeMap ProgramError::ErrorMessages = {
{ProgramErrCodes::UNDEFINED, "Error"},
{ProgramErrCodes::LINKING_ERROR, "Linker error"}
};
Shader::Shader(GLenum target_, const std::string& source_)
: Shader(target_, std::vector<std::string>({source_})) {}
Shader::Shader(GLenum target_, const std::vector<std::string>& strings_)
: target(target_), _sources(strings_) {
declare();
compile();
}
Shader::Shader(Shader&& cpy)
: target(cpy.target), _success(cpy._success), _sources(cpy._sources) {
_id = cpy._id;
cpy._success = false;
cpy._sources = {};
cpy._id = 0;
}
Shader::operator bool() { return success(); }
bool Shader::success() const {
return _success;
}
GLint Shader::status(GLenum parameter) const {
GLint param = 0;
glGetShaderiv(_id, parameter, &param);
return param;
}
std::string Shader::log() const {
GLint logsize = status(GL_INFO_LOG_LENGTH);
char* log_ = new char[logsize];
glGetShaderInfoLog(_id, logsize, NULL, log_);
std::string ret(log_, logsize);
delete[] log_;
return ret;
}
Program::Program(SharedVector<Shader> shaders_) {
declare();
for (auto shad_ptr : shaders_) {
glAttachShader(_id, shad_ptr->id());
}
glLinkProgram(_id);
_success = status(GL_LINK_STATUS);
if (!_success) {
WARN(log(), 0x0FE);
}
}
Program::operator bool() { return _success; }
GLint Program::status(GLenum parameter) const {
GLint param = 0;
glGetProgramiv(_id, parameter, &param);
return param;
}
std::string Program::log() const {
GLint logsize = status(GL_INFO_LOG_LENGTH);
char* log_ = new char[logsize];
glGetProgramInfoLog(_id, logsize, NULL, log_);
std::string ret(log_, logsize);
delete[] log_;
return ret;
}
}

View File

@ -0,0 +1,7 @@
#include "Textures.hpp"
namespace nb {
Texture::Texture(GLenum target_) : Base(target_) {}
} // namespace nb

View File

@ -1,225 +0,0 @@
#include "VAOManager.hpp"
namespace NB {
using BufferManagerPointer = std::shared_ptr<Buffer>;
VAOManager::VAOManager() { glGenVertexArrays(1, &_id); }
VAOManager::VAOManager(
std::vector<BufferManagerPointer> vert_bufs,
BufferManagerPointer elmt_buf,
const VertexAttributeList& vert_attrs
) : VAOManager() {
_elmt_buffer = elmt_buf;
for (BufferManagerPointer vb : vert_bufs) {
_vert_buffers[vb->id()] = vb;
}
if (vert_attrs.size()!=0) {
generate(vert_attrs);
}
}
VAOManager::VAOManager(VAOManager&& rhs) { *this = std::move(rhs); }
VAOManager& VAOManager::operator=(VAOManager&& rhs) {
remove();
_vert_buffers = rhs._vert_buffers;
_elmt_buffer = rhs._elmt_buffer;
_vert_attrs = rhs._vert_attrs;
return *this;
}
VertexAttributeList VAOManager::getLayout() const { return _vert_attrs; }
GLuint VAOManager::id() const { return _id; }
bool VAOManager::isInitialized() const {
return _id && glIsVertexArray(_id);
}
void VAOManager::remove() const {
bind();
for (int i{0}; i < _vert_attrs.size(); ++i) {
glDisableVertexAttribArray(i);
}
unbind();
glDisableVertexAttribArray(_id);
}
unsigned int VAOManager::vertSize(GLuint id) const {
unsigned int size = 0;
for (const VertexAttribute& va : _vert_attrs) {
if (va.ptr.buffer == id) {
size += va.GLSLSize * GLSLTypeSize(va.GLSLType);
}
}
return size;
}
std::vector<BufferManagerPointer> VAOManager::getVertexBuffers() const {
std::vector<BufferManagerPointer> ret;
for (const auto& i : _vert_buffers) {
ret.emplace_back(i.second);
}
return ret;
}
RawVec VAOManager::attributeData(unsigned int i) {
if (i <= _vert_attrs.size()) {
throw std::out_of_range("No vertex attribute exists for specified index");
}
VertexAttribute attr = _vert_attrs[i];
BufferManagerPointer buffer = _vert_buffers[attr.ptr.buffer];
RawVec data = buffer->data();
unsigned int attr_size = attr.GLSLSize*GLSLTypeSize(attr.GLSLType);
RawVec ret((buffer->size()-attr.ptr.offset-attr_size)*attr_size/attr.ptr.stride);
int data_size = data.size();
for (int i{0}; i < data_size; ++i) {
if (isIndexInVertexAttribute(i, attr)) {
ret[i] = data[i];
}
}
return ret;
}
RawVec VAOManager::attributeData(unsigned int i, const RawVec& new_data) {
if (i >= _vert_attrs.size()) {
throw std::out_of_range("No vertex attribute exists for specified index.");
}
VertexAttribute attr = _vert_attrs[i];
BufferManagerPointer buffer = _vert_buffers[attr.ptr.buffer];
unsigned int attr_size = attr.GLSLSize*GLSLTypeSize(attr.GLSLType);
unsigned int offset = attr.ptr.offset;
unsigned int num_verts = buffer->size() / vertSize(buffer->id());
if (num_verts*attr_size != new_data.size()) {
// WHY HERE????
THROW_VAO_ERROR(
"Input data size of " + std::to_string(new_data.size())
+ " does not match data size for requested vertex attribute of total size " + std::to_string(num_verts*attr_size)
+ "."
);
}
uint64_t pos = uint64_t(new_data.data());
for (int i{0}; i<num_verts; i++) {
buffer->data((void*)(pos+i*attr_size), offset+i*attr.ptr.stride, attr_size);
}
return RawVec(new_data);
}
void VAOManager::bind() const {
glBindVertexArray(_id);
if (_elmt_buffer) { _elmt_buffer->bind(); }
}
void VAOManager::unbind() const {
glBindVertexArray(0);
if (_elmt_buffer) { _elmt_buffer->unbind(); }
}
void VAOManager::addVBO(BufferManagerPointer vert_buf) {
GLuint vert_id = vert_buf->id();
if (_vert_buffers.find(vert_id) == _vert_buffers.end()) {
_vert_buffers[vert_buf->id()] = vert_buf;
} else {
THROW_VAO_ERROR("Attempting to add identical VBO id of " + std::to_string(vert_id) + ".");
}
}
void VAOManager::changeEBO(BufferManagerPointer ebo) {
_elmt_buffer = ebo;
}
VertexAttributeList VAOManager::addVertexAttributes(const VertexAttributeList& vert_attrs) {
VertexAttributeList curr_vas = _vert_attrs;
curr_vas.insert(curr_vas.end(), vert_attrs.begin(), vert_attrs.end());
try {
throw checkValid(curr_vas);
} catch (VAOError vaoe) {
if (vaoe.error) {
THROW_VAO_ERROR(vaoe.what());
}
}
_vert_attrs = curr_vas;
generate();
return _vert_attrs;
}
VertexAttributeList VAOManager::addVertexAttributes(VertexAttribute vert_attr) {
return addVertexAttributes({vert_attr});
}
VertexAttributeList VAOManager::generate() {
bind();
unsigned int num_attrs = _vert_attrs.size();
VertexAttribute* va;
for (int i = 0; i < num_attrs; ++i) {
va = &(_vert_attrs[i]);
_vert_buffers[va->ptr.buffer]->bind();
glVertexAttribPointer(
i,
va->GLSLSize,
va->GLSLType,
va->GLSLNormalization,
va->ptr.stride,
(void*)va->ptr.offset
);
glVertexAttribDivisor(i, va->ptr.divisor);
glEnableVertexAttribArray(i);
}
if (_elmt_buffer != nullptr) {
_elmt_buffer->bind();
}
unbind();
return _vert_attrs;
}
VertexAttributeList VAOManager::generate(VertexAttributeList vert_attrs) {
try {
throw checkValid(vert_attrs);
} catch (VAOError vaoe) {
if (vaoe.error) {
THROW_VAO_ERROR(vaoe.what());
}
}
_vert_attrs.swap(vert_attrs);
return generate();
}
VertexAttributeList VAOManager::changeLayout(unsigned int i, VertexAttributePointer vap) {
_vert_attrs[i].ptr = vap;
bind();
const VertexAttribute* va = &(_vert_attrs[i]);
glDisableVertexAttribArray(i);
_vert_buffers[va->ptr.buffer]->bind();
glVertexAttribPointer(
_id,
va->GLSLSize,
va->GLSLType,
va->GLSLNormalization,
va->ptr.stride,
(void*)va->ptr.offset
);
glVertexAttribDivisor(i, va->ptr.divisor);
glEnableVertexAttribArray(i);
unbind();
return _vert_attrs;
}
VAOError VAOManager::checkValid(const VertexAttributeList& vert_attrs) {
GLuint va_id;
unsigned int num_attrs = vert_attrs.size();
for (int i = 0; i < num_attrs; ++i) {
va_id = vert_attrs[i].ptr.buffer;
if (_vert_buffers.find(va_id) == _vert_buffers.cend()) {
return VAOError("Attempting to point to unknown VBO of id " + std::to_string(va_id) +
" at Vertex Attribute " + std::to_string(i) + ".");
}
if (vert_attrs[i].ptr.stride<0) {
return VAOError("Invalid stride value at Vertex Attribute " + std::to_string(i) + ".");
}
}
return VAOError(false);
}
} // namespace NB

View File

@ -0,0 +1,251 @@
#include "VertexArray.hpp"
namespace nb {
using VAOErrorCodes = VAOError::Codes;
const std::string VAOError::type = "nb::VAOError";
const ErrorCodeMap VAOError::ErrorMessages = {
{ VAOErrorCodes::UNDEFINED, "Error" },
{ VAOErrorCodes::INVALID_ATTRIBUTE, "Targeting invalid attribute"}
};
using VertexCodes = VertexError::Codes;
const std::string VertexError::type = "nb::VertexError";
const ErrorCodeMap VertexError::ErrorMessages = {
{ VertexError::UNDEFINED, "Error" },
{ VertexError::MISALIGNED_DATA, "Data does not match vertex layout"}
};
VAO::VAO(const VertexAttributePointerList& attr_ptrs) {
attributes(attr_ptrs);
}
VAO::VAO(VAO&& other) {
*this = std::move(other);
}
VAO& VAO::operator=(VAO&& rhs) {
OpenGLObject::operator=(std::move(rhs));
_attrs = rhs._attrs;
rhs._attrs = {};
return *this;
}
VertexAttributePointerList VAO::attributes() const {
return _attrs;
}
VertexAttributePointerList VAO::attributes(const VertexAttributePointerList& attrs_) {
declare();
disable();
_attrs = attrs_;
bind();
for (auto attr_ptr : attrs_) {
glBindBuffer(GL_ARRAY_BUFFER, attr_ptr.buffer);
GLuint idx = attr_ptr.index;
glVertexAttribPointer(
idx,
attr_ptr.attribute.GLSLSize,
attr_ptr.attribute.GLSLType,
attr_ptr.attribute.GLSLNormalization,
attr_ptr.attribute.layout.stride,
(void*)attr_ptr.attribute.layout.offset
);
glEnableVertexAttribArray(idx);
}
unbind();
return _attrs;
}
VertexAttributePointer VAO::attr(GLuint idx) const {
for (auto attr_ptr : _attrs) {
if (idx == attr_ptr.index) {
return attr_ptr;
}
}
THROW(VAOError(Codes::INVALID_ATTRIBUTE));
}
void VAO::enable() const {
if (_id) {
bind();
for(auto attr_ptr : _attrs) {
glEnableVertexAttribArray(attr_ptr.index);
}
unbind();
}
}
void VAO::enable(GLuint idx) const {
if(_id) {
bind();
glEnableVertexAttribArray(attr(idx).index);
unbind();
}
}
void VAO::disable() const {
if(_id) {
bind();
for(auto attr_ptr : _attrs) {
glDisableVertexAttribArray(attr_ptr.index);
}
unbind();
}
}
void VAO::disable(GLuint idx) const {
if(_id) {
bind();
glDisableVertexAttribArray(attr(idx).index);
unbind();
}
}
VertexGroup::VertexGroup(VertexGroup&& other) {
*this = std::move(other);
}
VertexGroup& VertexGroup::operator=(VertexGroup&& rhs) {
_vertex_data = rhs._vertex_data;
_ebo = rhs._ebo;
_vao = rhs._vao;
rhs._vertex_data = {};
rhs._ebo = nullptr;
rhs._vao = nullptr;
return *this;
}
void VertexGroup::draw() const {
bind();
glDrawElements(primitive, _ebo->size(), _ebo->glslType(), 0);
}
size_t VertexGroup::addBuffer(const VertexData& vertex_data_) {
VertexData data = vertex_data_;
_vertex_data.emplace_back(data);
VertexAttributePointerList attrs = _vao->attributes();
GLuint idx = attrs.size();
for (const auto& attr : data.attrs) {
attrs.emplace_back(
VertexAttributePointer{attr, data.vbo->id(),idx}
);
idx++;
}
_vao->attributes(attrs);
return _vertex_data.size();
}
size_t VertexGroup::addBuffer(const ByteVector& data_, const VertexAttributeList& attrs_) {
return addBuffer({
std::make_shared<VBO>(data_),
attrs_
});
}
VertexData VertexGroup::getBuffers(size_t idx) {
return _vertex_data[idx];
}
VertexDataVec VertexGroup::getBuffers() {
return _vertex_data;
}
size_t VertexGroup::setBuffers(const VertexDataVec& vertex_data_) {
_vertex_data = vertex_data_;
VertexAttributePointerList attr_ptrs;
GLuint idx = 0;
for (const auto& data : _vertex_data) {
for (const auto& attr : data.attrs) {
attr_ptrs.emplace_back(
VertexAttributePointer{attr, data.vbo->id(), idx}
);
idx++;
}
}
_vao->attributes(attr_ptrs);
return _vertex_data.size();
}
VertexDataVec VertexGroup::dropBuffers() {
auto ret = _vertex_data;
setBuffers({});
return ret;
}
VertexData VertexGroup::dropBuffer(size_t idx) {
if (idx >= _vertex_data.size()) {
THROW(NBError(NBError::INDEX_ERROR));
}
VertexDataVec tmp;
VertexData ret;
size_t i = 0;
for (auto buf : _vertex_data) {
if (i == idx) {
ret = tmp[idx];
} else {
tmp.emplace_back(buf);
}
i++;
}
setBuffers(tmp);
return ret;
}
VertexAttributePointer VertexGroup::attribute(size_t idx_) const {
return _vao->attr(idx_);
}
void VertexGroup::enableAttr(GLuint idx) {
bind();
_vao->enable(idx);
unbind();
}
void VertexGroup::disableAttr(GLuint idx) {
bind();
_vao->disable(idx);
unbind();
}
void VertexGroup::disableBuffer(size_t idx) {
auto buf_idx = _vertex_data[idx].vbo->id();
bind();
for (auto attr : _vao->attributes()) {
if (attr.buffer == buf_idx) {
_vao->disable(attr.index);
}
}
unbind();
}
void VertexGroup::enableBuffer(size_t idx) {
auto buf_idx = _vertex_data[idx].vbo->id();
bind();
for (auto attr : _vao->attributes()) {
if (attr.buffer == buf_idx) {
_vao->enable(attr.index);
}
}
unbind();
}
void VertexGroup::enable() { _vao->enable(); }
void VertexGroup::disable() { _vao->disable(); }
std::shared_ptr<EBO> VertexGroup::indices() const { return _ebo; }
std::shared_ptr<EBO> VertexGroup::indices(const std::vector<uint32_t>& data) {
_ebo->data(data);
return _ebo;
}
std::shared_ptr<EBO> VertexGroup::indices(std::shared_ptr<EBO> buffer) {
_ebo = buffer;
return _ebo;
}
} // namespace nb

View File

@ -16,9 +16,23 @@ static std::map<int, int> defailt_window_hints = {
#endif #endif
}; };
GLError::GLError(const std::string& msg) : std::runtime_error(msg) {} using OpenGLErrorCodes = OpenGLError::Codes;
const std::string OpenGLError::type = "nb::OpenGLError";
const ErrorCodeMap OpenGLError::ErrorMessages = {
{OpenGLErrorCodes::UNDEFINED, "Error"},
{OpenGLErrorCodes::INIT_FAILED, "GLFW initialization failed"},
{OpenGLErrorCodes::GLFW_INTIALIZED, "GLFW has already been initialized"},
{OpenGLErrorCodes::GLAD_FAILED, "GLAD initialization failed"}
};
WindowError::WindowError(const std::string &msg) : std::runtime_error(msg) {} using WindowErrorCodes = WindowError::Codes;
const std::string WindowError::type = "nb::WindowError";
const ErrorCodeMap WindowError::ErrorMessages = {
{WindowErrorCodes::UNDEFINED, "Error"},
{WindowErrorCodes::INITIALIZED_WINDOW, "Window already initialized"},
{WindowErrorCodes::NO_GLFW, "GLFW has not been initialized"},
{WindowErrorCodes::INIT_FAILED, "Could not intialized window"}
};
int Window::getGLFWHint(int hint_key) { int Window::getGLFWHint(int hint_key) {
if (GLFWHints.find(hint_key) == GLFWHints.end()) { if (GLFWHints.find(hint_key) == GLFWHints.end()) {
@ -30,7 +44,7 @@ int Window::getGLFWHint(int hint_key) {
int Window::setGLFWHint(int hint_key, int hint_val) { int Window::setGLFWHint(int hint_key, int hint_val) {
if (Window::_glfw_init) { if (Window::_glfw_init) {
throw GLError("Cannot set GLFW hint after window is initialized."); THROW(OpenGLError(OpenGLErrorCodes::GLFW_INTIALIZED));
} else { } else {
GLFWHints[hint_key] = hint_val; GLFWHints[hint_key] = hint_val;
} }
@ -60,7 +74,7 @@ Window::Window(const uint16_t x, const uint16_t y, const char* initName, GLFWmon
Window::_glfw_init = true; Window::_glfw_init = true;
} else { } else {
if (Window::StrictInitialization) { if (Window::StrictInitialization) {
throw GLError("Failed to load GLFW with glfwInit()="+std::to_string(glfwResponse)+"."); THROW(OpenGLError(OpenGLErrorCodes::INIT_FAILED));
} }
} }
} }
@ -103,7 +117,7 @@ int Window::getWindowHint(int hint_key) const {
int Window::setWindowHint(int hint_key, int hint_val) { int Window::setWindowHint(int hint_key, int hint_val) {
if (_init) { if (_init) {
throw WindowError("Cannot set window hint after window is initialized."); THROW(WindowError(WindowErrorCodes::INITIALIZED_WINDOW));
} else { } else {
windowHints[hint_key] = hint_val; windowHints[hint_key] = hint_val;
} }
@ -112,7 +126,7 @@ int Window::setWindowHint(int hint_key, int hint_val) {
int Window::init() { int Window::init() {
if (!_glfw_init) { if (!_glfw_init) {
throw GLError("GLFW has not been initialized."); THROW(WindowError(WindowErrorCodes::NO_GLFW));
} }
for (const auto& hint : windowHints) { for (const auto& hint : windowHints) {
glfwWindowHint(hint.first, hint.second); glfwWindowHint(hint.first, hint.second);
@ -123,7 +137,7 @@ int Window::init() {
Window::WindowContexts.erase(window); Window::WindowContexts.erase(window);
if (Window::WindowContexts.size()==0 && Window::_glfw_init) { glfwTerminate(); } if (Window::WindowContexts.size()==0 && Window::_glfw_init) { glfwTerminate(); }
if (Window::StrictInitialization) { if (Window::StrictInitialization) {
throw WindowError("Could not create window in glfwCreateWindow()."); THROW(WindowError(WindowErrorCodes::INIT_FAILED));
} }
} }
glfwMakeContextCurrent(window); glfwMakeContextCurrent(window);
@ -133,10 +147,7 @@ int Window::init() {
if (!gladResponse) { if (!gladResponse) {
Window::checkKillGLFW(); Window::checkKillGLFW();
if (Window::StrictInitialization) { if (Window::StrictInitialization) {
throw GLError("Failed to load GLAD with \ THROW(OpenGLError(OpenGLErrorCodes::GLAD_FAILED));
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)="+\
std::to_string(gladResponse)+"."
);
} }
} }

View File

@ -1,742 +0,0 @@
#include "Shader.h"
// #define _PREPROC_FUNC_PARAM_NAMES_ (const ShaderPreprocessor& proc, ShaderUnit& shad, unsigned int linenum, const std::string& line, std::vector<uint8_t>& params)
namespace NB{
File::FilePath get_file_path(std::string name) {
const std::vector<char> allowed_special_chars = {
'.', '!', '#', '$', '%', '&', '\'', '(', ')', '+', ',', '-', ';', '=', '@', '[', ']', '^', '_', '`', '~'
};
std::vector<std::string> path = {""};
for (const char c : name) {
if (c == '/' || c == '\\') {
path.push_back("");
} else if (std::isalnum(c)) {
path.back() += c;
} else {
bool spec_char_found = false;
for (const char sc : allowed_special_chars) {
if (c == sc) {
path.back() += c;
spec_char_found = true;
break;
}
}
if (!spec_char_found) {
throw std::runtime_error("'" + name + "' is not valid filepath.");
}
}
}
File::FilePath ret;
for (const auto& tk : path) {
if (tk == path.back()) {
size_t period = tk.find(".");
if (period == std::string::npos) {
ret.basename = tk;
ret.ext = "";
} else {
ret.basename = tk.substr(0, period);
ret.ext = tk.substr(period);
}
} else {
ret.dir += tk + "/";
}
}
return ret;
}
// ShaderPreprocessorError class
ShaderPreprocessorError::ShaderPreprocessorError(
const std::string& msg,
const std::string& file,
int line
) : code(Codes::UNDEFINED), std::runtime_error(formatDebugString(msg, file, line)) {}
ShaderPreprocessorError::ShaderPreprocessorError(
Codes err_code,
const std::string& arg,
const std::string& file,
int line
) : code(err_code), std::runtime_error(formatDebugString(errorCodeParser(err_code, arg), file, line)) {}
std::string ShaderPreprocessorError::errorCodeParser(Codes err_code, const std::string& arg) {
switch(err_code) {
case Codes::FILE_NOT_FOUND:
return "File '" + arg + "' not found.";
case Codes::BUILTIN_NOT_FOUND:
return "Built-in '" + arg + "' not found.";
case Codes::CUSTOM:
case Codes::UNDEFINED:
return arg;
case Codes::NONE:
default:
return "";
}
}
// ShaderError class
ShaderError::ShaderError(
const std::string& msg,
const char* shad,
const std::string& file,
int line
) : std::runtime_error(formatString(msg, shad, file, line)) {}
std::string ShaderError::formatString(
const std::string& msg,
const char* shad,
const std::string& file,
int line
) {
std::stringstream ret;
if (file != "") {
ret << "In file " << file;
if (line >= 0) {
ret << " at line " << line;
}
ret << ":\n\t";
}
ret << msg;
if (shad != nullptr) {
ret << " with shader error: " << shad;
}
return ret.str();
}
// ShaderPreprocessor class
std::string ShaderPreprocessor::TokenName(const ShaderPreprocessor::TokenType& x) {
switch(x) {
case TK:
return "Token";
break;
case DR:
return "Directive";
break;
case WS:
return "Whitespace";
break;
case NL:
return "NewLine";
break;
case LC:
return "LineComment";
break;
case BC:
return "BlockComment";
break;
default:
return "Unrecognized";
break;
}
}
ShaderPreprocessor::ShaderPreprocessor() {}
File ShaderPreprocessor::loadFromBase(const std::string path, const std::string base) const {
File ret;
std::ifstream filestream;
filestream.open(base + path);
if (filestream.is_open()) {
ret.path = get_file_path(base + path);
ret.src << filestream.rdbuf();
return ret;
}
filestream.close();
std::string ext;
for (const auto& kv : AcceptedExtensions) {
ext = kv.first;
filestream.open(base + path + ext);
if (filestream.is_open()) {
ret.path = get_file_path(base + path + ext);
ret.src << filestream.rdbuf();
return ret;
}
filestream.close();
}
throw ShaderPreprocessorError(Codes::FILE_NOT_FOUND, base + path);
}
File ShaderPreprocessor::loadFromDirectories(const std::string name) const {
File ret;
std::ifstream fstream;
for (const std::string& path : Directories) {
fstream.open(path + name);
if (fstream.is_open()) {
ret.path = get_file_path(path + name);
ret.src << fstream.rdbuf();
return ret;
}
fstream.close();
}
throw ShaderPreprocessorError(Codes::FILE_NOT_FOUND, name);
}
File ShaderPreprocessor::load(const std::string path, bool builtin_first) const {
if(builtin_first) {
return load_BuiltInFirst(path);
}
return load_FilesFirst(path);
}
File ShaderPreprocessor::loadFromBuiltIn(const std::string name) const {
File ret;
//std::stringstream ret;
decltype(BuiltIns)::const_iterator builtin_it = BuiltIns.find(name);
if (builtin_it != BuiltIns.end()) {
ret.path = File::FilePath{"builtin:", name, ""};
ret.src << builtin_it->second;
return ret;
}
throw ShaderPreprocessorError(Codes::BUILTIN_NOT_FOUND, name);
}
File ShaderPreprocessor::load_FilesFirst(const std::string path) const {
try {
return loadFromBase(path);
} catch (ShaderPreprocessorError e) {
if (e.code == Codes::FILE_NOT_FOUND) {
try {
return loadFromDirectories(path);
} catch (ShaderPreprocessorError f) {
if (f.code == Codes::FILE_NOT_FOUND) {
try {
return loadFromBuiltIn(path);
} catch(ShaderPreprocessorError g) {
if (g.code == Codes::BUILTIN_NOT_FOUND) {
throw ShaderPreprocessorError(Codes::FILE_NOT_FOUND, path);
} else { throw g; }
}
} else { throw f; }
}
} else { throw e; }
}
}
File ShaderPreprocessor::load_BuiltInFirst(const std::string path) const {
try {
return loadFromBuiltIn(path);
} catch (ShaderPreprocessorError f) {
if (f.code == Codes::BUILTIN_NOT_FOUND) {
try {
return loadFromDirectories(path);
} catch (ShaderPreprocessorError e) {
if (e.code == Codes::FILE_NOT_FOUND) {
return loadFromBase(path);
} else {
throw e;
}
}
} else {
throw f;
}
}
}
std::vector<ShaderPreprocessor::Token> ShaderPreprocessor::tokenize(const std::string& code) const {
enum State {
FSlash,
WhiteSpace,
LineComment,
BlockComment,
BlockCommentEndStar,
Directive,
Token
};
std::vector<ShaderPreprocessor::Token> tks;
std::string token = "";
State state = WhiteSpace;
for(char c : code) {
if (c==13) {
continue;
}
switch(state) {
case WhiteSpace:
if (c=='/') {
if (token != "") { tks.push_back({WS, token}); }
token = c;
state = FSlash;
} else if (c=='#') {
if (token != "") { tks.push_back({WS, token}); }
token = c;
state = Directive;
} else if (c=='\n') {
if (token != "") { tks.push_back({WS, token}); }
tks.push_back({NL, "\n"});
token = "";
state = WhiteSpace;
} else if (std::isblank(c)) {
token += c;
} else {
if (token != "") { tks.push_back({WS, token}); }
token = c;
state = Token;
}
break;
case FSlash:
if (c=='/') {
token += c;
state = LineComment;
} else if (c=='*') {
token += c;
state = BlockComment;
} else if (c=='\n') {
tks.push_back({TK, token});
tks.push_back({NL, "\n"});
token = "";
state = WhiteSpace;
} else if (std::isblank(c)) {
tks.push_back({TK, token});
token = c;
}else {
token += c;
state = Token;
}
break;
case LineComment:
if (c=='\n') {
tks.push_back({LC, token});
tks.push_back({NL, "\n"});
token = "";
state = WhiteSpace;
} else {
token += c;
}
break;
case BlockComment:
token += c;
if (c=='*') {
state = BlockCommentEndStar;
}
break;
case BlockCommentEndStar:
token += c;
if (c=='/') {
tks.push_back({BC, token});
token = "";
state = WhiteSpace;
} else {
state = BlockComment;
}
break;
case Directive:
if (c=='\n') {
tks.push_back({DR, token});
tks.push_back({NL, "\n"});
token = "";
state = WhiteSpace;
} else if (c=='/') {
tks.push_back({DR, token});
token = c;
state = FSlash;
} else {
token += c;
}
break;
case Token:
if (c=='\n') {
tks.push_back({TK, token});
tks.push_back({NL, "\n"});
token = "";
state = WhiteSpace;
} else if (std::isblank(c)) {
tks.push_back({TK, token});
token = c;
state = WhiteSpace;
} else if (c=='/') {
tks.push_back({TK, token});
token = c;
state = FSlash;
}else {
token += c;
}
break;
default:
break;
}
}
switch(state) {
case WhiteSpace:
if (token != "") { tks.push_back({WS, token}); }
case FSlash:
tks.push_back({TK, token});
break;
case LineComment:
tks.push_back({LC, token});
break;
case BlockComment:
case BlockCommentEndStar:
tks.push_back({BC, token});
break;
case Directive:
tks.push_back({DR, token});
break;
case Token:
tks.push_back({TK, token});
break;
default:
break;
}
return tks;
}
ShaderUnit& ShaderPreprocessor::preprocess(const std::string& code, ShaderUnit& shad) const {
typedef ShaderPreprocessor::Token Token;
std::vector<Token> tks = tokenize(code);
for (int i{0}; i < tks.size(); ++i) {
switch(tks[i].first) {
case DR:
directive_dispatch(shad, tks[i].second);
break;
case TK:
case NL:
case LC:
case BC:
case WS:
default:
shad.preprocSource += tks[i].second;
break;
}
}
if (shad.vMajor == 0 && shad.vMinor == 0) {
shad.vMajor = 1;
shad.vMinor = 10;
}
return shad;
}
ShaderUnit ShaderPreprocessor::preprocess(File file, GLenum shader_type) const {
ShaderUnit ret;
ret.file = file;
if (shader_type) {
ret.type = shader_type;
} else {
decltype(AcceptedExtensions.begin()) find_type = AcceptedExtensions.find(file.path.ext);
if (find_type != AcceptedExtensions.end()) {
ret.type = find_type->second;
}
}
preprocess(file.src.str(), ret);
return ret;
}
ShaderUnit ShaderPreprocessor::preprocess(const std::string& code, GLenum shader_type) const {
File local;
local.path = File::FilePath{"live:", "live", ".shad"};
return preprocess(local, shader_type);
}
ShaderProgram ShaderPreprocessor::CreateShaderProgram(std::vector<std::string> shads) const {
std::vector<ShaderUnit> _shader_units;
for (const auto& name : shads) {
_shader_units.push_back(preprocess(load(name)));
}
return ShaderProgram::CreateShaderProgram(_shader_units);
}
ShaderProgram ShaderPreprocessor::ReloadFromFile(const ShaderProgram& rhs) const {
std::vector<std::string> shader_names;
shader_names.reserve(rhs._shader_units.size());
std::string filename;
for (const ShaderUnit& shad : rhs._shader_units) {
filename = shad.file.path.dir + shad.file.path.basename + shad.file.path.ext;
shader_names.emplace_back(filename);
}
return CreateShaderProgram(shader_names);
}
bool ShaderPreprocessor::directive_dispatch(ShaderUnit& shad, const std::string& line) const {
StringVec dir_tks = {""};
for (char c : line) {
if (std::isblank(c)) {
if (dir_tks.back() != "") {
dir_tks.push_back("");
}
} else {
dir_tks.back() += c;
}
}
if (!dir_tks.size()) { return false; }
if (dir_tks[0][0] != '#') { return false; }
if (dir_tks[0] == "#define") {
return preprocessor_define(shad, dir_tks, line);
} else if (dir_tks[0] == "#version") {
return preprocessor_version(shad, dir_tks, line);
} else if (dir_tks[0] == "#include") {
return preprocessor_include(shad, dir_tks, line);
}
return false;
}
typedef std::vector<std::string> StringVec;
bool ShaderPreprocessor::preprocessor_include(
ShaderUnit& shad,
const StringVec& tokens,
const std::string& line
) const
{
try {
if (tokens[0] != "#include") { return false; }
} catch (std::out_of_range e) {
return false;
}
std::string path = "";
for (const auto& tk : tokens) {
if (tk != tokens.front()) {
path += tk;
}
}
// Add file-inclusion base +
// Do path cleanup +
// Restructure preprocessing data flow
std::string filename = path.substr(1, path.size()-2);
try {
if (path[0] == '"' && path.back() == '"') {
preprocess(load(filename).src.str(), shad);
return true;
} else if (path[0] == '<' && path.back() == '>') {
preprocess(load(filename, true).src.str(), shad);
return true;
}
} catch (ShaderPreprocessorError e) {
if (e.code == Codes::FILE_NOT_FOUND) {
std::cout << "COULD NOT FIND " << filename << ".\n";
} else {
throw e;
}
}
return false;
}
bool ShaderPreprocessor::preprocessor_define(ShaderUnit& shad, const StringVec& tokens, const std::string& line) const {
shad.preprocSource += line;
try {
if (tokens[0] != "#define") { return false; }
try {
shad.defines[tokens[1]] = tokens[2];
} catch (std::length_error& f) {
shad.defines[tokens[1]] = "";
}
return true;
} catch (std::out_of_range& e) {
return false;
}
}
bool ShaderPreprocessor::preprocessor_version(ShaderUnit& shad, const StringVec& tokens, const std::string& line) const {
shad.preprocSource += line;
std::cout << "Shader version: ";
try {
if (tokens[0] != "#version") { return false; }
if (tokens[1].size() == 3) {
short vMajor = tokens[1][0]-'0';
short vMinorA = tokens[1][1]-'0';
short vMinorB = tokens[1][2]-'0';
if (vMajor > 10 || vMinorA > 10 || vMinorB > 10) {
return false;
}
shad.vMajor = vMajor;
shad.vMinor = vMinorA*10 + vMinorB;
shad.profile = AcceptedProfiles.at(tokens[2]);
std::cout << shad.vMajor << "." << shad.vMinor << "\n";
return true;
} else {
return false;
}
} catch (std::out_of_range& e) {
return false;
}
}
/* bool ShaderPreprocessor::preprocessor_uniform(
ShaderUnit& shad,
const std::string& type,
const std::string& name
) const {
std::string type_str = "";
unsigned int type_str_len = 0;
for (const char& c : type) {
if (type_str_len) {
if (std::isdigit(c)) {
type_str += c;
continue;
} else if (c=='[') {
type_str += '_';
}else if (c == ']' || std::isblank(c)){
continue;
} else {
return false;
}
} else {
if (std::isalnum(c)) {
type_str += c;
continue;
} else if (c == '[') {
type_str_len = type_str.length();
type_str += '_';
continue;
} else {
return false;
}
}
}
std::string name_str = "";
unsigned int name_str_len = 0;
for (const char& c : name) {
if (c == ';') {
break;
}
if (name_str_len) {
if (std::isdigit(c)) {
type_str.insert(type_str_len, 1, c);
type_str_len++;
continue;
} else if (c=='[') {
type_str.insert(type_str_len, "_");
type_str_len++;
continue;
}else if (c == ']' || std::isblank(c)){
continue;
} else {
return false;
}
} else {
if (std::isalnum(c)) {
name_str += c;
continue;
} else if ( c == '[') {
name_str_len = name_str.length();
type_str.insert(type_str_len, "_");
type_str_len++;
continue;
} else {
return false;
}
}
}
shad.uniforms.push_back(UniformHandle{
name_str,
type_str,
0x0,
0x0
});
return true;
} */
// ShaderProgram
ShaderProgram::ShaderProgram(ShaderProgram&& rhs) {
_shader_units = rhs._shader_units;
_id = rhs._id;
rhs._id = 0;
}
ShaderProgram::~ShaderProgram() {
glDeleteProgram(_id);
}
ShaderProgram& ShaderProgram::operator=(ShaderProgram&& rhs) {
_shader_units = rhs._shader_units;
_id = rhs._id;
rhs._id = 0;
return *this;
}
ShaderProgram ShaderProgram::CreateShaderProgram(std::vector<ShaderUnit>& shaders) {
int success;
ShaderProgram ret(shaders);
char infoLog[512];
unsigned int shad_id;
std::vector<unsigned int> shad_ids;
shad_ids.reserve(shaders.size());
for (auto& shad : ret._shader_units) {
const char* source = shad.preprocSource.data();
shad_id = glCreateShader(shad.type);
shad_ids.emplace_back(shad_id);
glShaderSource(shad_id, 1, &source, NULL);
glCompileShader(shad_id);
glGetShaderiv(shad_id, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(shad_id, 512, NULL, infoLog);
File::FilePath& fp = shad.file.path;
std::string filename = fp.dir + fp.basename + fp.ext;
// std::cout << "Could not compile '" + filename + "': " << infoLog << "\n";
// return *ret;
throw ShaderError("Could not compile '" + filename + "'.", infoLog);
}
}
ret._id = glCreateProgram();
for(auto& id : shad_ids) {
glAttachShader(ret._id, id);
}
glLinkProgram(ret._id);
glGetProgramiv(ret._id, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(ret._id, 512, NULL, infoLog);
throw ShaderError("Could not link shader program.", infoLog);
}
for (auto& id : shad_ids) {
glDeleteShader(id);
}
return ret;
}
unsigned int ShaderProgram::id() const { return _id; }
void ShaderProgram::use() const {
glUseProgram(_id);
}
std::vector<ShaderUnit> ShaderProgram::getShaders() const {
return _shader_units;
}
ShaderUnit ShaderProgram::getShaders(unsigned int idx) const {
return _shader_units[idx];
}
void ShaderProgram::setBool(const std::string& name, bool value) const {
glUniform1i(glGetUniformLocation(_id, name.c_str()), (int)value);
}
void ShaderProgram::setInt(const std::string& name, int value) const {
glUniform1i(glGetUniformLocation(_id, name.c_str()), (int)value);
}
void ShaderProgram::setFloat(const std::string& name, float value) const {
glUniform1f(glGetUniformLocation(_id, name.c_str()), (int)value);
}
void ShaderProgram::setMat4(const std::string& name, glm::mat4& value) const {
glUniformMatrix4fv(glGetUniformLocation(_id, name.c_str()), 1, GL_FALSE, glm::value_ptr(value));
}
/* // Shader class
Shader::Shader() { _id = 0x0; }
Shader::Shader(const Shader& cpy_shader) { _id = cpy_shader._id; }
Shader& Shader::operator=(const Shader& cpy_shader) { _id = cpy_shader._id; return *this; }
void Shader::use() const{
glUseProgram(_id);
}
*/
}

View File

@ -0,0 +1,26 @@
cmake_minimum_required(VERSION 3.26.0)
if (NB_BUILD_TESTS)
enable_testing()
include(GoogleTest)
add_executable(TestWindow
./TestWindow.cpp
)
target_link_libraries(TestWindow
NBCore
NBGraphics
)
add_executable(TestImages
./testImages.cpp
)
target_link_libraries(TestImages
NBCore
NBGraphics
GTest::gtest_main
)
gtest_discover_tests(TestImages)
endif()

View File

@ -0,0 +1,107 @@
#include "GLLoad.hpp"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "Image.hpp"
#include "ProgramPipeline.hpp"
#include "VertexArray.hpp"
#include "Window.hpp"
#include "Textures.hpp"
int main() {
nb::logger.log("Howdy!");
nb::Window window(400, 400, "Hello!");
window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
window.init();
auto vert = std::make_shared<nb::Shader>(
GL_VERTEX_SHADER,
"#version 330 core\n"
"layout (location = 0) in vec2 aPos;\n"
"layout (location = 1) in vec2 tPos;\n"
"out vec2 vPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);\n"
" vPos = tPos;\n"
"}\0"
);
LOG(vert->log());
auto frag = std::make_shared<nb::Shader>(
GL_FRAGMENT_SHADER,
"#version 330 core\n"
"in vec2 vPos;\n"
"out vec4 FragColor;\n"
"uniform sampler2D tex;\n"
"void main()\n"
"{\n"
" FragColor = texture(tex, vPos);\n"
"}\n\0"
);
LOG(frag->log());
nb::ByteVector data = nb::vectorToBytes<float>({
-0.5, -0.5, 0,0,
-0.5, 0.5, 0,1,
0.5, 0.5, 1,1,
0.5, -0.5, 1,0
});
nb::Program prog({vert, frag});
prog.bind();
std::vector<uint32_t> indxs = {0, 1, 2, 0, 2, 3};
nb::VertexGroup tri(data, {
nb::VertexAttribute{
2,
GL_FLOAT,
false,
{0, 16}
},
nb::VertexAttribute{
2,
GL_FLOAT,
false,
{8, 16}
}
}, indxs);
tri.bind();
int width, height, numChannels;
auto raw_img_data = stbi_load(
"./awesomeface.png",
&width,
&height,
&numChannels,
0
);
LOG(numChannels);
using RGBA = nb::Pixel<uint8_t, nb::Red, nb::Green, nb::Blue, nb::Alpha>;
nb::ImageReference<RGBA> img(width, height, raw_img_data);
auto tex = nb::ImageTexture<RGBA>();
tex.parameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
tex.parameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
tex.setImage(img);
tex.bind();
tri.bind();
LOG(img.at(256, 256).r);
stbi_image_free(raw_img_data);
LOG(prog.log());
GLFWwindow* window_ptr = window.getWindow();
while(!glfwWindowShouldClose(window_ptr)) {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
tri.draw();
glfwPollEvents();
glfwSwapBuffers(window_ptr);
}
return 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

View File

@ -0,0 +1,156 @@
#include <gtest/gtest.h>
#include <vector>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "Image.hpp"
TEST(TestImage, SinglePixel) {
using RGB = nb::Pixel<uint8_t, nb::Red, nb::Green, nb::Blue>;
RGB p1;
p1.r = 0x00;
p1.g = 0x0F;
p1.b = 0xFF;
ASSERT_EQ(p1.r, 0x00);
ASSERT_EQ(p1.g, 0x0F);
ASSERT_EQ(p1.b, 0xFF);
RGB p2(p1);
ASSERT_EQ(p2.r, 0x00);
ASSERT_EQ(p2.g, 0x0F);
ASSERT_EQ(p2.b, 0xFF);
RGB p3(0xA, 0xB, 0xC);
ASSERT_EQ(p3.r, 0xA);
ASSERT_EQ(p3.g, 0xB);
ASSERT_EQ(p3.b, 0xC);
RGB p4 = p3;
ASSERT_EQ(p4.r, 0xA);
ASSERT_EQ(p4.g, 0xB);
ASSERT_EQ(p4.b, 0xC);
RGB p5(0xA0, 0xB0, 0xC0);
ASSERT_EQ(p5.r, 0xA0);
ASSERT_EQ(p5.g, 0xB0);
ASSERT_EQ(p5.b, 0xC0);
using RBAG = nb::Pixel<float,
nb::Red, nb::Blue, nb::Alpha, nb::Green
>;
float a=0.5, b=0.4, c=0.0, d=0.3;
RBAG p6 = {a, b, c, d};
ASSERT_EQ(p6.r, a);
ASSERT_EQ(p6.b, b);
ASSERT_EQ(p6.a, c);
ASSERT_EQ(p6.g, d);
RBAG p7 = p6;
ASSERT_EQ(p7.r, a);
ASSERT_EQ(p7.b, b);
ASSERT_EQ(p7.a, c);
ASSERT_EQ(p7.g, d);
}
TEST(TestImage, PixelReference) {
using RGB = nb::Pixel<uint8_t, nb::Red, nb::Green, nb::Blue>;
using RGBRef = nb::PixelReference<RGB>;
using RBAG = nb::Pixel<float,
nb::Red, nb::Blue, nb::Alpha, nb::Green
>;
using RBAGRef = nb::PixelReference<RBAG>;
RGB p1{255, 254, 253};
RGBRef rp1(p1);
ASSERT_EQ(rp1.r, p1.r);
ASSERT_EQ(rp1.g, p1.g);
ASSERT_EQ(rp1.b, p1.b);
RGB p2{0xa, 0xb, 0xc};
rp1 = p2;
ASSERT_EQ(p1.r, p2.r);
ASSERT_EQ(p1.g, p2.g);
ASSERT_EQ(p1.b, p2.b);
RGB p3 = rp1;
ASSERT_EQ(p3.r, p1.r);
ASSERT_EQ(p3.g, p1.g);
ASSERT_EQ(p3.b, p1.b);
RGBRef rp2 = rp1;
rp2 = RGB(2, 4, 8);
ASSERT_EQ(p1.r, 2);
ASSERT_EQ(p1.g, 4);
ASSERT_EQ(p1.b, 8);
int val = 27;
rp1.b = val;
ASSERT_EQ(rp1.r, p1.r);
ASSERT_EQ(rp1.g, p1.g);
ASSERT_EQ(rp1.b, p1.b);
ASSERT_EQ(p1.b, val);
}
TEST(TestImage, SimpleImage) {
unsigned char data[] = {
0x00, 0x00,
0x00, 0xFF,
0xFF, 0x00,
0xFF, 0xFF
};
using RG = nb::Pixel<uint8_t, nb::Red, nb::Blue>;
nb::Image<RG> img(
2, 2, data
);
for (int i = 0; i < sizeof(data); ++i) {
ASSERT_EQ(img.data()[i], data[i]);
}
auto pixel = img.at(0, 1);
ASSERT_EQ(pixel.r, data[4]);
ASSERT_EQ(pixel.b, data[5]);
}
TEST(TestImage, LoadImage) {
int width, height, numChannels;
unsigned char* data = stbi_load(
"./awesomeface.png",
&width,
&height,
&numChannels,
0
);
using RGBA = nb::Pixel<unsigned char, nb::Red, nb::Green, nb::Blue, nb::Alpha>;
nb::Image<RGBA> img(
width, height, data
);
for(int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
auto pixel = img.at(j, i);
ASSERT_EQ(pixel.r, data[4*(i*width+j)]);
ASSERT_EQ(pixel.g, data[4*(i*width+j) + 1]);
ASSERT_EQ(pixel.b, data[4*(i*width+j) + 2]);
ASSERT_EQ(pixel.a, data[4*(i*width+j) + 3]);
}
}
stbi_image_free(data);
}
TEST(TestImage, ImageBounds) {
size_t len = 10;
uint8_t val = 0xAA;
std::vector<uint8_t> vec(2*len*len, val);
using RB = nb::Pixel<uint8_t, nb::Red, nb::Blue>;
nb::Image<RB> img(
len, len, vec.data()
);
for (int i=0; i < 15; ++i) {
if (i<len) {
auto pixel = img.at(len/2, i);
ASSERT_EQ(pixel.r, val);
ASSERT_EQ(pixel.b, val);
} else {
ASSERT_THROW(img.at(len/2, i), nb::ImageError);
ASSERT_THROW(img.at(i, len/2), nb::ImageError);
}
}
}