Compare commits

..

13 Commits

Author SHA1 Message Date
NaifBanana
ac671c3770 Uhhhhh big big changes 2026-08-20 08:13:26 -05:00
NaifBanana
3e7e6acc3a Made NBGraphics installable 2026-08-20 08:12:55 -05:00
NaifBanana
a9fbef13c6 Huge graphics overhaul 2026-08-20 08:12:55 -05:00
NaifBanana
b76f65e51f Forgot to actually compile the shader :P 2026-08-20 08:12:55 -05:00
NaifBanana
5b4ec4f047 Change invalid buffer binding to warning instead of error 2026-08-20 08:12:55 -05:00
NaifBanana
f3fd158e6f Added vertex buffers/data handling and shader/program handling 2026-08-20 08:12:54 -05:00
NaifBanana
d0d97c9985 Mild updates to Window and other pieces to match the rest 2026-08-20 08:12:54 -05:00
NaifBanana
d4620c3b00 Make VertexAttributePointer store index instead of buffer pointer 2026-08-20 08:12:54 -05:00
NaifBanana
9699ab3bd3 Made buildable now 2026-08-20 08:12:54 -05:00
NaifBanana
d527d2adc4 Large OpenGL Object handling overhaul 2026-08-20 08:12:54 -05:00
NaifBanana
91cdfc1754 Merge branch 'main' of https://git.naifb.com/naifb/NBEngine 2026-08-20 08:10:29 -05:00
NaifBanana
9628a75710 Better sinks, better loggers, etx 2026-08-20 08:08:20 -05:00
352a45bce0 Update README.md 2026-06-26 14:54:17 +00:00
35 changed files with 1150 additions and 586 deletions

View File

@ -9,6 +9,7 @@ set(CMAKE_CXX_EXTENSIONS OFF)
include(GNUInstallDirs) include(GNUInstallDirs)
include(CMakePackageConfigHelpers) include(CMakePackageConfigHelpers)
include(CMakeDependentOption)
function(toAbsolutePath SETVAR PATHS) function(toAbsolutePath SETVAR PATHS)
set(PATHS ${PATHS} ${ARGN}) set(PATHS ${PATHS} ${ARGN})
@ -31,13 +32,42 @@ if(CMAKE_BUILD_TYPE STREQUAL "Release")
message(STATUS "Targeting Release build") message(STATUS "Targeting Release build")
elseif(CMAKE_BUILD_TYPE STREQUAL "Debug") elseif(CMAKE_BUILD_TYPE STREQUAL "Debug")
message(STATUS "Targeting Debug build") message(STATUS "Targeting Debug build")
set(NB_LOGGING ON) set(NB_DEBUG_BUILD ON)
set(NB_BUILD_TESTS ON)
set(NB_BUILD_DOCS ON)
set(NBENGINE_INSTALL ON)
add_compile_definitions(_NB_BUILD_DEBUG) add_compile_definitions(_NB_BUILD_DEBUG)
endif() endif()
cmake_dependent_option(NB_LOGGING
"Creates a default logger and automatically logs with code locations."
ON
NB_DEBUG_BUILD
OFF
)
cmake_dependent_option(NB_BUILD_TESTS
"Build unit tests"
ON
NB_DEBUG_BUILD
OFF
)
cmake_dependent_option(NB_BUILD_DOCS
"Build documentation"
ON
NB_DEBUG_BUILD
OFF
)
cmake_dependent_option(NBENGINE_INSTALL
"Install NBEngine"
ON
NB_DEBUG_BUILD
OFF
)
cmake_dependent_option(NB_MONITOR_OPENGL_CALLS
"Monitors every OpenGL call for errors"
ON
NB_DEBUG_BUILD
OFF
)
if(CMAKE_SYSTEM_NAME STREQUAL "Windows") if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
message(STATUS "Building for Windows") message(STATUS "Building for Windows")
set(NB_TARGET_WINDOWS ON) set(NB_TARGET_WINDOWS ON)
@ -67,15 +97,16 @@ if (NB_LOGGING)
add_compile_definitions(_NB_CODE_ERROR_LOCATIONS) add_compile_definitions(_NB_CODE_ERROR_LOCATIONS)
endif() endif()
if (NB_TARGET_WINDOWS) if(NB_TARGET_WINDOWS)
add_compile_definitions(_NB_TARGET_WINDOWS) add_compile_definitions(_NB_TARGET_WINDOWS)
elseif (NB_TARGET_LINUX) endif()
if(NB_TARGET_LINUX)
add_compile_definitions(_NB_TARGET_LINUX) add_compile_definitions(_NB_TARGET_LINUX)
endif() endif()
get_filename_component(NBENGINE_ROOT ./ ABSOLUTE) get_filename_component(NBENGINE_ROOT ${CMAKE_CURRENT_LIST_DIR} ABSOLUTE)
add_subdirectory(./engine) add_subdirectory(./engine ${PROJECT_BINARY_DIR}/${CMAKE_BUILD_TYPE})
# Toggle # Toggle
set(NB_REBUILD_DOCS) set(NB_REBUILD_DOCS)
@ -84,22 +115,23 @@ if (NB_BUILD_DOCS)
add_subdirectory(./docs) add_subdirectory(./docs)
endif() endif()
if (NBENGINE_INSTALL) include(CMakePackageConfigHelpers)
include(GNUInstallDirs) configure_package_config_file(
include(CMakePackageConfigHelpers)
configure_package_config_file(
"NBEngineConfig.cmake.in" "NBEngineConfig.cmake.in"
"NBEngineConfig.cmake" "${PROJECT_BINARY_DIR}/cmake/NBEngineConfig.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
PATH_VARS CMAKE_INSTALL_LIBDIR PATH_VARS CMAKE_INSTALL_LIBDIR
) )
write_basic_package_version_file( write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/NBEngineConfigVersion.cmake" "${PROJECT_BINARY_DIR}/cmake/NBEngineConfigVersion.cmake"
COMPATIBILITY AnyNewerVersion COMPATIBILITY AnyNewerVersion
) )
if (NBENGINE_INSTALL)
include(GNUInstallDirs)
install(FILES install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/NBEngineConfig.cmake" "${PROJECT_BINARY_DIR}/cmake/NBEngineConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/NBEngineConfigVersion.cmake" "${PROJECT_BINARY_DIR}/cmake/NBEngineConfigVersion.cmake"
DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake" DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
) )
endif() endif()

View File

@ -4,6 +4,9 @@
These are subject to (hopefully) grow in size as more stuff gets added. These are subject to (hopefully) grow in size as more stuff gets added.
* NBCore: Core/foundational functionality for all other subpackages to be built upon.
* Erroring and Logging
* Basic data structures and declarations
* NBWindow: Creates and manages GLFW windows * NBWindow: Creates and manages GLFW windows
* NBEvents: Multithreading event manager. Very unstable. Sucks a lot. * NBEvents: Multithreading event manager. Very unstable. Sucks a lot.

View File

@ -3,17 +3,28 @@ add_subdirectory(./NBCore)
get_target_property(NBCORE_INTERFACE_INCLUDES NBCore INTERFACE_INCLUDE_DIRECTORIES) get_target_property(NBCORE_INTERFACE_INCLUDES NBCore INTERFACE_INCLUDE_DIRECTORIES)
include_directories(${NBCORE_INTERFACE_INCLUDES}) include_directories(${NBCORE_INTERFACE_INCLUDES})
add_subdirectory(./NBEvents) #add_subdirectory(./NBEvents)
add_subdirectory(./NBGraphics) add_subdirectory(./NBGraphics)
add_subdirectory(./NBData)
if (NB_CORE_SOURCE OR NB_EVENTS_SOURCE OR NB_GRAPHICS_SOURCE) if (NB_CORE_SOURCE OR NB_EVENTS_SOURCE OR NB_GRAPHICS_SOURCE OR NB_DATA_SOURCE)
set(NB_SOURCE_FILES "") set(NB_SOURCE_FILES "")
list(APPEND NB_SOURCE_FILES ${NB_CORE_SOURCE} ${NB_GRAPHICS_SOURCE} ${NB_EVENTS_SOURCE}) list(APPEND NB_SOURCE_FILES
${NB_CORE_SOURCE}
${NB_GRAPHICS_SOURCE}
${NB_EVENTS_SOURCE}
${NB_DATA_SOURCE}
)
set(NB_SOURCE_FILES ${NB_SOURCE_FILES} PARENT_SCOPE) set(NB_SOURCE_FILES ${NB_SOURCE_FILES} PARENT_SCOPE)
endif() endif()
if (NB_CORE_INCLUDE OR NB_EVENTS_INCLUDE OR NB_GRAPHICS_INCLUDE) if (NB_CORE_INCLUDE OR NB_EVENTS_INCLUDE OR NB_GRAPHICS_INCLUDE OR NB_DATA_INCLUDE)
set(NB_INCLUDE_FILES "") set(NB_INCLUDE_FILES "")
list(APPEND NB_INCLUDE_FILES ${NB_CORE_INCLUDE} ${NB_GRAPHICS_INCLUDE} ${NB_EVENTS_INCLUDE}) list(APPEND NB_INCLUDE_FILES
${NB_CORE_INCLUDE}
${NB_GRAPHICS_INCLUDE}
${NB_EVENTS_INCLUDE}
${NB_DATA_INCLUDE}
)
set(NB_INCLUDE_FILES ${NB_INCLUDE_FILES} PARENT_SCOPE) set(NB_INCLUDE_FILES ${NB_INCLUDE_FILES} PARENT_SCOPE)
endif() endif()

View File

@ -1,6 +1,13 @@
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.10)
project(NBCore VERSION 0.1) project(NBCore VERSION 0.1)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
toAbsolutePath(NB_CORE_SOURCE toAbsolutePath(NB_CORE_SOURCE
./src/ErrorsImpl.cpp ./src/ErrorsImpl.cpp
./src/Logger.cpp ./src/Logger.cpp
@ -14,6 +21,7 @@ toAbsolutePath(NB_CORE_INCLUDE
./include/NBCore/Errors.hpp ./include/NBCore/Errors.hpp
./include/NBCore/ErrorsImpl.hpp ./include/NBCore/ErrorsImpl.hpp
./include/NBCore/Logger.hpp ./include/NBCore/Logger.hpp
./include/NBCore/Printer.hpp
./include/NBCore/Processes.hpp ./include/NBCore/Processes.hpp
./include/NBCore/StringUtils.hpp ./include/NBCore/StringUtils.hpp
./include/NBCore/ThreadsafeQueue.hpp ./include/NBCore/ThreadsafeQueue.hpp
@ -28,45 +36,51 @@ set(NB_CORE_INCLUDE ${NB_CORE_INCLUDE} PARENT_SCOPE)
add_library(NBCore ${NB_CORE_SOURCE}) add_library(NBCore ${NB_CORE_SOURCE})
add_library(NBEngine::Core ALIAS NBCore) add_library(NBEngine::Core ALIAS NBCore)
target_include_directories(NBCore target_include_directories(NBCore
PUBLIC "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>" PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>" PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
) )
export(
TARGETS NBCore
FILE "${CMAKE_BINARY_DIR}/cmake/NBCoreTargets.cmake"
NAMESPACE NBEngine::
)
configure_package_config_file(
"NBCoreConfig.cmake.in"
"${CMAKE_BINARY_DIR}/cmake/NBCoreConfig.cmake"
INSTALL_DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
PATH_VARS CMAKE_INSTALL_LIBDIR
)
write_basic_package_version_file(
"${CMAKE_BINARY_DIR}/cmake/NBCoreConfigVersion.cmake"
COMPATIBILITY AnyNewerVersion
)
if (NBENGINE_INSTALL) if (NBENGINE_INSTALL)
message("Installing NBCore to ${CMAKE_INSTALL_PREFIX}") message("Installing NBCore to ${CMAKE_INSTALL_PREFIX}")
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
install( install(
TARGETS NBCore TARGETS NBCore
EXPORT NBCoreTargets EXPORT NBCoreTargets
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
INCLUDES DESTINATION include
) )
install( install(
DIRECTORY "${PROJECT_SOURCE_DIR}/include/NBCore" DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/NBCore"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp" FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
) )
install( install(
EXPORT NBCoreTargets EXPORT NBCoreTargets
DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
NAMESPACE NBEngine:: NAMESPACE NBEngine::
) )
configure_package_config_file(
"NBCoreConfig.cmake.in"
"NBCoreConfig.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
PATH_VARS CMAKE_INSTALL_LIBDIR
)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/NBCoreConfigVersion.cmake"
COMPATIBILITY AnyNewerVersion
)
install(FILES install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/NBCoreConfig.cmake" "${CMAKE_BINARY_DIR}/cmake/NBCoreConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/NBCoreConfigVersion.cmake" "${CMAKE_BINARY_DIR}/cmake/NBCoreConfigVersion.cmake"
DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake" DESTINATION "${CMAKE_INSTALL_PREFIX}/CMake"
) )
endif() endif()
if (NB_BUILD_TESTS) if (NB_BUILD_TESTS)
add_subdirectory(./tests) add_subdirectory(./tests )
endif() endif()

View File

@ -4,6 +4,7 @@
#include <atomic> #include <atomic>
#include <thread> #include <thread>
#include <utility>
#include <NBCore/ThreadSafeQueue.hpp> #include <NBCore/ThreadSafeQueue.hpp>
@ -11,121 +12,170 @@ namespace nb {
template<typename DataType> template<typename DataType>
class DataSink { class DataSink {
public: public:
DataSink(const DataSink&) = delete; DataSink(const DataSink&) = delete;
DataSink(DataSink&&) = delete; DataSink(DataSink&&) = delete;
DataSink& operator=(const DataSink&) = delete; DataSink& operator=(const DataSink&) = delete;
virtual bool isRunning() const noexcept { virtual bool isRunning() const noexcept {
return _running; std::atomic_thread_fence(std::memory_order_acquire);
return _running.load(std::memory_order_acquire);
} }
virtual bool stop() noexcept = 0; virtual bool stop() noexcept = 0;
virtual bool run() = 0; virtual bool run() = 0;
virtual bool in(const DataType&) = 0; virtual bool in(const DataType&) = 0;
protected: protected:
DataSink() = default; DataSink() {
_running.store(false, std::memory_order_release);
}
std::atomic<bool> _running; std::atomic<bool> _running;
}; };
template<typename DataType, typename SinkTypes=DataSink<DataType>>
class MultiSink : public DataSink<DataType> {
protected:
using Base = DataSink<DataType>;
using SinkPtr = std::shared_ptr<SinkTypes>;
using Base::_running;
std::vector<SinkPtr> _sinks;
public:
MultiSink(std::vector<SinkPtr> sinks={}) : _sinks(sinks) {}
virtual void addSink(SinkPtr sink) {
_sinks.push_back(sink);
}
virtual std::vector<SinkPtr>& getSinks() { return _sinks; }
bool isRunning() const noexcept override {
return Base::isRunning();
}
bool stop() noexcept override {
_running.store(false, std::memory_order_release);
for (auto& sink : _sinks) {
sink->stop();
}
return isRunning();
}
bool run() override {
_running.store(true, std::memory_order_release);
for (auto& sink : _sinks) {
sink->run();
}
return isRunning();
}
bool in(const DataType& data) override {
if (isRunning()) {
bool success = true;
for (auto& sink : _sinks) {
success &= sink->in(data);
}
return success;
}
return false;
}
};
template<typename DataType, typename BufferType, typename ProcessorType> template<typename DataType, typename BufferType, typename ProcessorType>
class BufferedDataProcessor : public DataSink<DataType> { class BufferedDataProcessor : public DataSink<DataType> {
using Base = DataSink<DataType>; private:
public: ProcessorType* const type_ptr = static_cast<ProcessorType*>(this);
using Base::Base;
protected:
using Base = DataSink<DataType>;
using Base::_running;
BufferType _buffer;
virtual unsigned int count() const {
return type_ptr->count();
}
virtual bool pop(std::shared_ptr<DataType> ret) {
return type_ptr->pop(ret);
}
virtual void flush() {
type_ptr->flush();
}
virtual void clear() {
type_ptr->clear();
}
virtual bool process(const DataType& val) = 0;
public:
using Base::Base;
virtual bool stop() noexcept override { return type_ptr->stop(); } virtual bool stop() noexcept override { return type_ptr->stop(); }
virtual bool run() override { return type_ptr->run(); } virtual bool run() override { return type_ptr->run(); }
virtual bool in(const DataType& val) override { return type_ptr->in(val); } virtual bool in(const DataType& val) override { return type_ptr->in(val); }
protected:
unsigned int count() const {
return type_ptr->count();
}
void push(const DataType& val) {
type_ptr->push(val);
}
DataType pop() {
return type_ptr->pop();
}
void flush() {
type_ptr->flush();
}
void clear() {
type_ptr->clear();
}
bool process(const DataType& val) {
return type_ptr->process(val);
}
using Base::_running;
BufferType _buffer;
private:
ProcessorType* const type_ptr = static_cast<ProcessorType*>(this);
}; };
template<typename DataType, typename ProcessorType> template<typename DataType, typename ProcessorType>
class MultithreadedDataProcessor class MultithreadedDataProcessor
: public BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType> { : public BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType> {
using Base = BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType>; private:
public: ProcessorType* const type_ptr = static_cast<ProcessorType*>(this);
~MultithreadedDataProcessor() { type_ptr->stop(); } std::mutex _pause;
bool isRunning() const noexcept override { protected:
return this->_running; using Base = BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType>;
using Base::Base;
using Base::process;
using Base::_running;
std::shared_ptr<std::thread> _runningThread;
virtual unsigned int count() const override {
return type_ptr->_buffer.size();
} }
virtual bool pop(std::shared_ptr<DataType> ret=nullptr) override {
type_ptr->_buffer.pop(ret);
return this->process(*ret);
}
virtual bool popBlock(std::shared_ptr<DataType> ret=nullptr) {
ret = type_ptr->_buffer.popBlock();
return this->process(*ret);
}
virtual void flush() override {
while(type_ptr->count()) {
type_ptr->pop();
}
}
virtual void clear() override {
type_ptr->_buffer.empty();
}
virtual std::unique_lock<std::mutex> pause() {
return std::move(std::unique_lock<std::mutex>(_pause));
}
public:
using Base::isRunning;
virtual ~MultithreadedDataProcessor() { type_ptr->stop(); }
bool run() override { bool run() override {
if (!type_ptr->isRunning()) { if (!type_ptr->isRunning()) {
this->_running = true; _running.store(true, std::memory_order_release);
_runningThread = std::make_shared<std::thread>([&]{ _runningThread = std::make_shared<std::thread>([&]{
while(type_ptr->isRunning()) { while(type_ptr->isRunning()) {
flush(); std::lock_guard<std::mutex> lock(_pause);
type_ptr->flush();
} }
type_ptr->flush();
type_ptr->stop();
}); });
} }
return this->isRunning(); return type_ptr->isRunning();
} }
bool stop() noexcept override { bool stop() noexcept override {
if (type_ptr->isRunning()) { if (type_ptr->isRunning()) {
this->_running = false; _running.store(false, std::memory_order_release);
if (_runningThread) {
_runningThread->join(); _runningThread->join();
_runningThread = nullptr; _runningThread = nullptr;
} }
type_ptr->flush();
}
return !type_ptr->isRunning(); return !type_ptr->isRunning();
} }
bool in(const DataType& val) override {
protected: type_ptr->_buffer.push(val);
using Base::Base; return type_ptr->isRunning();
unsigned int count() const {
return this->_buffer.size();
} }
void push(const DataType& val) {
this->_buffer.push(val);
};
DataType pop() {
std::shared_ptr<DataType> event;
this->_buffer.pop(event);
this->process(*event);
return *event;
}
void flush() {
while(type_ptr->count()) {
pop();
}
}
void clear() {
this->_buffer.empty();
}
std::shared_ptr<std::thread> _runningThread;
private:
ProcessorType* type_ptr = static_cast<ProcessorType*>(this);
}; };

View File

@ -8,35 +8,57 @@
namespace nb { namespace nb {
#ifdef _NB_AUTOLOG #ifdef _NB_AUTOLOG
#ifndef LOG_W_CODE_LOC
#define LOG_W_CODE_LOC(file, line, args...) nb::logger.msg(args, file, line)
#endif // LOG_W_CODE_LOC
#ifndef WARN_W_CODE_LOC
#define WARN_W_CODE_LOC(file, line, args...) nb::logger.warn(args, file, line)
#endif // WARN_W_CODE_LOC
#ifndef ERROR_W_CODE_LOC
#define ERROR_W_CODE_LOC(file, line, args...) nb::logger.error(args, file, line)
#endif // ERROR_W_CODE_LOC
#ifdef _NB_CODE_ERROR_LOCATIONS #ifdef _NB_CODE_ERROR_LOCATIONS
#ifndef LOG #ifndef LOG
#define LOG(args...) nb::logger.log(args, __FILE__, __LINE__) #define LOG(arg) LOG_W_CODE_LOC(__FILE__, __LINE__, arg)
#endif // LOG #endif // LOG
#ifndef WARN #ifndef WARN
#define WARN(args...) nb::logger.warn(args, __FILE__, __LINE__) #define WARN(args...) WARN_W_CODE_LOC(__FILE__, __LINE__, args)
#endif // WARN #endif // WARN
#ifndef ERROR #ifndef ERROR
#define ERROR(args...) nb::logger.error(args, __FILE__, __LINE__) #define ERROR(arg) ERROR_W_CODE_LOC(__FILE__, __LINE__, arg)
#endif // ERROR #endif // ERROR
#else #else
#ifndef LOG #ifndef LOG
#define LOG(args...) nb::logger.log(args) #define LOG(args) nb::logger.msg(args)
#endif // LOG #endif // LOG
#ifndef WARN #ifndef WARN
#define WARN(args...) nb::logger.warn(args) #define WARN(args...) nb::logger.warn(args)
#endif // WARN #endif // WARN
#ifndef ERROR #ifndef ERROR
#define ERROR(args...) nb::logger.error(args) #define ERROR(args) nb::logger.error(args)
#endif // ERROR #endif // ERROR
#endif // _NB_CODE_ERROR_LOCATIONS #endif // _NB_CODE_ERROR_LOCATIONS
#ifndef THROW_W_CODE_LOC
#define THROW_W_CODE_LOC(file, line, args...) ERROR_W_CODE_LOC(file, line, args); throw args
#endif // THROW_W_CODE_LOC
#else
#ifndef LOG
#define LOG(args)
#endif // LOG
#ifndef WARN
#define WARN(args...)
#endif // WARN
#ifndef ERROR
#define ERROR(args)
#endif // ERROR
#endif // _NB_AUTOLOG #endif // _NB_AUTOLOG
#ifndef THROW #ifndef THROW
#ifdef _NB_AUTOLOG #ifdef _NB_AUTOLOG
#define THROW(args...) ERROR(args); nb::logger.stop(); throw args #define THROW(args...) THROW_W_CODE_LOC(__FILE__, __LINE__, args)
#else #else
#define THROW(args...) throw args #define THROW(args...) throw args
#endif // _NB_CODE_ERROR_LOCATIONS #endif // _NB_AUTOLOG
#endif // THROW #endif // THROW
} // namespace nb } // namespace nb

View File

@ -6,13 +6,13 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include <unordered_map>
#include <NBCore/StringUtils.hpp> #include <NBCore/StringUtils.hpp>
#include <NBCore/Utils.hpp>
namespace nb { namespace nb {
typedef std::unordered_map<unsigned int, std::string> ErrorCodeMap; using ErrorCodeMap = ConstantMap<unsigned int, std::string>;
class ErrorBase { class ErrorBase {
protected: protected:
@ -25,11 +25,10 @@ class ErrorBase {
ErrorBase(const ErrorBase&) = default; ErrorBase(const ErrorBase&) = default;
ErrorBase(const std::exception&) noexcept; ErrorBase(const std::exception&) noexcept;
ErrorBase(const std::string&) noexcept;
virtual std::string what() const noexcept { virtual std::string what() const noexcept {
std::string ret = msg; std::string ret = msg;
if (trace) { if (trace) {
std::string trace_msg = msg; std::string trace_msg = trace->what();
ret += NEWLINE + indent_strblock( ret += NEWLINE + indent_strblock(
trace_msg, trace_msg,
TABOVER, TABOVER,
@ -45,12 +44,12 @@ class ErrorBase {
std::string msg_, std::string msg_,
std::string type_, std::string type_,
std::shared_ptr<ErrorBase> trace_ std::shared_ptr<ErrorBase> trace_
) noexcept : ) noexcept :
code(code_), code(code_),
msg(msg_), msg(msg_),
type(type_), type(type_),
trace{trace_} trace{trace_}
{} {}
}; };
template <class ErrorType=NoneType> template <class ErrorType=NoneType>
@ -70,16 +69,15 @@ class Error : public ErrorBase {
); );
} }
protected: public:
using ErrorBase::ErrorBase; using ErrorBase::ErrorBase;
public:
Error( Error(
unsigned int code_, unsigned int code_,
const ErrorBase& trace_ const ErrorBase& trace_
) noexcept : ErrorBase( ) noexcept : ErrorBase(
code_, code_,
ErrorType::ErrorMessages.at(code_), ErrorType::ErrorMessages[code_],
ErrorType::type, ErrorType::type,
std::make_shared<ErrorBase>(trace_) std::make_shared<ErrorBase>(trace_)
) { check_asserts(); } ) { check_asserts(); }
@ -88,7 +86,7 @@ class Error : public ErrorBase {
std::string msg_, std::string msg_,
const ErrorBase& trace_ const ErrorBase& trace_
) noexcept : ErrorBase( ) noexcept : ErrorBase(
0, ErrorType::Codes::UNDEFINED,
msg_, msg_,
ErrorType::type, ErrorType::type,
std::make_shared<ErrorBase>(trace_) std::make_shared<ErrorBase>(trace_)
@ -96,13 +94,13 @@ class Error : public ErrorBase {
Error(unsigned int code_) noexcept : ErrorBase( Error(unsigned int code_) noexcept : ErrorBase(
code_, code_,
ErrorType::ErrorMessages.at(code_), ErrorType::ErrorMessages[code_],
ErrorType::type, ErrorType::type,
nullptr nullptr
) { check_asserts(); } ) { check_asserts(); }
Error(std::string msg_) noexcept : ErrorBase( Error(std::string msg_) noexcept : ErrorBase(
0, ErrorType::Codes::UNDEFINED,
msg_, msg_,
ErrorType::type, ErrorType::type,
nullptr nullptr
@ -114,14 +112,14 @@ class Error : public ErrorBase {
const ErrorBase& trace_ const ErrorBase& trace_
) noexcept : ErrorBase( ) noexcept : ErrorBase(
code_, code_,
ErrorType::ErrorMessages.at(code_) + " (" + note_ + ")", ErrorType::ErrorMessages[code_] + " (" + note_ + ")",
ErrorType::type, ErrorType::type,
std::make_shared<ErrorBase>(trace_) std::make_shared<ErrorBase>(trace_)
) { check_asserts(); } ) { check_asserts(); }
Error(unsigned int code_, const std::string& note_) noexcept : ErrorBase( Error(unsigned int code_, const std::string& note_) noexcept : ErrorBase(
code_, code_,
ErrorType::ErrorMessages.at(code_) + " (" + note_ + ")", ErrorType::ErrorMessages[code_] + " (" + note_ + ")",
ErrorType::type, ErrorType::type,
nullptr nullptr
) { check_asserts(); } ) { check_asserts(); }
@ -142,14 +140,18 @@ class Error<NoneType> : public Error<Error<NoneType>> {
using Base::what; using Base::what;
using Base::code; using Base::code;
using Base::trace; using Base::trace;
using Base::Base;
enum Codes : unsigned int { enum Codes : unsigned int {
STANDARD, UNDEFINED, INDEX_ERROR STANDARD, UNDEFINED, OUT_OF_RANGE, VALUE_ERROR, OVERWRITE_ERROR
}; };
inline static const std::string type = "nb::Error"; inline static const std::string type = "nb::Error";
inline static const ErrorCodeMap ErrorMessages = { inline static const ErrorCodeMap ErrorMessages = {
{STANDARD, "std::exception"}, {STANDARD, "std::exception"},
{UNDEFINED, "Error"}, {UNDEFINED, "Error"},
{INDEX_ERROR, "Indexing error"} {OUT_OF_RANGE, "Out-of-range error"},
{VALUE_ERROR, "Invalid value"},
{OVERWRITE_ERROR, "Attempting to overwrite managed data"}
}; };
Error(unsigned int code_=1) noexcept : Base(code_) {} Error(unsigned int code_=1) noexcept : Base(code_) {}
@ -159,13 +161,6 @@ class Error<NoneType> : public Error<Error<NoneType>> {
"std::exception", "std::exception",
nullptr nullptr
) {} ) {}
Error(const std::string& msg_) noexcept : Base(
Codes::UNDEFINED,
msg_,
type,
nullptr
) {}
}; };
template<typename... Args> template<typename... Args>

View File

@ -3,13 +3,13 @@
#define _NB_LOGGER #define _NB_LOGGER
#include <chrono> #include <chrono>
#include <ostream>
#include <thread> #include <thread>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <NBCore/DataSink.hpp> #include <NBCore/DataSink.hpp>
#include <NBCore/ErrorsImpl.hpp> #include <NBCore/ErrorsImpl.hpp>
#include <NBCore/Printer.hpp>
#include <NBCore/Processes.hpp> #include <NBCore/Processes.hpp>
#include <NBCore/ThreadSafeQueue.hpp> #include <NBCore/ThreadSafeQueue.hpp>
#include <NBCore/TypeTraits.hpp> #include <NBCore/TypeTraits.hpp>
@ -26,32 +26,32 @@ typedef std::chrono::time_point<
typedef std::string (*LogProcessFunction)(const LoggerTimePoint&, const std::string&); typedef std::string (*LogProcessFunction)(const LoggerTimePoint&, const std::string&);
typedef std::unordered_map<uint8_t, LogProcessFunction> LogProcessFunctionMap; typedef std::unordered_map<uint8_t, LogProcessFunction> LogProcessFunctionMap;
template<typename LogType, typename Logger, typename ST=std::ostream*> template<typename LogType, typename Logger>
class LoggerBase class LoggerBase : public MultithreadedDataProcessor<LogType, Logger>{
: public MultithreadedDataProcessor<LogType, Logger>{ private:
using StreamType = ST; Logger* const type_ptr = static_cast<LoggerType*>(this);
using LoggerType = Logger;
using Base = MultithreadedDataProcessor<LogType, LoggerType>;
public:
bool run() override {
if (!static_cast<LoggerType*>(this)->isRunning()) {
this->_running = true;
this->_runningThread = std::make_shared<std::thread>([&]{
while(static_cast<LoggerType*>(this)->isRunning()) {
static_cast<LoggerType*>(this)->flush();
}
static_cast<LoggerType*>(this)->flush();
});
}
return static_cast<LoggerType*>(this)->isRunning();
}
using Base::flush;
protected: protected:
LoggerBase() = default; using LoggerType = Logger;
using Base = MultithreadedDataProcessor<LogType, LoggerType>;
using SinkType = DataSink<LogType>;
using Base::process;
std::shared_ptr<SinkType> _logsink;
LoggerBase(std::shared_ptr<SinkType> sink) : _logsink(sink) {}
public:
using Base::flush;
bool run() override {
_logsink->run();
return Base::run();
}
using Base::pause;
bool stop() noexcept override {
auto ret = Base::stop();
_logsink->stop();
return ret;
}
StreamType _ostream;
}; };
struct LogEvent{ struct LogEvent{
@ -64,59 +64,42 @@ struct LogEvent{
const unsigned int line=0; const unsigned int line=0;
}; };
class LogEventHandler : public DataSink<LogEvent> {
protected:
using Base = DataSink<LogEvent>;
using Base::_running;
std::atomic<uint8_t> _logLevel;
public:
using Base::isRunning;
LogEventHandler(uint8_t logging_level=0x01);
virtual uint8_t logLevel(uint8_t);
virtual uint8_t logLevel() const;
bool stop() noexcept override;
bool run() override;
};
template <typename LT> template <typename LT>
class DebugLogger : public LoggerBase<LogEvent, LT, std::vector<std::ostream*>>{ class DebugLogger : public LoggerBase<LogEvent, LT>{
using StreamType = std::vector<std::ostream*>; private:
using LoggerType = LT; LT* const type_ptr = static_cast<LT*>(this);
using Base = LoggerBase<LogEvent, LoggerType, StreamType>;
public:
template<typename... ST>
DebugLogger(ST&... streams) : _ostream(nb::RefPackToPtrVec<std::ostream, ST...>(streams...).vec) {}
~DebugLogger() { static_cast<LoggerType*>(this)->stop(); }
template<typename U>
void log(
U val,
std::string file="",
unsigned int line=0
) { static_cast<LoggerType*>(this)->write_message(val, 0x00, file, line); }
template<typename U>
void warn(
U val,
uint8_t lvl=0x01,
std::string file="",
unsigned int line=0
) { static_cast<LoggerType*>(this)->write_message(val, lvl, file, line); }
void error(
const ErrorBase& val,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->write_message(val, 0xFF, file, line);
static_cast<LoggerType*>(this)->flush();
}
void error(
const std::string& val,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->write_message(Error(val), 0xFF, file, line);
static_cast<LoggerType*>(this)->flush();
}
protected: protected:
std::vector<std::ostream*> _ostream; using LoggerType = LT;
void write_message( using Base = LoggerBase<LogEvent, LoggerType>;
using SinkType = LogEventHandler;
using SinkPtr = std::shared_ptr<SinkType>;
using Distributor = MultiSink<LogEvent, LogEventHandler>;
using Base::_logsink;
using Base::process;
std::atomic<uint8_t> _loglvl;
virtual void write_message(
std::string msg, std::string msg,
uint8_t lvl=0x00, uint8_t lvl=0x00,
std::string file="", std::string file="",
unsigned int line=0 unsigned int line=0
) { ) {
static_cast<LoggerType*>(this)->push(LogEvent{ type_ptr->in(LogEvent{
std::chrono::system_clock::now(), std::chrono::system_clock::now(),
lvl, lvl,
msg, msg,
@ -126,7 +109,6 @@ public:
line line
}); });
} }
template <size_t N> template <size_t N>
void write_message( void write_message(
char const(&msg) [N], char const(&msg) [N],
@ -134,18 +116,16 @@ public:
std::string file="", std::string file="",
unsigned int line=0 unsigned int line=0
) { ) {
static_cast<LoggerType*>(this)->write_message(std::string(msg), lvl, file, line); this->write_message(std::string(msg), lvl, file, line);
} }
void write_message( void write_message(
const ErrorBase& err, const ErrorBase& err,
uint8_t lvl=0x00, uint8_t lvl=0x00,
std::string file="", std::string file="",
unsigned int line=0 unsigned int line=0
) { ) {
static_cast<LoggerType*>(this)->write_message(err.what(), lvl, file, line); this->write_message(err.what(), lvl, file, line);
} }
template<typename U> template<typename U>
std::enable_if_t<std::is_integral_v<U>, void> write_message( std::enable_if_t<std::is_integral_v<U>, void> write_message(
const U& val, const U& val,
@ -153,38 +133,115 @@ public:
std::string file="", std::string file="",
unsigned int line=0 unsigned int line=0
) { ) {
static_cast<LoggerType*>(this)->write_message(std::to_string(val), lvl, file, line); this->write_message(std::to_string(val), lvl, file, line);
}
public:
DebugLogger(std::vector<SinkPtr> sinks={}) : Base(
std::static_pointer_cast<DataSink<LogEvent>>(std::make_shared<Distributor>())
) {
for (auto sink : sinks) {
addLogHandler(sink);
}
}
~DebugLogger() { static_cast<LoggerType*>(this)->stop(); }
void addLogHandler(SinkPtr sink) {
auto multsink = std::static_pointer_cast<Distributor>(_logsink);
multsink->addSink(sink);
}
uint8_t minimalLogLevel() const {
return _loglvl.load(std::memory_order_acquire);
}
uint8_t minimalLogLevel(uint8_t level) {
_loglvl.store(level, std::memory_order_release);
auto multsink = std::static_pointer_cast<Distributor>(_logsink);
for (auto& sink : multsink->getSinks()) {
if (sink->logLevel() < level) {
sink->logLevel(level);
}
}
return minimalLogLevel();
}
template<typename U>
void msg(
U val,
std::string file="",
unsigned int line=0
) { this->write_message(val, 0x00, file, line); }
template<typename U>
void warn(
U val,
uint8_t lvl=0x01,
std::string file="",
unsigned int line=0
) { this->write_message(val, lvl, file, line); }
void error(
const ErrorBase& val,
std::string file="",
unsigned int line=0
) {
this->write_message(val, 0xFF, file, line);
auto lock = this->pause();
this->flush();
}
void error(
const std::string& val,
std::string file="",
unsigned int line=0
) {
this->write_message(Error<>(val), 0xFF, file, line);
auto lock = this->pause();
this->flush();
} }
}; };
class DefaultTerminalLogEventPrinter : public LogEventHandler {
protected:
using Base = LogEventHandler;
using Base::_running;
public:
using Base::isRunning;
using Base::logLevel;
using Base::stop;
using Base::run;
using Base::Base;
bool in(const LogEvent&) override;
};
class DefaultDebugLogger : public DebugLogger<DefaultDebugLogger> { class DefaultDebugLogger : public DebugLogger<DefaultDebugLogger> {
protected:
using LoggerType = DefaultDebugLogger; using LoggerType = DefaultDebugLogger;
using Base = DebugLogger<DefaultDebugLogger>; using Base = DebugLogger<DefaultDebugLogger>;
using MultiLogSink = MultiSink<LogEvent>;
template <typename... Ts> using SinkPtr = std::shared_ptr<LogEventHandler>;
struct LogRow; using Base::_logsink;
using Base::write_message;
virtual bool process(const LogEvent& msg) override;
public: public:
using Base::Base; using Base::Base;
using Base::msg;
using Base::warn;
using Base::error;
using Base::addLogHandler;
using Base::minimalLogLevel;
DefaultDebugLogger(std::vector<SinkPtr> sinks={}) : Base(sinks) {}
~DefaultDebugLogger() { stop(); } ~DefaultDebugLogger() { stop(); }
friend class BufferedDataProcessor<LogEvent, ThreadsafeQueue<LogEvent>, DefaultDebugLogger>; friend class BufferedDataProcessor<LogEvent, ThreadsafeQueue<LogEvent>, DefaultDebugLogger>;
template <typename STR, typename... Ts>
friend STR& operator<<(STR&, const DefaultDebugLogger::LogRow<Ts...>&);
protected:
using Base::_ostream;
bool process(const LogEvent& msg);
}; };
extern const bool LOGGER_RUNNING; extern const bool LOGGER_RUNNING;
#ifndef _NB_NO_LOGGER extern const bool LOGGER_RUNNING;
#ifdef _NB_AUTOLOG
extern DefaultDebugLogger logger; extern DefaultDebugLogger logger;
#endif // _NB_NO_LOGGER #endif // _NB_AUTOLOG
// Taking Charge of Adult ADHD by Russell Barkley // Taking Charge of Adult ADHD by Russell Barkley

View File

@ -0,0 +1,52 @@
#pragma once
#ifndef _NB_PRINTER
#define _NB_PRINTER
#include <condition_variable>
#include <iostream>
#include <memory>
#include <mutex>
namespace nb {
template<typename STREAM, typename PrinterType>
class Printer {
private:
PrinterType* const type_ptr = static_cast<PrinterType*>(this);
protected:
STREAM& _stream;
Printer(STREAM* const stream_) : _stream(stream_) {}
public:
template<typename T>
PrinterType& operator<<(const T& val_) {
(*type_ptr) << val_;
return type_ptr;
}
};
class Terminal : public Printer<decltype(std::cout), Terminal> {
private:
Terminal* const type_ptr = static_cast<Terminal*>(this);
using MutexLock = std::lock_guard<std::mutex>;
protected:
using Base = Printer<decltype(std::cout), Terminal>;
using Base::_stream;
std::mutex _mutex;
public:
using Base::Base;
template<typename T>
Terminal& operator<<(const T& val_) {
MutexLock lock(_mutex);
_stream << val_;
return *type_ptr;
}
};
} // namespace nb
#endif // _NB_PRINTER

View File

@ -2,7 +2,6 @@
#ifndef _NB_STRING_UTILS #ifndef _NB_STRING_UTILS
#define _NB_STRING_UTILS #define _NB_STRING_UTILS
#include <iostream>
#include <string> #include <string>
#include <string_view> #include <string_view>
@ -21,24 +20,6 @@ namespace nb {
const std::string TABOVER = " "; const std::string TABOVER = " ";
// std::wstring str_to_wstr(std::string in);
// std::string wstr_to_str(std::wstring in);
template <typename Stream, typename... Args>
void stream(const Stream& s, Args&&... args);
template <typename Stream, typename... Args>
void stream(const Stream& s, Args&&... args) {
(s << ... << args);
}
template<typename... Args>
void term(Args&&... args) { stream(std::cout, args..., NEWLINE); }
template<typename... Args>
void wterm(Args&&... args) { stream(std::wcout, args..., nb::WNEWLINE); }
template <typename T = char> template <typename T = char>
std::basic_string<T> find_and_replace( std::basic_string<T> find_and_replace(
ExplicitType_t<std::basic_string<T>> original, ExplicitType_t<std::basic_string<T>> original,

View File

@ -90,6 +90,15 @@ struct RunAndOutput {
} }
}; };
template<typename A, typename B>
using SubtractType = decltype(std::declval<A>() - std::declval<B>());
template<typename A, typename B>
using MultiplyType = decltype(std::declval<A>() * std::declval<B>());
template<typename A, typename B>
using AdditionType = decltype(std::declval<A>() + std::declval<B>());
template<typename Func, std::size_t N=0, typename... Pack> template<typename Func, std::size_t N=0, typename... Pack>
inline typename std::enable_if<N==sizeof...(Pack), void>::type inline typename std::enable_if<N==sizeof...(Pack), void>::type
ForEach(std::tuple<Pack...>&, Func) {} ForEach(std::tuple<Pack...>&, Func) {}

View File

@ -2,13 +2,27 @@
#ifndef _NB_CORE_TYPES #ifndef _NB_CORE_TYPES
#define _NB_CORE_TYPES #define _NB_CORE_TYPES
#include <mutex> #include <exception>
#include <memory>
#include <unordered_map>
#include <vector> #include <vector>
#include <NBCore/Errors.hpp> // #include <NBCore/Errors.hpp>
namespace nb { namespace nb {
template<typename A, typename B>
class ConstantMap : public std::unordered_map<A, B> {
using Base = std::unordered_map<A, B>;
public:
using Base::Base;
using Base::at;
const B& operator[](const A& key) const {
return at(key);
}
};
template<typename T> template<typename T>
using SharedVector = std::vector<std::shared_ptr<T>>; using SharedVector = std::vector<std::shared_ptr<T>>;
@ -17,7 +31,7 @@ using RValueVector = std::vector<T&&>;
using ByteVector = std::vector<uint8_t>; using ByteVector = std::vector<uint8_t>;
class ObjectManagerError : public Error<ObjectManagerError> { /* class ObjectManagerError : public Error<ObjectManagerError> {
using Base = Error<ObjectManagerError>; using Base = Error<ObjectManagerError>;
public: public:
@ -29,7 +43,7 @@ class ObjectManagerError : public Error<ObjectManagerError> {
static const std::string type; static const std::string type;
static const ErrorCodeMap ErrorMessages; static const ErrorCodeMap ErrorMessages;
}; }; */
template<typename T> template<typename T>
ByteVector vectorToBytes(const std::vector<T>& vec) { ByteVector vectorToBytes(const std::vector<T>& vec) {
@ -54,9 +68,10 @@ ByteVector concatVectorBytes(const std::vector<T>& vec1, const std::vector<S>& v
template<typename T> template<typename T>
std::vector<T> bytesToVector(const ByteVector& vec) { std::vector<T> bytesToVector(const ByteVector& vec) {
if (vec.size() % sizeof(T) != 0) { if (vec.size() % sizeof(T) != 0) {
THROW(Error<NoneType>( /* THROW(Error<NoneType>(
std::runtime_error("Data size does not align to std::vector<" + std::string(typeid(T).name()) + ">.") std::runtime_error("Data size does not align to std::vector<" + std::string(typeid(T).name()) + ">.")
)); )); */
throw "byyyyeeee";
} }
unsigned int num_elmts = vec.size() / sizeof(T); unsigned int num_elmts = vec.size() / sizeof(T);
std::vector<T> ret(num_elmts); std::vector<T> ret(num_elmts);
@ -65,7 +80,7 @@ std::vector<T> bytesToVector(const ByteVector& vec) {
return ret; return ret;
} }
template <typename T> /* template <typename T>
class ThreadsafeObjectLock; class ThreadsafeObjectLock;
template <typename T> template <typename T>
@ -114,7 +129,7 @@ class ThreadsafeObjectLock {
_manager->_mutex.lock(); _manager->_mutex.lock();
} }
ThreadsafeObject<T>* const _manager; ThreadsafeObject<T>* const _manager;
}; }; */
} // namespace nb } // namespace nb
#endif // _NB_CORE_TYPES #endif // _NB_CORE_TYPES

View File

@ -1,38 +1,82 @@
#include <iostream> #include <iostream>
#include <sstream>
#include <NBCore/Logger.hpp> #include <NBCore/Logger.hpp>
#include <NBCore/StringUtils.hpp> #include <NBCore/StringUtils.hpp>
namespace nb { namespace nb {
#ifndef _NB_NO_LOGGER static bool RUN_LOGGER(nb::DefaultDebugLogger& logger_) {
nb::DefaultDebugLogger logger(std::cout); logger_.run();
#endif // _NB_NO_LOGGER return logger_.isRunning();
}
bool nb::DefaultDebugLogger::process(const LogEvent& msg) { #ifdef _NB_AUTOLOG
DefaultDebugLogger logger({std::static_pointer_cast<LogEventHandler>(
std::make_shared<DefaultTerminalLogEventPrinter>(0x0)
)});
const bool LOGGER_RUNNING = RUN_LOGGER(logger);
#else
const bool LOGGER_RUNNING = false;
#endif // _NB_AUTOLOG
// class LogEventHandler
LogEventHandler::LogEventHandler(uint8_t logging_level) {
_logLevel.store(logging_level, std::memory_order_release);
}
bool LogEventHandler::stop() noexcept {
_running.store(false, std::memory_order_release);
return isRunning();
}
bool LogEventHandler::run() {
_running.store(true, std::memory_order_release);
return isRunning();
}
uint8_t LogEventHandler::logLevel(uint8_t val) {
_logLevel.store(val, std::memory_order_release);
return logLevel();
}
uint8_t LogEventHandler::logLevel() const {
return _logLevel.load();
}
// class DefaultTerminalLogEventPrinter
bool DefaultTerminalLogEventPrinter::in(const LogEvent& msg) {
if (!isRunning()) {
return false;
}
if (msg.lvl < logLevel()) {
return false;
}
constexpr size_t level_field_width = 5; constexpr size_t level_field_width = 5;
constexpr size_t msg_prompt_length = level_field_width+7; constexpr size_t msg_prompt_length = level_field_width+7;
for (const auto os : this->_ostream) { std::stringstream formatted_stream;
*os << "["; formatted_stream << "[";
os->width(level_field_width); formatted_stream.width(level_field_width);
*os << std::to_string(msg.lvl) << "] :: "; formatted_stream << std::to_string(msg.lvl) << "] :: ";
std::string fileloc=""; std::string fileloc="";
if (!msg.file.empty()) { if (!msg.file.empty()) {
fileloc += "(" + msg.file + ":" + std::to_string(msg.line) + ") - "; fileloc += "(" + msg.file + ":" + std::to_string(msg.line) + ") - ";
} }
*os << indent_strblock( formatted_stream << indent_strblock(
fileloc + msg.msg, fileloc + msg.msg,
std::string(20 - msg_prompt_length, ' '), std::string(20 - msg_prompt_length, ' '),
"" ""
) << nb::NEWLINE; ) << nb::NEWLINE;
} std::string formatted_string = formatted_stream.str();
std::cout << formatted_string << std::flush;
return true; return true;
} }
static bool RUN_LOGGER(nb::DefaultDebugLogger& log) { // class DefaultDebugLogger
return log.run();
bool DefaultDebugLogger::process(const LogEvent& msg) {
return _logsink->in(msg);
} }
const bool LOGGER_RUNNING = RUN_LOGGER(logger);
} // namespace nb } // namespace nb

View File

@ -2,7 +2,7 @@
namespace nb { namespace nb {
using ObjectManagerCodes = ObjectManagerError::Codes; /* using ObjectManagerCodes = ObjectManagerError::Codes;
const std::string ObjectManagerError::type = "nb::ObjectManagerError"; const std::string ObjectManagerError::type = "nb::ObjectManagerError";
const ErrorCodeMap ObjectManagerError::ErrorMessages({ const ErrorCodeMap ObjectManagerError::ErrorMessages({
{ObjectManagerCodes::UNDEFINED, "Error"}, {ObjectManagerCodes::UNDEFINED, "Error"},
@ -22,6 +22,6 @@ const ErrorCodeMap ObjectManagerError::ErrorMessages({
ObjectManagerCodes::BAD_THREAD, ObjectManagerCodes::BAD_THREAD,
"Attempting operation from a bad thread" "Attempting operation from a bad thread"
} }
}); }); */
}; // namespace nb }; // namespace nb

View File

@ -1,3 +1,4 @@
#define _NB_AUTOLOG
#include <exception> #include <exception>
#include <NBCore/Errors.hpp> #include <NBCore/Errors.hpp>
@ -29,17 +30,19 @@ const nb::ErrorCodeMap TestError::ErrorMessages{
}; };
int main() { int main() {
nb::logger.log("Whoop!"); while(!nb::LOGGER_RUNNING) {}
nb::logger.minimalLogLevel(0x0);
nb::logger.msg("Whoop!");
try { try {
THROW(TestError(0, TestError(1, TestError(2, TestError(3, TestError(2)))))); THROW(TestError(0, TestError(1, TestError(2, TestError(3, TestError(2))))));
} catch (TestError e){ } catch (TestError e){
nb::logger.log("nb::Error was thrown!"); nb::logger.msg("nb::Error was thrown!");
} }
try { try {
THROW(std::exception()); THROW(std::exception());
} catch (std::exception e){ } catch (std::exception e){
nb::logger.log("std::exception was thrown!"); nb::logger.msg("std::exception was thrown!");
} }
ERROR("hello there!"); ERROR("hello there!");
return 0; return 0;

View File

@ -1,10 +1,11 @@
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.10)
project(NBGraphics VERSION 0.1) project(NBGraphics VERSION 0.1)
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
set(GLAD_PATH ${NBENGINE_ROOT}/../glad/) set(GLAD_PATH ${NBENGINE_ROOT}/../glad/)
set(STBIMAGE_PATH ${NBENGINE_ROOT}/../stbi_image)
get_filename_component(GLAD_PATH ${GLAD_PATH} ABSOLUTE) get_filename_component(GLAD_PATH ${GLAD_PATH} ABSOLUTE)
get_filename_component(STBIMAGE_PATH ${STBIMAGE_PATH} ABSOLUTE)
set(CMAKE_PREFIX_PATH set(CMAKE_PREFIX_PATH
"${CMAKE_PREFIX_PATH}" "${CMAKE_PREFIX_PATH}"
@ -21,6 +22,10 @@ else()
endif() endif()
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
if (NB_MONITOR_OPENGL_CALLS)
add_compile_definitions(_NB_MONITOR_OPENGL_CALLS)
endif()
toAbsolutePath(NB_GRAPHICS_SOURCE toAbsolutePath(NB_GRAPHICS_SOURCE
./src/Buffers.cpp ./src/Buffers.cpp
./src/FrameBuffers.cpp ./src/FrameBuffers.cpp
@ -53,29 +58,45 @@ add_library(NBGraphics
${GLAD_PATH}/src/glad.c ${GLAD_PATH}/src/glad.c
) )
add_library(NBEngine::Graphics ALIAS NBGraphics) add_library(NBEngine::Graphics ALIAS NBGraphics)
add_dependencies(NBGraphics NBCore)
add_dependencies(NBGraphics glfw)
target_link_libraries(NBGraphics target_link_libraries(NBGraphics
PUBLIC glfw PUBLIC glfw
PUBLIC NBCore PUBLIC NBCore
) )
get_target_property(GLFW_INTERFACE_INCLUDES glfw INTERFACE_INCLUDE_DIRECTORIES)
#include_directories(${GLFW_INTERFACE_INCLUDES})
target_include_directories(NBGraphics target_include_directories(NBGraphics
PUBLIC "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>" PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>" PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
PUBLIC "${STBIMAGE_PATH}"
PUBLIC "${GLAD_PATH}/include" PUBLIC "${GLAD_PATH}/include"
) )
export(
TARGETS NBGraphics
FILE "${CMAKE_BINARY_DIR}/cmake/NBGraphicsTargets.cmake"
NAMESPACE NBEngine::
)
configure_package_config_file(
"NBGraphicsConfig.cmake.in"
"${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfig.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
PATH_VARS CMAKE_INSTALL_LIBDIR
)
write_basic_package_version_file(
"${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfigVersion.cmake"
COMPATIBILITY AnyNewerVersion
)
if (NBENGINE_INSTALL) if (NBENGINE_INSTALL)
message("Installing NBGraphics to ${CMAKE_INSTALL_PREFIX}") message("Installing NBGraphics to ${CMAKE_INSTALL_PREFIX}")
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
install( install(
TARGETS NBGraphics TARGETS NBGraphics
EXPORT NBGraphicsTargets EXPORT NBGraphicsTargets
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
INCLUDES DESTINATION include
) )
install( install(
DIRECTORY "${PROJECT_SOURCE_DIR}/include/NBGraphics" DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/NBGraphics"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp" FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
) )
@ -84,20 +105,10 @@ if (NBENGINE_INSTALL)
DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
NAMESPACE NBEngine:: NAMESPACE NBEngine::
) )
configure_package_config_file(
"NBGraphicsConfig.cmake.in"
"NBGraphicsConfig.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
PATH_VARS CMAKE_INSTALL_LIBDIR
)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/NBGraphicsConfigVersion.cmake"
COMPATIBILITY AnyNewerVersion
)
install(FILES install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/NBGraphicsConfig.cmake" "${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/NBGraphicsConfigVersion.cmake" "${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfigVersion.cmake"
DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake" DESTINATION "${CMAKE_INSTALL_PREFIX}/CMake"
) )
endif() endif()

View File

@ -1,2 +1,6 @@
@PACKAGE_INIT@ @PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/NBGraphicsTargets.cmake") include("${CMAKE_CURRENT_LIST_DIR}/NBGraphicsTargets.cmake")
include(CMakeFindDependencyMacro)
find_dependency(NBCore REQUIRED)
find_dependency(OpenGL REQUIRED)
find_dependency(glfw3 REQUIRED)

View File

@ -14,7 +14,7 @@
namespace nb { namespace nb {
extern const std::unordered_map<GLenum, std::string> BufferTypes; extern const ConstantMap <GLenum, std::string> BufferTypes;
template<GLenum N> template<GLenum N>
struct GLSLEnum; struct GLSLEnum;
@ -72,7 +72,7 @@ class Buffer : public OpenGLObject {
Buffer(GLenum target) : Target(target) {} Buffer(GLenum target) : Target(target) {}
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
glGenBuffers(1, &_id); OPENGL_CALL(glGenBuffers(1, &_id));
} }
bind(); bind();
return _id; return _id;
@ -80,7 +80,7 @@ class Buffer : public OpenGLObject {
virtual void remove() override { virtual void remove() override {
if (_id) { if (_id) {
unbind(); unbind();
glDeleteBuffers(1, &_id); OPENGL_CALL(glDeleteBuffers(1, &_id));
_id = 0; _id = 0;
} }
} }
@ -93,15 +93,17 @@ class Buffer : public OpenGLObject {
virtual void bind() const override { virtual void bind() const override {
if (_id) { if (_id) {
glBindBuffer(Target, _id); OPENGL_CALL(glBindBuffer(Target, _id));
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ BufferType " + BufferTypes.at(Target) "w/ BufferType " + BufferTypes[Target]
)); ));
} }
} }
virtual void unbind() const override { glBindBuffer(Target, 0); } virtual void unbind() const override {
OPENGL_CALL(glBindBuffer(Target, 0));
}
GLenum usage() const; GLenum usage() const;
size_t size() const; size_t size() const;
ByteVector data() const; ByteVector data() const;

View File

@ -9,13 +9,12 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <NBGraphics/Buffers.h> #include <NBGraphics/Buffers.hpp>
#include <NBGraphics/Shader.h> #include <NBGraphics/VertexArray.hpp>
#include <NBGraphics/VAOManager.hpp>
#define THROW_DRAW_ERROR(msg) throw DrawError(msg, __FILE__, __LINE__); #define THROW_DRAW_ERROR(msg) throw DrawError(msg, __FILE__, __LINE__);
namespace NB{ namespace nb{
class DrawError : public std::runtime_error { class DrawError : public std::runtime_error {
public: public:

View File

@ -29,19 +29,25 @@ class RenderBuffer : public RenderTarget {
protected: protected:
GLuint declare() override { GLuint declare() override {
if (!_id) { if (!_id) {
glRenderbufferStorage( OPENGL_CALL(
glGenRenderbuffers(1, &_id)
);
bind();
OPENGL_CALL(glRenderbufferStorage(
GL_RENDERBUFFER, GL_RENDERBUFFER,
format, format,
width, width,
height height
); ));
return _id;
} }
bind();
return _id; return _id;
} }
void remove() override { void remove() override {
if (_id) { if (_id) {
unbind(); unbind();
glDeleteRenderbuffers(1, &_id); OPENGL_CALL(glDeleteRenderbuffers(1, &_id));
_id = 0; _id = 0;
} }
} }
@ -50,11 +56,14 @@ class RenderBuffer : public RenderTarget {
const unsigned int width; const unsigned int width;
const unsigned int height; const unsigned int height;
const GLenum format; const GLenum format;
template<typename PixelType> RenderBuffer(
RenderBuffer(unsigned int width_, unsigned int height_) : GLenum format_,
unsigned int width_,
unsigned int height_
) :
format(format_),
width(width_), width(width_),
height(height_), height(height_),
format(OGLPixelFormat<PixelType>::glFormat),
RenderTarget(GL_RENDERBUFFER) RenderTarget(GL_RENDERBUFFER)
{ declare(); } { declare(); }
RenderBuffer(RenderBuffer&& rhs) : RenderBuffer(RenderBuffer&& rhs) :
@ -66,16 +75,16 @@ class RenderBuffer : public RenderTarget {
RenderBuffer& operator=(RenderBuffer&&) = delete; RenderBuffer& operator=(RenderBuffer&&) = delete;
void bind() const override { void bind() const override {
if (_id) { if (_id) {
glBindRenderbuffer(GL_RENDERBUFFER, _id); OPENGL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, _id));
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ RenderBuffer" "w/ RenderBuffer"
)); ));
} }
} }
void unbind() const override { void unbind() const override {
glBindRenderbuffer(GL_RENDERBUFFER, 0); OPENGL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
} }
}; };
@ -85,8 +94,10 @@ class FrameBufferBase : public OpenGLObject {
static bool texTypeIs2D(GLenum texType) { static bool texTypeIs2D(GLenum texType) {
switch(texType) { switch(texType) {
case GL_TEXTURE_2D: case GL_TEXTURE_2D:
default:
return true; return true;
case GL_TEXTURE_1D:
default:
return false;
break; break;
} }
} }
@ -98,6 +109,19 @@ class FrameBufferBase : public OpenGLObject {
GLuint declare() override; GLuint declare() override;
void remove() override; void remove() override;
std::shared_ptr<RenderTarget> detach(GLenum); std::shared_ptr<RenderTarget> detach(GLenum);
void attach(
GLenum attachment,
std::shared_ptr<RenderBuffer> renderbuffer
);
public:
const GLenum Target;
void bind() const override;
void unbind() const override;
GLenum status() const;
bool complete() const;
AttachmentMap getAllBuffers() const;
std::shared_ptr<RenderTarget> getBuffer(GLenum) const;
void attach( void attach(
GLenum attachment, GLenum attachment,
std::shared_ptr<Texture> texture, std::shared_ptr<Texture> texture,
@ -109,32 +133,6 @@ class FrameBufferBase : public OpenGLObject {
unsigned int level, unsigned int level,
unsigned int layer 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 ReadFrameBuffer;
@ -178,12 +176,6 @@ class WriteFrameBuffer : public virtual FrameBufferBase {
WriteFrameBuffer(); WriteFrameBuffer();
WriteFrameBuffer& operator=(ReadFrameBuffer&&); WriteFrameBuffer& operator=(ReadFrameBuffer&&);
WriteFrameBuffer& operator=(WriteFrameBuffer&&); 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; DrawTexVec getWriteBuffers() const;
std::vector<GLenum> getWriteLocations() const; std::vector<GLenum> getWriteLocations() const;
DrawTexVec setWriteBuffers(const std::vector<GLenum>& attachments); DrawTexVec setWriteBuffers(const std::vector<GLenum>& attachments);

View File

@ -5,4 +5,8 @@
#include <glad/glad.h> #include <glad/glad.h>
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
namespace nb {
} // namespace nb
#endif #endif

View File

@ -134,40 +134,95 @@ class Image;
template<typename T, typename... Channels> template<typename T, typename... Channels>
class Image<Pixel<T, Channels...>> { class Image<Pixel<T, Channels...>> {
private:
Error<> sizeCompare(const Image& rhs) {
const std::string errmsg = "Cannot assign images of different size";
if (width != rhs.width) {
return Error<>(
Error<>::VALUE_ERROR,
errmsg+"[ Width: "+std::to_string(width)+\
" != "+std::to_string(rhs.width)+" ]"
);
}
if (height != rhs.height) {
return Error<>(
Error<>::VALUE_ERROR,
errmsg+"[ Width: "+std::to_string(width)+\
" != "+std::to_string(rhs.width)+" ]"
);
}
return Error<>("NoError");
}
protected: protected:
using Codes = ImageError::Codes; using Codes = ImageError::Codes;
bool _data_managed;
T* _data; T* _data;
Image(unsigned int x, unsigned int y) void clear() {
: width(x), height(y), _data(nullptr) {} if (_data_managed) {
delete[] _data;
_data_managed = false;
}
_data = nullptr;
}
public: public:
using PixelType = Pixel<T, Channels...>; using PixelType = Pixel<T, Channels...>;
static constexpr size_t NumberChannels = sizeof...(Channels); static constexpr size_t NumberChannels = sizeof...(Channels);
const unsigned int width; const unsigned int width;
const unsigned int height; const unsigned int height;
Image(unsigned int x, unsigned int y, const T* data) static Image&& CreateImageStorage(
: Image(x, y) { unsigned int width,
size_t data_size = width*height*NumberChannels; unsigned int height,
_data = new T[data_size]; T* data=nullptr
std::memcpy(_data, data, data_size*sizeof(T)); ) {
unsigned int data_size = NumberChannels*width*height*sizeof(T);
T* data_ptr = new T[data_size];
auto& ret = Image(width, height, data_ptr);
if (data) {
std::memcpy(data_ptr, data, data_size);
}
ret._data_managed = true;
return std::move(ret);
}
Image(unsigned int x, unsigned int y, T* data=nullptr)
: width(x), height(y), _data(data), _data_managed(false) {}
Image(const Image& cpy)
: Image(cpy.width, cpy.height) {
*this = cpy;
} }
Image(const Image&) = delete;
Image& operator=(const Image&) = delete;
Image& operator=(Image&&) = delete;
Image(Image&& mv) Image(Image&& mv)
: width(mv.width), height(mv.height), _data(mv._data) { : Image(mv.width, mv.height) {
mv._data = nullptr; *this = std::move(mv);
}
Image& operator=(const Image& cpy) {
if (_data_managed) {
THROW(Error<>(Error<>::OVERWRITE_ERROR));
}
const Error<> sizeErr = sizeCompare(cpy);
if (sizeErr.code!=1) { THROW(sizeErr); }
_data = cpy._data;
return this;
}
Image& operator=(Image&& mv) {
if (_data_managed) {
THROW(Error<>(Error<>::OVERWRITE_ERROR));
}
const Error<> sizeErr = sizeCompare(mv);
if (sizeErr.code!=1) { THROW(sizeErr); }
_data = mv._data;
_data_managed = mv._data_managed;
mv._data_managed = false;
return this;
} }
~Image() { virtual ~Image() {
if (_data) { clear();
delete[] _data;
}
} }
const T* data() const { return _data; } const T* data() const { return _data; }
Image&& copy() const { Image<PixelType>&& copy() const {
return Image(width, height, _data); return CreateImageStorage(width, height, _data);
} }
PixelReference<PixelType> at(unsigned int x, unsigned int y) { PixelReference<PixelType> at(unsigned int x, unsigned int y) {
if (!(x<width) || !(y<height)) { if (!(x<width) || !(y<height)) {
@ -188,29 +243,6 @@ class Image<Pixel<T, Channels...>> {
}; };
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 } // namespace nb
#endif // _NB_IMAGE #endif // _NB_IMAGE

View File

@ -2,14 +2,40 @@
#ifndef _NB_OGL_OBJECTS #ifndef _NB_OGL_OBJECTS
#define _NB_OGL_OBJECTS #define _NB_OGL_OBJECTS
#include <NBGraphics/GLLoad.hpp>
#include <NBCore/Errors.hpp> #include <NBCore/Errors.hpp>
#include <NBGraphics/GLLoad.hpp>
#include <NBCore/Utils.hpp>
namespace nb { namespace nb {
class OGLError : public Error<OGLError> { typedef ConstantMap<GLenum, std::string> GLEnumTableType;
using Base = Error<OGLError>;
extern const GLEnumTableType GLenumTable;
class OpenGLError : public Error<OpenGLError> {
using Base = Error<OpenGLError>;
public:
using Base::Base;
enum Codes : unsigned int {
NO_ERROR = GL_NO_ERROR,
INVALID_ENUM = GL_INVALID_ENUM,
INVALID_VALUE = GL_INVALID_VALUE,
INVALID_OPERATION = GL_INVALID_OPERATION,
INVALID_FRAMEBUFFER_OPERATION = GL_INVALID_FRAMEBUFFER_OPERATION,
OUT_OF_MEMORY = GL_OUT_OF_MEMORY,
STACK_UNDERFLOW = GL_STACK_UNDERFLOW,
STACK_OVERFLOW = GL_STACK_OVERFLOW
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
static OpenGLError status();
};
class OpenGLObjectError : public Error<OpenGLObjectError> {
using Base = Error<OpenGLObjectError>;
public: public:
using Base::Base; using Base::Base;
@ -35,7 +61,7 @@ class OpenGLObject {
GLuint id() const { return _id; } GLuint id() const { return _id; }
protected: protected:
using Codes = OGLError::Codes; using Codes = OpenGLObjectError::Codes;
OpenGLObject() = default; OpenGLObject() = default;
virtual GLuint declare() = 0; virtual GLuint declare() = 0;
@ -45,4 +71,43 @@ class OpenGLObject {
}; };
} // namespace nb } // namespace nb
#ifndef OPENGL_CALL
#ifdef _NB_MONITOR_OPENGL_CALLS
namespace NB_OPENGL_CALL_MONITORING {
template<typename Fn>
inline auto run_expression(
const std::string& file,
unsigned int line,
Fn fn
) {
auto check_ = [file, line]() {
const auto no_err = nb::OpenGLError::NO_ERROR;
auto stat = nb::OpenGLError::status();
if (stat.code != no_err) {
THROW_W_CODE_LOC(file, line, stat);
}
};
if constexpr(std::is_same_v<std::invoke_result_t<Fn>, void>) {
check_();
fn();
check_();
} else {
check_();
auto ret = fn();
check_();
return ret;
}
}
};
#define OPENGL_CALL(expression) NB_OPENGL_CALL_MONITORING::run_expression(\
__FILE__,\
__LINE__,\
[&]() {return expression;}\
)
#else
#define OPENGL_CALL(x) x
#endif // _NB_MONITOR_OPENGL_CALLS
#endif // OPENGL_CALL
#endif // _NB_OGL_OBJECTS #endif // _NB_OGL_OBJECTS

View File

@ -78,8 +78,8 @@ class Shader : public OpenGLObject {
for (int i=0; i < num_srcs; ++i) { for (int i=0; i < num_srcs; ++i) {
src_ptrs[i] = _sources[i].data(); src_ptrs[i] = _sources[i].data();
} }
glShaderSource(_id, num_srcs, src_ptrs.data(), NULL); OPENGL_CALL(glShaderSource(_id, num_srcs, src_ptrs.data(), NULL));
glCompileShader(_id); OPENGL_CALL(glCompileShader(_id));
_success = status(GL_COMPILE_STATUS); _success = status(GL_COMPILE_STATUS);
if (!_success) { if (!_success) {
WARN(log(), 0x0FE); WARN(log(), 0x0FE);
@ -88,14 +88,14 @@ class Shader : public OpenGLObject {
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
_id = _id = glCreateShader(target); _id = _id = OPENGL_CALL(glCreateShader(target));
} }
return _id; return _id;
} }
virtual void remove() override { virtual void remove() override {
if (_id) { if (_id) {
glDeleteShader(_id); OPENGL_CALL(glDeleteShader(_id));
} }
} }
@ -113,7 +113,7 @@ class Program : public OpenGLObject {
operator bool(); operator bool();
~Program() { remove(); } ~Program() { remove(); }
virtual void bind() const override { virtual void bind() const override {
glUseProgram(_id); OPENGL_CALL(glUseProgram(_id));
} }
virtual void unbind() const override { /* TODO: Some warning of some kind perhaps*/ } virtual void unbind() const override { /* TODO: Some warning of some kind perhaps*/ }
GLint status(GLenum) const; GLint status(GLenum) const;
@ -125,13 +125,13 @@ class Program : public OpenGLObject {
GLint _success; GLint _success;
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
_id = glCreateProgram(); _id = OPENGL_CALL(glCreateProgram());
} }
return _id; return _id;
} }
virtual void remove() override { virtual void remove() override {
if (_id) { if (_id) {
glDeleteProgram(_id); OPENGL_CALL(glDeleteProgram(_id));
} }
} }

View File

@ -6,6 +6,8 @@
#include <NBGraphics/Image.hpp> #include <NBGraphics/Image.hpp>
#include <NBGraphics/OGLObjects.hpp> #include <NBGraphics/OGLObjects.hpp>
/*! @file Textures.hpp */
namespace nb { namespace nb {
class TextureBuffer : public virtual Buffer { class TextureBuffer : public virtual Buffer {
@ -14,6 +16,9 @@ class TextureBuffer : public virtual Buffer {
}; };
/*!
@brief An OpenGL object that may be rendered to within a Framebuffer.
*/
class RenderTarget : public OpenGLObject { class RenderTarget : public OpenGLObject {
protected: protected:
using Base = OpenGLObject; using Base = OpenGLObject;
@ -23,11 +28,13 @@ class RenderTarget : public OpenGLObject {
: Target(rhs.Target), Base(std::move(rhs)) {} : Target(rhs.Target), Base(std::move(rhs)) {}
public: public:
using Base::Base;
using Base::id; using Base::id;
const GLenum Target; const GLenum Target;
}; };
/*!
@brief An OpenGL Target object
*/
class Texture : public RenderTarget { class Texture : public RenderTarget {
protected: protected:
using Base = RenderTarget; using Base = RenderTarget;
@ -35,7 +42,7 @@ class Texture : public RenderTarget {
Texture(GLenum); Texture(GLenum);
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
glGenTextures(1, &_id); OPENGL_CALL(glGenTextures(1, &_id));
} }
bind(); bind();
return _id; return _id;
@ -43,57 +50,69 @@ class Texture : public RenderTarget {
virtual void remove() override { virtual void remove() override {
if (_id) { if (_id) {
bind(); bind();
glDeleteTextures(0, &_id); OPENGL_CALL(glDeleteTextures(0, &_id));
} }
} }
public: public:
using Base::Base;
using Base::id; using Base::id;
using Base::Target; using Base::Target;
virtual void bind() const override { virtual void bind() const override {
if (_id) { if (_id) {
glBindTexture(Target, _id); OPENGL_CALL(glBindTexture(Target, _id));
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ Texture" "w/ Texture"
)); ));
} }
} }
virtual void unbind() const override { virtual void unbind() const override {
glBindTexture(Target, 0); OPENGL_CALL(glBindTexture(Target, 0));
} }
template <typename T> template <typename T>
void parameter(GLenum param_, const T& val_); void parameter(GLenum param_, const T& val_);
void parameter(GLenum param_, const float& val_) {
declare();
OPENGL_CALL(
glTexParameterf(Target, param_, val_)
);
}
void parameter(GLenum param_, const int& val_) { void parameter(GLenum param_, const int& val_) {
declare(); declare();
glTexParameteri(_id, param_, val_); OPENGL_CALL(
} glTexParameteri(Target, 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_) { void parameter(GLenum param_, const std::vector<float>& val_) {
declare(); declare();
glTexParameterfv(_id, param_, val_.data()); OPENGL_CALL(
glTexParameterfv(Target, param_, val_.data())
);
}
void parameter(GLenum param_, const std::vector<int>& val_) {
declare();
OPENGL_CALL(
glTexParameteriv(Target, param_, val_.data())
);
} }
void parameter(GLenum param_, const std::vector<unsigned int>& val_) { void parameter(GLenum param_, const std::vector<unsigned int>& val_) {
declare(); declare();
glTexParameterIuiv(_id, param_, val_.data()); OPENGL_CALL(
glTexParameterIuiv(Target, param_, val_.data())
);
} }
void generateMipmaps() const { void generateMipmaps() const {
bind(); bind();
glGenerateMipmap(Target); OPENGL_CALL(
glGenerateMipmap(Target)
);
} }
}; };
template<typename T>
class ImageTexture;
template<typename T> template<typename T>
struct OGLPixelFormat; struct OGLPixelFormat;
@ -102,52 +121,110 @@ struct OGLPixelFormat<Pixel<T, Channels...>>;
template<> template<>
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue>> { struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue>> {
static constexpr GLenum glFormat = GL_RGB; static constexpr GLenum glBase = GL_RGB;
static constexpr GLenum glFormat = GL_RGB8UI;
static constexpr GLenum glData = GL_UNSIGNED_BYTE; static constexpr GLenum glData = GL_UNSIGNED_BYTE;
}; };
template<> template<>
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue, Alpha>> { struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue, Alpha>> {
static constexpr GLenum glFormat = GL_RGBA; static constexpr GLenum glBase = GL_RGBA;
static constexpr GLenum glFormat = GL_RGBA8UI;
static constexpr GLenum glData = GL_UNSIGNED_BYTE; static constexpr GLenum glData = GL_UNSIGNED_BYTE;
}; };
template<>
struct OGLPixelFormat<Pixel<float, Red, Green>> {
static constexpr GLenum glBase = GL_RG;
static constexpr GLenum glFormat = GL_RG32F;
static constexpr GLenum glData = GL_FLOAT;
};
template<typename T>
class Texture2D;
template<typename T, typename... Channels> template<typename T, typename... Channels>
class ImageTexture<Pixel<T, Channels...>> : public Texture { class Texture2D<Pixel<T, Channels...>> : public Texture {
protected: protected:
using Texture::Texture; using Texture::Texture;
using PixelType = Pixel<T, Channels...>; using PixelType = Pixel<T, Channels...>;
public: public:
using Texture::generateMipmaps; using Texture::generateMipmaps;
ImageTexture() : Texture(GL_TEXTURE_2D) {} Texture2D() : Texture(GL_TEXTURE_2D) {}
ImageTexture(ImageTexture&& cpy) { Texture2D(Texture2D&& cpy) {
*this = std::move(cpy); *this = std::move(cpy);
} }
ImageTexture& operator=(ImageTexture&& rhs) { Texture2D& operator=(Texture2D&& rhs) {
return Texture::operator=(std::move(rhs)); return Texture::operator=(std::move(rhs));
} }
void setImage(const Image<PixelType>& img, unsigned int layer) { void setLayer(const Image<PixelType>& img, unsigned int layer) {
using Format = OGLPixelFormat<PixelType>; using Format = OGLPixelFormat<PixelType>;
declare(); declare();
glTexImage2D( auto data = img.data();
OPENGL_CALL(glTexImage2D(
Target, Target,
layer, layer,
Format::glFormat, Format::glFormat,
img.width, img.width,
img.height, img.height,
0, 0,
Format::glFormat, Format::glBase,
Format::glData, Format::glData,
img.data() data ? data : nullptr
); ));
} }
void setImage(const Image<PixelType>& img, bool generateMipmap=true) { void setTexture(const Image<PixelType>& img, bool generateMipmap=true) {
setImage(img, (unsigned int)0); setLayer(img, 0);
if (generateMipmap) { generateMipmaps(); } if (generateMipmap) { generateMipmaps(); }
} }
}; };
template<typename T>
class Texture1D;
template<typename T, typename... Channels>
class Texture1D<Pixel<T, Channels...>> : public Texture {
protected:
using Texture::Texture;
using PixelType = Pixel<T, Channels...>;
public:
using Texture::generateMipmaps;
Texture1D() : Texture(GL_TEXTURE_1D) {}
Texture1D(Texture1D&& cpy) {
*this = std::move(cpy);
}
Texture1D& operator=(Texture1D&& rhs) {
return Texture::operator=(std::move(rhs));
}
void setLayer(const Image<PixelType>& tex, unsigned int layer) {
if (tex.height != 1) {
THROW(Error<>(
Error<>::VALUE_ERROR,
"Image must be of height 1"
));
}
using Format = OGLPixelFormat<PixelType>;
declare();
auto data = tex.data();
OPENGL_CALL(glTexImage1D(
Target,
layer,
Format::glFormat,
tex.width,
0,
Format::glBase,
Format::glData,
data ? data : nullptr
));
}
void setTexture(const Image<PixelType>& tex, bool generateMipmap=true) {
setLayer(tex, 0);
if (generateMipmap) { generateMipmaps(); }
}
};
} // namespace nb } // namespace nb
#endif // _NB_TEXTURES #endif // _NB_TEXTURES

View File

@ -88,15 +88,17 @@ class VAO : public OpenGLObject {
virtual void bind() const override { virtual void bind() const override {
if(_id) { if(_id) {
glBindVertexArray(_id); OPENGL_CALL(glBindVertexArray(_id));
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ VertexArrayObject" "w/ VertexArrayObject"
)); ));
} }
} }
virtual void unbind() const override { glBindVertexArray(0); } virtual void unbind() const override {
OPENGL_CALL(glBindVertexArray(0));
}
VertexAttributePointerList attributes() const; VertexAttributePointerList attributes() const;
VertexAttributePointerList attributes(const VertexAttributePointerList&); VertexAttributePointerList attributes(const VertexAttributePointerList&);
@ -114,13 +116,13 @@ class VAO : public OpenGLObject {
if(_id) { if(_id) {
disable(); disable();
bind(); bind();
glDeleteVertexArrays(1, &_id); OPENGL_CALL(glDeleteVertexArrays(1, &_id));
_id = 0; _id = 0;
} }
} }
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
glGenVertexArrays(1, &_id); OPENGL_CALL(glGenVertexArrays(1, &_id));
} }
bind(); bind();
return _id; return _id;

View File

@ -3,6 +3,7 @@
#define _NB_WINDOW #define _NB_WINDOW
#include <NBGraphics/GLLoad.hpp> #include <NBGraphics/GLLoad.hpp>
#include <NBGraphics/OGLObjects.hpp>
#include <array> #include <array>
#include <map> #include <map>
@ -13,8 +14,8 @@
namespace nb { namespace nb {
class OpenGLError : public Error<OpenGLError> { class GLFWError : public Error<GLFWError> {
using Base = Error<OpenGLError>; using Base = Error<GLFWError>;
public: public:
using Base::Base; using Base::Base;

View File

@ -2,7 +2,7 @@
namespace nb { namespace nb {
const std::unordered_map<GLenum, std::string> BufferTypes({ const ConstantMap<GLenum, std::string> BufferTypes({
{GL_ARRAY_BUFFER, "GL_ARRAY_BUFFER"}, {GL_ARRAY_BUFFER, "GL_ARRAY_BUFFER"},
{GL_ELEMENT_ARRAY_BUFFER, "GL_ELEMENT_BUFFER"} {GL_ELEMENT_ARRAY_BUFFER, "GL_ELEMENT_BUFFER"}
}); });
@ -22,10 +22,10 @@ Buffer::Buffer(Buffer&& rval) : Target(rval.Target) {
Buffer& Buffer::operator=(Buffer&& rhs) { Buffer& Buffer::operator=(Buffer&& rhs) {
if (Target != rhs.Target) { if (Target != rhs.Target) {
auto targ_name = BufferTypes.at(Target); auto targ_name = BufferTypes[Target];
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ BufferType "+targ_name+" != BufferType "+BufferTypes.at(rhs.Target) "w/ BufferType "+targ_name+" != BufferType "+BufferTypes[Target]
)); ));
} }
OpenGLObject::operator=(std::move(rhs)); OpenGLObject::operator=(std::move(rhs));
@ -44,13 +44,13 @@ size_t Buffer::size() const { return _size; }
ByteVector Buffer::data() const { ByteVector Buffer::data() const {
bind(); bind();
ByteVector ret(_size); ByteVector ret(_size);
glGetBufferSubData(Target, 0, _size, ret.data()); OPENGL_CALL(glGetBufferSubData(Target, 0, _size, ret.data()));
return ret; return ret;
} }
void Buffer::data(const void* data_, size_t size_, GLenum usage_) { void Buffer::data(const void* data_, size_t size_, GLenum usage_) {
declare(); declare();
glBufferData(Target, size_, data_, usage_); OPENGL_CALL(glBufferData(Target, size_, data_, usage_));
_size = size_; _size = size_;
_usage = usage_; _usage = usage_;
} }
@ -65,7 +65,7 @@ void Buffer::subdata(const void* data_, size_t size_, GLintptr offset_) {
if (offset_+size_ <= _size) { if (offset_+size_ <= _size) {
THROW(BufferError(BufferError::Codes::DATA_OVERFLOW)); THROW(BufferError(BufferError::Codes::DATA_OVERFLOW));
} }
glBufferSubData(Target, offset_, size_, data_); OPENGL_CALL(glBufferSubData(Target, offset_, size_, data_));
} }
void Buffer::subdata(const ByteVector& data_, GLintptr offset_) { void Buffer::subdata(const ByteVector& data_, GLintptr offset_) {

View File

@ -11,7 +11,9 @@ const ErrorCodeMap FrameBufferError::ErrorMessages = {
GLuint FrameBufferBase::declare() { GLuint FrameBufferBase::declare() {
if (!_id) { if (!_id) {
glGenFramebuffers(1, &_id); OPENGL_CALL(
glGenFramebuffers(1, &_id)
);
} }
bind(); bind();
return _id; return _id;
@ -20,7 +22,9 @@ GLuint FrameBufferBase::declare() {
void FrameBufferBase::remove() { void FrameBufferBase::remove() {
if (_id) { if (_id) {
unbind(); unbind();
glDeleteFramebuffers(1, &_id); OPENGL_CALL(
glDeleteFramebuffers(1, &_id)
);
_id=0; _id=0;
} }
} }
@ -31,7 +35,9 @@ std::shared_ptr<RenderTarget> FrameBufferBase::detach(GLenum attch_) {
bind(); bind();
auto ret = _attachments.at(attch_); auto ret = _attachments.at(attch_);
_attachments.erase(attch_); _attachments.erase(attch_);
glFramebufferTexture(Target, attch_, 0, 0); OPENGL_CALL(
glFramebufferTexture(Target, attch_, 0, 0)
);
return ret; return ret;
} }
@ -47,13 +53,13 @@ void FrameBufferBase::attach(
"Cannot attach object to `GL_NONE`" "Cannot attach object to `GL_NONE`"
)); ));
} }
glFramebufferTextureLayer( OPENGL_CALL(glFramebufferTextureLayer(
Target, Target,
attachment_, attachment_,
texture_->id(), texture_->id(),
level_, level_,
layer_ layer_
); ));
_attachments[attachment_] = texture_; _attachments[attachment_] = texture_;
} }
@ -69,43 +75,72 @@ void FrameBufferBase::attach(
)); ));
} }
if (texTypeIs2D(texture_->Target)) { if (texTypeIs2D(texture_->Target)) {
glFramebufferTexture2D( OPENGL_CALL(glFramebufferTexture2D(
Target, Target,
attachment_, attachment_,
texture_->Target, texture_->Target,
texture_->id(), texture_->id(),
level_ level_
); ));
} else { } else {
glFramebufferTexture1D( OPENGL_CALL(glFramebufferTexture1D(
Target, Target,
attachment_, attachment_,
texture_->Target, texture_->Target,
texture_->id(), texture_->id(),
level_ level_
); ));
} }
_attachments[attachment_] = texture_; _attachments[attachment_] = texture_;
} }
void FrameBufferBase::attach(
GLenum attachment,
std::shared_ptr<RenderBuffer> renderbuffer
) {
declare();
if (attachment == GL_NONE) {
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
"Cannot attach RenderBuffer to `GL_NONE`"
));
}
OPENGL_CALL(glFramebufferRenderbuffer(
Target,
attachment,
GL_RENDERBUFFER,
renderbuffer->id()
));
_attachments[attachment] = renderbuffer;
}
void FrameBufferBase::bind() const { void FrameBufferBase::bind() const {
if (_id) { if (_id) {
glBindFramebuffer(Target, _id); OPENGL_CALL(
glBindFramebuffer(Target, _id)
);
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ FrameBuffer" "w/ FrameBuffer"
)); ));
} }
} }
void FrameBufferBase::unbind() const { void FrameBufferBase::unbind() const {
glBindFramebuffer(Target, 0); OPENGL_CALL(
glBindFramebuffer(Target, 0)
);
} }
GLenum FrameBufferBase::status() const { GLenum FrameBufferBase::status() const {
bind(); bind();
return glCheckFramebufferStatus(Target); return OPENGL_CALL(
glCheckFramebufferStatus(Target)
);
}
bool FrameBufferBase::complete() const {
return status() == GL_FRAMEBUFFER_COMPLETE;
} }
FrameBufferBase::AttachmentMap FrameBufferBase::getAllBuffers() const { FrameBufferBase::AttachmentMap FrameBufferBase::getAllBuffers() const {
@ -166,7 +201,7 @@ std::shared_ptr<RenderTarget> ReadFrameBuffer::setReadBuffer(GLenum attch_) {
} }
} }
_location = attch_; _location = attch_;
glReadBuffer(_location); OPENGL_CALL(glReadBuffer(_location));
return getReadBuffer(); return getReadBuffer();
} }
@ -222,7 +257,9 @@ WriteFrameBuffer::DrawTexVec WriteFrameBuffer::setWriteBuffers(const std::vector
} }
} }
_locations = attchs_; _locations = attchs_;
glDrawBuffers(_locations.size(), _locations.data()); OPENGL_CALL(
glDrawBuffers(_locations.size(), _locations.data())
);
return getWriteBuffers(); return getWriteBuffers();
} }
@ -230,7 +267,9 @@ std::shared_ptr<Texture> WriteFrameBuffer::setWriteBuffer(GLenum attch_) {
bind(); bind();
if (attch_ == GL_NONE) { if (attch_ == GL_NONE) {
std::vector<GLenum> tmp(_locations.size(), GL_NONE); std::vector<GLenum> tmp(_locations.size(), GL_NONE);
glDrawBuffers(tmp.size(), tmp.data()); OPENGL_CALL(
glDrawBuffers(tmp.size(), tmp.data())
);
_locations = {}; _locations = {};
return nullptr; return nullptr;
} }
@ -241,13 +280,17 @@ std::shared_ptr<Texture> WriteFrameBuffer::setWriteBuffer(GLenum attch_) {
fRGBA WriteFrameBuffer::clearColorValue() const { fRGBA WriteFrameBuffer::clearColorValue() const {
bind(); bind();
float rgba[4]; float rgba[4];
glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); OPENGL_CALL(
glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba)
);
return fRGBA{rgba[0], rgba[1], rgba[2], rgba[3]}; return fRGBA{rgba[0], rgba[1], rgba[2], rgba[3]};
} }
fRGBA WriteFrameBuffer::clearColorValue(const fRGBA& color) { fRGBA WriteFrameBuffer::clearColorValue(const fRGBA& color) {
declare(); declare();
glClearColor(color.r, color.g, color.b, color.a); OPENGL_CALL(
glClearColor(color.r, color.g, color.b, color.a)
);
return color; return color;
} }
@ -258,32 +301,42 @@ fRGBA WriteFrameBuffer::clearColorValue(float r, float g, float b, float a) {
double WriteFrameBuffer::clearDepthValue() const { double WriteFrameBuffer::clearDepthValue() const {
bind(); bind();
double ret; double ret;
glGetDoublev(GL_DEPTH_CLEAR_VALUE, &ret); OPENGL_CALL(
glGetDoublev(GL_DEPTH_CLEAR_VALUE, &ret)
);
return ret; return ret;
} }
double WriteFrameBuffer::clearDepthValue(double d_) { double WriteFrameBuffer::clearDepthValue(double d_) {
declare(); declare();
glClearDepth(d_); OPENGL_CALL(
glClearDepth(d_)
);
return d_; return d_;
} }
GLint WriteFrameBuffer::clearStencilValue() const { GLint WriteFrameBuffer::clearStencilValue() const {
bind(); bind();
GLint ret; GLint ret;
glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &ret); OPENGL_CALL(
glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &ret)
);
return ret; return ret;
} }
GLint WriteFrameBuffer::clearStencilValue(GLint s_) { GLint WriteFrameBuffer::clearStencilValue(GLint s_) {
declare(); declare();
glClearStencil(s_); OPENGL_CALL(
glClearStencil(s_)
);
return s_; return s_;
} }
void WriteFrameBuffer::clear(GLbitfield mask_) const { void WriteFrameBuffer::clear(GLbitfield mask_) const {
bind(); bind();
glClear(mask_); OPENGL_CALL(
glClear(mask_)
);
} }
void WriteFrameBuffer::clearDepth() const { void WriteFrameBuffer::clearDepth() const {
@ -292,7 +345,9 @@ void WriteFrameBuffer::clearDepth() const {
void WriteFrameBuffer::clearDepth(float val_) const { void WriteFrameBuffer::clearDepth(float val_) const {
bind(); bind();
glClearBufferfv(GL_DEPTH, 0, &val_); OPENGL_CALL(
glClearBufferfv(GL_DEPTH, 0, &val_)
);
} }
void WriteFrameBuffer::clearStencil() const { void WriteFrameBuffer::clearStencil() const {
@ -301,7 +356,9 @@ void WriteFrameBuffer::clearStencil() const {
void WriteFrameBuffer::clearStencil(GLint val_) const { void WriteFrameBuffer::clearStencil(GLint val_) const {
bind(); bind();
glClearBufferiv(GL_STENCIL, 0, &val_); OPENGL_CALL(
glClearBufferiv(GL_STENCIL, 0, &val_)
);
} }
void WriteFrameBuffer::clearDepthStencil() const { void WriteFrameBuffer::clearDepthStencil() const {
@ -310,7 +367,9 @@ void WriteFrameBuffer::clearDepthStencil() const {
void WriteFrameBuffer::clearDepthStencil(float d_, GLint s_) const { void WriteFrameBuffer::clearDepthStencil(float d_, GLint s_) const {
bind(); bind();
glClearBufferfi(GL_DEPTH_STENCIL, 0, d_, s_); OPENGL_CALL(
glClearBufferfi(GL_DEPTH_STENCIL, 0, d_, s_)
);
} }
FrameBuffer::FrameBuffer() FrameBuffer::FrameBuffer()

View File

@ -1,23 +1,65 @@
#include <NBGraphics/OGLObjects.hpp> #include <NBGraphics/OGLObjects.hpp>
#ifndef GLENUMSTRPAIR
#define GLENUMSTRPAIR(x) {x, #x}
#endif // GLENUMSTRPAIR
namespace nb { namespace nb {
const std::string OGLError::type = "nb::OGLError"; const std::string OpenGLObjectError::type = "nb::OpenGLObjectError";
const ErrorCodeMap OGLError::ErrorMessages = { const ErrorCodeMap OpenGLObjectError::ErrorMessages = {
{ OGLError::Codes::UNDEFINED, "Error" }, { OpenGLObjectError::Codes::UNDEFINED, "Error" },
{OGLError::Codes::HANGING_OBJECT, "Attempting to leave a hanging OpenGL object"}, {OpenGLObjectError::Codes::HANGING_OBJECT, "Attempting to leave a hanging OpenGL object"},
{OGLError::Codes::INVALID_OBJECT, "Attempting operation with invalid object"} {OpenGLObjectError::Codes::INVALID_OBJECT, "Attempting operation with invalid object"}
}; };
const std::string OpenGLError::type = "nb::OpenGLError";
const ErrorCodeMap OpenGLError::ErrorMessages = {
GLENUMSTRPAIR(GL_NO_ERROR),
GLENUMSTRPAIR(GL_INVALID_ENUM),
GLENUMSTRPAIR(GL_INVALID_ENUM),
GLENUMSTRPAIR(GL_INVALID_VALUE),
GLENUMSTRPAIR(GL_INVALID_OPERATION),
GLENUMSTRPAIR(GL_INVALID_FRAMEBUFFER_OPERATION),
GLENUMSTRPAIR(GL_OUT_OF_MEMORY),
GLENUMSTRPAIR(GL_STACK_UNDERFLOW),
GLENUMSTRPAIR(GL_STACK_OVERFLOW)
};
OpenGLError OpenGLError::status() {
return OpenGLError(glGetError());
}
OpenGLObject::OpenGLObject(OpenGLObject&& rval) { OpenGLObject::OpenGLObject(OpenGLObject&& rval) {
*this = std::move(rval); *this = std::move(rval);
} }
OpenGLObject& OpenGLObject::operator=(OpenGLObject&& rhs) { OpenGLObject& OpenGLObject::operator=(OpenGLObject&& rhs) {
if (_id) { THROW(OGLError(Codes::HANGING_OBJECT)); } if (_id) { THROW(OpenGLObjectError(Codes::HANGING_OBJECT)); }
_id = rhs._id; _id = rhs._id;
rhs._id = 0; rhs._id = 0;
return *this; return *this;
} }
const GLEnumTableType GLenumTable = {
GLENUMSTRPAIR(GL_DRAW_FRAMEBUFFER),
GLENUMSTRPAIR(GL_FRAMEBUFFER),
GLENUMSTRPAIR(GL_FRAMEBUFFER_COMPLETE),
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT),
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER),
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS),
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT),
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE),
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER),
GLENUMSTRPAIR(GL_FRAMEBUFFER_UNDEFINED),
GLENUMSTRPAIR(GL_FRAMEBUFFER_UNSUPPORTED),
GLENUMSTRPAIR(GL_READ_FRAMEBUFFER),
GLENUMSTRPAIR(GL_RG),
GLENUMSTRPAIR(GL_RG32F),
GLENUMSTRPAIR(GL_RGB),
GLENUMSTRPAIR(GL_RGB8UI),
GLENUMSTRPAIR(GL_RGBA8UI),
GLENUMSTRPAIR(GL_RGBA),
};
} // namespace nb } // namespace nb

View File

@ -41,14 +41,14 @@ bool Shader::success() const {
GLint Shader::status(GLenum parameter) const { GLint Shader::status(GLenum parameter) const {
GLint param = 0; GLint param = 0;
glGetShaderiv(_id, parameter, &param); OPENGL_CALL(glGetShaderiv(_id, parameter, &param));
return param; return param;
} }
std::string Shader::log() const { std::string Shader::log() const {
GLint logsize = status(GL_INFO_LOG_LENGTH); GLint logsize = status(GL_INFO_LOG_LENGTH);
char* log_ = new char[logsize]; char* log_ = new char[logsize];
glGetShaderInfoLog(_id, logsize, NULL, log_); OPENGL_CALL(glGetShaderInfoLog(_id, logsize, NULL, log_));
std::string ret(log_, logsize); std::string ret(log_, logsize);
delete[] log_; delete[] log_;
return ret; return ret;
@ -57,9 +57,9 @@ std::string Shader::log() const {
Program::Program(SharedVector<Shader> shaders_) { Program::Program(SharedVector<Shader> shaders_) {
declare(); declare();
for (auto shad_ptr : shaders_) { for (auto shad_ptr : shaders_) {
glAttachShader(_id, shad_ptr->id()); OPENGL_CALL(glAttachShader(_id, shad_ptr->id()));
} }
glLinkProgram(_id); OPENGL_CALL(glLinkProgram(_id));
_success = status(GL_LINK_STATUS); _success = status(GL_LINK_STATUS);
if (!_success) { if (!_success) {
WARN(log(), 0x0FE); WARN(log(), 0x0FE);
@ -70,14 +70,14 @@ Program::operator bool() { return _success; }
GLint Program::status(GLenum parameter) const { GLint Program::status(GLenum parameter) const {
GLint param = 0; GLint param = 0;
glGetProgramiv(_id, parameter, &param); OPENGL_CALL(glGetProgramiv(_id, parameter, &param));
return param; return param;
} }
std::string Program::log() const { std::string Program::log() const {
GLint logsize = status(GL_INFO_LOG_LENGTH); GLint logsize = status(GL_INFO_LOG_LENGTH);
char* log_ = new char[logsize]; char* log_ = new char[logsize];
glGetProgramInfoLog(_id, logsize, NULL, log_); OPENGL_CALL(glGetProgramInfoLog(_id, logsize, NULL, log_));
std::string ret(log_, logsize); std::string ret(log_, logsize);
delete[] log_; delete[] log_;
return ret; return ret;

View File

@ -41,17 +41,17 @@ VertexAttributePointerList VAO::attributes(const VertexAttributePointerList& att
_attrs = attrs_; _attrs = attrs_;
bind(); bind();
for (auto attr_ptr : attrs_) { for (auto attr_ptr : attrs_) {
glBindBuffer(GL_ARRAY_BUFFER, attr_ptr.buffer); OPENGL_CALL(glBindBuffer(GL_ARRAY_BUFFER, attr_ptr.buffer));
GLuint idx = attr_ptr.index; GLuint idx = attr_ptr.index;
glVertexAttribPointer( OPENGL_CALL(glVertexAttribPointer(
idx, idx,
attr_ptr.attribute.GLSLSize, attr_ptr.attribute.GLSLSize,
attr_ptr.attribute.GLSLType, attr_ptr.attribute.GLSLType,
attr_ptr.attribute.GLSLNormalization, attr_ptr.attribute.GLSLNormalization,
attr_ptr.attribute.layout.stride, attr_ptr.attribute.layout.stride,
(void*)attr_ptr.attribute.layout.offset (void*)attr_ptr.attribute.layout.offset
); ));
glEnableVertexAttribArray(idx); OPENGL_CALL(glEnableVertexAttribArray(idx));
} }
unbind(); unbind();
return _attrs; return _attrs;
@ -70,7 +70,7 @@ void VAO::enable() const {
if (_id) { if (_id) {
bind(); bind();
for(auto attr_ptr : _attrs) { for(auto attr_ptr : _attrs) {
glEnableVertexAttribArray(attr_ptr.index); OPENGL_CALL(glEnableVertexAttribArray(attr_ptr.index));
} }
unbind(); unbind();
} }
@ -79,7 +79,7 @@ void VAO::enable() const {
void VAO::enable(GLuint idx) const { void VAO::enable(GLuint idx) const {
if(_id) { if(_id) {
bind(); bind();
glEnableVertexAttribArray(attr(idx).index); OPENGL_CALL(glEnableVertexAttribArray(attr(idx).index));
unbind(); unbind();
} }
} }
@ -88,7 +88,7 @@ void VAO::disable() const {
if(_id) { if(_id) {
bind(); bind();
for(auto attr_ptr : _attrs) { for(auto attr_ptr : _attrs) {
glDisableVertexAttribArray(attr_ptr.index); OPENGL_CALL(glDisableVertexAttribArray(attr_ptr.index));
} }
unbind(); unbind();
} }
@ -97,7 +97,7 @@ void VAO::disable() const {
void VAO::disable(GLuint idx) const { void VAO::disable(GLuint idx) const {
if(_id) { if(_id) {
bind(); bind();
glDisableVertexAttribArray(attr(idx).index); OPENGL_CALL(glDisableVertexAttribArray(attr(idx).index));
unbind(); unbind();
} }
} }
@ -120,7 +120,9 @@ VertexGroup& VertexGroup::operator=(VertexGroup&& rhs) {
void VertexGroup::draw() const { void VertexGroup::draw() const {
bind(); bind();
glDrawElements(primitive, _ebo->size(), _ebo->glslType(), 0); OPENGL_CALL(
glDrawElements(primitive, _ebo->size(), _ebo->glslType(), 0)
);
} }
size_t VertexGroup::addBuffer(const VertexData& vertex_data_) { size_t VertexGroup::addBuffer(const VertexData& vertex_data_) {
@ -177,7 +179,7 @@ VertexDataVec VertexGroup::dropBuffers() {
VertexData VertexGroup::dropBuffer(size_t idx) { VertexData VertexGroup::dropBuffer(size_t idx) {
if (idx >= _vertex_data.size()) { if (idx >= _vertex_data.size()) {
THROW(Error(Error<>::INDEX_ERROR)); THROW(Error(Error<>::OUT_OF_RANGE));
} }
VertexDataVec tmp; VertexDataVec tmp;
VertexData ret; VertexData ret;

View File

@ -16,13 +16,13 @@ static std::map<int, int> defailt_window_hints = {
#endif #endif
}; };
using OpenGLErrorCodes = OpenGLError::Codes; using GLFWCodes = GLFWError::Codes;
const std::string OpenGLError::type = "nb::OpenGLError"; const std::string GLFWError::type = "nb::GLFWError";
const ErrorCodeMap OpenGLError::ErrorMessages = { const ErrorCodeMap GLFWError::ErrorMessages = {
{OpenGLErrorCodes::UNDEFINED, "Error"}, {GLFWCodes::UNDEFINED, "Error"},
{OpenGLErrorCodes::INIT_FAILED, "GLFW initialization failed"}, {GLFWCodes::INIT_FAILED, "GLFW initialization failed"},
{OpenGLErrorCodes::GLFW_INTIALIZED, "GLFW has already been initialized"}, {GLFWCodes::GLFW_INTIALIZED, "GLFW has already been initialized"},
{OpenGLErrorCodes::GLAD_FAILED, "GLAD initialization failed"} {GLFWCodes::GLAD_FAILED, "GLAD initialization failed"}
}; };
using WindowErrorCodes = WindowError::Codes; using WindowErrorCodes = WindowError::Codes;
@ -44,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(OpenGLError(OpenGLErrorCodes::GLFW_INTIALIZED)); THROW(GLFWError(GLFWCodes::GLFW_INTIALIZED));
} else { } else {
GLFWHints[hint_key] = hint_val; GLFWHints[hint_key] = hint_val;
} }
@ -74,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(OpenGLError(OpenGLErrorCodes::INIT_FAILED)); THROW(GLFWError(GLFWCodes::INIT_FAILED));
} }
} }
} }
@ -147,12 +147,14 @@ int Window::init() {
if (!gladResponse) { if (!gladResponse) {
Window::checkKillGLFW(); Window::checkKillGLFW();
if (Window::StrictInitialization) { if (Window::StrictInitialization) {
THROW(OpenGLError(OpenGLErrorCodes::GLAD_FAILED)); THROW(GLFWError(GLFWCodes::GLAD_FAILED));
} }
} }
_init = true; _init = true;
glViewport(0, 0, windowSize[0], windowSize[1]); OPENGL_CALL(
glViewport(0, 0, windowSize[0], windowSize[1])
);
return gladResponse; return gladResponse;
} }
@ -173,7 +175,9 @@ std::string Window::getName() const {
void Window::resize(const std::array<uint16_t, 2> newSize) { void Window::resize(const std::array<uint16_t, 2> newSize) {
windowSize = newSize; windowSize = newSize;
_aspect_ratio = float(newSize[0]) / float(newSize[1]); _aspect_ratio = float(newSize[0]) / float(newSize[1]);
glViewport(0, 0, windowSize[0], windowSize[1]); OPENGL_CALL(
glViewport(0, 0, windowSize[0], windowSize[1])
);
glfwSetWindowSize(window, windowSize[0], windowSize[1]); glfwSetWindowSize(window, windowSize[0], windowSize[1]);
} }

View File

@ -4,21 +4,29 @@ if (NB_BUILD_TESTS)
enable_testing() enable_testing()
include(GoogleTest) include(GoogleTest)
set(STBIMAGE_PATH ${NBENGINE_ROOT}/../stbi_image)
get_filename_component(STBIMAGE_PATH ${STBIMAGE_PATH} ABSOLUTE)
add_executable(TestWindow add_executable(TestWindow
./TestWindow.cpp ./TestWindow.cpp
) )
target_link_libraries(TestWindow target_link_libraries(TestWindow
NBGraphics NBGraphics
) )
target_include_directories(TestWindow
PRIVATE "${STBIMAGE_PATH}"
)
add_executable(TestImages add_executable(TestImages
./testImages.cpp ./testImages.cpp
) )
target_link_libraries(TestImages target_link_libraries(TestImages
NBCore
NBGraphics NBGraphics
GTest::gtest_main GTest::gtest_main
) )
target_include_directories(TestImages
PRIVATE "${STBIMAGE_PATH}"
)
gtest_discover_tests(TestImages) gtest_discover_tests(TestImages)

View File

@ -2,14 +2,16 @@
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" #include "stb_image.h"
#include <NBCore/Errors.hpp>
#include <NBGraphics/Image.hpp> #include <NBGraphics/Image.hpp>
#include <NBGraphics/ProgramPipeline.hpp> #include <NBGraphics/ProgramPipeline.hpp>
#include <NBGraphics/VertexArray.hpp> #include <NBGraphics/VertexArray.hpp>
#include <NBGraphics/Window.hpp> #include <NBGraphics/Window.hpp>
#include <NBGraphics/Textures.hpp> #include <NBGraphics/Textures.hpp>
int main() { int main() {
nb::logger.log("Howdy!"); LOG("Howdy!");
nb::Window window(400, 400, "Hello!"); nb::Window window(400, 400, "Hello!");
window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
@ -19,12 +21,12 @@ int main() {
GL_VERTEX_SHADER, GL_VERTEX_SHADER,
"#version 330 core\n" "#version 330 core\n"
"layout (location = 0) in vec2 aPos;\n" "layout (location = 0) in vec2 aPos;\n"
"layout (location = 1) in vec2 tPos;\n" "out vec4 vColor;\n"
"out vec2 vPos;\n"
"void main()\n" "void main()\n"
"{\n" "{\n"
" gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);\n" " gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);\n"
" vPos = tPos;\n" " vec2 tmp = (aPos+vec2(1.0, 1.0))*0.5;\n"
" vColor = vec4(tmp.x, 0, tmp.y, 1.0);\n"
"}\0" "}\0"
); );
@ -33,71 +35,41 @@ int main() {
auto frag = std::make_shared<nb::Shader>( auto frag = std::make_shared<nb::Shader>(
GL_FRAGMENT_SHADER, GL_FRAGMENT_SHADER,
"#version 330 core\n" "#version 330 core\n"
"in vec2 vPos;\n" "in vec4 vColor;\n"
"out vec4 FragColor;\n" "out vec4 FragColor;\n"
"uniform sampler2D tex;\n"
"void main()\n" "void main()\n"
"{\n" "{\n"
" FragColor = texture(tex, vPos);\n" " FragColor = vColor;\n"
"}\n\0" "}\n\0"
); );
LOG(frag->log()); LOG(frag->log());
nb::ByteVector data = nb::vectorToBytes<float>({ nb::ByteVector data = nb::vectorToBytes<float>({
-0.5, -0.5, 0,0, -0.5, -0.5,
-0.5, 0.5, 0,1, 0, 0.5,
0.5, 0.5, 1,1, 0.5, -0.5
0.5, -0.5, 1,0
}); });
nb::Program prog({vert, frag}); nb::Program prog({vert, frag});
prog.bind(); prog.bind();
std::vector<uint32_t> indxs = {0, 1, 2, 0, 2, 3}; std::vector<uint32_t> indxs = {0, 1, 2};
nb::VertexGroup tri(data, { nb::VertexGroup tri(data, {
nb::VertexAttribute{ nb::VertexAttribute{
2, 2,
GL_FLOAT, GL_FLOAT,
false, false,
{0, 16} {0, 8}
}, },
nb::VertexAttribute{
2,
GL_FLOAT,
false,
{8, 16}
}
}, indxs); }, 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()); LOG(prog.log());
GLFWwindow* window_ptr = window.getWindow(); GLFWwindow* window_ptr = window.getWindow();
while(!glfwWindowShouldClose(window_ptr)) { while(!glfwWindowShouldClose(window_ptr)) {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f); OPENGL_CALL(glClearColor(0.2f, 0.3f, 0.3f, 1.0f));
glClear(GL_COLOR_BUFFER_BIT); OPENGL_CALL(glClear(GL_COLOR_BUFFER_BIT));
tri.draw(); tri.draw();
glfwPollEvents(); glfwPollEvents();
glfwSwapBuffers(window_ptr); glfwSwapBuffers(window_ptr);