check it out

This commit is contained in:
L-Nafaryus 2023-03-13 22:27:09 +05:00
parent 2811c525d3
commit 9599029c3d
159 changed files with 11334 additions and 8402 deletions

8
.gitignore vendored
View File

@ -1,8 +1,10 @@
cmake-wsl-build-debug
cmake-build-debug/
cmake-build*/
build*/
.idea/
build/
.ccls-cache/
compile_commands.json
.cache/
temp/

View File

@ -1,29 +1,34 @@
cmake_minimum_required (VERSION 3.16)
#
set(HPR_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
set(HPR_EXTERNAL_PATH "${HPR_MODULE_PATH}/external")
set(HPR_TOOLCHAINS_PATH "${HPR_MODULE_PATH}/toolchains")
set(HPR_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/source")
# toolchain
#if (MINGW)
# set(CMAKE_TOOLCHAIN_FILE "${HPR_TOOLCHAINS_PATH}/mingw-gcc.cmake")
#else()
# set(CMAKE_TOOLCHAIN_FILE "${HPR_TOOLCHAINS_PATH}/linux-gcc.cmake")
#endif()
# Extract project version from source
file(STRINGS "source/hpr/core/common.hpp"
hpr_version_defines REGEX "#define HPR_VERSION_(MAJOR|MINOR|PATCH) ")
include(${HPR_MODULE_PATH}/hpr-macros.cmake)
foreach(ver ${hpr_version_defines})
if(ver MATCHES [[#define HPR_VERSION_(MAJOR|MINOR|PATCH) +([^ ]+)$]])
set(HPR_VERSION_${CMAKE_MATCH_1} "${CMAKE_MATCH_2}")
endif()
endforeach()
if(HPR_VERSION_PATCH MATCHES [[\.([a-zA-Z0-9]+)$]])
set(hpr_VERSION_TYPE "${CMAKE_MATCH_1}")
endif()
string(REGEX MATCH "^[0-9]+" HPR_VERSION_PATCH "${HPR_VERSION_PATCH}")
set(HPR_PROJECT_VERSION "${HPR_VERSION_MAJOR}.${HPR_VERSION_MINOR}.${HPR_VERSION_PATCH}")
hpr_parse_version("${HPR_SOURCE_DIR}/hpr/hpr.hpp" "#define HPR_VERSION_(MAJOR|MINOR|PATCH)")
# Main project
project(
hpr
VERSION "${HPR_PROJECT_VERSION}"
VERSION "${HPR_VERSION}"
LANGUAGES CXX
)
# Compiler settings
set(CMAKE_CXX_STANDARD 20)
# Detect how project is used
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)
@ -35,133 +40,124 @@ if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
message(AUTHOR_WARNING ${lines})
endif()
set(HPR_MASTER_PROJECT ON)
set(CMAKE_CXX_STANDARD 20)
message(STATUS ${CMAKE_SOURCE_DIR})
set(HPR_IS_TOP_LEVEL ON)
else()
set(HPR_MASTER_PROJECT OFF)
set(HPR_IS_TOP_LEVEL OFF)
endif()
# Project options
option(HPR_INSTALL "Install hpr files?" ${HPR_IS_TOP_LEVEL})
option(HPR_TEST "Build hpr tests?" ${HPR_IS_TOP_LEVEL})
# Standard includes
# Installation settings
include(GNUInstallDirs)
include(CPack)
# Options
option(HPR_INSTALL "Install hpr files?" ${HPR_MASTER_PROJECT})
option(HPR_TEST "Build hpr tests?" ${HPR_MASTER_PROJECT})
set(HPR_INSTALL_INTERFACE "$<INSTALL_INTERFACE:include/${PROJECT_NAME}") # ! '>' not included
# Package manager
include(${HPR_MODULE_PATH}/tools/CPM.cmake)
# Testing
if(HPR_TEST)
enable_testing()
option(INSTALL_GMOCK "" OFF)
option(INSTALL_GTEST "" OFF)
include(${CMAKE_SOURCE_DIR}/cmake/external/googletest.cmake)
include("${HPR_EXTERNAL_PATH}/googletest.cmake")
include(GoogleTest)
endif()
# Modules
option(WITH_CONTAINERS "" ON)
option(WITH_MATH "" ON)
option(WITH_IO "" ON)
option(WITH_MESH "" ON)
option(WITH_CSG "" ON)
option(USE_SYSTEM_OCCT "" ON)
option(WITH_GPU "" ON)
option(WITH_WINDOW_SYSTEM "" ON)
# Uninstall target
if (NOT TARGET uninstall)
configure_file(
"${CMAKE_CURRENT_LIST_DIR}/cmake/templates/cmake_uninstall.cmake.in" cmake_uninstall.cmake
IMMEDIATE @ONLY
)
set_property(GLOBAL PROPERTY HPR_MODULES "")
macro(add_module MODULE)
set_property(GLOBAL APPEND PROPERTY HPR_MODULES "${MODULE}")
endmacro()
add_custom_target(uninstall "${CMAKE_COMMAND}" -P "${PROJECT_BINARY_DIR}/cmake_uninstall.cmake")
endif()
# Modules
option(HPR_WITH_CONTAINERS "" ON)
option(HPR_WITH_MATH "" ON)
option(HPR_WITH_IO "" ON)
option(HPR_WITH_MESH "" ON)
option(HPR_WITH_CSG "" ON)
option(HPR_WITH_GPU "" ON)
option(HPR_WITH_PARALLEL "" ON)
include_directories(${HPR_SOURCE_DIR})
add_subdirectory(source/hpr)
get_property(hpr_modules GLOBAL PROPERTY HPR_MODULES)
foreach(module ${hpr_modules})
get_target_property(module_type ${module} TYPE)
if(module_type STREQUAL "INTERFACE_LIBRARY")
list(APPEND HPR_INTERFACE_LIBS "${PROJECT_NAME}::${module}")
else()
list(APPEND HPR_PUBLIC_LIBS "${PROJECT_NAME}::${module}")
endif()
set(hpr_modules_summary "${hpr_modules_summary} ${module}")
endforeach()
hpr_collect_modules()
# Main library
add_library(hpr SHARED
source/hpr/hpr.cpp)
add_library(hpr SHARED source/hpr/hpr.cpp)
add_library(hpr::hpr ALIAS hpr)
target_sources(hpr
INTERFACE
"$<BUILD_INTERFACE:source/hpr/hpr.hpp>"
"$<INSTALL_INTERFACE:include/${PROJECT_NAME}>"
INTERFACE "$<BUILD_INTERFACE:source/hpr/hpr.hpp>" "${HPR_INSTALL_INTERFACE}>"
)
target_link_libraries(hpr
INTERFACE
${HPR_INTERFACE_LIBS}
PUBLIC
${HPR_PUBLIC_LIBS}
INTERFACE ${HPR_INTERFACE_LIBS}
PUBLIC ${HPR_PUBLIC_LIBS}
)
# Installation
if (HPR_INSTALL)
include(CMakePackageConfigHelpers)
configure_package_config_file(
"${PROJECT_SOURCE_DIR}/cmake/${PROJECT_NAME}Config.cmake.in"
"${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
INSTALL_DESTINATION
${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}-${PROJECT_VERSION}
"${HPR_MODULE_PATH}/templates/Config.cmake.in" "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}
)
write_basic_package_version_file(
"${PROJECT_NAME}ConfigVersion.cmake"
VERSION ${PROJECT_VERSION}
COMPATIBILITY SameMajorVersion
VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion
)
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
DESTINATION
${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}-${PROJECT_VERSION}
${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake
${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} COMPONENT devel
)
install(
TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_SKIP
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT devel
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT devel
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} COMPONENT devel
)
install(
EXPORT ${PROJECT_NAME}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CMAKE_PROJECT_NAME}-${HPR_PROJECT_VERSION}
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} COMPONENT devel
NAMESPACE ${CMAKE_PROJECT_NAME}::
)
install(
TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_ONLY
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
FILES source/${PROJECT_NAME}/${PROJECT_NAME}.hpp
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} COMPONENT devel
)
set(CPACK_PACKAGE_NAME "${PROJECT_NAME}")
set(CPACK_PACKAGE_VERSION "${HPR_VERSION}")
include(CPack)
cpack_add_component(devel DISPLAY_NAME "Development")
cpack_add_component(runtime DISPLAY_NAME "Runtime libraries")
endif()
# Project summary
set(summary
"Summary:\n"
"Version: ${HPR_PROJECT_VERSION}\n"
"Master: ${HPR_MASTER_PROJECT}\n"
"Modules: ${hpr_modules_summary}"
)
message(STATUS ${summary})
hpr_print_summary()
# Documentation
#add_subdirectory(docs)
# Additional applications
add_subdirectory(source/applications)
add_subdirectory(source/creator)
add_subdirectory(source/applications)

View File

@ -0,0 +1,36 @@
# hpr
## Installation from sources
### Prerequisites
- CMake version 3.16 (or newer)
### Configure
```
cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug -B cmake-build-debug -S .
```
### Build
```
cmake --build cmake-build-debug --target hpr
```
### Install
```
cmake --install cmake-build-debug --component devel
```
The following install components are supported:
- `runtime` - runtime package (core shared libraries and `.dll` files on Windows* OS).
- `devel` - development package (header files, CMake integration files, library symbolic links, and `.lib` files on Windows* OS).
### Pack
```
cd cmake-build-debug[.gitignore](.gitignore)
cpack
```

View File

@ -1,4 +1,3 @@
include(${CMAKE_SOURCE_DIR}/cmake/tools/CPM.cmake)
CPMAddPackage(
NAME glad
@ -6,10 +5,45 @@ CPMAddPackage(
#VERSION 2.0.2
VERSION 0.1.36
GIT_PROGRESS TRUE
OPTIONS "GLAD_EXPORT ON" "GLAD_INSTALL ON"
EXCLUDE_FROM_ALL ON
OPTIONS "GLAD_EXPORT OFF" "GLAD_INSTALL OFF"
)
#if(glad_ADDED)
# add_subdirectory("${glad_SOURCE_DIR}/cmake" glad_cmake)
# glad_add_library(glad REPRODUCIBLE API gl:core=3.3)
#endif()
if(glad_ADDED)
set(EXTERNAL_PROJECT_NAME glad)
include(GNUInstallDirs)
add_library(glad::glad ALIAS glad)
install(
TARGETS ${EXTERNAL_PROJECT_NAME}
EXPORT ${EXTERNAL_PROJECT_NAME}Targets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
COMPONENT runtime
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
COMPONENT devel
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
COMPONENT devel
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
COMPONENT devel
)
install(
EXPORT ${EXTERNAL_PROJECT_NAME}Targets
FILE ${EXTERNAL_PROJECT_NAME}Targets.cmake
NAMESPACE ${EXTERNAL_PROJECT_NAME}::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${EXTERNAL_PROJECT_NAME}
COMPONENT devel
)
install(
DIRECTORY ${glad_BINARY_DIR}/include/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
COMPONENT devel
FILES_MATCHING
PATTERN "*.h"
PATTERN "*.hpp"
)
endif()

View File

@ -1,8 +1,43 @@
include(${CMAKE_SOURCE_DIR}/cmake/tools/CPM.cmake)
CPMAddPackage(
NAME glfw
GIT_REPOSITORY https://github.com/glfw/glfw.git
GIT_TAG 3.3.7
EXCLUDE_FROM_ALL ON
#EXCLUDE_FROM_ALL ON
OPTIONS "GLFW_INSTALL OFF" "GLFW_BUILD_EXAMPLES OFF" "GLFW_BUILD_TESTS OFF"
)
if(glad_ADDED)
set(EXTERNAL_PROJECT_NAME glfw)
include(GNUInstallDirs)
add_library(glfw::glfw ALIAS glfw)
install(DIRECTORY "${glfw_SOURCE_DIR}/include/GLFW" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
COMPONENT devel
FILES_MATCHING PATTERN glfw3.h PATTERN glfw3native.h)
install(FILES "${glfw_BINARY_DIR}/src/glfw3Config.cmake"
"${glfw_BINARY_DIR}/src/glfw3ConfigVersion.cmake"
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/glfw3
COMPONENT devel)
install(EXPORT glfwTargets FILE glfw3Targets.cmake
EXPORT_LINK_INTERFACE_LIBRARIES
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/glfw3
COMPONENT devel)
install(FILES "${glfw_BINARY_DIR}/src/glfw3.pc"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig"
COMPONENT devel)
install(
TARGETS ${EXTERNAL_PROJECT_NAME}
EXPORT ${EXTERNAL_PROJECT_NAME}Targets
RUNTIME COMPONENT runtime
LIBRARY COMPONENT devel
ARCHIVE COMPONENT devel
INCLUDES COMPONENT devel
)
endif()

5
cmake/external/glm.cmake vendored Normal file
View File

@ -0,0 +1,5 @@
CPMAddPackage(
NAME glm
GIT_REPOSITORY https://github.com/g-truc/glm.git
GIT_TAG 0.9.9.8
)

View File

@ -1,7 +1,8 @@
include(${CMAKE_SOURCE_DIR}/cmake/tools/CPM.cmake)
CPMAddPackage(
NAME googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.12.1
EXCLUDE_FROM_ALL ON
OPTIONS "BUILD_GMOCK OFF" "INSTALL_GTEST OFF"
)

View File

@ -1,4 +1,3 @@
include(${CMAKE_SOURCE_DIR}/cmake/tools/CPM.cmake)
# branch: docking
CPMAddPackage(
@ -16,9 +15,9 @@ if(imgui_external_ADDED)
find_package(PkgConfig REQUIRED)
find_package(Freetype REQUIRED)
find_package(OpenGL REQUIRED)
pkg_search_module(GLFW REQUIRED glfw3)
find_package(GLFW REQUIRED)
add_library(${EXTERNAL_PROJECT_NAME} STATIC
add_library(${EXTERNAL_PROJECT_NAME}
${imgui_external_SOURCE_DIR}/imgui.cpp
${imgui_external_SOURCE_DIR}/imgui_demo.cpp
${imgui_external_SOURCE_DIR}/imgui_draw.cpp
@ -60,12 +59,21 @@ if(imgui_external_ADDED)
EXCLUDE_FROM_ALL ON
)
if(IMGUI_INSTALL)
include(GNUInstallDirs)
install(
TARGETS ${EXTERNAL_PROJECT_NAME}
EXPORT ${EXTERNAL_PROJECT_NAME}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/${EXTERNAL_PROJECT_NAME}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
COMPONENT runtime
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
COMPONENT devel
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
COMPONENT devel
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
COMPONENT devel
)
install(
@ -73,10 +81,11 @@ if(imgui_external_ADDED)
FILE ${EXTERNAL_PROJECT_NAME}Targets.cmake
NAMESPACE ${EXTERNAL_PROJECT_NAME}::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${EXTERNAL_PROJECT_NAME}
COMPONENT devel
)
install(
DIRECTORY ${imgui_external_SOURCE_DIR}
DIRECTORY ${imgui_external_SOURCE_DIR}/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${EXTERNAL_PROJECT_NAME}
COMPONENT devel
FILES_MATCHING
@ -84,3 +93,4 @@ if(imgui_external_ADDED)
PATTERN "*.hpp"
)
endif()
endif()

73
cmake/external/implot.cmake vendored Normal file
View File

@ -0,0 +1,73 @@
CPMAddPackage(
NAME implot_external
GIT_REPOSITORY https://github.com/epezent/implot.git
GIT_TAG v0.14
DOWNLOAD_ONLY YES
)
if(implot_external_ADDED)
set(EXTERNAL_PROJECT_NAME implot)
set(CMAKE_CXX_STANDARD 17)
find_package(PkgConfig REQUIRED)
find_package(Freetype REQUIRED)
find_package(OpenGL REQUIRED)
find_package(GLFW REQUIRED)
add_library(${EXTERNAL_PROJECT_NAME}
${implot_external_SOURCE_DIR}/implot.cpp
${implot_external_SOURCE_DIR}/implot_demo.cpp
${implot_external_SOURCE_DIR}/implot_items.cpp
)
add_library(implot::implot ALIAS ${EXTERNAL_PROJECT_NAME})
target_include_directories(${EXTERNAL_PROJECT_NAME}
PUBLIC
$<BUILD_INTERFACE:${implot_external_SOURCE_DIR}>
)
target_link_libraries(${EXTERNAL_PROJECT_NAME}
PUBLIC
imgui::imgui
)
set_target_properties(${EXTERNAL_PROJECT_NAME}
PROPERTIES
POSITION_INDEPENDENT_CODE ON
OUTPUT_NAME implot
EXCLUDE_FROM_ALL ON
)
if(IMPLOT_INSTALL)
include(GNUInstallDirs)
install(
TARGETS ${EXTERNAL_PROJECT_NAME}
EXPORT ${EXTERNAL_PROJECT_NAME}Targets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT devel
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT devel
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} COMPONENT devel
)
install(
EXPORT ${EXTERNAL_PROJECT_NAME}Targets
FILE ${EXTERNAL_PROJECT_NAME}Targets.cmake
NAMESPACE ${EXTERNAL_PROJECT_NAME}::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${EXTERNAL_PROJECT_NAME}
COMPONENT devel
)
install(
DIRECTORY ${implot_external_SOURCE_DIR}/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${EXTERNAL_PROJECT_NAME}
COMPONENT devel
FILES_MATCHING
PATTERN "*.h"
PATTERN "*.hpp"
)
endif()
endif()

View File

@ -1,26 +1,17 @@
if(USE_SYSTEM_OCCT)
find_package(OpenCASCADE REQUIRED)
if(OpenCASCADE_FOUND)
message(STATUS "OCCT: Found")
else()
message(FATAL "OCCT: Not Found")
endif()
else()
include(${CMAKE_SOURCE_DIR}/cmake/tools/CPM.cmake)
find_package(OpenCASCADE QUIET)
if (NOT OpenCASCADE_FOUND)
CPMAddPackage(
NAME occt
NAME OpenCASCADE
GIT_REPOSITORY https://github.com/Open-Cascade-SAS/OCCT.git
GIT_TAG V7_6_2
DOWNLOAD_ONLY YES
)
if(occt_ADDED)
if(OpenCASCADE_ADDED)
# They are using CMAKE_SOURCE_DIR and CMAKE_BINARY_DIR for the project root, fix it
file(READ ${occt_SOURCE_DIR}/CMakeLists.txt filedata_)
file(READ ${OpenCASCADE_SOURCE_DIR}/CMakeLists.txt filedata_)
string(FIND "${filedata_}" "CMAKE_SOURCE_DIR" need_patch)
if(NOT ${need_patch} EQUAL -1)
@ -29,9 +20,9 @@ else()
string(REPLACE "project (OCCT)" "" filedata_ "${filedata_}")
string(PREPEND filedata_ "project(OCCT)\nset(OCCT_BINARY_DIR $\{_OCCT_BINARY_DIR\})\n")
endif()
file(WRITE ${occt_SOURCE_DIR}/CMakeLists.txt "${filedata_}")
file(WRITE ${OpenCASCADE_SOURCE_DIR}/CMakeLists.txt "${filedata_}")
file(GLOB_RECURSE files_to_patch ${occt_SOURCE_DIR}/adm/cmake "occt_*")
file(GLOB_RECURSE files_to_patch ${OpenCASCADE_SOURCE_DIR}/adm/cmake "occt_*")
foreach(file_path ${files_to_patch})
file(READ ${file_path} filedata_)
@ -40,10 +31,10 @@ else()
file(WRITE ${file_path} "${filedata_}")
endforeach()
project(OCCT)
#project(OCCT)
# find better way to pass build directory
set(_OCCT_BINARY_DIR ${occt_BINARY_DIR})
set(INSTALL_DIR ${occt_BINARY_DIR} CACHE BOOL "" FORCE)
#set(_OCCT_BINARY_DIR ${OpenCASCADE_BINARY_DIR})
set(INSTALL_DIR ${OpenCASCADE_BINARY_DIR} CACHE BOOL "" FORCE)
set(USE_TK OFF CACHE BOOL "" FORCE)
set(USE_FREETYPE OFF CACHE BOOL "" FORCE)
@ -53,11 +44,11 @@ else()
set(BUILD_MODULE_ApplicationFramework OFF CACHE BOOL "" FORCE)
set(BUILD_MODULE_Draw OFF CACHE BOOL "" FORCE)
add_subdirectory(${occt_SOURCE_DIR})
add_subdirectory(${OpenCASCADE_SOURCE_DIR})
endif()
endif()
set(OCCT_LIBRARIES
set(OpenCASCADE_LIBS
TKernel
TKService
TKV3d
@ -73,4 +64,4 @@ set(OCCT_LIBRARIES
TKPrim
TKSTEP
)
set(OCCT_INCLUDE_DIRS ${OpenCASCADE_INCLUDE_DIR})

8
cmake/external/onetbb.cmake vendored Normal file
View File

@ -0,0 +1,8 @@
CPMAddPackage(
NAME onetbb
GIT_REPOSITORY https://github.com/oneapi-src/oneTBB.git
GIT_TAG v2021.8.0
EXCLUDE_FROM_ALL ON
OPTIONS "TBB_INSTALL ON" "TBB_TEST OFF" "TBB_BENCH OFF" "BUILD_SHARED_LIBS ON"
)

8
cmake/external/openxlsx.cmake vendored Normal file
View File

@ -0,0 +1,8 @@
CPMAddPackage(
NAME OpenXLSX
GIT_REPOSITORY https://github.com/troldal/OpenXLSX.git
GIT_TAG b80da42d1454f361c29117095ebe1989437db390
#EXCLUDE_FROM_ALL ON
)
set(OPENXLSX_LIBRARY_TYPE "STATIC")

View File

@ -1,4 +1,3 @@
include(${CMAKE_SOURCE_DIR}/cmake/tools/CPM.cmake)
CPMAddPackage(
NAME stb_external
@ -10,7 +9,7 @@ CPMAddPackage(
if(stb_external_ADDED)
set(EXTERNAL_PROJECT_NAME stb)
add_library(${EXTERNAL_PROJECT_NAME} INTERFACE)
add_library(${EXTERNAL_PROJECT_NAME} INTERFACE EXCLUDE_FROM_ALL)
add_library(stb::stb ALIAS ${EXTERNAL_PROJECT_NAME})
target_include_directories(${EXTERNAL_PROJECT_NAME}
@ -29,6 +28,7 @@ if(stb_external_ADDED)
TARGETS ${EXTERNAL_PROJECT_NAME}
EXPORT ${EXTERNAL_PROJECT_NAME}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/${EXTERNAL_PROJECT_NAME}
COMPONENT devel
)
install(
@ -36,10 +36,11 @@ if(stb_external_ADDED)
FILE ${EXTERNAL_PROJECT_NAME}Targets.cmake
NAMESPACE ${EXTERNAL_PROJECT_NAME}::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${EXTERNAL_PROJECT_NAME}
COMPONENT devel
)
install(
DIRECTORY ${stb_external_SOURCE_DIR}
DIRECTORY ${stb_external_SOURCE_DIR}/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${EXTERNAL_PROJECT_NAME}
COMPONENT devel
FILES_MATCHING

137
cmake/hpr-macros.cmake Normal file
View File

@ -0,0 +1,137 @@
# args: <file to parse> <regex>
# provide: HPR_VERSION
macro(hpr_parse_version _file _regex)
file(
STRINGS "${_file}" _version_defines
REGEX "${_regex}"
)
set(_regex_match "${_regex} +([^ ]+)$")
foreach(_ver ${_version_defines})
if(_ver MATCHES ${_regex_match})
set(_VERSION_${CMAKE_MATCH_1} "${CMAKE_MATCH_2}")
endif()
endforeach()
if(_VERSION_PATCH MATCHES [[\.([a-zA-Z0-9]+)$]])
set(_VERSION_TYPE "${CMAKE_MATCH_1}")
endif()
string(REGEX MATCH "^[0-9]+" _VERSION_PATCH "${_VERSION_PATCH}")
set(HPR_VERSION "${_VERSION_MAJOR}.${_VERSION_MINOR}.${_VERSION_PATCH}")
endmacro()
# args: <project name> <paths to headers>...
# provide : *_HEADERS *_HEADERS_INTERFACE
macro(hpr_collect_interface _project_name)
file(GLOB ${_project_name}_HEADERS ${ARGN})
foreach(_header_path ${${_project_name}_HEADERS})
list(APPEND ${_project_name}_HEADERS_INTERFACE "$<BUILD_INTERFACE:${_header_path}>")
endforeach()
endmacro()
# args: <project name> <paths to sources>...
# provide : *_SOURCES
macro(hpr_collect_sources _project_name)
file(GLOB ${_project_name}_SOURCES ${ARGN})
endmacro()
# Common installation
# args: <project name> <source dir>
macro(hpr_install _project_name _project_source_dir)
if (HPR_INSTALL)
install(
TARGETS ${_project_name}
EXPORT ${_project_name}Targets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} NAMELINK_SKIP COMPONENT runtime
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT devel
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/hpr COMPONENT devel
)
if (BUILD_SHARED_LIBS)
install(
TARGETS ${target}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} NAMELINK_ONLY COMPONENT devel
)
endif()
install(
EXPORT ${_project_name}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/hpr COMPONENT devel
NAMESPACE hpr::
)
install(
DIRECTORY ${_project_source_dir}
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/hpr COMPONENT devel
FILES_MATCHING
PATTERN "*.h"
PATTERN "*.hpp"
PATTERN "tests" EXCLUDE
)
install(
FILES ../${_project_name}.hpp
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/hpr COMPONENT devel
)
endif()
endmacro()
# Common tests template
# args: <project name> <directory with tests>
macro(hpr_tests _project_name _tests_dir)
if (HPR_TEST)
file(GLOB tests_cpp "${_tests_dir}/*.cpp")
add_executable(${_project_name}-tests ${tests_cpp})
target_link_libraries(
${_project_name}-tests
PUBLIC hpr::${_project_name}
PRIVATE GTest::gtest_main
)
gtest_add_tests(TARGET ${_project_name}-tests)
endif()
endmacro()
# Collect modules
# args: -
macro(hpr_collect_modules_)
set_property(GLOBAL PROPERTY _HPR_MODULES "")
endmacro()
# Add module library
# args: <library name> <library type>
macro(hpr_add_library _library_name _library_type)
set_property(GLOBAL APPEND PROPERTY _HPR_MODULES "${_library_name}")
add_library(${_library_name} ${_library_type})
add_library(hpr::${_library_name} ALIAS ${_library_name})
endmacro()
# args: -
# provide: HPR_MODULES HPR_INTERFACE_LIBS HPR_PUBLIC_LIBS
macro(hpr_collect_modules)
get_property(_hpr_modules GLOBAL PROPERTY _HPR_MODULES)
foreach(_module ${_hpr_modules})
get_target_property(_module_type ${_module} TYPE)
if(_module_type STREQUAL "INTERFACE_LIBRARY")
list(APPEND HPR_INTERFACE_LIBS "${PROJECT_NAME}::${_module}")
else()
list(APPEND HPR_PUBLIC_LIBS "${PROJECT_NAME}::${_module}")
endif()
set(HPR_MODULES "${HPR_MODULES} ${_module}")
endforeach()
endmacro()
# args: -
macro(hpr_print_summary)
set(_summary "hpr-${HPR_VERSION}:${HPR_MODULES}")
message(STATUS ${_summary})
endmacro()

View File

@ -2,6 +2,6 @@
include(CMakeFindDependencyMacro)
include("${CMAKE_CURRENT_LIST_DIR}/hprTargets.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake")
check_required_components("@PROJECT_NAME@")

View File

@ -0,0 +1,29 @@
if (NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
message(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"")
endif()
file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
string(REGEX REPLACE "\n" ";" files "${files}")
foreach (file ${files})
message(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"")
if (EXISTS "$ENV{DESTDIR}${file}")
exec_program("@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
OUTPUT_VARIABLE rm_out
RETURN_VALUE rm_retval)
if (NOT "${rm_retval}" STREQUAL 0)
MESSAGE(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"")
endif()
elseif (IS_SYMLINK "$ENV{DESTDIR}${file}")
EXEC_PROGRAM("@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
OUTPUT_VARIABLE rm_out
RETURN_VALUE rm_retval)
if (NOT "${rm_retval}" STREQUAL 0)
message(FATAL_ERROR "Problem when removing symlink \"$ENV{DESTDIR}${file}\"")
endif()
else()
message(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.")
endif()
endforeach()

View File

@ -0,0 +1,10 @@
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_ARCH x86_64)
set(CMAKE_C_COMPILER /bin/gcc)
set(CMAKE_CXX_COMPILER /bin/g++)
set(CMAKE_MAKE_PROGRAM /bin/ninja)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

View File

@ -0,0 +1,12 @@
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_ARCH x86_64)
set(MINGW_PREFIX /mingw64)
set(CMAKE_C_COMPILER ${MINGW_PREFIX}/bin/gcc)
set(CMAKE_CXX_COMPILER ${MINGW_PREFIX}/bin/g++)
set(CMAKE_MAKE_PROGRAM ${MINGW_PREFIX}/bin/ninja)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

View File

@ -1 +1,2 @@
add_subdirectory(periodic)
#add_subdirectory(periodic)
add_subdirectory(fes)

View File

@ -0,0 +1,29 @@
cmake_minimum_required (VERSION 3.16)
include(${CMAKE_SOURCE_DIR}/cmake/external/imgui.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/external/implot.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/external/openxlsx.cmake)
project(
fes
VERSION 0.1.0
LANGUAGES CXX
)
# Compiler options
set(CMAKE_CXX_STANDARD 20)
add_executable(${PROJECT_NAME}
fes.cpp
)
target_link_libraries(${PROJECT_NAME}
hpr::gpu
imgui::imgui
implot::implot
OpenXLSX::OpenXLSX
)
target_link_libraries(${PROJECT_NAME} -static gcc stdc++ winpthread -dynamic)
#message(STATUS "${OpenXLSX_DIR}")
#target_include_directories(${PROJECT_NAME} PUBLIC ${OpenXLSX_DIR})

View File

@ -0,0 +1,152 @@
#include <iostream>
#include <OpenXLSX.hpp>
#include <hpr/gpu.hpp>
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <imgui_internal.h>
#include <implot.h>
#include <string>
#include <hpr/containers.hpp>
int main()
{
OpenXLSX::XLDocument doc;
doc.open("fes.xlsx");
auto wb = doc.workbook();
auto wks = wb.worksheet("Капилляриметрия");
std::cout << wb.sheetCount() << std::endl;
auto rng = wks.range(OpenXLSX::XLCellReference("B7"), OpenXLSX::XLCellReference("B52"));
//for (auto cell : rng)
// std::cout << cell.value() << std::endl;
//xlnt::workbook wb;
//wb.load("fes.xlsx");
//auto ws = wb.active_sheet();
//std::clog << wb.sheet_count() << std::endl;
auto window = hpr::gpu::Window{50, 50, 1000, 800, "FES", hpr::gpu::Window::Windowed, nullptr, nullptr};
window.keyClickCallback([](hpr::gpu::Window* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE)
window->state(hpr::gpu::Window::Closed);
});
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImPlot::CreateContext();
ImGui_ImplGlfw_InitForOpenGL(window.instance(), true);
ImGui_ImplOpenGL3_Init("#version 430");
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
while (window.state() != hpr::gpu::Window::Closed)
{
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
static int selected = 0;
if (ImGui::Begin("Table"))
{
if (ImGui::BeginTable("##table", 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable | ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_BordersOuterV))
{
ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_WidthFixed, 100.0f);
ImGui::TableSetupColumn("Core sample", ImGuiTableColumnFlags_NoHide);
ImGui::TableSetupColumn("Depth", ImGuiTableColumnFlags_NoHide);
ImGui::TableSetupColumn("Lithotype", ImGuiTableColumnFlags_NoHide);
ImGui::TableHeadersRow();
const int start = 7;//54;
const int end = 11;//113;
int n = start;
auto sample_range = wks.range(OpenXLSX::XLCellReference("B" + std::to_string(7)), OpenXLSX::XLCellReference("B" + std::to_string(11)));
hpr::darray<OpenXLSX::XLCell> sample {sample_range.begin(), sample_range.end()};
//auto depth_range = wks.range(OpenXLSX::XLCellReference("H" + std::to_string(start)), OpenXLSX::XLCellReference("H" + std::to_string(end)));
//hpr::darray<OpenXLSX::XLCell> depth {sample_range.begin(), sample_range.end()};
//auto lithotype_range = wks.range(OpenXLSX::XLCellReference("K" + std::to_string(start)), OpenXLSX::XLCellReference("K" + std::to_string(end)));
//hpr::darray<OpenXLSX::XLCell> lithotype {sample_range.begin(), sample_range.end()};
for ( ; n < end; ++n)
{
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextDisabled("#%d", n);
ImGui::TableNextColumn();
//float value = static_cast<float>(cell.value());
if (ImGui::Selectable(sample[n - start].value().get<std::string>().c_str()))
{
selected = n;
}
ImGui::TableNextColumn();
//ImGui::Text(depth[n - start].value().get<std::string>().c_str());
ImGui::TableNextColumn();
//ImGui::Text(lithotype[n - start].value().get<std::string>().c_str());
++n;
}
ImGui::EndTable();
}
ImGui::End();
}
if (ImGui::Begin("Capillarimetry"))
{
hpr::darray<double> P_c { 0.025, 0.05, 0.1, 0.3, 0.5, 0.7, 1.0};
hpr::darray<double> data;
if (ImGui::BeginTabBar("Graphs", ImGuiTabBarFlags_None))
{
const hpr::darray<std::string> vars {"K_w", "P_n"};
std::map<std::string, hpr::darray<std::string>> cols {
{"K_w", hpr::darray<std::string>{"S", "V", "Y", "AB", "AE", "AH", "AK"}},
{"P_n", hpr::darray<std::string>{"U", "X", "AA", "AD", "AG", "AJ", "AM"}}
};
for (const auto& var : vars)
if (ImGui::BeginTabItem(var.data()))
{
//ImPlot::SetNextAxesToFit();
if (ImPlot::BeginPlot(var.data(), ImVec2(-1, -1) ))
{
ImPlot::SetupAxes("P_c",var.data());
for (const auto& col : cols[var])
data.push(wks.cell(col + std::to_string(selected)).value().get<double>());
ImPlot::PlotLine(var.data(), P_c.data(), data.data(), data.size());
ImPlot::EndPlot();
}
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::End();
}
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
window.swapBuffers();
window.pollEvents();
}
ImPlot::DestroyContext();
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
return 0;
}

Binary file not shown.

View File

@ -89,7 +89,7 @@ public:
vec3 ox {1, 0, 0};
vec3 oy {0, 1, 0};
vec3 oz {0, 0, 1};
vec3 ox1 = hpr::rotate(ox, oz, radians(-p_angles[2]));
vec3 ox1 = hpr::rotate(ox, oz, rad(-p_angles[2]));
p_controlPoints.push(vec3{0, 0, 0});
p_controlPoints.push(vec3{0, p_lengths[0], 0});
vec3 t1 = hpr::translate(p_controlPoints.back(), ox1 * p_lengths[1]);
@ -97,29 +97,29 @@ public:
p_controlPoints.push(hpr::translate(p_controlPoints.front(), ox1 * p_lengths[1]));
print(t1);
print(ox1);
scalar c1 = cos(radians(p_angles[2])), c2 = cos(radians(p_angles[1])), c3 = cos(radians(p_angles[0]));
scalar D1 = sqrt(mat3(
1, cos(radians(p_angles[2])), cos(radians(p_angles[1])),
cos(radians(p_angles[2])), 1, cos(radians(p_angles[0])),
cos(radians(p_angles[1])), cos(radians(p_angles[0])), 1).det());
scalar c1 = cos(rad(p_angles[2])), c2 = cos(rad(p_angles[1])), c3 = cos(rad(p_angles[0]));
scalar D1 = sqrt(det(mat3(
1, cos(rad(p_angles[2])), cos(rad(p_angles[1])),
cos(rad(p_angles[2])), 1, cos(rad(p_angles[0])),
cos(rad(p_angles[1])), cos(rad(p_angles[0])), 1)));
scalar volume = 1. / 6. * p_lengths[0] * p_lengths[1] * p_lengths[2] *
D1;
scalar s1 = sqrt(std::pow(p_lengths[0], 2) + std::pow(p_lengths[1], 2) - 2 *
p_lengths[0] * p_lengths[1] * cos(radians(p_angles[2])));
scalar s2 = sqrt(std::pow(p_lengths[1], 2) + std::pow(p_lengths[2], 2) - 2 *
p_lengths[1] * p_lengths[2] * cos(radians(p_angles[1])));
scalar s3 = sqrt(std::pow(p_lengths[0], 2) + std::pow(p_lengths[2], 2) - 2 *
p_lengths[0] * p_lengths[2] * cos(radians(p_angles[0])));
scalar s1 = sqrt(pow(p_lengths[0], 2) + pow(p_lengths[1], 2) - 2 *
p_lengths[0] * p_lengths[1] * cos(rad(p_angles[2])));
scalar s2 = sqrt(pow(p_lengths[1], 2) + pow(p_lengths[2], 2) - 2 *
p_lengths[1] * p_lengths[2] * cos(rad(p_angles[1])));
scalar s3 = sqrt(pow(p_lengths[0], 2) + pow(p_lengths[2], 2) - 2 *
p_lengths[0] * p_lengths[2] * cos(rad(p_angles[0])));
scalar area = 1. / 2. * p_lengths[0] * p_lengths[1] *
sqrt(mat2{1, cos(radians(p_angles[2])), cos(radians(p_angles[2])), 1}.det());
sqrt(det(mat2{1, cos(rad(p_angles[2])), cos(rad(p_angles[2])), 1}));
scalar h1 = 3 * volume / area;
scalar a1 = asin(h1 / p_lengths[2]);
scalar sh1 = sqrt(std::pow(p_lengths[2], 2) - std::pow(h1, 2));
scalar sh2 = p_lengths[2] * cos(radians(p_angles[0]));
scalar sh1 = sqrt(pow(p_lengths[2], 2) - pow(h1, 2));
scalar sh2 = p_lengths[2] * cos(rad(p_angles[0]));
scalar a2 = acos(sh2 / sh1);
vec3 ox2 = hpr::rotate(ox, oy, a1);
if (!std::isnan(a2))
if (!isnan(a2))
ox2 = hpr::rotate(ox2, oz, a2);
print(ox2);
for (auto n = 0; n < 4; ++n)

View File

@ -1,3 +1,8 @@
cmake_minimum_required (VERSION 3.16)
include(${CMAKE_SOURCE_DIR}/cmake/external/imgui.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/external/implot.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/external/glm.cmake)
project(
hyporo-creator
@ -7,55 +12,36 @@ project(
# Compiler options
set(CMAKE_CXX_STANDARD 20)
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
# Project options
include(GNUInstallDirs)
#include(GNUInstallDirs)
#include (InstallRequiredSystemLibraries)
if (MINGW)
list(APPEND MINGW_SYSTEM_RUNTIME_LIBS
"/mingw64/bin/libgcc_s_seh-1.dll"
"/mingw64/bin/libwinpthread-1.dll"
"/mingw64/bin/libstdc++-6.dll"
)
endif()
#add_executable(${PROJECT_NAME}
# creator.cpp
#)
include(${CMAKE_SOURCE_DIR}/cmake/external/imgui.cmake)
#message(STATUS "project name: ${PROJECT_NAME}")
#target_link_libraries(${PROJECT_NAME}
# hpr::hpr
# imgui
#)
#target_include_directories(${PROJECT_NAME}
# PRIVATE
# ../
#)
#find_package(hpr REQUIRED)
#set(CMAKE_CXX_STANDARD 20)
#add_executable(testi
# test.cpp
#)
#target_include_directories(testi
# PRIVATE
# ../
#)
#target_link_libraries(testi
# hpr::hpr
# imgui
#)
set(CMAKE_CXX_STANDARD 20)
add_executable(hyporo-creator
test2.cpp
)
target_include_directories(hyporo-creator
PRIVATE
../
)
target_link_libraries(hyporo-creator
hpr::gpu
hpr::window-system
imgui
imgui::imgui
implot::implot
glm::glm
)
target_link_libraries(hyporo-creator -static gcc stdc++ winpthread -dynamic)

135
source/creator/camera.hpp Normal file
View File

@ -0,0 +1,135 @@
#pragma once
#include <hpr/math.hpp>
class Camera
{
public:
enum Projection
{
Perspective,
Orthographic
};
protected:
Projection p_projectionType;
hpr::scalar p_distance;
hpr::scalar p_aspect;
hpr::scalar p_fieldOfView;
hpr::scalar p_nearPlane;
hpr::scalar p_farPlane;
hpr::vec3 p_target;
hpr::vec3 p_left;
hpr::vec3 p_front;
hpr::vec3 p_up;
hpr::vec3 p_angles;
hpr::vec3 p_position;
public:
inline
Camera() :
p_projectionType {Perspective},
p_distance {10},
p_aspect {4.f / 3.f},
p_fieldOfView {45},
p_nearPlane {0.1},//{-100},
p_farPlane {100},
p_target {0, 0, 0},
p_left {1, 0, 0},
p_front {0, 0, -1},
p_up {0, 0, 1},
p_angles {45, 45, 0},
p_position {}
{}
virtual
~Camera() = default;
virtual inline
void projection(Projection projection)
{
p_projectionType = projection;
}
hpr::scalar& aspect()
{
return p_aspect;
}
virtual inline
hpr::mat4 projection() const
{
switch (p_projectionType)
{
case Perspective:
return hpr::perspective(hpr::rad(p_fieldOfView), p_aspect, p_nearPlane, p_farPlane);
case Orthographic:
return hpr::ortho(-p_distance * p_aspect, p_distance * p_aspect, -p_distance, p_distance, p_nearPlane, p_farPlane);
}
}
virtual inline
hpr::mat4 view() = 0;
virtual inline
hpr::vec3& position()
{
return p_position;
}
};
class OrbitCamera : public Camera
{
public:
inline
OrbitCamera() :
Camera {}
{}
virtual
~OrbitCamera() = default;
inline
hpr::mat4 view() override
{
hpr::vec3 rotation {
hpr::cos(hpr::rad(p_angles[1])) * hpr::sin(hpr::rad(p_angles[0])),
hpr::cos(hpr::rad(p_angles[1])) * hpr::cos(hpr::rad(p_angles[0])),
hpr::sin(hpr::rad(p_angles[1]))};
hpr::vec3 pos = p_target + p_distance * rotation;
p_front = p_target - pos;
p_front /= hpr::length(p_front);
p_up = hpr::vec3(0, 0, 1);
p_left = hpr::normalize(hpr::cross(p_up, p_front));
p_up = hpr::cross(p_front, p_left);
p_position = pos;
return hpr::lookAt(pos, pos + p_front, p_up);
}
void rotateEvent(float xdelta, float ydelta)
{
p_angles += hpr::vec3(xdelta, ydelta, 0);
}
void moveEvent(float xdelta, float ydelta)
{
p_target += (p_left * xdelta + p_up * ydelta) * 1e-3f;
}
void scrollEvent(float xdelta, float ydelta)
{
p_distance -= ydelta;
}
};

View File

@ -0,0 +1,12 @@
execute_process(
COMMAND ldd "@CPACK_PACKAGE_DIRECTORY@/@PROJECT_NAME@.exe"
COMMAND grep "mingw"
COMMAND cut "-d" " " "-f" "3"
COMMAND xargs "cp" "-t" "@CMAKE_INSTALL_BINDIR@"
RESULT_VARIABLE EXIT_CODE
)
if(NOT EXIT_CODE EQUAL 0)
message(STATUS "Running pre-build command failed with exit code ${EXIT_CODE}.")
endif()

238
source/creator/drawable.hpp Normal file
View File

@ -0,0 +1,238 @@
#pragma once
#include <hpr/gpu.hpp>
#include <hpr/math.hpp>
using hpr::darray;
class Drawable
{
protected:
gpu::ArrayObject p_arrayObject;
gpu::BufferObject p_vertexBuffer;
gpu::BufferObject p_normalBuffer;
gpu::BufferObject p_colorBuffer;
gpu::BufferObject p_indexBuffer;
gpu::ShaderProgram* p_shaderProgram;
gpu::ArrayObject::Mode p_renderMode;
hpr::vec4 p_color;
public:
gpu::ArrayObject& array()
{
return p_arrayObject;
}
friend constexpr void swap(Drawable& main, Drawable& other)
{
using std::swap;
//swap(main.p)
}
Drawable() :
p_arrayObject {},
p_vertexBuffer {gpu::BufferObject::Vertex},
p_normalBuffer {gpu::BufferObject::Vertex},
p_colorBuffer {gpu::BufferObject::Vertex},
p_indexBuffer {gpu::BufferObject::Index},
p_shaderProgram {nullptr},
p_renderMode {gpu::ArrayObject::Triangles},
p_color {0.7, 0.7, 0.7}
{}
inline explicit
Drawable(gpu::ShaderProgram* shaderProgram) :
p_arrayObject {},
p_vertexBuffer {gpu::BufferObject::Vertex},
p_normalBuffer {gpu::BufferObject::Vertex},
p_colorBuffer {gpu::BufferObject::Vertex},
p_indexBuffer {gpu::BufferObject::Index},
p_shaderProgram {shaderProgram},
p_renderMode {gpu::ArrayObject::Triangles},
p_color {0.7, 0.7, 0.7}
{}
inline
Drawable(const Drawable& drawable) = default;
virtual
~Drawable() = default;
void destroy()
{
p_arrayObject.destroy();
p_vertexBuffer.destroy();
p_normalBuffer.destroy();
p_colorBuffer.destroy();
p_indexBuffer.destroy();
}
[[nodiscard]]
constexpr
gpu::ShaderProgram* shaderProgram() const
{
return p_shaderProgram;
}
constexpr virtual
void renderMode(gpu::ArrayObject::Mode mode)
{
p_renderMode = mode;
}
[[nodiscard]]
constexpr virtual
gpu::ArrayObject::Mode renderMode() const
{
return p_renderMode;
}
template <IsVector V>
inline
void addVertices(const darray<V>& vertices)
{
if (!p_arrayObject.valid())
p_arrayObject.create();
p_arrayObject.bind();
darray<float> data;
data.resize(vertices.size() * vertices[0].size());
for (auto v : vertices) for (auto c : v) data.push(c);
p_vertexBuffer.create(data);
p_arrayObject.attribPointer(p_vertexBuffer, 0, vertices[0].size());
p_arrayObject.unbind();
}
template <IsVector V>
inline
void editVertices(const darray<V>& vertices)
{
if (!p_vertexBuffer.valid())
throw std::runtime_error("Invalid buffer object");
p_arrayObject.bind();
darray<float> data;
data.resize(vertices.size() * vertices[0].size());
for (auto v : vertices) for (auto c : v) data.push(c);
p_vertexBuffer.edit(data);
p_arrayObject.unbind();
}
template <IsVector V>
inline
void addNormals(const darray<V>& normals)
{
if (!p_arrayObject.valid())
p_arrayObject.create();
p_arrayObject.bind();
darray<float> data;
data.resize(normals.size() * normals[0].size());
for (auto v : normals) for (auto c : v) data.push(c);
p_normalBuffer.create(data);
p_arrayObject.attribPointer(p_normalBuffer, 1, normals[0].size());
p_arrayObject.unbind();
}
template <IsVector V>
inline
void addColors(const darray<V>& colors)
{
if (!p_arrayObject.valid())
p_arrayObject.create();
p_arrayObject.bind();
darray<float> data;
data.resize(colors.size() * colors[0].size());
for (auto v : colors) for (auto c : v) data.push(c);
p_colorBuffer.create(data);
p_arrayObject.attribPointer(p_colorBuffer, 2, colors[0].size());
p_arrayObject.unbind();
}
template <IsVector V>
inline
void editColors(const darray<V>& colors)
{
if (!p_colorBuffer.valid())
throw std::runtime_error("Invalid buffer object");
p_arrayObject.bind();
darray<float> data;
data.resize(colors.size() * colors[0].size());
for (auto v : colors) for (auto c : v) data.push(c);
p_colorBuffer.edit(data);
p_arrayObject.unbind();
}
template <IsVector V>
inline
void addIndices(const darray<V>& indices)
{
if (!p_arrayObject.valid())
p_arrayObject.create();
p_arrayObject.bind();
darray<unsigned int> data;
data.resize(indices.size() * indices[0].size());
for (auto v : indices) for (auto c : v) data.push(c);
p_indexBuffer.create(data);
p_arrayObject.unbind();
}
inline virtual
void render(gpu::ArrayObject::Mode mode)
{
p_shaderProgram->bind();
//std::cout << p_shaderProgram->index() << std::endl;
p_arrayObject.bind();
if (!p_colorBuffer.valid()) {
shaderProgram()->uniformVector<float, 4>("objectColor", 1, p_color.data());
}
if (p_indexBuffer.valid())
{
p_indexBuffer.bind();
p_arrayObject.drawElements(mode, p_indexBuffer.size());
}
else
{
p_arrayObject.drawArrays(mode, p_vertexBuffer.size());
}
p_arrayObject.unbind();
p_shaderProgram->unbind();
}
inline virtual
void render()
{
render(p_renderMode);
}
inline virtual
void color(const hpr::vec4& color)
{
p_color = color;
}
inline virtual
hpr::vec4& color()
{
return p_color;
}
};

80
source/creator/entity.hpp Normal file
View File

@ -0,0 +1,80 @@
#pragma once
#include <hpr/gpu.hpp>
#include <hpr/math.hpp>
#include "drawable.hpp"
class Entity : public Drawable
{
protected:
hpr::vec3 p_position;
hpr::quat p_rotation;
hpr::vec3 p_scale;
public:
Entity() :
Drawable {}
{}
inline explicit
Entity(gpu::ShaderProgram* shaderProgram) :
Drawable {shaderProgram}
{}
inline
Entity(const Entity& entity) = default;
/*{
std::cout << "copy" << std::endl;
}*/
~Entity() override = default;
inline virtual
void rotation(const hpr::vec3& angles)
{
p_rotation = hpr::quat(hpr::quat::XYZ, angles);
}
inline virtual
hpr::quat& rotation()
{
return p_rotation;
}
inline virtual
void rotate(const hpr::vec3& axis, hpr::scalar angle)
{
p_rotation *= hpr::quat(axis, angle);
}
hpr::mat4 model()
{
hpr::mat4 model = hpr::mat4::identity();
hpr::translate(model, p_position);
hpr::rotate(model, p_rotation);
hpr::scale(model, p_scale);
return model;
}
inline
void render() override
{
shaderProgram()->bind();
//std::cout << shaderProgram()->index() << std::endl;
//for (auto v : model)
// std::cout << v << " ";
//std::cout << std::endl;
shaderProgram()->uniformMatrix<4, 4>("model", 1, true, model().data());
Drawable::render();
shaderProgram()->unbind();
}
};

157
source/creator/grid.hpp Normal file
View File

@ -0,0 +1,157 @@
#pragma once
#include "entity.hpp"
class Grid : public Entity
{
public:
enum Mode
{
XY,
XZ,
YZ
};
protected:
hpr::scalar p_length;
hpr::scalar p_width;
hpr::scalar p_height;
hpr::scalar p_scale;
Mode p_mode;
public:
Grid(gpu::ShaderProgram* shaderProgram, Mode mode = XY, hpr::scalar scale = 1, hpr::scalar length = 100, hpr::scalar width = 100, hpr::scalar height = 100) :
Entity {shaderProgram},
p_length {length},
p_width {width},
p_height {height},
p_scale {scale},
p_mode {mode}
{
darray<vec3> vertices;
darray<vec3> colors;
construct(vertices, colors);
Entity::addVertices(vertices);
Entity::addColors(colors);
Entity::renderMode(gpu::ArrayObject::Lines);
}
protected:
void construct(darray<vec3>& vertices, darray<vec3>& colors)
{
const darray<vec3> red {vec3(0.98f, 0.21f, 0.32f), vec3(0.98f, 0.21f, 0.32f)};
const darray<vec3> green {vec3(0.45f, 0.67f, 0.1f), vec3(0.45f, 0.67f, 0.1f)};
const darray<vec3> blue {vec3(0.17f, 0.47f, 0.80f), vec3(0.17f, 0.47f, 0.80f)};
const darray<vec3> white {vec3(0.5f, 0.5f, 0.5f), vec3(0.5f, 0.5f, 0.5f)};
switch (p_mode) {
case XY: {
// Y
vertices.push({vec3(0.f, -p_width, 0.f), vec3(0.f, p_width, 0.f)});
colors.push(green);
for (hpr::scalar x = p_scale; x <= p_length; )
{
vertices.push({vec3(x, -p_width, 0.f), vec3(x, p_width, 0.f)});
colors.push(white);
vertices.push({vec3(-x, -p_width, 0.f), vec3(-x, p_width, 0.f)});
colors.push(white);
x += p_scale;
}
// X
vertices.push({vec3(-p_length, 0.f, 0.f), vec3(p_length, 0.f, 0.f)});
colors.push(red);
for (hpr::scalar y = p_scale; y <= p_width; )
{
vertices.push({vec3(-p_length, y, 0.f), vec3(p_length, y, 0.f)});
colors.push(white);
vertices.push({vec3(-p_length, -y, 0.f), vec3(p_length, -y, 0.f)});
colors.push(white);
y += p_scale;
}
break;
}
case XZ: {
// Z
vertices.push({vec3(0.f, 0.f, -p_height), vec3(0.f, 0.f, p_height)});
colors.push(blue);
for (hpr::scalar x = p_scale; x <= p_length; )
{
vertices.push({vec3(x, 0.f, -p_height), vec3(x, 0.f, p_height)});
colors.push(white);
vertices.push({vec3(-x, 0.f, -p_height), vec3(-x, 0.f, p_height)});
colors.push(white);
x += p_scale;
}
// X
vertices.push({vec3(-p_length, 0.f, 0.f), vec3(p_length, 0.f, 0.f)});
colors.push(red);
for (hpr::scalar z = p_scale; z <= p_height; )
{
vertices.push({vec3(-p_length, 0.f, z), vec3(p_length, 0.f, z)});
colors.push(white);
vertices.push({vec3(-p_length, 0.f, -z), vec3(p_length, 0.f, -z)});
colors.push(white);
z += p_scale;
}
break;
}
case YZ: {
// Y
vertices.push({vec3(0.f, -p_width, 0.f), vec3(0.f, p_width, 0.f)});
colors.push(green);
for (hpr::scalar z = p_scale; z <= p_height; )
{
vertices.push({vec3(0.f, -p_width, z), vec3(0.f, p_width, z)});
colors.push(white);
vertices.push({vec3(0.f, -p_width, -z), vec3(0.f, p_width, -z)});
colors.push(white);
z += p_scale;
}
// Z
vertices.push({vec3(0.f, 0.f, -p_height), vec3(0.f, 0.f, p_height)});
colors.push(blue);
for (hpr::scalar y = p_scale; y <= p_width; )
{
vertices.push({vec3(0.f, y, -p_height), vec3(0.f, y, p_height)});
colors.push(white);
vertices.push({vec3(0.f, -y, -p_height), vec3(0.f, -y, p_height)});
colors.push(white);
y += p_scale;
}
}
}
}
public:
void rebuild()
{
darray<vec3> vertices;
darray<vec3> colors;
construct(vertices, colors);
Entity::editVertices(vertices);
Entity::editColors(colors);
Entity::renderMode(gpu::ArrayObject::Lines);
}
void mode(Mode mode)
{
p_mode = mode;
}
void scale(hpr::scalar scale)
{
p_scale = scale;
}
};

134
source/creator/ray.hpp Normal file
View File

@ -0,0 +1,134 @@
#pragma once
#include <hpr/math.hpp>
#include "camera.hpp"
#include "entity.hpp"
using namespace hpr;
vec3 unproject(const vec3& win, const mat4& model, const mat4& proj, const vec4& viewport)
{
mat4 inverse = inv(proj * model);
vec4 tmp = vec4(win, 1.);
tmp[0] = (tmp[0] - viewport[0]) / viewport[2];
tmp[1] = (tmp[1] - viewport[1]) / viewport[3];
tmp = tmp * 2.f - 1.f;
vec4 obj = inverse * tmp;
obj /= obj[3];
return vec3(obj);
}
class Ray
{
public:
vec3 p_position;
vec3 p_direction;
Ray() :
p_position {},
p_direction {}
{}
Ray(const vec3& position, const vec3& direction) :
p_position {position},
p_direction {direction}
{}
void fromScreen(int x, int y, int width, int height, Camera* camera, Entity* entity)
{
/*vec4 start {2.f * (float)x / (float)width - 1.f, 2.f * (float)y / (float)height - 1.f, 0.f, 1.f};
vec4 end {2.f * (float)x / (float)width - 1.f, 2.f * (float)y / (float)height - 1.f, 1.f, 1.f};
mat4 invPV = inv(transpose(camera->projection()) * transpose(camera->view()));
vec4 startWorld = invPV * start;
startWorld /= startWorld[3];
vec4 endWorld = invPV * end;
endWorld /= endWorld[3];*/
vec3 end = unproject(vec3(x, y, 0), entity->model(), camera->projection(), vec4(0, 0, width, height));
p_position = vec3(startWorld);
p_direction = normalize(vec3(endWorld - startWorld));
}
bool obb(const vec3& aabbMin, const vec3& aabbMax, Entity* entity, float& tMin, float& tMax)
{
tMin = 0.;
tMax = 1e+5;
mat4 model = entity->model();
vec3 obbPos {model(0, 3), model(1, 3), model(2, 3)};
vec3 delta = obbPos - p_position;
for (auto n = 0; n < 3; ++n)
{
vec3 axis {model(0, n), model(1, n), model(2, n)};
scalar e = dot(axis, delta);
scalar f = dot(p_direction, axis);
if (hpr::abs(f) > 1e-3)
{
scalar t1 = (e + aabbMin[n]) / f;
scalar t2 = (e + aabbMax[n]) / f;
if (t1 > t2)
std::swap(t1, t2);
if (t2 < tMax)
tMax = t2;
if (t1 > tMin)
tMin = t1;
if (tMax < tMin)
return false;
}
else
{
if (-e + aabbMin[n] > 0.f || -e + aabbMax[n] < 0.f)
return false;
}
}
//dist = tMin;
return true;
}
};
/*
bool RayIntersectsTriangle(Vector3D rayOrigin,
Vector3D rayVector,
Triangle* inTriangle,
Vector3D& outIntersectionPoint)
{
const float EPSILON = 0.0000001;
Vector3D vertex0 = inTriangle->vertex0;
Vector3D vertex1 = inTriangle->vertex1;
Vector3D vertex2 = inTriangle->vertex2;
Vector3D edge1, edge2, h, s, q;
float a,f,u,v;
edge1 = vertex1 - vertex0;
edge2 = vertex2 - vertex0;
h = rayVector.crossProduct(edge2);
a = edge1.dotProduct(h);
if (a > -EPSILON && a < EPSILON)
return false; // This ray is parallel to this triangle.
f = 1.0/a;
s = rayOrigin - vertex0;
u = f * s.dotProduct(h);
if (u < 0.0 || u > 1.0)
return false;
q = s.crossProduct(edge1);
v = f * rayVector.dotProduct(q);
if (v < 0.0 || u + v > 1.0)
return false;
// At this stage we can compute t to find out where the intersection point is on the line.
float t = f * edge2.dotProduct(q);
if (t > EPSILON) // ray intersection
{
outIntersectionPoint = rayOrigin + rayVector * t;
return true;
}
else // This means that there is a line intersection but not a ray intersection.
return false;
}
*/

80
source/creator/scene.hpp Normal file
View File

@ -0,0 +1,80 @@
#pragma once
#include "camera.hpp"
#include "entity.hpp"
#include <hpr/containers/graph.hpp>
class Scene
{
protected:
Camera* p_camera;
hpr::darray<hpr::TreeNode<Entity>> p_nodes;
public:
inline
Scene()
{}
virtual
~Scene()
{
delete p_camera;
for (auto& node : p_nodes)
node.data()->destroy();
}
inline
void camera(Camera* camera)
{
p_camera = camera;
}
inline
Camera* camera()
{
return p_camera;
}
inline
void add(const hpr::TreeNode<Entity>& entityNode)
{
p_nodes.push(entityNode);
}
inline
darray<hpr::TreeNode<Entity>>& nodes()
{
return p_nodes;
}
void render()
{
for (auto node : p_nodes)
{
node.data()->render();
node.data()->shaderProgram()->bind();
// camera
node.data()->shaderProgram()->uniformMatrix<4, 4>("view", 1, true, p_camera->view().data());
node.data()->shaderProgram()->uniformMatrix<4, 4>("projection", 1, true, p_camera->projection().data());
node.data()->shaderProgram()->uniformVector<float, 3>("viewPos", 1, p_camera->position().data());
// light
hpr::vec3 lightColor {1.0f, 1.0f, 1.0f};
node.data()->shaderProgram()->uniformVector<float, 3>("lightColor", 1, lightColor.data());
hpr::vec3 lightPos {1.0f, 1.0f, 1.0f};
node.data()->shaderProgram()->uniformVector<float, 3>("lightPos", 1, lightPos.data());
node.data()->shaderProgram()->unbind();
//for (auto descendant : node.descendants())
// descendant->data()->render();
}
}
};

145
source/creator/shaders.hpp Normal file
View File

@ -0,0 +1,145 @@
#pragma once
const char* vertexSource = R"glsl(
#version 430 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec3 color;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
uniform vec3 lightPos;
out vec3 Normal;
out vec3 Color;
out vec3 FragPos;
out vec3 LightPos;
void main()
{
gl_Position = projection * view * model * vec4(position, 1.0);
gl_PointSize = 5;
Normal = mat3(transpose(inverse(model))) * normal;
Color = color;
FragPos = vec3(view * model * vec4(position, 1.0));
LightPos = lightPos; vec3(view * vec4(lightPos, 1.0));
}
)glsl";
const char* fragmentSource = R"glsl(
#version 430 core
in vec3 Normal;
in vec3 Color;
in vec3 FragPos;
in vec3 LightPos;
//uniform vec3 lightPos;
uniform vec3 lightColor;
uniform vec4 objectColor;
uniform vec3 viewPos;
out vec4 FragColor;
void main()
{
float ambientStrength = 0.1;
vec3 ambient = ambientStrength * lightColor;
// diffuse
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(LightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * lightColor;
// specular
float specularStrength = 0.2;
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
vec3 specular = specularStrength * spec * lightColor;
vec3 result = (ambient + diffuse) * vec3(objectColor);
FragColor = vec4(result, 1.0);
}
)glsl";
const char* gridVertexSource = R"glsl(
#version 430 core
uniform mat4 view;
uniform mat4 projection;
vec3 position = vec3(0, 0, 0);
// Grid position are in xy clipped space
vec3 gridPlane[6] = vec3[](
vec3(1, 1, 0), vec3(-1, -1, 0), vec3(-1, 1, 0),
vec3(-1, -1, 0), vec3(1, 1, 0), vec3(1, -1, 0)
);
// normal vertice projection
void main() {
gl_Position = projection * view * vec4(gridPlane[gl_VertexID].xyz, 1.0);
}
)glsl";
const char* gridFragmentSource = R"glsl(
#version 430 core
const float tileSize = 0.2;
const float borderSize = 0.468;
const float lineBlur = 0.2;
vec2 aGrid(vec2 uv) {
return vec2(mod(uv.x, 1.0), mod(uv.y * 2.0, 1.0));
}
vec2 bGrid(vec2 uv) {
return vec2(mod(uv.x - 0.5, 1.0), mod((uv.y * 2.0) - 0.5, 1.0));
}
float los(vec2 pos) {
vec2 abspos = abs(pos - vec2(0.5));
return smoothstep(borderSize, borderSize + lineBlur, abspos.x + abspos.y);
}
out vec4 fragColor;
void main() {
vec2 uv = vec2(1.0, 0.);//fragCoord;// / iResolution.xy;
vec2 size = uv / tileSize;
float alos = los(aGrid(size));
float blos = los(bGrid(size));
float color = min(alos, blos);
color = pow(color, 1.0 / 2.2);
fragColor = vec4(color);
}
)glsl";
/*
float4 HeatMapColor(float value, float minValue, float maxValue)
{
#define HEATMAP_COLORS_COUNT 6
float4 colors[HEATMAP_COLORS_COUNT] =
{
float4(0.32, 0.00, 0.32, 1.00),
float4(0.00, 0.00, 1.00, 1.00),
float4(0.00, 1.00, 0.00, 1.00),
float4(1.00, 1.00, 0.00, 1.00),
float4(1.00, 0.60, 0.00, 1.00),
float4(1.00, 0.00, 0.00, 1.00),
};
float ratio=(HEATMAP_COLORS_COUNT-1.0)*saturate((value-minValue)/(maxValue-minValue));
float indexMin=floor(ratio);
float indexMax=min(indexMin+1,HEATMAP_COLORS_COUNT-1);
return lerp(colors[indexMin], colors[indexMax], ratio-indexMin);
}
* */

View File

@ -0,0 +1,551 @@
/*
#include "hpr/gpu.hpp"
#include "hpr/window_system/window_system.hpp"
#include "hpr/window_system/glfw/window_system.hpp"
#include "hpr/window_system/glfw/window.hpp"
#include "hpr/math.hpp"
#include "hpr/mesh.hpp"
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
void GLAPIENTRY
MessageCallback( GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam )
{
fprintf( stderr, "GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n\n",
( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "" ),
type, severity, message );
}
*/
/*
const char *vertexShaderSource = "#version 430 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char *fragmentShaderSource = "#version 430 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
const GLchar* vertexSource = R"glsl(
#version 150 core
in vec2 position;
in vec3 color;
out vec3 Color;
void main()
{
Color = color;
gl_Position = vec4(position, 0.0, 1.0);
}
)glsl";
const GLchar* fragmentSource = R"glsl(
#version 150 core
in vec3 Color;
out vec4 outColor;
void main()
{
outColor = vec4(Color, 1.0);
}
)glsl";
int main()
{
using namespace hpr;
gpu::WindowSystem *ws = gpu::WindowSystem::create(gpu::WindowContext::Provider::GLFW);
gpu::Window *w = ws->newWindow();
w->init("test", gpu::Window::Style::Windowed, 50, 50, 600, 400, nullptr, nullptr);
if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress))
throw std::runtime_error("Cannot initialize gl context");
// During init, enable debug output
glEnable ( GL_DEBUG_OUTPUT );
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback( glDebugOutput, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
gpu::Shader vshader {gpu::Shader::Type::Vertex, vertexShaderSource};
gpu::Shader fshader {gpu::Shader::Type::Fragment, fragmentShaderSource};
gpu::ShaderProgram sprogram {};
vshader.create();
fshader.create();
sprogram.create();
sprogram.attach(vshader);
sprogram.attach(fshader);
sprogram.link();
gpu::Shader vshader2 {gpu::Shader::Type::Vertex, vertexSource};
gpu::Shader fshader2 {gpu::Shader::Type::Fragment, fragmentSource};
gpu::ShaderProgram sprogram2 {};
vshader2.create();
fshader2.create();
sprogram2.create();
sprogram2.attach(vshader2);
sprogram2.attach(fshader2);
sprogram2.link();
//vshader.destroy();
//fshader.destroy();
for (auto& sh : sprogram.shaders())
std::cout << sh.index() << std::endl;
std::cout << sprogram.index() << std::endl;
darray<float> vertices {
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f // top left
};
darray<unsigned int> indices2 { // note that we start from 0!
0, 1, 3, // first Triangle
1, 2, 3 // second Triangle
};
gpu::ArrayObject vao {};
gpu::BufferObject vbo {gpu::BufferObject::Type::Vertex};
gpu::BufferObject ebo {gpu::BufferObject::Type::Index};
vao.create();
vao.bind();
vbo.create<float>(vertices);
ebo.create<unsigned int>(indices2);
vao.attribPointer(vbo, 0, 3);
vao.unbind();
// Create Vertex Array Object
GLuint vao2;
glGenVertexArrays(1, &vao2);
glBindVertexArray(vao2);
// Create a Vertex Buffer Object and copy the vertex data to it
GLuint vbo2;
glGenBuffers(1, &vbo2);
GLfloat vertices2[] = {
-0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
-0.5f, -0.5f, 1.0f, 1.0f, 1.0f // Bottom-left
};
glBindBuffer(GL_ARRAY_BUFFER, vbo2);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices2, GL_STATIC_DRAW);
// Create an element array
GLuint ebo2;
glGenBuffers(1, &ebo2);
GLuint elements2[] = {
0, 1, 2,
2, 3, 0
};
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo2);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements2), elements2, GL_STATIC_DRAW);
// Specify the layout of the vertex data
GLint posAttrib = glGetAttribLocation(sprogram2.index(), "position");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), 0);
GLint colAttrib = glGetAttribLocation(sprogram2.index(), "color");
glEnableVertexAttribArray(colAttrib);
glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));
std::cout << sprogram2.index() << std::endl;
gpu::Viewport viewport {{0, 0}, {600, 400}};
gpu::ColorBuffer colorBuffer;
gpu::DepthBuffer depthBuffer {true};
/*IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
io.IniFilename = nullptr;
io.LogFilename = nullptr;
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(dynamic_cast<gpu::glfw::Window*>(w)->instance(), true);
ImGui_ImplOpenGL3_Init("#version 430");
while (w->isOpen())
{
viewport.set();
//colorBuffer.clear({0.2f, 0.2f, 0.2f, 1.0f});
//depthBuffer.clear();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
sprogram.bind();
vao.bind();
ebo.bind();
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
sprogram2.bind();
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
/*
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
bool yes = true;
ImGui::ShowDemoWindow(&yes);
ImGui::Begin("Hello, world!");
{
if (ImGui::Button("Exit"))
w->state(gpu::Window::State::Closed);
ImGui::End();
}
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
dynamic_cast<gpu::glfw::Window*>(w)->swapBuffers();
dynamic_cast<gpu::glfw::Window*>(w)->pollEvents();
}
sprogram.destroy();
vbo.destroy();
ebo.destroy();
vao.destroy();
/*
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
ws->destroyWindow(w);
gpu::WindowSystem::destroy(ws);
return 0;
}
*/
// Link statically with GLEW
#define GLEW_STATIC
// Headers
//#include <GL/glew.h>
//#include <SFML/Window.hpp>
#include "hpr/gpu.hpp"
#include <iostream>
void APIENTRY glDebugOutput(
GLenum source,
GLenum type,
unsigned int id,
GLenum severity,
GLsizei length,
const char* message,
const void* userParam
)
{
// ignore non-significant error/warning codes
if (id == 131169 || id == 131185 || id == 131218 || id == 131204)
return;
std::cout << "Debug::GL[" << id << "]: " << message << std::endl;
switch (source)
{
case GL_DEBUG_SOURCE_API:
std::cout << "Source: API";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
std::cout << "Source: Window System";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER:
std::cout << "Source: Shader Compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY:
std::cout << "Source: Third Party";
break;
case GL_DEBUG_SOURCE_APPLICATION:
std::cout << "Source: Application";
break;
case GL_DEBUG_SOURCE_OTHER:
std::cout << "Source: Other";
break;
}
std::cout << std::endl;
switch (type)
{
case GL_DEBUG_TYPE_ERROR:
std::cout << "Type: Error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
std::cout << "Type: Deprecated Behaviour";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
std::cout << "Type: Undefined Behaviour";
break;
case GL_DEBUG_TYPE_PORTABILITY:
std::cout << "Type: Portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
std::cout << "Type: Performance";
break;
case GL_DEBUG_TYPE_MARKER:
std::cout << "Type: Marker";
break;
case GL_DEBUG_TYPE_PUSH_GROUP:
std::cout << "Type: Push Group";
break;
case GL_DEBUG_TYPE_POP_GROUP:
std::cout << "Type: Pop Group";
break;
case GL_DEBUG_TYPE_OTHER:
std::cout << "Type: Other";
break;
}
std::cout << std::endl;
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH:
std::cout << "Severity: high";
break;
case GL_DEBUG_SEVERITY_MEDIUM:
std::cout << "Severity: medium";
break;
case GL_DEBUG_SEVERITY_LOW:
std::cout << "Severity: low";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
std::cout << "Severity: notification";
break;
}
std::cout << std::endl;
}
// Shader sources
const GLchar* vertexSource = R"glsl(
#version 430 core
layout (location = 0) in vec2 position;
layout (location = 1) in vec3 color;
//in vec2 position;
//in vec3 color;
out vec3 Color;
void main()
{
Color = color;
gl_Position = vec4(position, 0.0, 1.0);
}
)glsl";
const GLchar* fragmentSource = R"glsl(
#version 430 core
in vec3 Color;
out vec4 outColor;
void main()
{
//outColor = vec4(1.0, 1.0, 1.0, 1.0); //vec4(Color, 1.0);
outColor = vec4(Color, 1.0);
}
)glsl";
int main()
{
/*sf::ContextSettings settings;
settings.depthBits = 24;
settings.stencilBits = 8;
settings.majorVersion = 3;
settings.minorVersion = 2;
sf::Window window(sf::VideoMode(800, 600, 32), "OpenGL", sf::Style::Titlebar | sf::Style::Close, settings);
*/
using namespace hpr;
//gpu::WindowSystem *ws = gpu::WindowSystem::create(gpu::WindowContext::Provider::GLFW);
//gpu::Window *w = ws->newWindow();
//w->init("test", gpu::Window::Style::Windowed, 50, 50, 600, 400, nullptr, nullptr);
gpu::Window w {50, 50, 600, 400, "Test", gpu::Window::Style::Windowed, nullptr, nullptr};
w.keyClickCallback([](gpu::Window* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE)
window->state(gpu::Window::Closed);
});
w.context().debug();
// Initialize GLEW
//glewExperimental = GL_TRUE;
//glewInit();
// Create Vertex Array Object
/*GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);*/
gpu::ArrayObject vao {};
vao.create();
vao.bind();
// Create a Vertex Buffer Object and copy the vertex data to it
//GLuint vbo;
//glGenBuffers(1, &vbo);
gpu::BufferObject vbo2 {gpu::BufferObject::Type::Vertex};
darray<float> vertices {
-0.5f, 0.5f, //1.0f, 0.0f, 0.0f, // Top-left
0.5f, 0.5f, //0.0f, 1.0f, 0.0f, // Top-right
0.5f, -0.5f, //0.0f, 0.0f, 1.0f, // Bottom-right
-0.5f, -0.5f, //1.0f, 1.0f, 1.0f // Bottom-left
};
darray<float> colors {
1.0f, 0.0f, 0.0f, // Top-left
0.0f, 1.0f, 0.0f, // Top-right
0.0f, 0.0f, 1.0f, // Bottom-right
1.0f, 1.0f, 1.0f // Bottom-left
};
float vertices2[] = {
-0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
-0.5f, -0.5f, 1.0f, 1.0f, 1.0f // Bottom-left
};
//glBindBuffer(GL_ARRAY_BUFFER, vbo);
//glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW);
//glBindBuffer(GL_ARRAY_BUFFER, vbo.index());
//glBufferData(static_cast<GLenum>(gpu::BufferObject::Type::Vertex), sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
//vbo.bind();
vbo2.create(vertices);
vbo2.bind();
gpu::BufferObject vboColors {gpu::BufferObject::Type::Vertex};
vboColors.create(colors);
vboColors.bind();
//vbo2.destroy();
// Create an element array
/*GLuint ebo;
glGenBuffers(1, &ebo);
GLuint elements[] = {
0, 1, 2,
2, 3, 0
};*/
darray<unsigned int> elements {
0, 1, 2,
2, 3, 0
};
/*
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
*/
gpu::BufferObject els {gpu::BufferObject::Type::Index};
els.create(elements);
els.bind();
// Create and compile the vertex shader
/*GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexSource, NULL);
glCompileShader(vertexShader);*/
gpu::Shader vshader {gpu::Shader::Type::Vertex, vertexSource};
vshader.create();
// Create and compile the fragment shader
/*GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
glCompileShader(fragmentShader);*/
gpu::Shader fshader {gpu::Shader::Type::Fragment, fragmentSource};
fshader.create();
// Link the vertex and fragment shader into a shader program
/*GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
//glBindFragDataLocation(shaderProgram, 0, "outColor");
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);*/
gpu::ShaderProgram sprogram {};
sprogram.create();
sprogram.attach(vshader);
sprogram.attach(fshader);
sprogram.link();
sprogram.bind();
// Specify the layout of the vertex data
/*GLint posAttrib = glGetAttribLocation(sprogram.index(), "position");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 0);*/
vao.attribPointer(vbo2, 0, 2);
vao.attribPointer(vboColors, 1, 3);
/*vbo2.bind();
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);
vboColors.bind();
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);*/
/*GLint colAttrib = glGetAttribLocation(sprogram.index(), "color");
glEnableVertexAttribArray(colAttrib);
glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(2 * sizeof(float)));*/
gpu::ColorBuffer cb;
bool running = true;
while (w.state() != gpu::Window::Closed)
{
/*sf::Event windowEvent;
while (window.pollEvent(windowEvent))
{
switch (windowEvent.type)
{
case sf::Event::Closed:
running = false;
break;
}
}*/
// Clear the screen to black
//glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
//glClear(GL_COLOR_BUFFER_BIT);
cb.clear(vec4(0.0f, 0.0f, 0.0f, 1.0f));
// Draw a rectangle from the 2 triangles using 6 indices
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
// Swap buffers
//window.display();
w.swapBuffers();
w.pollEvents();
}
sprogram.destroy();
vshader.destroy();
fshader.destroy();
/*glDeleteProgram(shaderProgram);
glDeleteShader(fragmentShader);
glDeleteShader(vertexShader);*/
//glDeleteBuffers(1, &ebo);
//glDeleteBuffers(1, &vbo);
vbo2.destroy();
//glDeleteVertexArrays(1, &vao);
vao.destroy();
w.destroy();
return 0;
}

View File

@ -1,133 +1,319 @@
#include "hpr/gpu.hpp"
#include "hpr/window_system/window_system.hpp"
#include "hpr/window_system/glfw/window_system.hpp"
#include "hpr/window_system/glfw/window.hpp"
#include "hpr/math.hpp"
#include "hpr/mesh.hpp"
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <iostream>
const char *vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char *fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
#include "visual.hpp"
#include "entity.hpp"
#include "ui.hpp"
//#include "transform.hpp"
#include "camera.hpp"
#include "scene.hpp"
#include "grid.hpp"
#include <implot.h>
#include "ray.hpp"
int main()
{
using namespace hpr;
gpu::WindowSystem *ws = gpu::WindowSystem::create(gpu::WindowContext::Provider::GLFW);
gpu::Window *w = ws->newWindow();
w->init("test", gpu::Window::Style::Windowed, 0, 0, 600, 400, nullptr, nullptr);
Visual visual;
if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress))
throw std::runtime_error("Cannot initialize gl context");
gpu::Shader vshader {gpu::Shader::Type::Vertex, vertexShaderSource};
gpu::Shader fshader {gpu::Shader::Type::Fragment, fragmentShaderSource};
gpu::ShaderProgram sprogram {};
vshader.create();
fshader.create();
sprogram.create();
sprogram.attach(vshader);
sprogram.attach(fshader);
sprogram.link();
for (auto& sh : sprogram.shaders())
std::cout << sh.index() << std::endl;
darray<float> vertices {
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f // top left
};
darray<unsigned int> indices2 { // note that we start from 0!
0, 1, 3, // first Triangle
1, 2, 3 // second Triangle
};
gpu::ArrayObject vao {};
gpu::BufferObject vbo {gpu::BufferObject::Type::Vertex};
gpu::BufferObject ebo {gpu::BufferObject::Type::Index};
vao.create();
vao.bind();
vbo.create<float>(vertices);
ebo.create<unsigned int>(indices2);
vao.attribPointer(vbo, 0, 3);
vao.unbind();
gpu::Viewport viewport {{0, 0}, {600, 400}};
gpu::ColorBuffer colorBuffer;
gpu::DepthBuffer depthBuffer {true};
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(dynamic_cast<gpu::glfw::Window*>(w)->instance(), true);
ImGui_ImplOpenGL3_Init("#version 420");
while (w->isOpen())
visual.window()->keyClickCallback([](gpu::Window* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE)
window->state(gpu::Window::Closed);
});
visual.window()->context().debug();
UI ui {visual.window()};
darray<vec3> vertices {
/*vec2(-0.5f, 0.5f),
vec2(0.5f, 0.5f),
vec2(0.5f, -0.5f),
vec2(-0.5f, -0.5f)*/
vec3(-0.5f, -0.5f, -0.5f),
vec3(0.5f, -0.5f, -0.5f),
vec3(0.5f, 0.5f, -0.5f),
vec3(0.5f, 0.5f, -0.5f),
vec3(-0.5f, 0.5f, -0.5f),
vec3(-0.5f, -0.5f, -0.5f),
vec3(-0.5f, -0.5f, 0.5f),
vec3(0.5f, -0.5f, 0.5f),
vec3(0.5f, 0.5f, 0.5f),
vec3(0.5f, 0.5f, 0.5f),
vec3(-0.5f, 0.5f, 0.5f),
vec3(-0.5f, -0.5f, 0.5f),
vec3(-0.5f, 0.5f, 0.5f),
vec3(-0.5f, 0.5f, -0.5f),
vec3(-0.5f, -0.5f, -0.5f),
vec3(-0.5f, -0.5f, -0.5f),
vec3(-0.5f, -0.5f, 0.5f),
vec3(-0.5f, 0.5f, 0.5f),
vec3(0.5f, 0.5f, 0.5f),
vec3(0.5f, 0.5f, -0.5f),
vec3(0.5f, -0.5f, -0.5f),
vec3(0.5f, -0.5f, -0.5f),
vec3(0.5f, -0.5f, 0.5f),
vec3(0.5f, 0.5f, 0.5f),
vec3(-0.5f, -0.5f, -0.5f),
vec3(0.5f, -0.5f, -0.5f),
vec3(0.5f, -0.5f, 0.5f),
vec3(0.5f, -0.5f, 0.5f),
vec3(-0.5f, -0.5f, 0.5f),
vec3(-0.5f, -0.5f, -0.5f),
vec3(-0.5f, 0.5f, -0.5f),
vec3(0.5f, 0.5f, -0.5f),
vec3(0.5f, 0.5f, 0.5f),
vec3(0.5f, 0.5f, 0.5f),
vec3(-0.5f, 0.5f, 0.5f),
vec3(-0.5f, 0.5f, -0.5f)
};
darray<vec3> normals {
vec3(0.0f, 0.0f, -1.0f),
vec3(0.0f, 0.0f, -1.0f),
vec3(0.0f, 0.0f, -1.0f),
vec3(0.0f, 0.0f, -1.0f),
vec3(0.0f, 0.0f, -1.0f),
vec3(0.0f, 0.0f, -1.0f),
vec3(0.0f, 0.0f, 1.0f),
vec3(0.0f, 0.0f, 1.0f),
vec3(0.0f, 0.0f, 1.0f),
vec3(0.0f, 0.0f, 1.0f),
vec3(0.0f, 0.0f, 1.0f),
vec3(0.0f, 0.0f, 1.0f),
vec3(-1.0f, 0.0f, 0.0f),
vec3(-1.0f, 0.0f, 0.0f),
vec3(-1.0f, 0.0f, 0.0f),
vec3(-1.0f, 0.0f, 0.0f),
vec3(-1.0f, 0.0f, 0.0f),
vec3(-1.0f, 0.0f, 0.0f),
vec3(1.0f, 0.0f, 0.0f),
vec3(1.0f, 0.0f, 0.0f),
vec3(1.0f, 0.0f, 0.0f),
vec3(1.0f, 0.0f, 0.0f),
vec3(1.0f, 0.0f, 0.0f),
vec3(1.0f, 0.0f, 0.0f),
vec3(0.0f, -1.0f, 0.0f),
vec3(0.0f, -1.0f, 0.0f),
vec3(0.0f, -1.0f, 0.0f),
vec3(0.0f, -1.0f, 0.0f),
vec3(0.0f, -1.0f, 0.0f),
vec3(0.0f, -1.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f)
};
darray<vec3> colors {
vec3(1.0f, 0.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f),
vec3(0.0f, 0.0f, 1.0f),
vec3(1.0f, 1.0f, 1.0f)
};
darray<Vector<unsigned int, 3>> indices {
Vector<unsigned int, 3>(0, 1, 2),
Vector<unsigned int, 3>(2, 3, 0)
};
Entity entity {visual.shaderProgram()};
entity.addVertices(vertices);
entity.addNormals(normals);
//entity.addColors(colors);
//entity.addIndices(indices);
Scene scene;
scene.camera(new OrbitCamera());
scene.add(TreeNode<Entity>(entity));
//Transform transform {&entity};
//gpu::DepthBuffer depthBuffer {true};
visual.depthBuffer().bind();
//gpu::CullFace cullFace {gpu::CullFace::Mode::FrontAndBack};
float angle = 0;
glEnable(GL_PROGRAM_POINT_SIZE);
/*gpu::ShaderProgram shaderProgram;
gpu::Shader vertexShader {gpu::Shader::Type::Vertex, gridVertexSource};
vertexShader.create();
gpu::Shader fragmentShader {gpu::Shader::Type::Fragment, gridFragmentSource};
fragmentShader.create();
shaderProgram.create();
shaderProgram.attach(vertexShader);
shaderProgram.attach(fragmentShader);
shaderProgram.link();
shaderProgram.bind();
shaderProgram.uniformMatrix<4, 4>("view", 1, true, scene.camera()->view().data());
shaderProgram.uniformMatrix<4, 4>("projection", 1, true, scene.camera()->projection().data());
shaderProgram.unbind();*/
/*Entity grid {visual.shaderProgram()};
darray<vec3> vertices2;
auto genVert = [](float x, float y){;
return darray<vec3>{
vec3(-1.0f + x, 0.f + y, 0.f),
vec3(1.0f + x, 0.f + y, 0.f),
vec3(0.f + x, -1.0f + y, 0.f),
vec3(0.f + x, 1.0f + y, 0.f)
};};
for (auto x = -100; x < 100; ++x)
for (auto y = -100; y < 100; ++y)
vertices2.push(genVert(x, y));
grid.addVertices(vertices2);
grid.color(vec4(1, 1, 1, 1));
grid.renderMode(gpu::ArrayObject::Lines);*/
//Grid grid {visual.shaderProgram()};
//scene.add(TreeNode<Entity>(grid));
/*
gpu::ArrayObject ao;
gpu::BufferObject bo;
ao.create();
ao.bind();
bo.create(vertices2);
bo.bind();
ao.attribPointer(bo, 0, 3);
ao.unbind();
bo.unbind();*/
glfwWindowHint(GLFW_SAMPLES, 4);
ImPlot::CreateContext();
glEnable(GL_MULTISAMPLE);
/*gpu::Texture tex;
tex.create();
gpu::Renderbuffer rb;
rb.create();*/
gpu::Framebuffer framebuffer;
framebuffer.create();
gpu::Viewport viewport;
/*framebuffer.bind();
framebuffer.attach(tex);
framebuffer.attach(rb);
framebuffer.unbind();*/
const vec4 background = vec4(0.2f, 0.2f, 0.2f, 1.0f);
while (visual.window()->state() != gpu::Window::Closed)
{
visual.colorBuffer().clear(background);
visual.depthBuffer().clear();
//cullFace.bind();
//entity.render(hpr::gpu::ArrayObject::Triangles);
//angle += 1;
//transform.rotate({0, 1, 0}, angle);
//transform.rotate({0, 0, 1}, angle);
//transform.render();
viewport.size() = vec2(framebuffer.width(), framebuffer.height());
viewport.set();
framebuffer.bind();
framebuffer.rescale();
colorBuffer.clear({0.8f, 0.2f, 0.2f, 1.0f});
depthBuffer.clear();
visual.colorBuffer().clear(background);
visual.depthBuffer().clear();
sprogram.bind();
vao.bind();
glDrawArrays(GL_TRIANGLES, 0, 6);
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
scene.camera()->aspect() = (float)framebuffer.width() / (float)framebuffer.height();
scene.render();
framebuffer.unbind();
viewport.size() = vec2((float)visual.window()->width(), (float)visual.window()->height());
viewport.set();
//shaderProgram.bind();
ui.createFrame();
bool yes = true;
ImGui::ShowDemoWindow(&yes);
ImPlot::ShowDemoWindow(&yes);
ImGui::Begin("Hello, world!");
{
if (ImGui::Button("Exit"))
w->state(gpu::Window::State::Closed);
visual.window()->state(gpu::Window::Closed);
ImGui::End();
}
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
dynamic_cast<gpu::glfw::Window*>(w)->swapBuffers();
dynamic_cast<gpu::glfw::Window*>(w)->pollEvents();
ui.render();
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
if (ImGui::Begin("Scene"))
{
ImGui::PopStyleVar();
if (!ImGui::IsWindowCollapsed())
{
framebuffer.width() = static_cast<int>(ImGui::GetContentRegionAvail().x);
framebuffer.height() = static_cast<int>(ImGui::GetContentRegionAvail().y);
ImGui::Image(reinterpret_cast<void *>(framebuffer.texture().index()), ImGui::GetContentRegionAvail(),
ImVec2{0, 1}, ImVec2{1, 0});
ImGuiIO& io = ImGui::GetIO();
Ray ray;
ray.fromScreen(io.MousePos.x, io.MousePos.y, framebuffer.width(), framebuffer.height(), scene.camera());
float tMin, tMax;
Entity* ent = scene.nodes()[0].data();
bool rayOBB = ray.obb({-1.0f, -1.0f, -1.0f}, {1.0f, 1.0f, 1.0f}, ent, tMin, tMax);
//std::cout << rayOBB << std::endl;
if (rayOBB)
ent->color(vec4(1.f, 0.f, 0.f, 1.f));
else
ent->color(vec4(0.f, 1.f, 0.f, 1.f));
if (ImGui::Begin("Properties"))
{
ImGui::DragFloat3("position", ray.p_position.data());
ImGui::DragFloat3("direction", ray.p_direction.data());
vec2 mouse {io.MousePos.x, io.MousePos.y};
ImGui::DragFloat2("mouse", mouse.data());
ImGui::Checkbox("ray", &rayOBB);
ImGui::DragFloat("dist", &tMin);
ImGui::DragFloat("dist", &tMax);
ImGui::End();
}
if (ImGui::IsWindowHovered())
{
if (io.WantCaptureMouse)
{
dynamic_cast<OrbitCamera*>(scene.camera())->scrollEvent(0, io.MouseWheel);
if (ImGui::IsMouseDown(ImGuiMouseButton_Middle)) //(io.MouseDown[ImGuiMouseButton_Middle])
{
if (ImGui::IsKeyDown(ImGuiKey_LeftShift)) //(io.KeysDown[ImGuiKey_LeftShift])
{
dynamic_cast<OrbitCamera*>(scene.camera())->moveEvent(io.MouseDelta.x, io.MouseDelta.y);
}
else
{
dynamic_cast<OrbitCamera*>(scene.camera())->rotateEvent(io.MouseDelta.x, io.MouseDelta.y);
}
}
sprogram.destroy();
vshader.destroy();
fshader.destroy();
vbo.destroy();
ebo.destroy();
vao.destroy();
if (ImGui::IsMouseClicked(ImGuiMouseButton_Left))
{
ws->destroyWindow(w);
gpu::WindowSystem::destroy(ws);
}
}
}
}
ImGui::End();
}
ui.renderFrame();
visual.render();
}
ImPlot::DestroyContext();
framebuffer.destroy();
return 0;
}

View File

@ -0,0 +1,184 @@
#pragma once
#include <hpr/math.hpp>
#include <hpr/gpu/shader_program.hpp>
#include "entity.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
class Transform
{
public:
enum Projection
{
Perspective,
Orthographic
};
protected:
Projection p_projection;
hpr::scalar p_distance;
hpr::scalar p_aspect;
hpr::scalar p_fieldOfView;
hpr::scalar p_nearPlane;
hpr::scalar p_farPlane;
hpr::vec3 p_target;
hpr::vec3 p_left;
hpr::vec3 p_front;
hpr::vec3 p_up;
hpr::vec3 p_rotation;
hpr::mat4 p_model;
Entity* p_entity;
hpr::vec3 p_position;
public:
inline Transform() = delete;
inline Transform(Entity* entity) :
p_projection {Orthographic},
p_distance {10},
p_aspect {800.f / 600},
p_fieldOfView {45},
p_nearPlane {0.1},
p_farPlane {100},
p_target {0, 0, 0},
p_left {1, 0, 0},
p_front {0, 0, -1},
p_up {0, 0, 1},
p_rotation {45, 45, 0},
p_model {hpr::mat4::identity()},
p_entity {entity},
p_position {}
{
//for (auto v : p_model)
// std::cout << v << std::endl;
}
hpr::mat4 view()
{
hpr::vec3 rotation {
hpr::cos(hpr::rad(p_rotation[1])) * hpr::sin(hpr::rad(p_rotation[0])),
hpr::cos(hpr::rad(p_rotation[1])) * hpr::cos(hpr::rad(p_rotation[0])),
hpr::sin(hpr::rad(p_rotation[1]))};
hpr::vec3 pos = p_target + p_distance * rotation;
p_front = p_target - pos;
p_front /= hpr::length(p_front);
p_up = hpr::vec3(0, 0, 1);
p_left = hpr::normalize(hpr::cross(p_up, p_front));
p_up = hpr::cross(p_front, p_left);
auto dd = glm::lookAt(glm::vec3(pos[0], pos[1], pos[2]), glm::vec3(pos[0] + p_front[0], pos[1] + p_front[1], pos[2] + p_front[2]), glm::vec3(p_up[0], p_up[1], p_up[2]));
auto dd2 = hpr::lookAt(pos, pos + p_front, p_up);
p_position = pos;
//for (auto v : dd2)
// std::cout << v << " ";
//std::cout << std::endl;
return dd2;
}
/*
-0.707107 0.707107 0 -0
-0.5 -0.5 0.707107 -1.90735e-06
0.5 0.5 0.707107 -10
0 0 0 1
*/
void rotateEvent(float xdelta, float ydelta)
{
p_rotation += hpr::vec3(xdelta, ydelta, 0);
}
void moveEvent(float xdelta, float ydelta)
{
p_target += (p_left * xdelta + p_up * ydelta) * 1e-3f;
}
void scrollEvent(float xdelta, float ydelta)
{
p_distance -= ydelta;
}
hpr::mat4 projection(Projection projection)
{
p_projection = projection;
switch (p_projection)
{
case Perspective:
return hpr::perspective(hpr::rad(p_fieldOfView), p_aspect, p_nearPlane, p_farPlane);
case Orthographic:
return hpr::ortho(-p_distance * p_aspect, p_distance * p_aspect, -p_distance, p_distance, p_nearPlane, p_farPlane);
}
}
void clear()
{
p_model = hpr::mat4::identity();
}
void translate(const hpr::vec3& position)
{
p_model = hpr::translate(p_model, position);
}
void rotate(const hpr::vec3& axis, hpr::scalar angle)
{
p_model = hpr::rotate(p_model, axis, hpr::rad(angle));
}
void scale(const hpr::vec3& size)
{
p_model = hpr::scale(p_model, size);
}
/*struct Vec {
float x, y, z, w;
};*/
void render()
{
//double model[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
//Vec model2[] = {Vec{0, 0, 0, 0}, Vec{0, 0, 0, 0},Vec{0, 0, 0, 0},Vec{0, 0, 0, 0}};
//static_assert(sizeof(model2) == sizeof(float) * 16 && std::is_standard_layout_v<Vec>);
//static_assert((sizeof(hpr::StaticArray<float, 16>::pointer) == (sizeof(GLfloat) * 16)) &&
// (std::is_standard_layout<hpr::mat4>::value),
// "Matrix4 does not satisfy contiguous storage requirements");
p_entity->shaderProgram()->bind();
//glUniformMatrix4fv(glGetUniformLocation(p_entity->shaderProgram()->index(), "model"),
// 1, GL_FALSE, p_model.data());
p_entity->shaderProgram()->uniformMatrix<4, 4, float>("model", 1, true, p_model.data());
hpr::mat4 _view = view();
p_entity->shaderProgram()->uniformMatrix<4, 4, float>("view", 1, true, _view.data());
hpr::mat4 _projection = projection(p_projection);
p_entity->shaderProgram()->uniformVector<float, 3>("viewPos", 1, p_position.data());
//for (auto v : _projection)
// std::cout << v << std::endl;
glm::mat4 _proj = glm::ortho(-p_distance * p_aspect, p_distance * p_aspect, -p_distance, p_distance, p_nearPlane, p_farPlane);
p_entity->shaderProgram()->uniformMatrix<4, 4, float>("projection", 1, true, _projection.data());
hpr::vec3 objectColor {1.0f, 0.5f, 0.31f};
p_entity->shaderProgram()->bind();
p_entity->shaderProgram()->uniformVector<float, 3>("objectColor", 1, objectColor.data());
p_entity->render(gpu::ArrayObject::Mode::Triangles);
objectColor = {1.0f, 1.0f, 1.0f};
p_entity->shaderProgram()->bind();
p_entity->shaderProgram()->uniformVector<float, 3>("objectColor", 1, objectColor.data());
p_entity->render(gpu::ArrayObject::Mode::LineLoop);
p_entity->shaderProgram()->unbind();
clear();
}
};

157
source/creator/ui.hpp Normal file
View File

@ -0,0 +1,157 @@
#pragma once
#include <hpr/gpu/window.hpp>
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <imgui_internal.h>
//#include <imgui_stdlib.h>
using namespace hpr;
class UI
{
public:
UI(gpu::Window* window)
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGui_ImplGlfw_InitForOpenGL(window->instance(), true);
ImGui_ImplOpenGL3_Init("#version 430");
io().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io().ConfigFlags |= ImGuiConfigFlags_DockingEnable;
}
~UI()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void createFrame()
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void renderFrame()
{
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
inline
ImGuiIO& io()
{
return ImGui::GetIO();
}
inline
void render()
{
static auto first_time = true;
static bool show_object_explorer = true;
static bool show_properties = true;
static bool show_demo = false;
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("Options"))
{
ImGui::MenuItem("Undo", "CTRL+Z");
ImGui::EndMenu();
}
if (ImGui::BeginMenu("View"))
{
ImGui::MenuItem("Object explorer", nullptr, &show_object_explorer);
ImGui::MenuItem("Properties", nullptr, &show_properties);
ImGui::MenuItem("Demo", nullptr, &show_demo);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
if (show_demo)
ImGui::ShowDemoWindow();
const ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->WorkPos);
ImGui::SetNextWindowSize(viewport->WorkSize);
ImGui::SetNextWindowViewport(viewport->ID);
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar; // ImGuiWindowFlags_NoDocking;
window_flags |= ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
//window_flags |= ImGuiWindowFlags_MenuBar;
//window_flags |= ImGuiWindowFlags_NoBackground;
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
if (ImGui::Begin("Main dockspace", nullptr, window_flags))
{
ImGui::PopStyleVar(3);
ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
if (first_time)
{
first_time = false;
ImGui::DockBuilderRemoveNode(dockspace_id);
ImGui::DockBuilderAddNode(dockspace_id, dockspace_flags | ImGuiDockNodeFlags_DockSpace);
ImGui::DockBuilderSetNodeSize(dockspace_id, viewport->Size);
ImGuiID dock_id_left = ImGui::DockBuilderSplitNode(dockspace_id, ImGuiDir_Right, 0.2f, nullptr, &dockspace_id);
//ImGuiID dock_id_down = ImGui::DockBuilderSplitNode(dockspace_id, ImGuiDir_Right, 1.0f, &dockspace_id, nullptr);
ImGuiID dock_id_down = ImGui::DockBuilderSplitNode(dock_id_left, ImGuiDir_Down, 0.5f, nullptr, &dock_id_left);
ImGuiDockNode* node = ImGui::DockBuilderGetNode(dockspace_id);
node->LocalFlags |= ImGuiDockNodeFlags_NoCloseButton;
ImGui::DockBuilderDockWindow("Scene", dockspace_id);
ImGui::DockBuilderDockWindow("Object explorer", dock_id_left);
// Properties
node = ImGui::DockBuilderGetNode(dock_id_down);
node->LocalFlags |= ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoTabBar;
ImGui::DockBuilderDockWindow("Properties", dock_id_down);
//ImGui::DockBuilderDockWindow("Scene_", dock_id_down);
ImGui::DockBuilderFinish(dockspace_id);
}
ImGui::End();
}
ImGuiViewport* viewport2 = ImGui::GetMainViewport();
ImGuiWindowFlags window_flags2 = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;
float height = ImGui::GetFrameHeight();
if (ImGui::BeginViewportSideBar("##SecondaryMenuBar", viewport2, ImGuiDir_Up, height, window_flags2)) {
if (ImGui::BeginMenuBar()) {
ImGui::Text("menu bar");
ImGui::EndMenuBar();
}
ImGui::End();
}
if (ImGui::BeginViewportSideBar("#MainStatusBar", viewport2, ImGuiDir_Down, height, window_flags2)) {
if (ImGui::BeginMenuBar()) {
ImGui::Text("status bar");
ImGui::EndMenuBar();
}
ImGui::End();
}
}
};

78
source/creator/visual.hpp Normal file
View File

@ -0,0 +1,78 @@
#pragma once
#include <hpr/gpu.hpp>
#include "shaders.hpp"
using namespace hpr;
class Visual
{
protected:
gpu::Window* p_window;
gpu::ShaderProgram* p_shaderProgram;
gpu::ColorBuffer p_colorBuffer;
gpu::DepthBuffer p_depthBuffer;
public:
Visual() :
p_window {new gpu::Window{50, 50, 1000, 800, "Hyporo", gpu::Window::Windowed, nullptr, nullptr}},
p_shaderProgram {new gpu::ShaderProgram},
p_colorBuffer {},
p_depthBuffer {}
{
gpu::Shader vertexShader {gpu::Shader::Type::Vertex, vertexSource};
vertexShader.create();
gpu::Shader fragmentShader {gpu::Shader::Type::Fragment, fragmentSource};
fragmentShader.create();
p_shaderProgram->create();
p_shaderProgram->attach(vertexShader);
p_shaderProgram->attach(fragmentShader);
p_shaderProgram->link();
vertexShader.destroy();
fragmentShader.destroy();
p_window->framebufferResizeCallback([](gpu::Window* w, int width, int height){
w->size(width, height);
});
}
~Visual()
{
p_shaderProgram->destroy();
delete p_shaderProgram;
p_window->destroy();
delete p_window;
}
gpu::Window* window()
{
return p_window;
}
gpu::ShaderProgram* shaderProgram()
{
return p_shaderProgram;
}
gpu::ColorBuffer& colorBuffer()
{
return p_colorBuffer;
}
gpu::DepthBuffer& depthBuffer()
{
return p_depthBuffer;
}
void render()
{
p_window->swapBuffers();
p_window->pollEvents();
}
};

View File

@ -1,22 +1,39 @@
# Modules
add_subdirectory(core)
# Modules and dependencies
if (HPR_WITH_CONTAINERS)
add_subdirectory(containers)
add_subdirectory(math)
add_subdirectory(io)
add_subdirectory(mesh)
add_subdirectory(geometry)
endif()
if(WITH_CSG)
include(${CMAKE_SOURCE_DIR}/cmake/external/occt.cmake)
if (HPR_WITH_MATH)
add_subdirectory(math)
endif()
if (HPR_WITH_IO)
add_subdirectory(io)
endif()
if (HPR_WITH_MESH)
add_subdirectory(mesh)
endif()
if (HPR_WITH_GEOMETRY)
add_subdirectory(geometry)
endif()
if(HPR_WITH_CSG)
include(${HPR_EXTERNAL_PATH}/occt.cmake)
add_subdirectory(csg)
endif()
if(WITH_GPU)
include(${CMAKE_SOURCE_DIR}/cmake/external/glad.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/external/stb.cmake)
if(HPR_WITH_GPU)
include(${HPR_EXTERNAL_PATH}/glad.cmake)
include(${HPR_EXTERNAL_PATH}/glfw.cmake)
include(${HPR_EXTERNAL_PATH}/stb.cmake)
add_subdirectory(gpu)
endif()
if(WITH_WINDOW_SYSTEM)
include(${CMAKE_SOURCE_DIR}/cmake/external/glfw.cmake)
add_subdirectory(window_system)
if(HPR_WITH_PARALLEL)
include(${HPR_EXTERNAL_PATH}/onetbb.cmake)
add_subdirectory(parallel)
endif()

View File

@ -1,3 +1,3 @@
#pragma once
#include "containers/array.hpp"
#include <hpr/containers/array.hpp>

View File

@ -1,62 +1,21 @@
cmake_minimum_required(VERSION 3.16)
project(containers
VERSION "${HPR_PROJECT_VERSION}"
VERSION "${HPR_VERSION}"
LANGUAGES CXX
)
add_library(${PROJECT_NAME} INTERFACE)
add_library(${CMAKE_PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
add_module(${PROJECT_NAME})
hpr_add_library(${PROJECT_NAME} INTERFACE)
file(GLOB ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS
"../containers.hpp" "*.hpp" "array/*.hpp"
hpr_collect_interface(${PROJECT_NAME}
"../containers.hpp"
"*.hpp"
"array/*.hpp"
)
foreach(_header_path ${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS})
list(APPEND ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE "$<BUILD_INTERFACE:${_header_path}>")
endforeach()
target_sources(${PROJECT_NAME}
INTERFACE
${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE}
$<INSTALL_INTERFACE:include/${CMAKE_PROJECT_NAME}/${PROJECT_NAME}>
INTERFACE ${${PROJECT_NAME}_HEADERS_INTERFACE} ${HPR_INSTALL_INTERFACE}/${PROJECT_NAME}>
)
install(
TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_SKIP
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
EXPORT ${PROJECT_NAME}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CMAKE_PROJECT_NAME}-${HPR_PROJECT_VERSION}
NAMESPACE ${CMAKE_PROJECT_NAME}::
)
install(
TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_ONLY
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
DIRECTORY ${PROJECT_SOURCE_DIR}
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
FILES_MATCHING
PATTERN "*.h"
PATTERN "*.hpp"
PATTERN "tests" EXCLUDE
)
install(
FILES ../${PROJECT_NAME}.hpp
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
)
if(HPR_TEST)
add_subdirectory(tests)
endif()
hpr_tests(${PROJECT_NAME} tests)
hpr_install(${PROJECT_NAME} ${PROJECT_SOURCE_DIR})

View File

@ -1,4 +1,5 @@
#pragma once
#include "array/dynamic_array.hpp"
#include "array/static_array.hpp"
#include <hpr/containers/array/iterator.hpp>
#include <hpr/containers/array/dynamic_array.hpp>
#include <hpr/containers/array/static_array.hpp>

View File

@ -1,127 +1,124 @@
#pragma once
#include "iterator.hpp"
#include <limits>
#include <memory>
#include <hpr/containers/array/sequence.hpp>
#include <functional>
#include <limits>
namespace hpr
{
template <typename Type>
class DynamicArray
// forward declaration
template <typename T>
class DynamicArray;
// type traits
template <typename T>
struct is_sequence<DynamicArray<T>> : public std::true_type
{};
// aliases
template <typename T>
using darray = DynamicArray<T>;
// class definition
template <typename T>
class DynamicArray : public Sequence<T>
{
using base = Sequence<T>;
public:
using difference_type = std::ptrdiff_t;
using value_type = Type;
using size_type = size_t;
using pointer = Type*;
using reference = Type&;
using iterator = Iterator<Type>;
using const_pointer = Type const*;
using const_reference = Type const&;
using const_iterator = Iterator<const Type>;
protected:
size_type p_size;
size_type p_capacity;
pointer p_start;
pointer p_end;
pointer p_storage_end;
using value_type = T;
using size_type = Size;
using pointer = T*;
using reference = T&;
using iterator = Iterator<T>;
using const_pointer = T const*;
using const_reference = T const&;
using const_iterator = Iterator<const T>;
public:
inline
DynamicArray() :
p_size {0},
p_capacity {1},
p_start {new value_type[p_capacity]},
p_end {p_start},
p_storage_end {p_end + p_capacity}
friend constexpr
void swap(DynamicArray& main, DynamicArray& other) noexcept
{
using std::swap;
swap(static_cast<base&>(main), static_cast<base&>(other));
}
constexpr
DynamicArray() noexcept :
base {}
{}
inline
DynamicArray(const DynamicArray& arr) :
p_size {arr.p_size},
p_capacity {arr.p_capacity},
p_start {new value_type[arr.p_size]},
p_end {p_start + p_size},
p_storage_end {p_start + p_capacity}
{
std::copy(arr.p_start, arr.p_end, p_start);
}
constexpr explicit
DynamicArray(const base& b) noexcept :
base {b}
{}
constexpr
DynamicArray(const DynamicArray& arr) noexcept :
base {static_cast<base>(arr)}
{}
//! Move constructor
inline
constexpr
DynamicArray(DynamicArray&& arr) noexcept :
DynamicArray {}
{
swap(*this, arr);
}
base {std::forward<base>(static_cast<base>(arr))}
{}
inline
DynamicArray(const_iterator start, const_iterator end) :
p_size {size_type(end.operator->() - start.operator->())},
p_capacity {p_size},
p_start {new value_type[p_size]},
p_end {p_start + p_size},
p_storage_end {p_start + p_capacity}
{
std::copy(start, end, p_start);
}
template <typename Iter>
constexpr
DynamicArray(Iter start, Iter end) :
base {start, end}
{}
inline
DynamicArray(iterator start, iterator end) :
p_size {size_type(end.operator->() - start.operator->())},
p_capacity {p_size},
p_start {new value_type[p_size]},
p_end {p_start + p_size},
p_storage_end {p_start + p_capacity}
{
std::copy(start, end, p_start);
}
constexpr
DynamicArray(typename base::iterator start, typename base::iterator end) :
base {start, end}
{}
inline
constexpr
DynamicArray(typename base::const_iterator start, typename base::const_iterator end) :
base {start, end}
{}
constexpr
DynamicArray(typename base::iterator start, typename base::iterator end, size_type capacity) :
base {start, end, capacity}
{}
constexpr
DynamicArray(typename base::const_iterator start, typename base::const_iterator end, size_type capacity) :
base {start, end, capacity}
{}
constexpr
DynamicArray(std::initializer_list<value_type> list) :
p_size {list.size()},
p_capacity {list.size()},
p_start {new value_type[p_capacity]},
p_end {p_start + p_size},
p_storage_end {p_start + p_capacity}
{
std::copy(list.begin(), list.end(), p_start);
}
base {list.begin(), list.end()}
{}
inline
DynamicArray(size_type size, value_type value) :
p_size {0},
p_capacity {size},
p_start {new value_type[p_capacity]},
p_end {p_start + p_size},
p_storage_end {p_start + p_capacity}
{
for (auto n = 0; n < size; ++n)
push(value);
}
constexpr
DynamicArray(size_type size, value_type value) noexcept :
base {size, value}
{}
inline
DynamicArray& operator=(const DynamicArray& vs) noexcept
constexpr
DynamicArray& operator=(DynamicArray other) noexcept
{
delete[] p_start;
p_size = vs.p_size;
p_capacity = vs.p_size;
p_start = new value_type[p_capacity];
p_end = p_start + p_size;
p_storage_end = p_start + p_capacity;
std::copy(vs.begin(), vs.end(), begin());
swap(*this, other);
return *this;
}
inline
constexpr
DynamicArray& operator=(DynamicArray&& arr) noexcept
{
swap(*this, arr);
@ -129,255 +126,164 @@ public:
}
virtual
~DynamicArray()
{
//std::destroy(p_start, p_end);
delete[] p_start;
}
~DynamicArray() = default;
// Member functions
virtual
iterator begin()
[[nodiscard]] virtual constexpr
size_type capacity() const noexcept
{
return iterator(p_start);
return base::p_capacity;
}
[[nodiscard]] virtual
const_iterator begin() const
{
return const_iterator(p_start);
}
virtual
iterator end()
{
return iterator(p_end);
}
virtual
const_iterator end() const
{
return const_iterator(p_end);
}
[[nodiscard]] virtual
size_type size() const
{
return size_type(p_end - p_start);
}
[[nodiscard]] virtual
size_type capacity() const
{
return size_type(p_storage_end - p_start);
}
[[nodiscard]] virtual
[[nodiscard]] virtual constexpr
bool is_empty() const
{
return begin() == end();
return base::begin() == base::end();
}
virtual
reference operator[](size_type n)
virtual constexpr
iterator storage_end()
{
if (n >= size())
throw std::out_of_range("Index out of bounds");
return *(p_start + n);
return iterator(base::p_start + base::p_capacity);
}
virtual
const_reference operator[](size_type n) const
virtual constexpr
const_iterator storage_end() const
{
if (n >= size())
throw std::out_of_range("Index out of bounds");
return *(p_start + n);
return const_iterator(base::p_start + base::p_capacity);
}
virtual
reference front()
{
return *p_start;
}
virtual
reference back()
{
return *(p_end - 1);
}
virtual
pointer data()
{
return p_start;
}
[[nodiscard]] virtual
const_pointer data() const
{
return p_start;
}
virtual
virtual constexpr
void resize(size_type newCapacity)
{
if (newCapacity == p_capacity)
if (newCapacity == base::p_capacity)
return;
if (std::numeric_limits<size_type>::max() - size() < newCapacity)
throw std::length_error("Wrong capacity value passed (possibly negative)");
pointer newStart = new value_type[newCapacity];
if (std::numeric_limits<size_type>::max() - base::size() < newCapacity)
throw hpr::LengthError("Invalid capacity value passed");
if (newCapacity > p_capacity)
if (newCapacity > base::p_capacity)
{
std::move(p_start, p_end, newStart);
}
else if (newCapacity < p_capacity)
{
if (newCapacity < p_size) {
std::move(p_start, p_start + newCapacity, newStart);
p_size = newCapacity;
DynamicArray tmp {base::begin(), base::end(), newCapacity};
swap(*this, tmp);
}
else
{
std::move(p_start, p_end, newStart);
if (newCapacity >= base::p_size)
{
DynamicArray tmp {base::begin(), base::end()};
swap(*this, tmp);
}
else
{
DynamicArray tmp {base::begin(), base::begin() + newCapacity};
swap(*this, tmp);
}
}
}
delete[] p_start;
std::swap(p_start, newStart);
p_capacity = newCapacity;
p_end = p_start + p_size;
p_storage_end = p_start + p_capacity;
}
virtual
virtual constexpr
void push(const value_type& val)
{
if (p_end == p_storage_end)
resize(p_capacity * 2);
*p_end = val;
++p_end;
++p_size;
if (base::end() == storage_end())
resize(base::p_capacity * 2);
*base::end() = val;
++base::p_size;
}
virtual
virtual constexpr
void push(value_type&& val)
{
if (p_end == p_storage_end)
resize(p_capacity * 2);
*p_end = std::move(val);
++p_end;
++p_size;
if (base::end() == storage_end())
resize(base::p_capacity * 2);
*base::end() = std::move(val);
++base::p_size;
}
virtual
virtual constexpr
void push(const DynamicArray<T>& arr)
{
for (const value_type& el : arr)
push(el);
}
virtual constexpr
value_type pop()
{
if (is_empty())
throw std::length_error("Cannot pop element from empty array");
value_type val = back();
std::destroy_at(p_end);
--p_end;
--p_size;
throw hpr::LengthError("Cannot pop element from empty array");
value_type val = base::back();
std::destroy_at(base::p_start + base::p_size);
--base::p_size;
return val;
}
virtual
virtual constexpr
void insert(size_type position, const value_type& val)
{
if (p_end == p_storage_end)
resize(p_capacity * 2);
for (size_type n = p_size; n > position; --n)
*(p_start + n) = std::move(*(p_start + n - 1));
*(p_start + position) = val;
++p_size;
++p_end;
if (base::end() == storage_end())
resize(base::p_capacity * 2);
for (size_type n = base::p_size; n > position; --n)
*(base::p_start + n) = std::move(*(base::p_start + n - 1));
*(base::p_start + position) = val;
++base::p_size;
}
virtual
virtual constexpr
void insert(size_type position, value_type&& val)
{
if (p_end == p_storage_end)
resize(p_capacity * 2);
for (size_type n = p_size; n > position; --n)
*(p_start + n) = std::move(*(p_start + n - 1));
*(p_start + position) = std::move(val);
++p_size;
++p_end;
if (base::end() == storage_end())
resize(base::p_capacity * 2);
for (size_type n = base::p_size; n > position; --n)
*(base::p_start + n) = std::move(*(base::p_start + n - 1));
*(base::p_start + position) = std::move(val);
++base::p_size;
}
/*virtual
int findByAddress(const value_type& value)
{
// TODO: make better approach
for (int n = 0; n < p_size; ++n) {
std::equal_to
pointer lhs = (p_start + n); //*std::addressof(*(p_start + n));
pointer rhs = *value; //*std::addressof(value);
if (lhs == rhs)
return n;
}
return -1;
}*/
virtual
virtual constexpr
void remove(size_type position)
{
for (size_type n = position; n < p_size - 1; ++n)
*(p_start + n) = std::move(*(p_start + n + 1));
std::destroy_at(p_end);
--p_end;
--p_size;
for (size_type n = position; n < base::p_size - 1; ++n)
*(base::p_start + n) = std::move(*(base::p_start + n + 1));
std::destroy_at(base::p_start + base::p_size);
--base::p_size;
}
virtual
virtual constexpr
void remove(iterator position)
{
if (position + 1 != end())
std::copy(position + 1, end(), position);
std::destroy_at(p_end);
--p_end;
--p_size;
if (position + 1 != base::end())
std::copy(position + 1, base::end(), position);
std::destroy_at(base::p_start + base::p_size);
--base::p_size;
}
virtual
virtual constexpr
void remove(const std::function<bool(value_type)>& condition)
{
size_type newSize = p_size;
size_type newSize = base::p_size;
for (size_type offset = 0; offset < newSize; ++offset)
if (condition(*(p_start + offset))) {
for (size_type n = offset; n < newSize; ++n) {
*(p_start + n) = std::move(*(p_start + n + 1));
}
{
if (condition(*(base::p_start + offset)))
{
for (size_type n = offset; n < newSize; ++n)
*(base::p_start + n) = std::move(*(base::p_start + n + 1));
--newSize;
--offset;
}
p_size = newSize;
p_end = p_start + p_size;
}
base::p_size = newSize;
}
/*virtual
void remove(const value_type& value)
{
int index = findByAddress(value);
if (index != -1)
remove(index);
else
throw std::runtime_error("Value is not found to remove it");
}*/
virtual
virtual constexpr
void clear()
{
delete[] p_start;
p_size = 0;
p_capacity = 1;
p_start = new value_type[p_capacity];
p_end = p_start;
p_storage_end = p_end + p_capacity;
delete[] base::p_start;
base::p_size = 0;
base::p_capacity = 1;
base::p_start = new value_type[base::p_capacity];
}
DynamicArray slice(iterator start, iterator end)
@ -385,43 +291,7 @@ public:
return DynamicArray {start, end};
}
// Friend functions
friend
void swap(DynamicArray& lhs, DynamicArray& rhs)
{
std::swap(lhs.p_size, rhs.p_size);
std::swap(lhs.p_capacity, rhs.p_capacity);
std::swap(lhs.p_start, rhs.p_start);
std::swap(lhs.p_end, rhs.p_end);
std::swap(lhs.p_storage_end, rhs.p_storage_end);
}
friend
bool operator==(const DynamicArray& lhs, const DynamicArray& rhs)
{
for (auto n = 0; n < lhs.size(); ++n)
if (lhs[n] != rhs[n])
return false;
return true;
}
friend
DynamicArray operator+(const DynamicArray& lhs, const DynamicArray& rhs)
{
DynamicArray arr {rhs.size() + lhs.size(), {}};
for (auto n = 0; n < rhs.size(); ++n)
{
arr[n] = rhs[n];
arr[n + rhs.size()] = lhs[n];
}
return arr;
}
};
// Aliases
template <typename Type>
using darray = DynamicArray<Type>;
}

View File

@ -9,7 +9,9 @@ namespace hpr
template <typename Type, typename Category = std::forward_iterator_tag>
class Iterator
{
public:
using iterator_category = Category;
using difference_type = std::ptrdiff_t;
using value_type = Type;
@ -21,6 +23,7 @@ public:
using const_iterator = Iterator const;
protected:
pointer p_ptr;
public:

View File

@ -0,0 +1,314 @@
#pragma once
#include <hpr/containers/array/iterator.hpp>
#include <hpr/exception.hpp>
#include <hpr/math/integer.hpp>
namespace hpr
{
// forward declaration
template <typename T>
class Sequence;
// type traits
template <typename T>
struct is_sequence : public std::false_type
{};
template <typename T>
struct is_sequence<Sequence<T>> : public std::true_type
{};
// class definition
template <typename T>
class Sequence
{
public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using size_type = Size;
using pointer = T*;
using reference = T&;
using iterator = Iterator<T>;
using const_pointer = T const*;
using const_reference = T const&;
using const_iterator = Iterator<const T>;
protected:
size_type p_size;
size_type p_capacity;
pointer p_start;
protected:
constexpr
Sequence(size_type size, size_type capacity, pointer start) :
p_size {size},
p_capacity {capacity},
p_start {start}
{}
constexpr explicit
Sequence(size_type size, size_type capacity) :
p_size {size},
p_capacity {capacity},
p_start {p_capacity ? new value_type[p_capacity] : nullptr}
{}
public:
friend constexpr
void swap(Sequence& main, Sequence& other) noexcept
{
using std::swap;
swap(main.p_size, other.p_size);
swap(main.p_capacity, other.p_capacity);
swap(main.p_start, other.p_start);
}
constexpr
Sequence() noexcept :
p_size {0},
p_capacity {1},
p_start {new value_type[p_capacity]}
{}
constexpr
Sequence(const Sequence& seq) noexcept :
p_size {seq.p_size},
p_capacity {seq.p_capacity},
p_start {p_capacity ? new value_type[seq.p_capacity] : nullptr}
{
std::copy(seq.p_start, seq.p_start + seq.p_size, p_start);
}
//! Move constructor
constexpr
Sequence(Sequence&& seq) noexcept :
Sequence {}
{
swap(*this, seq);
}
template <typename Iter>
constexpr
Sequence(Iter start, Iter end) :
p_size {static_cast<size_type>(std::distance(start, end))},//size_type(end.operator->() - start.operator->())},
p_capacity {p_size},
p_start {p_capacity ? new value_type[p_capacity] : nullptr}
{
std::copy(start, end, p_start);
}
constexpr
Sequence(iterator start, iterator end) :
p_size {static_cast<size_type>(std::distance(start, end))},//size_type(end.operator->() - start.operator->())},
p_capacity {p_size},
p_start {p_capacity ? new value_type[p_capacity] : nullptr}
{
std::copy(start, end, p_start);
}
constexpr
Sequence(const_iterator start, const_iterator end) :
p_size {std::distance(start, end)},//{size_type(end.operator->() - start.operator->())},
p_capacity {p_size},
p_start {p_capacity ? new value_type[p_capacity] : nullptr}
{
std::copy(start, end, p_start);
}
constexpr
Sequence(iterator start, iterator end, size_type capacity) :
p_size {static_cast<size_type>(std::distance(start, end))},//size_type(end.operator->() - start.operator->())},
p_capacity {capacity},
p_start {p_capacity ? new value_type[p_capacity] : nullptr}
{
std::copy(start, end, p_start);
}
constexpr
Sequence(const_iterator start, const_iterator end, size_type capacity) :
p_size {std::distance(start, end)},//{size_type(end.operator->() - start.operator->())},
p_capacity {capacity},
p_start {p_capacity ? new value_type[p_capacity] : nullptr}
{
std::copy(start, end, p_start);
}
/*constexpr
Sequence(std::initializer_list<value_type> list) :
Sequence {list.begin(), list.end()}
{}*/
constexpr
Sequence(size_type size, value_type value) noexcept:
p_size {size},
p_capacity {size},
p_start {p_capacity ? new value_type[p_capacity] : nullptr}
{
for (auto n = 0; n < size; ++n)
*(p_start + n) = value;
}
constexpr
Sequence& operator=(Sequence other) noexcept
{
swap(*this, other);
return *this;
}
constexpr
Sequence& operator=(Sequence&& seq) noexcept
{
swap(*this, seq);
return *this;
}
virtual
~Sequence()
{
delete[] p_start;
}
// Member functions
virtual constexpr
iterator begin()
{
return iterator(p_start);
}
[[nodiscard]] virtual constexpr
const_iterator begin() const
{
return const_iterator(p_start);
}
virtual constexpr
iterator end()
{
return iterator(p_start + p_size);
}
virtual constexpr
const_iterator end() const
{
return const_iterator(p_start + p_size);
}
virtual constexpr
iterator storage_end()
{
return iterator(p_start + p_capacity);
}
virtual constexpr
const_iterator storage_end() const
{
return const_iterator(p_start + p_capacity);
}
[[nodiscard]] virtual constexpr
size_type size() const noexcept
{
return p_size;
}
virtual constexpr
reference operator[](size_type n)
{
if (n >= size())
throw hpr::OutOfRange();
return *(p_start + n);
}
virtual constexpr
const_reference operator[](size_type n) const
{
if (n >= size())
throw hpr::OutOfRange();
return *(p_start + n);
}
virtual constexpr
reference at(size_type n)
{
return operator[](n);
}
virtual constexpr
const_reference at(size_type n) const
{
return operator[](n);
}
virtual constexpr
reference front()
{
return *begin();
}
virtual constexpr
const_reference front() const
{
return *begin();
}
virtual constexpr
reference back()
{
return *(p_start + p_size - 1);
}
virtual constexpr
const_reference back() const
{
return *(p_start + p_size - 1);
}
virtual constexpr
pointer data()
{
return p_start;
}
[[nodiscard]] virtual constexpr
const_pointer data() const
{
return p_start;
}
// Friend functions
friend
bool operator==(const Sequence& lhs, const Sequence& rhs)
{
for (auto n = 0; n < lhs.size(); ++n)
if (lhs[n] != rhs[n])
return false;
return true;
}
friend
Sequence operator+(const Sequence& lhs, const Sequence& rhs)
{
Sequence seq {rhs.size() + lhs.size(), {}};
for (auto n = 0; n < rhs.size(); ++n)
{
seq[n] = rhs[n];
seq[n + rhs.size()] = lhs[n];
}
return seq;
}
};
}

View File

@ -1,257 +1,150 @@
#pragma once
#include "iterator.hpp"
#include <limits>
#include <functional>
#include <concepts>
#include <hpr/containers/array/sequence.hpp>
namespace hpr
{
template <typename Type, size_t Size>
class StaticArray
// forward declaration
template <typename T, Size S>
requires (S > 0)
class StaticArray;
// type traits
template <typename T, Size S>
struct is_sequence<StaticArray<T, S>> : public std::true_type
{};
// aliases
template <typename T, Size S>
using sarray = StaticArray<T, S>;
// class definition
template <typename T, Size S>
requires (S > 0)
class StaticArray : public Sequence<T>
{
using base = Sequence<T>;
public:
using difference_type = std::ptrdiff_t;
using value_type = Type;
using size_type = size_t;
using pointer = Type*;
using reference = Type&;
using iterator = Iterator<Type>;
using const_pointer = Type const*;
using const_reference = Type const&;
using const_iterator = Iterator<const Type>;
protected:
const size_type p_size;
pointer p_start;
pointer p_end;
protected:
inline
StaticArray(size_type size, pointer start, pointer end) :
p_size {size},
p_start {start},
p_end {end}
{}
using value_type = T;
using size_type = Size;
using pointer = T*;
using reference = T&;
using iterator = Iterator<T>;
using const_pointer = T const*;
using const_reference = T const&;
using const_iterator = Iterator<const T>;
public:
inline
StaticArray() :
p_size {Size},
p_start {new value_type[p_size] {}},
p_end {p_start + p_size}
friend constexpr
void swap(StaticArray& main, StaticArray& other) noexcept
{
using std::swap;
swap(static_cast<base&>(main), static_cast<base&>(other));
}
//! Default constructor
constexpr
StaticArray() noexcept :
base {S, S, new value_type[S] {}}
{}
inline
StaticArray(const StaticArray& arr) :
p_size {arr.p_size},
p_start {new value_type[arr.p_size]},
p_end {p_start + p_size}
{
std::copy(arr.p_start, arr.p_end, p_start);
}
constexpr explicit
StaticArray(const base& b) noexcept :
base {b}
{}
//! Copy constructor
constexpr
StaticArray(const StaticArray& arr) noexcept :
base {static_cast<base>(arr)}
{}
//! Move constructor
inline
constexpr
StaticArray(StaticArray&& arr) noexcept :
StaticArray {}
{
swap(*this, arr);
}
base {std::forward<base>(static_cast<base>(arr))}
{}
inline
StaticArray(const_iterator start, const_iterator end) :
p_size {Size},
p_start {new value_type[p_size]},
p_end {p_start + p_size}
{
std::copy(start, end, p_start);
}
constexpr
StaticArray(typename base::iterator start, typename base::iterator end) :
base {start, end}
{}
inline
StaticArray(iterator start, iterator end) :
p_size {Size},
p_start {new value_type[p_size]},
p_end {p_start + p_size}
{
std::copy(start, end, p_start);
}
constexpr
StaticArray(typename base::const_iterator start, typename base::const_iterator end) :
base {start, end}
{}
inline
constexpr
StaticArray(typename base::iterator start, typename base::iterator end, size_type capacity) :
base {start, end, capacity}
{}
constexpr
StaticArray(typename base::const_iterator start, typename base::const_iterator end, size_type capacity) :
base {start, end, capacity}
{}
constexpr
StaticArray(std::initializer_list<value_type> list) :
StaticArray {list.begin(), list.end()}
base {list.begin(), list.end()}
{}
template <std::convertible_to<value_type>... Args>
inline
StaticArray(const value_type& v, const Args& ...args) :
StaticArray {std::initializer_list<value_type>({std::forward<value_type>(v),
std::forward<value_type>(static_cast<value_type>(args))...})}
{
static_assert(1 + sizeof...(args) == Size, "Number of arguments must be equal to size of array");
}
constexpr explicit
StaticArray(const value_type& v, const Args& ...args)
requires (1 + sizeof...(args) == S) :
StaticArray {std::initializer_list<value_type>({v, static_cast<value_type>(args)...})}
{}
template <std::convertible_to<value_type>... Args>
inline
StaticArray(value_type&& v, Args&& ...args) :
StaticArray {std::initializer_list<value_type>({std::forward<value_type>(v),
std::forward<value_type>(static_cast<value_type>(args))...})}
{
static_assert(1 + sizeof...(args) == Size, "Number of arguments must be equal to size of array");
}
constexpr explicit
StaticArray(value_type&& v, Args&& ...args)
requires (1 + sizeof...(args) == S) :
StaticArray {std::initializer_list<value_type>({std::forward<value_type>(v), std::forward<value_type>(static_cast<value_type>(args))...})}
{}
template <size_type SubSize, std::convertible_to<value_type>... Args>
inline
StaticArray(const StaticArray<value_type, SubSize>& subarr, const value_type& v, const Args& ...args) :
p_size {Size},
p_start {new value_type[p_size]},
p_end {p_start + p_size}
template <size_type SS, std::convertible_to<value_type>... Args>
constexpr
StaticArray(const StaticArray<value_type, SS>& subArr, const value_type& v, const Args& ...args) noexcept
requires (SS + 1 + sizeof...(args) == S) :
base {S, S, new value_type[S] {}}
{
static_assert(SubSize + 1 + sizeof...(args) == Size,
"Number of arguments and sub-array elements must be equal to size of main array");
std::copy(subArr.begin(), subArr.end(), base::begin());
std::initializer_list<value_type> list {v, static_cast<value_type>(args)...};
std::copy(subarr.begin(), subarr.end(), begin());
size_type pos {subarr.size()};
for (auto& val : list)
(*this)[pos++] = val;
std::copy(list.begin(), list.end(), base::begin() + subArr.size());
}
inline
StaticArray& operator=(const StaticArray& vs)
constexpr
StaticArray& operator=(StaticArray other)
{
std::copy(vs.begin(), vs.end(), begin());
swap(*this, other);
return *this;
}
inline
StaticArray& operator=(StaticArray&& arr) noexcept
constexpr
StaticArray& operator=(StaticArray&& other) noexcept
{
swap(*this, arr);
swap(*this, other);
return *this;
}
virtual
~StaticArray()
{
//std::destroy(p_start, p_end);
delete[] p_start;
}
~StaticArray() = default;
// Member functions
virtual
iterator begin()
{
return iterator(p_start);
}
[[nodiscard]] virtual
const_iterator begin() const
{
return const_iterator(p_start);
}
virtual
iterator end()
{
return iterator(p_end);
}
virtual
const_iterator end() const
{
return const_iterator(p_end);
}
[[nodiscard]] virtual constexpr
size_type size() const
{
return size_type(p_end - p_start);
}
[[nodiscard]] virtual
bool is_empty() const
{
return begin() == end();
}
virtual
reference operator[](size_type n)
{
if (n >= size())
throw std::out_of_range("Index out of bounds");
return *(p_start + n);
}
virtual
const_reference operator[](size_type n) const
{
if (n >= size())
throw std::out_of_range("Index out of bounds");
return *(p_start + n);
}
virtual
reference front()
{
return *p_start;
}
virtual
reference back()
{
return *(p_end - 1);
}
virtual
pointer data()
{
return p_start;
}
[[nodiscard]] virtual
const_pointer data() const
{
return p_start;
}
// Friend functions
friend
void swap(StaticArray& lhs, StaticArray& rhs)
{
std::swap(lhs.p_start, rhs.p_start);
std::swap(lhs.p_end, rhs.p_end);
}
friend
void swap(StaticArray&& lhs, StaticArray&& rhs)
{
std::swap(lhs.p_start, rhs.p_start);
std::swap(lhs.p_end, rhs.p_end);
}
friend
bool operator==(const StaticArray& lhs, const StaticArray& rhs)
{
for (auto n = 0; n < Size; ++n)
if (lhs[n] != rhs[n])
return false;
return true;
}
};
// Aliases
template <typename Type, size_t Size>
using sarray = StaticArray<Type, Size>;
}

View File

@ -0,0 +1,3 @@
#pragma once
#include <hpr/containers/graph/tree_node.hpp>

View File

@ -0,0 +1,180 @@
#pragma once
#include <hpr/containers/array/dynamic_array.hpp>
#include <memory>
namespace hpr
{
template <typename Type>
class TreeNode
{
public:
using value_type = Type;
using pointer = Type*;
using reference = Type&;
using const_pointer = Type const*;
using const_reference = Type const&;
protected:
pointer p_data;
darray<TreeNode*> p_descendants;
TreeNode* p_ancestor;
public:
friend constexpr
void swap(TreeNode& main, TreeNode& other) noexcept
{
using std::swap;
swap(main.p_data, other.p_data);
swap(main.p_descendants, other.p_descendants);
swap(main.p_ancestor, other.p_ancestor);
}
inline
TreeNode() :
p_data {new value_type {}},
p_descendants {},
p_ancestor {}
{}
inline
TreeNode(const TreeNode& node) :
p_data {new value_type {*node.p_data}},
p_descendants {},
p_ancestor {}
{}
inline
TreeNode(TreeNode&& node) noexcept :
p_data {},
p_descendants {},
p_ancestor {}
{
swap(*this, node);
/*std::swap(p_data, node.p_data);
std::swap(p_descendants, node.p_descendants);
std::swap(p_ancestor, node.p_ancestor);*/
}
inline
TreeNode& operator=(TreeNode other)
{
swap(*this, other);
return *this;
}
inline explicit
TreeNode(const value_type& data) :
p_data {new value_type {data}},
p_descendants {},
p_ancestor {}
{}
inline
TreeNode(const value_type& data, const darray<TreeNode*>& descendants, TreeNode* ancestor) :
p_data {new value_type {data}},
p_descendants {descendants},
p_ancestor {ancestor}
{
for (auto descendant : p_descendants)
descendant->ancestor(this);
}
inline
TreeNode(const value_type& data, const darray<TreeNode*>& descendants) :
p_data {new value_type {data}},
p_descendants {descendants},
p_ancestor {}
{
for (auto descendant : p_descendants)
descendant->ancestor(this);
}
virtual
~TreeNode()
{
delete p_data;
//delete p_ancestor;
}
// Member functions
inline
pointer data()
{
return p_data;
}
inline
void ancestor(TreeNode* node)
{
p_ancestor = node;
}
inline
TreeNode* ancestor()
{
return p_ancestor;
}
inline
void descendants(const darray<TreeNode*>& descendants)
{
p_descendants = descendants;
}
inline
darray<TreeNode*>& descendants()
{
return p_descendants;
}
darray<TreeNode*> traverse_descendants()
{
std::function<darray<TreeNode*>(TreeNode*)> collect = [&](TreeNode* node)
{
darray<TreeNode*> ds;
if (!node->descendants().is_empty())
{
for (TreeNode* dnode: node->descendants())
{
ds.push(dnode);
if (!dnode->descendants().is_empty())
ds.push(collect(dnode));
}
}
return ds;
};
return collect(this);
}
darray<TreeNode*> traverse_ancestors()
{
std::function<darray<TreeNode*>(TreeNode*)> collect = [&](TreeNode* node)
{
darray<TreeNode*> ds;
if (node->p_ancestor)
{
ds.push(node);
ds.push(collect(node->p_ancestor));
}
return ds;
};
return collect(this);
}
};
}

View File

@ -1,15 +0,0 @@
file(GLOB tests_cpp "*.cpp")
add_executable(${PROJECT_NAME}-tests
${tests_cpp}
)
target_link_libraries(${PROJECT_NAME}-tests
PUBLIC
hpr::containers
PRIVATE
GTest::gtest_main
)
gtest_add_tests(TARGET ${PROJECT_NAME}-tests)

View File

@ -1,14 +1,25 @@
#include <gtest/gtest.h>
#include "../array.hpp"
#include <hpr/containers/array.hpp>
#include <hpr/containers/graph.hpp>
TEST(containers, StaticArray)
{
hpr::StaticArray<float, 3> arr {1, 3, 2};
hpr::StaticArray<float, 3> arr {7, 3, 2};
hpr::StaticArray<float, 4> sarr {arr, 5};
hpr::StaticArray<float, 4> sarr2 {1, 3, 2, 5};
hpr::StaticArray<float, 4> sarr2 {7, 3, 2, 5};
//hpr::StaticArray<float, 0> sarr4;
EXPECT_EQ(sarr, sarr2);
//EXPECT_EQ(sarr4.data(), nullptr);
//EXPECT_EQ(sarr4.is_empty(), true);
EXPECT_EQ(sarr.size(), 4);
EXPECT_EQ(sarr2.size(), 4);
EXPECT_EQ(sarr[0], 7);
EXPECT_EQ(sarr[1], 3);
EXPECT_EQ(sarr[2], 2);
EXPECT_EQ(sarr[3], 5);
}
TEST(containers, DynamicArray)
@ -16,6 +27,7 @@ TEST(containers, DynamicArray)
hpr::DynamicArray<float> arr {1, 3, 2};
hpr::DynamicArray<float> arr2 {1, 3, 2};
EXPECT_EQ(arr, arr2);
EXPECT_TRUE(arr == arr2);
arr.remove(1);
EXPECT_EQ(arr, hpr::darray<float>({1, 2}));
auto iter = arr2.begin();
@ -27,6 +39,26 @@ hpr::DynamicArray<float> arr3 {1, 3, 0, 2, 9, 0, 5};
arr3.remove([](float num) { return num == 0; });
EXPECT_EQ(arr3, hpr::darray<float>({1, 3, 2, 9, 5}));
EXPECT_EQ(arr3.size(), 5);
arr3.insert(3, 19);
EXPECT_EQ(arr3.size(), 6);
EXPECT_EQ(arr3[3], 19);
EXPECT_EQ(arr3.pop(), 5);
EXPECT_EQ(arr3.size(), 5);
arr3.resize(3);
EXPECT_EQ(arr3.size(), 3);
EXPECT_EQ(arr3.capacity(), 3);
EXPECT_EQ(arr3.back(), 2);
arr3.resize(4);
EXPECT_EQ(arr3.back(), 2);
arr3.push(17);
arr3.push(14);
EXPECT_EQ(arr3.back(), 14);
EXPECT_EQ(arr3.size(), 5);
arr3.clear();
EXPECT_EQ(arr3.is_empty(), true);
hpr::DynamicArray<float*> arr4;
arr4.push(new float(5));
@ -34,4 +66,28 @@ arr4.push(new float(7));
arr4.push(new float(9));
EXPECT_EQ(*arr4[0], 5.f);
EXPECT_EQ(*arr4[2], 9.f);
for (auto& v : arr4)
delete v;
}
TEST(containers, TreeNode)
{
hpr::TreeNode<float> node1 (5);
//std::shared_ptr<hpr::TreeNode<float>> ptr {node1};
hpr::TreeNode<float> node2 {7, {&node1}};
hpr::TreeNode<float> node3 {9, {&node2, &node1}};
hpr::TreeNode<float> node4 {11, {&node3}};
EXPECT_EQ(*node1.data(), 5);
//EXPECT_EQ(*node1->data(), *node2.ancestor()->data());
hpr::darray<hpr::TreeNode<float>*> tr = node1.traverse_descendants();
EXPECT_EQ(tr.size(), 0);
hpr::darray<hpr::TreeNode<float>*> tr2 = node4.traverse_descendants();
EXPECT_EQ(tr2.size(), 4);
hpr::darray<hpr::TreeNode<float>*> tr3 = node1.traverse_ancestors();
EXPECT_EQ(tr3.size(), 2); // node1 has changed ancestor
//
}

View File

View File

@ -1,55 +0,0 @@
cmake_minimum_required(VERSION 3.16)
project(core
VERSION "${HPR_PROJECT_VERSION}"
LANGUAGES CXX
)
add_library(${PROJECT_NAME} INTERFACE)
add_library(${CMAKE_PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
add_module(${PROJECT_NAME})
file(GLOB ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS "../core.hpp" "*.hpp")
foreach(_header_path ${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS})
list(APPEND ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE "$<BUILD_INTERFACE:${_header_path}>")
endforeach()
target_sources(${PROJECT_NAME}
INTERFACE
${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE}
$<INSTALL_INTERFACE:include/${CMAKE_PROJECT_NAME}/${PROJECT_NAME}>
)
install(
TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_SKIP
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
EXPORT ${PROJECT_NAME}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CMAKE_PROJECT_NAME}-${HPR_PROJECT_VERSION}
NAMESPACE ${CMAKE_PROJECT_NAME}::
)
install(
TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_ONLY
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
DIRECTORY ${PROJECT_SOURCE_DIR}
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
FILES_MATCHING
PATTERN "*.h"
PATTERN "*.hpp"
PATTERN "tests" EXCLUDE
)
install(
FILES ../${PROJECT_NAME}.hpp
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
)

View File

@ -1,5 +0,0 @@
#pragma once
#define HPR_VERSION_MAJOR 0
#define HPR_VERSION_MINOR 10
#define HPR_VERSION_PATCH 0

View File

@ -1,12 +1,12 @@
#pragma once
#include "csg/shape.hpp"
#include "csg/vertex.hpp"
#include "csg/edge.hpp"
#include "csg/wire.hpp"
#include "csg/face.hpp"
#include "csg/shell.hpp"
#include "csg/solid.hpp"
#include "csg/compound.hpp"
#include "csg/geometry.hpp"
#include "csg/surface.hpp"
#include <hpr/csg/shape.hpp>
#include <hpr/csg/vertex.hpp>
#include <hpr/csg/edge.hpp>
#include <hpr/csg/wire.hpp>
#include <hpr/csg/face.hpp>
#include <hpr/csg/shell.hpp>
#include <hpr/csg/solid.hpp>
#include <hpr/csg/compound.hpp>
#include <hpr/csg/geometry.hpp>
#include <hpr/csg/surface.hpp>

View File

@ -1,77 +1,33 @@
cmake_minimum_required(VERSION 3.16)
project(csg
VERSION "${HPR_PROJECT_VERSION}"
VERSION "${HPR_VERSION}"
LANGUAGES CXX
)
add_library(${PROJECT_NAME})
add_library(${CMAKE_PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
add_module(${PROJECT_NAME})
hpr_add_library(${PROJECT_NAME} STATIC)
file(GLOB ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS
"../csg.hpp" "*.hpp"
hpr_collect_interface(${PROJECT_NAME}
"../csg.hpp"
"*.hpp"
)
foreach(_header_path ${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS})
list(APPEND ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE "$<BUILD_INTERFACE:${_header_path}>")
endforeach()
file(GLOB ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_SOURCES
hpr_collect_sources(${PROJECT_NAME}
"*.cpp"
)
target_sources(${PROJECT_NAME}
INTERFACE
${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE}
$<INSTALL_INTERFACE:include/${CMAKE_PROJECT_NAME}/${PROJECT_NAME}>
PRIVATE
${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_SOURCES}
INTERFACE ${${PROJECT_NAME}_HEADERS_INTERFACE} ${HPR_INSTALL_INTERFACE}/${PROJECT_NAME}>
PRIVATE ${${PROJECT_NAME}_SOURCES}
)
target_link_libraries(${PROJECT_NAME}
${OCCT_LIBRARIES}
${OpenCASCADE_LIBS}
)
target_include_directories(${PROJECT_NAME}
PUBLIC
${OCCT_INCLUDE_DIRS}
PUBLIC ${OpenCASCADE_INCLUDE_DIR}
)
install(
TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_SKIP
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
EXPORT ${PROJECT_NAME}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CMAKE_PROJECT_NAME}-${HPR_PROJECT_VERSION}
NAMESPACE ${CMAKE_PROJECT_NAME}::
)
install(
TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_ONLY
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
DIRECTORY ${PROJECT_SOURCE_DIR}
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
FILES_MATCHING
PATTERN "*.h"
PATTERN "*.hpp"
PATTERN "tests" EXCLUDE
)
install(
FILES ../${PROJECT_NAME}.hpp
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
)
if(HPR_TEST)
add_subdirectory(tests)
endif()
hpr_install(${PROJECT_NAME} ${PROJECT_SOURCE_DIR})
hpr_tests(${PROJECT_NAME} tests)

View File

@ -1,7 +1,7 @@
#pragma once
#include "shape.hpp"
#include "solid.hpp"
#include <hpr/csg/shape.hpp>
#include <hpr/csg/solid.hpp>
namespace hpr::csg

View File

@ -1,7 +1,7 @@
#pragma once
#include "shape.hpp"
#include "vertex.hpp"
#include <hpr/csg/shape.hpp>
#include <hpr/csg/vertex.hpp>
namespace hpr::csg

View File

@ -1,7 +1,7 @@
#pragma once
#include "shape.hpp"
#include "wire.hpp"
#include <hpr/csg/shape.hpp>
#include <hpr/csg/wire.hpp>
namespace hpr::csg

View File

@ -1,6 +1,6 @@
#pragma once
#include "shape.hpp"
#include <hpr/csg/shape.hpp>
namespace hpr::csg

View File

@ -1,4 +1,4 @@
#include "shape.hpp"
#include <hpr/csg/shape.hpp>
bool std::less<hpr::csg::Shape>::operator()(const hpr::csg::Shape& s1, const hpr::csg::Shape& s2) const

View File

@ -1,8 +1,8 @@
#pragma once
#include "../containers/array.hpp"
#include "../math/scalar.hpp"
#include "../math/vector.hpp"
#include <hpr/containers/array.hpp>
#include <hpr/math/scalar.hpp>
#include <hpr/math/vector.hpp>
#include <map>
#include <string>

View File

@ -1,7 +1,7 @@
#pragma once
#include "shape.hpp"
#include "face.hpp"
#include <hpr/csg/shape.hpp>
#include <hpr/csg/face.hpp>
namespace hpr::csg

View File

@ -1,7 +1,7 @@
#pragma once
#include "shape.hpp"
#include "shell.hpp"
#include <hpr/csg/shape.hpp>
#include <hpr/csg/shell.hpp>
namespace hpr::csg

View File

@ -1,7 +1,7 @@
#pragma once
#include "geometry.hpp"
#include "face.hpp"
#include <hpr/csg/geometry.hpp>
#include <hpr/csg/face.hpp>
namespace hpr::csg

View File

@ -1,14 +0,0 @@
file(GLOB tests_cpp "*.cpp")
add_executable(${PROJECT_NAME}-tests
${tests_cpp}
)
target_link_libraries(${PROJECT_NAME}-tests
PUBLIC
hpr::${PROJECT_NAME}
PRIVATE
GTest::gtest_main
)
gtest_add_tests(TARGET ${PROJECT_NAME}-tests)

View File

@ -1,11 +1,12 @@
#include <gtest/gtest.h>
#include "../../csg.hpp"
#include <hpr/csg.hpp>
TEST(csgTest, Shape)
{
using namespace hpr;
double radius = 1.;
double volume = 4. / 3. * PI;
double volume = 4. / 3. * pi();
auto sphere = csg::sphere({0, 0, 0}, radius);
EXPECT_TRUE(equal(sphere.volume(), volume, 1e-6));
auto box = csg::box({0, 0, 0}, 1, 1, 1);

View File

@ -1,6 +1,6 @@
#pragma once
#include "shape.hpp"
#include <hpr/csg/shape.hpp>
namespace hpr::csg

View File

@ -1,7 +1,7 @@
#pragma once
#include "shape.hpp"
#include "edge.hpp"
#include <hpr/csg/shape.hpp>
#include <hpr/csg/edge.hpp>
namespace hpr::csg

54
source/hpr/exception.hpp Normal file
View File

@ -0,0 +1,54 @@
#pragma once
#include <exception>
#include <string>
#include <source_location>
#include <sstream>
#include <utility>
#include <vector>
namespace hpr
{
class Exception : public std::exception
{
protected:
std::string p_message;
public:
inline explicit
Exception(std::source_location location = std::source_location::current()) :
p_message {}
{
std::stringstream _message;
_message << "\t" << p_message
<< "\n where:\t\t" << location.file_name() << ":" << location.line() << ":" << location.column()
<< "\n function:\t" << location.function_name();
p_message = _message.str();
}
inline explicit
Exception(const std::string& message, std::source_location location = std::source_location::current()) :
p_message {message}
{
std::stringstream _message;
_message << "\t" << p_message
<< "\n where:\t" << location.file_name() << ":" << location.line() << ":" << location.column()
<< "\n function:\t" << location.function_name();
p_message = _message.str();
}
[[nodiscard]] const char* what() const noexcept override {
std::vector<float> vv;
return p_message.data();
}
};
struct OutOfRange : public Exception
{
inline explicit OutOfRange(std::source_location location = std::source_location::current()) : Exception {"Out of range", location} {}
inline explicit OutOfRange(const std::string& message, std::source_location location = std::source_location::current()) : Exception {message, location} {}
};
struct LengthError : public Exception
{
inline explicit LengthError(std::source_location location = std::source_location::current()) : Exception {"Length error", location} {}
inline explicit LengthError(const std::string& message, std::source_location location = std::source_location::current()) : Exception {message, location} {}
};
}

View File

@ -1,5 +1,5 @@
#pragma once
#include "geometry/polytope.hpp"
#include "geometry/triangle.hpp"
#include "geometry/tetrahedron.hpp"
#include <hpr/geometry/polytope.hpp>
#include <hpr/geometry/triangle.hpp>
#include <hpr/geometry/tetrahedron.hpp>

View File

@ -1,57 +1,21 @@
cmake_minimum_required(VERSION 3.16)
project(geometry
VERSION "${HPR_PROJECT_VERSION}"
VERSION "${HPR_VERSION}"
LANGUAGES CXX
)
add_library(${PROJECT_NAME} INTERFACE)
add_library(${CMAKE_PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
add_module(${PROJECT_NAME})
hpr_add_library(${PROJECT_NAME} INTERFACE)
file(GLOB ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS
"../geometry.hpp" "*.hpp"
hpr_collect_interface(${PROJECT_NAME}
"../geometry.hpp"
"*.hpp"
)
foreach(_header_path ${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS})
list(APPEND ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE "$<BUILD_INTERFACE:${_header_path}>")
endforeach()
target_sources(${PROJECT_NAME}
INTERFACE
${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE}
$<INSTALL_INTERFACE:include/${CMAKE_PROJECT_NAME}/${PROJECT_NAME}>
INTERFACE ${${PROJECT_NAME}_HEADERS_INTERFACE} ${HPR_INSTALL_INTERFACE}/${PROJECT_NAME}>
)
install(
TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_SKIP
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
EXPORT ${PROJECT_NAME}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CMAKE_PROJECT_NAME}-${HPR_PROJECT_VERSION}
NAMESPACE ${CMAKE_PROJECT_NAME}::
)
install(
TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_ONLY
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
DIRECTORY ${PROJECT_SOURCE_DIR}
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
FILES_MATCHING
PATTERN "*.h"
PATTERN "*.hpp"
PATTERN "tests" EXCLUDE
)
install(
FILES ../${PROJECT_NAME}.hpp
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
)
hpr_install(${PROJECT_NAME} ${PROJECT_SOURCE_DIR})

View File

@ -1,7 +1,7 @@
#pragma once
#include "../containers.hpp"
#include "../math.hpp"
#include <hpr/containers.hpp>
#include <hpr/math.hpp>
namespace hpr::geometry

View File

@ -1,4 +1,6 @@
#include "../math.hpp"
#pragma once
#include <hpr/math.hpp>
namespace hpr::geometry
{

View File

@ -1,4 +1,6 @@
#include "../math.hpp"
#pragma once
#include <hpr/math.hpp>
namespace hpr::geometry
{

View File

@ -1,15 +1,18 @@
#pragma once
#include "gpu/array_object.hpp"
#include "gpu/buffer_object.hpp"
#include "gpu/color_buffer.hpp"
#include "gpu/cull_face.hpp"
#include "gpu/depth_buffer.hpp"
#include "gpu/framebuffer.hpp"
#include "gpu/renderbuffer.hpp"
#include "gpu/shader.hpp"
#include "gpu/shader_program.hpp"
#include "gpu/stencil_buffer.hpp"
#include "gpu/texture.hpp"
#include "gpu/viewport.hpp"
#include <hpr/gpu/array_object.hpp>
#include <hpr/gpu/buffer_object.hpp>
#include <hpr/gpu/color_buffer.hpp>
#include <hpr/gpu/cull_face.hpp>
#include <hpr/gpu/depth_buffer.hpp>
#include <hpr/gpu/framebuffer.hpp>
#include <hpr/gpu/renderbuffer.hpp>
#include <hpr/gpu/shader.hpp>
#include <hpr/gpu/shader_program.hpp>
#include <hpr/gpu/stencil_buffer.hpp>
#include <hpr/gpu/texture.hpp>
#include <hpr/gpu/viewport.hpp>
#include <hpr/gpu/monitor.hpp>
#include <hpr/gpu/window.hpp>
#include <hpr/gpu/context.hpp>

View File

@ -1,68 +1,32 @@
cmake_minimum_required(VERSION 3.16)
project(gpu
VERSION "${HPR_PROJECT_VERSION}"
VERSION "${HPR_VERSION}"
LANGUAGES CXX
)
add_library(${PROJECT_NAME})
add_library(${CMAKE_PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
add_module(${PROJECT_NAME})
hpr_add_library(${PROJECT_NAME} INTERFACE)
file(GLOB ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS
"../gpu.hpp" "*.hpp"
hpr_collect_interface(${PROJECT_NAME}
"../gpu.hpp"
"*.hpp"
)
foreach(_header_path ${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS})
list(APPEND ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE "$<BUILD_INTERFACE:${_header_path}>")
endforeach()
file(GLOB ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_SOURCES
"*.cpp"
)
#hpr_collect_sources(${PROJECT_NAME}
# "*.cpp"
#)
target_sources(${PROJECT_NAME}
INTERFACE
${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE}
$<INSTALL_INTERFACE:include/${CMAKE_PROJECT_NAME}/${PROJECT_NAME}>
PRIVATE
${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_SOURCES}
INTERFACE ${${PROJECT_NAME}_HEADERS_INTERFACE} ${HPR_INSTALL_INTERFACE}/${PROJECT_NAME}>
PRIVATE ${${PROJECT_NAME}_SOURCES}
)
target_link_libraries(${PROJECT_NAME}
glad
stb
INTERFACE
glad::glad
glfw::glfw
stb::stb
)
install(
TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_SKIP
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
EXPORT ${PROJECT_NAME}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CMAKE_PROJECT_NAME}-${HPR_PROJECT_VERSION}
NAMESPACE ${CMAKE_PROJECT_NAME}::
)
install(
TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_ONLY
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
DIRECTORY ${PROJECT_SOURCE_DIR}
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
FILES_MATCHING
PATTERN "*.h"
PATTERN "*.hpp"
PATTERN "tests" EXCLUDE
)
install(
FILES ../${PROJECT_NAME}.hpp
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
)
hpr_install(${PROJECT_NAME} ${PROJECT_SOURCE_DIR})

View File

@ -1,2 +0,0 @@
#include <glad/glad.h>
#include "array_object.hpp"

View File

@ -1,6 +1,6 @@
#pragma once
#include "buffer_object.hpp"
#include <hpr/gpu/buffer_object.hpp>
#include <string>
@ -13,11 +13,27 @@ namespace hpr::gpu
class ArrayObject
{
public:
enum Mode
{
Points = GL_POINTS,
LineStrip = GL_LINE_STRIP,
LineLoop = GL_LINE_LOOP,
Lines = GL_LINES,
LineStripAdjacency = GL_LINE_STRIP_ADJACENCY,
LinesAdjacency = GL_LINES_ADJACENCY,
TriangleStrip = GL_TRIANGLE_STRIP,
TriangleFan = GL_TRIANGLE_FAN,
Triangles = 0x0004, //GL_TRIANGLES,
TriangleStripAdjacency = GL_TRIANGLE_STRIP_ADJACENCY,
TrianglesAdjacency = GL_TRIANGLES_ADJACENCY,
Patches = GL_PATCHES
};
protected:
unsigned int p_index;
GLuint p_index;
int p_size;
int p_stride;
bool p_binded;
@ -74,7 +90,7 @@ namespace hpr::gpu
glDeleteVertexArrays(1, &p_index);
}
void attribPointer(BufferObject& buffer, unsigned int location, unsigned int size)
void attribPointer(BufferObject& buffer, unsigned int location, int size)
{
if (buffer.type() == BufferObject::Type::Unknown)
throw std::runtime_error("Unknown buffer type");
@ -84,14 +100,19 @@ namespace hpr::gpu
throw std::runtime_error("BufferObject is invalid");
buffer.bind();
glVertexAttribPointer(location, size, GL_FLOAT, GL_FALSE, sizeof(float) * buffer.offset(), static_cast<void*>(nullptr));
glEnableVertexAttribArray(location);
glVertexAttribPointer(location, size, GL_FLOAT, GL_FALSE, sizeof(float) * buffer.offset(), static_cast<void*>(nullptr));
buffer.unbind();
}
void draw()
void drawElements(Mode mode, int count) const
{
glDrawElements(mode, count, GL_UNSIGNED_INT, nullptr);
}
void drawArrays(Mode mode, int count) const
{
glDrawArrays(mode, 0, count);
}
inline

View File

@ -1,27 +0,0 @@
#include <glad/glad.h>
#include "buffer_object.hpp"
namespace hpr::gpu
{
void BufferObject::bind()
{
glBindBuffer((GLenum)p_type, p_index);
p_binded = true;
}
void BufferObject::unbind()
{
glBindBuffer((GLenum)p_type, 0);
p_binded = false;
}
void BufferObject::destroy()
{
if (p_type == Type::Unknown)
std::runtime_error("Unknown buffer type");
glDeleteBuffers(1, &p_index);
}
}

View File

@ -1,6 +1,7 @@
#pragma once
#include "../containers.hpp"
#include <hpr/containers.hpp>
#include <string>
#ifndef __gl_h_
@ -16,7 +17,7 @@ class BufferObject
public:
enum class Type
enum Type
{
Vertex = 0x8892, // GL_ARRAY_BUFFER,
Index = 0x8893, // GL_ELEMENT_ARRAY_BUFFER,
@ -29,7 +30,7 @@ protected:
Type p_type;
unsigned int p_index;
int p_size;
int p_offset;
unsigned int p_offset;
bool p_binded;
public:
@ -79,9 +80,17 @@ public:
return p_offset;
}
void bind() ;
void bind()
{
glBindBuffer((GLenum)p_type, p_index);
p_binded = true;
}
void unbind();
void unbind()
{
glBindBuffer((GLenum)p_type, 0);
p_binded = false;
}
[[nodiscard]]
bool binded() const
@ -93,7 +102,7 @@ public:
void create(const darray<T>& data, unsigned int offset = 0)
{
if (p_type == Type::Unknown)
std::runtime_error("Unknown buffer type");
throw std::runtime_error("Unknown buffer type");
unsigned int drawType;
@ -104,24 +113,34 @@ public:
glGenBuffers(1, &p_index);
bind();
glBufferData((GLenum)p_type, sizeof(T) * data.size(), data.data(), drawType);
glBufferData(static_cast<GLenum>(p_type), sizeof(T) * data.size(), data.data(), drawType);
unbind();
p_offset = offset;
p_size = data.size();
}
template <typename T>
void edit(const darray<T>& data, unsigned int offset = 0)
{
if (p_type == Type::Unknown)
std::runtime_error("Unknown buffer type");
throw std::runtime_error("Unknown buffer type");
bind();
glBufferSubData(p_type, offset, sizeof(T) * data.size(), data.data());
unbind();
p_offset = offset;
p_size = data.size();
}
void destroy();
void destroy()
{
if (p_type == Type::Unknown)
throw std::runtime_error("Unknown buffer type");
glDeleteBuffers(1, &p_index);
}
[[nodiscard]]
inline

View File

@ -1,6 +1,6 @@
#pragma once
#include "../math.hpp"
#include <hpr/math.hpp>
namespace hpr::gpu

View File

@ -1,6 +1,7 @@
#pragma once
#include "../math/vector.hpp"
#include <hpr/math/vector.hpp>
#ifndef __gl_h_
#include <glad/glad.h>
#endif
@ -44,7 +45,8 @@ namespace hpr::gpu
virtual
~ColorBuffer() = default;
void mask(bool red, bool green, bool blue, bool alpha)
inline
void mask(bool red, bool green, bool blue, bool alpha) const
{
glColorMask(red, green, blue, alpha);
}

122
source/hpr/gpu/context.hpp Normal file
View File

@ -0,0 +1,122 @@
#pragma once
#ifndef __gl_h_
#include <glad/glad.h>
#endif
#include <GLFW/glfw3.h>
#include <stdexcept>
#include <iostream>
namespace hpr::gpu
{
class Context
{
protected:
bool p_glInitialized;
bool p_glfwInitialized;
public:
inline
Context() :
p_glInitialized {false},
p_glfwInitialized {false}
{
if (glfwInit())
p_glfwInitialized = true;
else
throw std::runtime_error("Cannot initialize GLFW context");
}
void link()
{
if (gladLoadGLLoader((GLADloadproc) glfwGetProcAddress))
p_glInitialized = true;
else
throw std::runtime_error("Cannot initialize GLAD context");
}
constexpr
bool valid() const
{
return p_glInitialized && p_glfwInitialized;
}
inline
void destroy() const
{
glfwTerminate();
}
inline
void debug(bool enable = true)
{
const auto debugOutput = [](GLenum source, GLenum type, unsigned int id, GLenum severity, GLsizei length, const char* message, const void* userParam)
{
// ignore non-significant error/warning codes
if (id == 131169 || id == 131185 || id == 131218 || id == 131204)
return;
std::cout << "Debug::GL[" << id << "]::";
switch (source)
{
case GL_DEBUG_SOURCE_API: std::cout << "API"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: std::cout << "Window_System"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: std::cout << "Shader_Compiler"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY: std::cout << "Third_Party"; break;
case GL_DEBUG_SOURCE_APPLICATION: std::cout << "Application"; break;
case GL_DEBUG_SOURCE_OTHER: std::cout << "Other"; break;
default: break;
}
std::cout << "::";
switch (type)
{
case GL_DEBUG_TYPE_ERROR: std::cout << "Error";break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: std::cout << "Deprecated_Behaviour"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: std::cout << "Undefined_Behaviour"; break;
case GL_DEBUG_TYPE_PORTABILITY: std::cout << "Portability"; break;
case GL_DEBUG_TYPE_PERFORMANCE: std::cout << "Performance"; break;
case GL_DEBUG_TYPE_MARKER: std::cout << "Marker"; break;
case GL_DEBUG_TYPE_PUSH_GROUP: std::cout << "Push_Group"; break;
case GL_DEBUG_TYPE_POP_GROUP: std::cout << "Pop_Group"; break;
case GL_DEBUG_TYPE_OTHER: std::cout << "Other"; break;
default: break;
}
std::cout << " ";
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: std::cout << "(high)"; break;
case GL_DEBUG_SEVERITY_MEDIUM: std::cout << "(medium)"; break;
case GL_DEBUG_SEVERITY_LOW: std::cout << "(low)"; break;
case GL_DEBUG_SEVERITY_NOTIFICATION: std::cout << "(notification)"; break;
default: break;
}
std::cout << ": " << message << std::endl;
};
if (enable)
{
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(debugOutput, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
}
else
{
glDisable(GL_DEBUG_OUTPUT);
glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
}
};
}

View File

@ -12,7 +12,9 @@ namespace hpr::gpu
class CullFace
{
enum class Mode
public:
enum Mode
{
Front = GL_FRONT,
Back = GL_BACK,
@ -37,7 +39,9 @@ public:
CullFace(Mode mode) :
p_binded {false},
p_mode {mode}
{}
{
set(mode);
}
virtual
~CullFace() = default;

View File

@ -1,7 +1,8 @@
#pragma once
#include "texture.hpp"
#include "renderbuffer.hpp"
#include <hpr/gpu/texture.hpp>
#include <hpr/gpu/renderbuffer.hpp>
#ifndef __gl_h_
#include <glad/glad.h>
@ -25,7 +26,7 @@ public:
inline
Framebuffer() :
p_index {0},
p_texture {},
p_texture {1, 1}, // non zero
p_renderbuffer {}
{}
@ -58,9 +59,9 @@ public:
void attach(const Texture& texture)
{
if (!binded() && valid())
std::runtime_error("Framebuffer not binded or invalid");
throw std::runtime_error("Framebuffer not binded or invalid");
if (!texture.valid())
std::runtime_error("Texture is not valid");
throw std::runtime_error("Texture is not valid");
p_texture = texture;
p_texture.bind();
@ -72,17 +73,19 @@ public:
void attach(const Renderbuffer& renderbuffer)
{
if (!binded() && valid())
std::runtime_error("Framebuffer not binded or invalid");
throw std::runtime_error("Framebuffer not binded or invalid");
if (!renderbuffer.valid())
std::runtime_error("Renderbuffer is not valid");
throw std::runtime_error("Renderbuffer is not valid");
p_renderbuffer = renderbuffer;
p_renderbuffer.bind();
p_renderbuffer.storage(p_texture.width(), p_texture.height());
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, p_renderbuffer.index());
std::stringstream ss;
ss << "Framebuffer is not complete: " << glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
throw std::runtime_error("Framebuffer is not complete");
throw std::runtime_error(ss.str());
p_renderbuffer.unbind();
}
@ -93,16 +96,32 @@ public:
bind();
if (!p_texture.valid())
{
p_texture.create();
attach(p_texture);
}
if (!p_renderbuffer.valid())
{
p_renderbuffer.create();
attach(p_renderbuffer);
}
unbind();
}
void rescale()
{
p_texture.bind();
p_texture.rescale();
p_renderbuffer.bind();
p_renderbuffer.storage(p_texture.width(), p_texture.height());
p_texture.unbind();
p_renderbuffer.unbind();
}
void rescale(int width, int height)
{
p_texture.bind();
@ -122,10 +141,38 @@ public:
glDeleteFramebuffers(1, &p_index);
}
[[nodiscard]]
bool valid() const
{
return p_index != 0;
}
Texture& texture()
{
return p_texture;
}
int& width()
{
return p_texture.width();
}
[[nodiscard]]
int width() const
{
return p_texture.width();
}
int& height()
{
return p_texture.height();
}
[[nodiscard]]
int height() const
{
return p_texture.height();
}
};
}

View File

@ -1,3 +0,0 @@
//
// Created by L-Nafaryus on 12/16/2022.
//

View File

@ -0,0 +1,34 @@
#pragma once
#include <GLFW/glfw3.h>
namespace hpr::gpu
{
class Monitor
{
protected:
GLFWmonitor* p_instance;
public:
inline
Monitor() :
p_instance {glfwGetPrimaryMonitor()}
{}
virtual
~Monitor() = default;
inline
GLFWmonitor* instance() const
{
return p_instance;
}
};
}

View File

@ -45,7 +45,7 @@ namespace hpr::gpu
void create()
{
glGenRenderbuffers(1, &p_index);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, p_index);
//glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, p_index);
}
void storage(int width, int height)

View File

@ -1,8 +0,0 @@
//
// Created by L-Nafaryus on 12/16/2022.
//
#ifndef HPR_SCENE_HPP
#define HPR_SCENE_HPP
#endif //HPR_SCENE_HPP

View File

@ -1,6 +1,8 @@
#pragma once
#include "../containers.hpp"
#include <hpr/containers.hpp>
#include <hpr/gpu/shader.hpp>
#include <hpr/exception.hpp>
#include <string>
@ -11,13 +13,18 @@
namespace hpr::gpu
{
struct ShaderProgramLinkError : public Exception
{
inline explicit ShaderProgramLinkError(std::source_location location = std::source_location::current()) : Exception {"Shader program link error", location} {}
inline explicit ShaderProgramLinkError(const std::string& message, std::source_location location = std::source_location::current()) : Exception {message, location} {}
};
class ShaderProgram
{
protected:
unsigned int p_index;
darray<Shader> p_shaders;
public:
@ -37,12 +44,7 @@ namespace hpr::gpu
return p_index;
}
darray<Shader> shaders()
{
return p_shaders;
}
void create(const std::string& label = "")
void create()
{
p_index = glCreateProgram();
}
@ -50,17 +52,10 @@ namespace hpr::gpu
void attach(const Shader& shader)
{
glAttachShader(p_index, shader.index());
p_shaders.push(shader);
}
void detach(const Shader& shader)
{
// WARNING: segfault, destroy_at (char)
p_shaders.remove([shader](const Shader& _shader)
{
return shader.index() == _shader.index();
});
glDetachShader(p_index, shader.index());
}
@ -72,14 +67,17 @@ namespace hpr::gpu
glGetProgramiv(p_index, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
throw std::runtime_error("Shader program link error");
{
GLsizei log_length = 0;
GLchar message[1024];
glGetProgramInfoLog(p_index, 1024, &log_length, message);
throw ShaderProgramLinkError(message);
}
}
void destroy()
{
//for (auto& shader : p_shaders)
// detach(shader);
glDeleteShader(p_index);
glDeleteProgram(p_index);
}
void bind()
@ -91,6 +89,180 @@ namespace hpr::gpu
{
glUseProgram(0);
}
inline
int uniformLocation(const std::string& label) const
{
return glGetUniformLocation(p_index, label.c_str());
}
template <typename T, std::convertible_to<T>... Args>
inline
void uniformValue(int location, T value, Args ...args)
{
auto arr = {value, static_cast<T>(args)...};
if constexpr (std::is_same<T, int>::value)
{
switch (arr.size())
{
case 1: glUniform1i(location, arr[0]); break;
case 2: glUniform2i(location, arr[0], arr[1]); break;
case 3: glUniform3i(location, arr[0], arr[1], arr[2]); break;
case 4: glUniform4i(location, arr[0], arr[1], arr[2], arr[3]); break;
}
}
else if constexpr (std::is_same<T, unsigned int>::value)
{
switch (arr.size())
{
case 1: glUniform1ui(location, arr[0]); break;
case 2: glUniform2ui(location, arr[0], arr[1]); break;
case 3: glUniform3ui(location, arr[0], arr[1], arr[2]); break;
case 4: glUniform4ui(location, arr[0], arr[1], arr[2], arr[3]); break;
}
}
else if constexpr (std::is_same<T, float>::value)
{
switch (arr.size())
{
case 1: glUniform1f(location, arr[0]); break;
case 2: glUniform2f(location, arr[0], arr[1]); break;
case 3: glUniform3f(location, arr[0], arr[1], arr[2]); break;
case 4: glUniform4f(location, arr[0], arr[1], arr[2], arr[3]); break;
}
}
else if constexpr (std::is_same<T, double>::value)
{
switch (arr.size())
{
case 1: glUniform1d(location, arr[0]); break;
case 2: glUniform2d(location, arr[0], arr[1]); break;
case 3: glUniform3d(location, arr[0], arr[1], arr[2]); break;
case 4: glUniform4d(location, arr[0], arr[1], arr[2], arr[3]); break;
}
}
else
throw std::runtime_error("Unsupported value type");
}
template <typename T, std::convertible_to<T>... Args>
inline
void uniformValue(const std::string& label, T value, Args ...args)
{
uniformValue(uniformLocation(label), value, std::forward<T>(args)...);
}
template <typename T, Size S>
inline
void uniformVector(int location, hpr::Size size, T* data)
{
if constexpr (std::is_same<T, int>::value)
{
switch (S)
{
case 1: glUniform1iv(location, size, data); break;
case 2: glUniform2iv(location, size, data); break;
case 3: glUniform3iv(location, size, data); break;
case 4: glUniform4iv(location, size, data); break;
}
}
else if constexpr (std::is_same<T, unsigned int>::value)
{
switch (S)
{
case 1: glUniform1uiv(location, size, data); break;
case 2: glUniform2uiv(location, size, data); break;
case 3: glUniform3uiv(location, size, data); break;
case 4: glUniform4uiv(location, size, data); break;
}
}
else if constexpr (std::is_same<T, float>::value)
{
switch (S)
{
case 1: glUniform1fv(location, size, data); break;
case 2: glUniform2fv(location, size, data); break;
case 3: glUniform3fv(location, size, data); break;
case 4: glUniform4fv(location, size, data); break;
}
}
else if constexpr (std::is_same<T, double>::value)
{
switch (size)
{
case 1: glUniform1dv(location, size, data); break;
case 2: glUniform2dv(location, size, data); break;
case 3: glUniform3dv(location, size, data); break;
case 4: glUniform4dv(location, size, data); break;
}
}
else
throw std::runtime_error("Unsupported value type");
}
template <typename T, Size S>
inline
void uniformVector(const std::string& label, hpr::Size size, T* data)
{
uniformVector<T, S>(uniformLocation(label), size, data);
}
template <typename T, hpr::Size C, hpr::Size R>
inline
void uniformMatrix(int location, hpr::Size size, bool transpose, T* data)
{
if constexpr (std::is_same<T, float>::value)
{
if constexpr (C == 2 && R == 2)
glUniformMatrix2fv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 3 && R == 3)
glUniformMatrix3fv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 4 && R == 4)
glUniformMatrix4fv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 2 && R == 3)
glUniformMatrix2x3fv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 3 && R == 2)
glUniformMatrix3x2fv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 2 && R == 4)
glUniformMatrix2x4fv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 4 && R == 2)
glUniformMatrix4x2fv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 3 && R == 4)
glUniformMatrix3x4fv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 4 && R == 3)
glUniformMatrix4x3fv(location, static_cast<GLsizei>(size), transpose, data);
}
else if constexpr (std::is_same<T, double>::value)
{
if constexpr (C == 2 && R == 2)
glUniformMatrix2dv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 3 && R == 3)
glUniformMatrix3dv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 4 && R == 4)
glUniformMatrix4dv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 2 && R == 3)
glUniformMatrix2x3dv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 3 && R == 2)
glUniformMatrix3x2dv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 2 && R == 4)
glUniformMatrix2x4dv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 4 && R == 2)
glUniformMatrix4x2dv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 3 && R == 4)
glUniformMatrix3x4dv(location, static_cast<GLsizei>(size), transpose, data);
else if constexpr (C == 4 && R == 3)
glUniformMatrix4x3dv(location, static_cast<GLsizei>(size), transpose, data);
}
else
throw std::runtime_error("Unsupported value type");
}
template <hpr::Size C, hpr::Size R, typename T>
inline
void uniformMatrix(const std::string& label, hpr::Size size, bool transpose, T* data)
{
uniformMatrix<T, C, R>(uniformLocation(label), size, transpose, data);
}
};
}

View File

@ -1,6 +1,6 @@
#pragma once
#include "../containers.hpp"
#include <hpr/containers.hpp>
#include <string>
#include <filesystem>
@ -53,6 +53,17 @@ namespace hpr::gpu
p_imageFormat {Format::RGBA}
{}
inline
Texture(int width, int height) :
p_index {0},
p_filename {},
p_source {},
p_width {width},
p_height {height},
p_internalFormat {Format::RGBA},
p_imageFormat {Format::RGBA}
{}
inline
Texture(const std::string& filename) :
p_index {0},
@ -73,29 +84,39 @@ namespace hpr::gpu
return p_index;
}
[[nodiscard]]
unsigned int width() const
int& width()
{
return p_width;
}
[[nodiscard]]
unsigned int height() const
int width() const
{
return p_width;
}
int& height()
{
return p_height;
}
void active()
[[nodiscard]]
int height() const
{
return p_height;
}
void active() const
{
glActiveTexture(GL_TEXTURE0 + p_index);
}
void bind()
void bind() const
{
glBindTexture(GL_TEXTURE_2D, p_index);
}
void unbind()
void unbind() const
{
glBindTexture(GL_TEXTURE_2D, 0);
}
@ -171,8 +192,17 @@ namespace hpr::gpu
unbind();
}
void rescale()
{
bind();
glTexImage2D(GL_TEXTURE_2D, 0, (GLint)p_internalFormat, p_width, p_height, 0, (GLint)p_imageFormat, GL_UNSIGNED_BYTE, !p_source.empty() ? p_source.data() : nullptr);
unbind();
}
void rescale(int width, int height)
{
p_width = width;
p_height = height;
bind();
glTexImage2D(GL_TEXTURE_2D, 0, (GLint)p_internalFormat, p_width, p_height, 0, (GLint)p_imageFormat, GL_UNSIGNED_BYTE, !p_source.empty() ? p_source.data() : nullptr);
unbind();

View File

@ -1,8 +0,0 @@
//
// Created by L-Nafaryus on 12/16/2022.
//
#ifndef HPR_VIEWER_HPP
#define HPR_VIEWER_HPP
#endif //HPR_VIEWER_HPP

View File

@ -1,6 +1,7 @@
#pragma once
#include "../math/vector.hpp"
#include <hpr/math/vector.hpp>
#ifndef __gl_h_
#include <glad/glad.h>
#endif
@ -34,6 +35,16 @@ public:
virtual
~Viewport() = default;
vec2& pos()
{
return p_pos;
}
vec2& size()
{
return p_size;
}
inline
void set()
{

296
source/hpr/gpu/window.hpp Normal file
View File

@ -0,0 +1,296 @@
#pragma once
#include <hpr/gpu/context.hpp>
#include <hpr/gpu/monitor.hpp>
#include <string>
#include <stdexcept>
#include <functional>
#include <GLFW/glfw3.h>
namespace hpr::gpu
{
class Window
{
public:
enum State
{
Visible,
Hidden,
Maximized,
Minimized,
Closed,
};
enum Style
{
Windowed,
Fullscreen,
Popup
};
protected:
int p_posX;
int p_posY;
int p_width;
int p_height;
std::string p_title;
State p_state;
Style p_style;
Window* p_parent;
Monitor* p_monitor;
bool p_isActive;
bool p_isResizing;
GLFWwindow* p_instance;
Context p_context;
public:
inline
Window() :
p_posX {0},
p_posY {0},
p_width {0},
p_height {0},
p_title {},
p_state {State::Hidden},
p_style {Style::Windowed},
p_parent {nullptr},
p_monitor {nullptr},
p_isActive {true},
p_isResizing {false},
p_context {}
{
p_instance = glfwCreateWindow(p_width, p_height, p_title.c_str(), p_monitor != nullptr ? p_monitor->instance() : nullptr, p_parent != nullptr ? p_parent->p_instance : nullptr);
if (p_instance == nullptr)
throw std::runtime_error("Cannot create Window");
glfwMakeContextCurrent(p_instance);
p_context.link();
glfwSetWindowUserPointer(p_instance, this);
glfwSetWindowPos(p_instance, p_posX, p_posY);
this->state(p_state);
this->style(p_style);
}
inline
Window(int x, int y, int width, int height, const std::string& title, Style style, Window* parent, Monitor* monitor) :
p_posX {x},
p_posY {y},
p_width {width},
p_height {height},
p_title {title},
p_state {State::Visible},
p_style {style},
p_parent {parent},
p_monitor {monitor},
p_isActive {true},
p_isResizing {false},
p_context {}
{
//glfwInit();
p_instance = glfwCreateWindow(p_width, p_height, p_title.c_str(), p_monitor != nullptr ? p_monitor->instance() : nullptr, p_parent != nullptr ? p_parent->p_instance : nullptr);
if (p_instance == nullptr)
throw std::runtime_error("Cannot create window");
glfwMakeContextCurrent(p_instance);
p_context.link();
glfwSetWindowUserPointer(p_instance, this);
glfwSetWindowPos(p_instance, p_posX, p_posY);
this->state(p_state);
this->style(p_style);
}
virtual
~Window()
{
p_context.destroy();
}
// member functions
inline
GLFWwindow* instance() const
{
return p_instance;
}
inline
Context& context()
{
return p_context;
}
inline
void pos(int x, int y)
{
p_posX = x;
p_posY = y;
}
inline
int x() const
{
return p_posX;
}
inline
int y() const
{
return p_posY;
}
inline
void size(int width, int height)
{
p_width = width;
p_height = height;
}
inline
int width() const
{
return p_width;
}
inline
int height() const
{
return p_height;
}
inline
void title(const std::string& title)
{
p_title = title;
}
inline
std::string title() const
{
return p_title;
}
inline
void state(State state)
{
switch (state)
{
case State::Visible:
glfwShowWindow(p_instance);
break;
case State::Hidden:
glfwHideWindow(p_instance);
break;
case State::Maximized:
glfwMaximizeWindow(p_instance);
break;
case State::Minimized:
glfwIconifyWindow(p_instance);
break;
case State::Closed:
glfwSetWindowShouldClose(p_instance, GLFW_TRUE);
break;
default:
break;
}
p_state = state;
}
inline
State state() const
{
return p_state;
}
inline
void style(Style style)
{
switch (style)
{
case Style::Windowed:
glfwSetWindowMonitor(p_instance, nullptr, p_posX, p_posY, p_width, p_height, GLFW_DONT_CARE);
break;
case Style::Fullscreen:
glfwSetWindowMonitor(p_instance, glfwGetPrimaryMonitor(), p_posX, p_posY, p_width, p_height, GLFW_DONT_CARE);
break;
default:
break;
}
p_style = style;
}
inline
Style style() const
{
return p_style;
}
inline
void destroy()
{
glfwDestroyWindow(p_instance);
p_instance = nullptr;
}
inline
void swapBuffers()
{
glfwSwapBuffers(p_instance);
}
inline
void pollEvents()
{
glfwPollEvents();
}
protected:
std::function<void(Window* window, int width, int height)> onFramebufferResize;
std::function<void(Window* window, int key, int scancode, int action, int mods)> onKeyClick;
public:
void framebufferResizeCallback(const std::function<void(Window* window, int width, int height)>& event)
{
onFramebufferResize = event;
glfwSetFramebufferSizeCallback(p_instance, [](GLFWwindow* window, int width, int height)
{
auto p = static_cast<Window*>(glfwGetWindowUserPointer(window));
if (p->onFramebufferResize)
p->onFramebufferResize(p, width, height);
});
}
void keyClickCallback(const std::function<void(Window* window, int key, int scancode, int action, int mods)>& event)
{
onKeyClick = event;
glfwSetKeyCallback(p_instance, [](GLFWwindow* window, int key, int scancode, int action, int mods)
{
auto p = static_cast<Window*>(glfwGetWindowUserPointer(window));
if (p->onKeyClick)
p->onKeyClick(p, key, scancode, action, mods);
});
}
};
}

View File

@ -1,49 +1,37 @@
#pragma once
#define HPR_VERSION_MAJOR 0
#define HPR_VERSION_MINOR 10
#define HPR_VERSION_PATCH 0
namespace hpr
{
/* Core */
// containers
// math
// io
/* Graphics */
namespace gpu
{
// gpu
// window_system
}
/* Mesh */
namespace mesh
{
// mesh
}
/* CSG */
namespace csg
{
// csg
}
}
#include "containers.hpp"
#include "math.hpp"
#include "io.hpp"
#if WITH_GPU
#include "gpu.hpp"
#if HPR_WITH_CONTAINERS
#include <hpr/containers.hpp>
#endif
#if WITH_WS
#include "window_system.hpp"
#if HPR_WITH_MATH
#include <hpr/math.hpp>
#endif
#if WITH_MESH
#include "mesh.hpp"
#if HPR_WITH_IO
#include <hpr/io.hpp>
#endif
#if WITH_CSG
#include "csg.hpp"
#if HPR_WITH_GPU
#include <hpr/gpu.hpp>
#endif
#if HPR_WITH_MESH
#include <hpr/mesh.hpp>
#endif
#if HPR_WITH_CSG
#include <hpr/csg.hpp>
#endif
#if HPR_WITH_GEOMETRY
#include <hpr/geometry.hpp>
#endif
#if HPR_WITH_PARALLEL
#include <hpr/parallel.hpp>
#endif

View File

@ -1,3 +1,3 @@
#pragma once
#include "io/file.hpp"
#include <hpr/io/file.hpp>

View File

@ -1,68 +1,27 @@
cmake_minimum_required(VERSION 3.16)
project(io
VERSION "${HPR_PROJECT_VERSION}"
VERSION "${HPR_VERSION}"
LANGUAGES CXX
)
add_library(${PROJECT_NAME})
add_library(${CMAKE_PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
add_module(${PROJECT_NAME})
hpr_add_library(${PROJECT_NAME} STATIC)
file(GLOB ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS
"../io.hpp" "*.hpp"
hpr_collect_interface(${PROJECT_NAME}
"../io.hpp"
"*.hpp"
)
foreach(_header_path ${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS})
list(APPEND ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE "$<BUILD_INTERFACE:${_header_path}>")
endforeach()
file(GLOB ${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_SOURCES
hpr_collect_sources(${PROJECT_NAME}
"*.cpp"
)
target_sources(${PROJECT_NAME}
INTERFACE
${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_HEADERS_INTERFACE}
$<INSTALL_INTERFACE:include/${CMAKE_PROJECT_NAME}/${PROJECT_NAME}>
PRIVATE
${${CMAKE_PROJECT_NAME}_${PROJECT_NAME}_SOURCES}
)
install(
TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_SKIP
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
EXPORT ${PROJECT_NAME}Targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CMAKE_PROJECT_NAME}-${HPR_PROJECT_VERSION}
NAMESPACE ${CMAKE_PROJECT_NAME}::
)
install(
TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}
NAMELINK_ONLY
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
DIRECTORY ${PROJECT_SOURCE_DIR}
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
FILES_MATCHING
PATTERN "*.h"
PATTERN "*.hpp"
PATTERN "tests" EXCLUDE
)
install(
FILES ../${PROJECT_NAME}.hpp
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_PROJECT_NAME}
COMPONENT devel
INTERFACE ${${PROJECT_NAME}_HEADERS_INTERFACE} ${HPR_INSTALL_INTERFACE}/${PROJECT_NAME}>
PRIVATE ${${PROJECT_NAME}_SOURCES}
)
if(HPR_TEST)
add_subdirectory(tests)
endif()
hpr_install(${PROJECT_NAME} ${PROJECT_SOURCE_DIR})
hpr_tests(${PROJECT_NAME} tests)

View File

@ -1,5 +1,5 @@
#include "file.hpp"
#include <hpr/io/file.hpp>
namespace hpr

View File

@ -1,17 +1,17 @@
#pragma once
#include "../containers/array.hpp"
#include <iostream>
#include <memory>
#include <sstream>
#include <vector>
#include <array>
#include <source_location>
#include <fstream>
#include <filesystem>
namespace hpr
namespace hpr::logging
{
namespace logging
{
enum Severity
{
Emergency,
@ -31,7 +31,7 @@ namespace logging
protected:
Severity p_severity;
std::string_view p_message;
std::string p_message;
public:
@ -45,13 +45,19 @@ namespace logging
p_message {}
{}
void addMessage(const std::string_view& message)
void addMessage(const std::string& message)
{
p_message = message;
}
virtual
void flush() = 0;
/*{
p_message.clear();
}*/
virtual
Sink* clone() const = 0;
virtual
@ -75,19 +81,101 @@ namespace logging
void flush() override
{
if (p_severity < Error)
std::cerr << p_message << "\n";
if (p_severity < Debug)
std::cout << p_message << "\n";
if (p_severity <= Error)
std::cerr << p_message;// << "\n";
if (p_severity > Error && p_severity <= Debug)
std::cout << p_message;// << "\n";
std::cout.flush();
//p_message.clear();
}
StandardOutput* clone() const override
{
return new StandardOutput(*this);
}
~StandardOutput() override = default;
};
enum class LoggerState
class FileOutput : public Sink
{
protected:
std::string p_filename;
static std::mutex mutex;
public:
FileOutput() = delete;
FileOutput(Severity severity, const std::string& filename) :
Sink {severity},
p_filename {filename}
{}
void flush() override
{
auto path = std::filesystem::canonical(std::filesystem::path(p_filename));
std::ofstream sf {path, std::ios::app};
if (!sf.is_open())
throw std::runtime_error("Failed to open file");
else
{
std::lock_guard<std::mutex> lock(mutex);
sf << p_message;
}
}
FileOutput* clone() const override
{
return new FileOutput(*this);
}
~FileOutput() override = default;
};
std::mutex FileOutput::mutex;
class DumbassOutput : public Sink
{
public:
DumbassOutput() :
Sink()
{}
explicit
DumbassOutput(Severity severity) :
Sink(severity)
{}
void flush() override
{
std::cout << "BLUAARUARA";// << "\n";
std::cout.flush();
p_message.clear();
}
DumbassOutput* clone() const override
{
return new DumbassOutput(*this);
}
~DumbassOutput() override = default;
};
class Logger
{
public:
enum class State
{
Endline,
Flush,
@ -95,180 +183,372 @@ namespace logging
Exit
};
class Logger
{
static Logger g_instance;
static darray<Sink*> g_sinks;
private:
static std::mutex mutex;
protected:
Severity p_severity;
std::ostringstream p_stream;
int p_exitcode;
sarray<std::string, 8> p_levelNames;
darray<std::string> p_buffer;
protected:
Logger() :
p_severity {Emergency},
p_stream {},
p_exitcode {-1},
p_levelNames { "Emergency", "Alert", "Critical", "Error", "Warning", "Notice", "Info", "Debug"}
{}
static Logger& instance()
{
return g_instance;
}
std::array<std::string, 8> p_levelNames;
std::vector<Sink*> p_sinks;
std::source_location p_location;
bool p_isGlobal;
std::string p_format;
public:
static void destroy()
Logger() :
p_severity {Emergency},
p_stream {"", std::ios::out | std::ios::ate },
p_exitcode {-1},
p_levelNames { "Emergency", "Alert", "Critical", "Error", "Warning", "Notice", "Info", "Debug"},
p_sinks {},
p_location {},
p_isGlobal {false},
p_format {"{levelname}({location}): {message}"}
{}
explicit
Logger(Severity severity) :
p_severity {severity},
p_stream {},
p_exitcode {-1},
p_levelNames { "Emergency", "Alert", "Critical", "Error", "Warning", "Notice", "Info", "Debug"},
p_sinks {},
p_location {},
p_isGlobal {false},
p_format {"{levelname}: {filename}:{location}: {message}"}
{}
Logger(const Logger& logger)
{
for (Sink* sink : g_sinks)
copy(*this, logger);
}
Logger& operator=(const Logger& logger)
{
copy(*this, logger);
return *this;
}
virtual
~Logger()
{
for (auto& sink : p_sinks)
delete sink;
g_sinks.clear();
}
static darray<Sink*>& sinks()
inline
void severity(Severity severity)
{
return g_sinks;
p_severity = severity;
}
static void addSink(Sink* sink)
inline
Severity severity()
{
return p_severity;
}
inline
std::string stream()
{
return p_stream.str();
}
inline
void levelname(Severity severity, const std::string& name)
{
p_levelNames[severity] = name;
}
inline
std::string levelname(Severity severity)
{
return p_levelNames[severity];
}
inline
void location(const std::source_location& location)
{
p_location = location;
}
inline
std::source_location location()
{
return p_location;
}
inline
void format(const std::string& format)
{
p_format = format;
}
inline
std::string format()
{
return p_format;
}
inline
const std::vector<Sink*>& sinks()
{
return p_sinks;
}
inline
void addSink(Sink* sink)
{
if (sink != nullptr)
g_sinks.push(sink);
}
static Severity severity()
{
return g_instance.p_severity;
p_sinks.push_back(sink->clone());
//p_sinks.push_back(new T());
//*p_sinks.back() = *sink;
//p_sinks.emplace_back();
//p_sinks.back() = reinterpret_cast<Sink *>(&sink);
}
}
static void severity(Severity severity)
inline
void removeSink(std::size_t n)
{
g_instance.p_severity = severity;
p_sinks.erase(p_sinks.begin() + n);
}
// begin functions
friend
std::ostringstream&& log(Severity severity);
inline
Sink* defaultSink()
{
return new StandardOutput(p_severity);
}
// end functions
friend
LoggerState endl();
friend
LoggerState flush();
friend
LoggerState exception();
friend
LoggerState exit(int code);
//
friend
std::ostream& operator<<(std::ostream& stream, const LoggerState& state);
std::string formatMessage(const std::string& message)
{
auto replace = [](std::string& lhs, const std::string& rep, const std::string& replacement)
{
std::size_t index = 0;
while ((index = lhs.find(rep, index)) != std::string::npos)
{
lhs.replace(index, rep.length(), replacement);
index += replacement.length();
}
return lhs;
};
//
Logger Logger::g_instance;
darray<Sink*> Logger::g_sinks;
std::string target = p_format;
target = replace(target, "{levelname}", p_levelNames[p_severity]);
target = replace(target, "{location}", std::to_string(p_location.line()));
target = replace(target, "{function}", p_location.function_name());
target = replace(target, "{filename}", p_location.file_name());
target = replace(target, "{message}", message);
//
std::ostringstream&& log(Severity severity)
{
Logger& instance = Logger::instance();
instance.p_severity = severity;
//std::ostringstream oss;
//return instance.p_stream;
return std::move(std::ostringstream());// oss;//std::forward(oss);
return target;
}
std::ostringstream&& error()
template <class T>
Logger& operator<<(const T& message)
{
return log(Error);
if constexpr (std::is_same_v<T, State>)
{
//std::lock_guard<std::mutex> lock(mutex);
if (message >= State::Endline)
{
p_stream << "\n";
}
//
LoggerState endl()
if (message >= State::Flush)
{
return LoggerState::Endline;
}
std::string formattedMessage = formatMessage(p_stream.str());
LoggerState flush()
if (p_sinks.empty())
{
return LoggerState::Flush;
}
LoggerState exception()
{
return LoggerState::Exception;
}
LoggerState exit(int code)
{
Logger& instance = Logger::instance();
instance.p_exitcode = code;
return LoggerState::Exit;
}
std::ostream& operator<<(std::ostream& stream, const LoggerState& state)
{
stream << std::endl;
std::ostringstream oss;
oss << stream.rdbuf();
std::string test = oss.str();
std::cout << test << std::endl;
//static std::mutex mtx;
//std::lock_guard<std::mutex> lock(mtx);
Logger& instance = Logger::instance();
if (state >= LoggerState::Endline)
{
stream << "\n";
}
//instance.p_stream << stream.rdbuf();
if (state >= LoggerState::Flush)
{
// default sink
if (Logger::sinks().is_empty())
{
std::unique_ptr<Sink> sink = std::make_unique<StandardOutput>(Logger::severity());
sink->addMessage(oss.str());
std::cout << "default sink" << std::endl;
Sink* sink = defaultSink();
sink->addMessage(formattedMessage);
sink->flush();
//delete sink;
delete sink;
}
// global sinks
for (Sink* sink : Logger::sinks())
else
{
sink->addMessage(oss.str());
std::cout << "local sinks" << std::endl;
for (auto& sink : p_sinks)
{
if (sink != nullptr)
{
sink->addMessage(formattedMessage);
sink->flush();
}
}
}
if (state == LoggerState::Exception)
p_stream.flush();
}
if (message == State::Exception)
{
throw std::runtime_error(oss.str());
throw std::runtime_error(p_stream.str());
}
if (state == LoggerState::Exit)
if (message == State::Exit)
{
std::exit(instance.p_exitcode);
std::exit(p_exitcode);
}
//instance.p_stream.flush();
return stream;
}
else
{
std::lock_guard<std::mutex> lock(mutex);
p_stream << message;
}
return *this;
}
friend inline
Logger log(Severity severity, std::source_location location);
public:
static void copy(Logger& lhs, const Logger& rhs)
{
lhs.p_severity = rhs.p_severity;
lhs.p_stream.flush();
lhs.p_stream << rhs.p_stream.str();
lhs.p_exitcode = rhs.p_exitcode;
lhs.p_levelNames = rhs.p_levelNames;
lhs.p_isGlobal = false;
lhs.p_location = rhs.p_location;
lhs.p_format = rhs.p_format;
if (!rhs.p_sinks.empty())
{
lhs.p_sinks.reserve(rhs.p_sinks.size());
for (const auto& sink : rhs.p_sinks)
{
lhs.p_sinks.push_back(sink->clone());
//*lhs.p_sinks.back() = *sink;
//lhs.p_sinks.push_back(std::unique_ptr<Sink>(sink));
}
}
}
private:
static std::shared_ptr<Logger> globalLogger;
public:
friend inline
void create();
friend inline
void destroy();
friend inline
std::shared_ptr<Logger>& get();
};
std::shared_ptr<Logger> Logger::globalLogger;
std::mutex Logger::mutex;
inline
Logger::State flush()
{
return Logger::State::Flush;
}
inline
Logger log(Severity severity, std::source_location location = std::source_location::current())
{
if (Logger::globalLogger != nullptr)
{
Logger::globalLogger->severity(severity);
Logger logger = *Logger::globalLogger;
logger.location(location);
return logger;
}
else
{
Logger logger = Logger(severity);
logger.location(location);
return logger;
}
}
inline
void create()
{
Logger::globalLogger = std::make_shared<Logger>();
Logger::globalLogger->p_isGlobal = true;
}
inline
void destroy()
{
if (Logger::globalLogger != nullptr)
Logger::globalLogger.reset();
}
inline
std::shared_ptr<Logger>& get()
{
return Logger::globalLogger;
}
inline
Logger emergency(std::source_location location = std::source_location::current())
{
return log(Emergency, location);
}
inline
Logger alert(std::source_location location = std::source_location::current())
{
return log(Alert, location);
}
inline
Logger critical(std::source_location location = std::source_location::current())
{
return log(Critical, location);
}
inline
Logger error(std::source_location location = std::source_location::current())
{
return log(Error, location);
}
inline
Logger warning(std::source_location location = std::source_location::current())
{
return log(Warning, location);
}
inline
Logger notice(std::source_location location = std::source_location::current())
{
return log(Notice, location);
}
inline
Logger info(std::source_location location = std::source_location::current())
{
return log(Info, location);
}
inline
Logger debug(std::source_location location = std::source_location::current())
{
return log(Debug, location);
}
}

View File

@ -1,14 +0,0 @@
file(GLOB tests_cpp "*.cpp")
add_executable(${PROJECT_NAME}-tests
${tests_cpp}
)
target_link_libraries(${PROJECT_NAME}-tests
PUBLIC
hpr::${PROJECT_NAME}
PRIVATE
GTest::gtest_main
)
gtest_add_tests(TARGET ${PROJECT_NAME}-tests)

View File

@ -1,8 +1,9 @@
#include <gtest/gtest.h>
#include "../logger.hpp"
#include <hpr/io/logger.hpp>
#include <thread>
void task1()
{
using namespace hpr;

Some files were not shown because too many files have changed in this diff Show More