From 04ab1a3420b46af046a898ee5510e0d9b25ed24c Mon Sep 17 00:00:00 2001 From: LaG1924 <12997935+LaG1924@users.noreply.github.com> Date: Sun, 27 Aug 2017 20:24:28 +0500 Subject: 2017-08-27 --- CMakeLists.txt | 44 +- cmake/FindSDL2_net.cmake | 88 ++ cwd/shaders/gui.fs | 21 + cwd/shaders/gui.vs | 27 + depedencies/include/mpark/config.hpp | 69 -- depedencies/include/mpark/in_place.hpp | 35 - depedencies/include/mpark/lib.hpp | 453 -------- depedencies/include/mpark/variant.hpp | 1827 -------------------------------- src/Block.hpp | 5 + src/Render.cpp | 178 ++-- src/Render.hpp | 6 +- src/Renderer.hpp | 11 +- src/RendererSection.cpp | 120 +-- src/RendererSection.hpp | 23 +- src/RendererWidget.cpp | 76 ++ src/RendererWidget.hpp | 15 + src/RendererWorld.cpp | 8 +- src/RendererWorld.hpp | 2 - src/Section.cpp | 267 ++--- src/Section.hpp | 44 +- src/Socket.cpp | 43 +- src/Socket.hpp | 8 +- src/Stream.cpp | 5 +- src/Widget.cpp | 124 +++ src/Widget.hpp | 74 ++ src/World.cpp | 65 +- src/World.hpp | 8 +- src/main.cpp | 17 +- 28 files changed, 803 insertions(+), 2860 deletions(-) create mode 100644 cmake/FindSDL2_net.cmake create mode 100644 cwd/shaders/gui.fs create mode 100644 cwd/shaders/gui.vs delete mode 100644 depedencies/include/mpark/config.hpp delete mode 100644 depedencies/include/mpark/in_place.hpp delete mode 100644 depedencies/include/mpark/lib.hpp delete mode 100644 depedencies/include/mpark/variant.hpp create mode 100644 src/RendererWidget.cpp create mode 100644 src/RendererWidget.hpp create mode 100644 src/Widget.cpp create mode 100644 src/Widget.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5655cd8..417efab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,8 @@ cmake_minimum_required(VERSION 3.8) project(AltCraft) set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) include(externalProject) @@ -26,7 +28,7 @@ add_definitions(${LOGGER_DEFINITIONS}) #Set compiler's flags and setup platfrom-dependent libraries if (CMAKE_COMPILER_IS_GNUCXX) - #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Wextra -Werror") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Wextra -Werror") #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0") #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3") #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address") @@ -34,6 +36,11 @@ if (CMAKE_COMPILER_IS_GNUCXX) #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -p") set(PLATFORM_LIBRARIES "pthread" "stdc++fs") endif () + +if(MSVC) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++17") +endif(MSVC) + target_link_libraries(AltCraft ${PLATFORM_LIBRARIES}) ############ @@ -45,29 +52,28 @@ add_subdirectory(depedencies) target_include_directories(AltCraft PUBLIC ./depedencies/include) target_link_libraries(AltCraft deps) -#Setup SFML -set (SFML_ROOT "${CMAKE_SOURCE_DIR}/external/SFML") -find_package(SFML 2.3 COMPONENTS system window graphics network REQUIRED) -if (SFML_FOUND) - target_link_libraries(AltCraft ${SFML_LIBRARIES}) - target_include_directories(AltCraft PUBLIC ${SFML_INCLUDE_DIR}) -else () - message(FATAL_ERROR "SFML not found!") -endif () +#Setup SDL2 +find_package(SDL2 REQUIRED) +target_link_libraries(AltCraft ${SDL2_LIBRARY}) +target_include_directories(AltCraft PUBLIC ${SDL2_INCLUDE_DIR}) + +#Setup SDL2_net +find_package(SDL2_net REQUIRED) +target_link_libraries(AltCraft ${SDL2_NET_LIBRARIES}) +target_include_directories(AltCraft PUBLIC ${SDL2_NET_INCLUDE_DIRS}) #Setup SFML -#add_subdirectory(external/SFML) -#target_include_directories(AltCraft PUBLIC external/SFML/include) -#target_link_libraries(AltCraft sfml-main sfml-system sfml-network sfml-window sfml-graphics) +set (SFML_ROOT "c:/dev/vcpkg/installed/x86-windows/") +find_package(SFML 2.3 COMPONENTS system window graphics network REQUIRED) +target_link_libraries(AltCraft ${SFML_LIBRARIES}) +target_include_directories(AltCraft PUBLIC ${SFML_INCLUDE_DIR}) #Setup OpenGL find_package(OpenGL REQUIRED) -if (OPENGL_FOUND) - target_link_libraries(AltCraft ${OPENGL_LIBRARIES}) - target_include_directories(AltCraft PUBLIC ${OPENGL_INCLUDE_DIRS}) -else () - message(FATAL_ERROR "OpenGL not found!") -endif () +target_link_libraries(AltCraft ${OPENGL_LIBRARIES}) +target_include_directories(AltCraft PUBLIC ${OPENGL_INCLUDE_DIRS}) + + ################# # COPY RESOURCES diff --git a/cmake/FindSDL2_net.cmake b/cmake/FindSDL2_net.cmake new file mode 100644 index 0000000..2ad6b9b --- /dev/null +++ b/cmake/FindSDL2_net.cmake @@ -0,0 +1,88 @@ +# - Locate SDL2_net library +# This module defines: +# SDL2_NET_LIBRARIES, the name of the library to link against +# SDL2_NET_INCLUDE_DIRS, where to find the headers +# SDL2_NET_FOUND, if false, do not try to link against +# SDL2_NET_VERSION_STRING - human-readable string containing the version of SDL2_net +# +# For backward compatiblity the following variables are also set: +# SDLNET_LIBRARY (same value as SDL2_NET_LIBRARIES) +# SDLNET_INCLUDE_DIR (same value as SDL2_NET_INCLUDE_DIRS) +# SDLNET_FOUND (same value as SDL2_NET_FOUND) +# +# $SDLDIR is an environment variable that would +# correspond to the ./configure --prefix=$SDLDIR +# used in building SDL. +# +# Created by Eric Wing. This was influenced by the FindSDL.cmake +# module, but with modifications to recognize OS X frameworks and +# additional Unix paths (FreeBSD, etc). + +#============================================================================= +# Copyright 2005-2009 Kitware, Inc. +# Copyright 2012 Benjamin Eikel +# +# Distributed under the OSI-approved BSD License (the "License"); +# see accompanying file Copyright.txt for details. +# +# This software is distributed WITHOUT ANY WARRANTY; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the License for more information. +#============================================================================= +# (To distribute this file outside of CMake, substitute the full +# License text for the above reference.) + +if(NOT SDL2_NET_INCLUDE_DIR AND SDLNET_INCLUDE_DIR) + set(SDL2_NET_INCLUDE_DIR ${SDLNET_INCLUDE_DIR} CACHE PATH "directory cache +entry initialized from old variable name") +endif() +find_path(SDL2_NET_INCLUDE_DIR SDL_net.h + HINTS + ENV SDLNETDIR + ENV SDLDIR + PATH_SUFFIXES include/SDL2 include/SDL2.0 include +) + +if(NOT SDL2_NET_LIBRARY AND SDLNET_LIBRARY) + set(SDL2_NET_LIBRARY ${SDLNET_LIBRARY} CACHE FILEPATH "file cache entry +initialized from old variable name") +endif() +find_library(SDL2_NET_LIBRARY + NAMES SDL2_net + HINTS + ENV SDLNETDIR + ENV SDLDIR + PATH_SUFFIXES lib +) + +if(SDL2_NET_INCLUDE_DIR AND EXISTS "${SDL2_NET_INCLUDE_DIR}/SDL2_net.h") + file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL2_net.h" SDL2_NET_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL2_NET_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL2_net.h" SDL2_NET_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL2_NET_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL2_net.h" SDL2_NET_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL2_NET_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL2_NET_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_MAJOR "${SDL2_NET_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL2_NET_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_MINOR "${SDL2_NET_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL2_NET_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_PATCH "${SDL2_NET_VERSION_PATCH_LINE}") + set(SDL2_NET_VERSION_STRING ${SDL2_NET_VERSION_MAJOR}.${SDL2_NET_VERSION_MINOR}.${SDL2_NET_VERSION_PATCH}) + unset(SDL2_NET_VERSION_MAJOR_LINE) + unset(SDL2_NET_VERSION_MINOR_LINE) + unset(SDL2_NET_VERSION_PATCH_LINE) + unset(SDL2_NET_VERSION_MAJOR) + unset(SDL2_NET_VERSION_MINOR) + unset(SDL2_NET_VERSION_PATCH) +endif() + +set(SDL2_NET_LIBRARIES ${SDL2_NET_LIBRARY}) +set(SDL2_NET_INCLUDE_DIRS ${SDL2_NET_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_net + REQUIRED_VARS SDL2_NET_LIBRARIES SDL2_NET_INCLUDE_DIRS + VERSION_VAR SDL2_NET_VERSION_STRING) + +# for backward compatiblity +set(SDLNET_LIBRARY ${SDL2_NET_LIBRARIES}) +set(SDLNET_INCLUDE_DIR ${SDL2_NET_INCLUDE_DIRS}) +set(SDLNET_FOUND ${SDL2_NET_FOUND}) + +mark_as_advanced(SDL2_NET_LIBRARY SDL2_NET_INCLUDE_DIR) \ No newline at end of file diff --git a/cwd/shaders/gui.fs b/cwd/shaders/gui.fs new file mode 100644 index 0000000..95196b9 --- /dev/null +++ b/cwd/shaders/gui.fs @@ -0,0 +1,21 @@ +#version 330 core + +in vec2 uv; + +uniform vec4 widgetTexture; +uniform sampler2D textureAtlas; + +vec2 TransformTextureCoord(vec4 TextureAtlasCoords, vec2 UvCoords) { + float x = TextureAtlasCoords.x; + float y = TextureAtlasCoords.y; + float w = TextureAtlasCoords.z; + float h = TextureAtlasCoords.w; + vec2 A = vec2(x, 1 - y - h); + vec2 B = vec2(x + w, 1 - y); + return A + UvCoords * (B - A); +} + +void main(){ + vec4 color = texture(textureAtlas,TransformTextureCoord(widgetTexture,uv)); + gl_FragColor = color; +} \ No newline at end of file diff --git a/cwd/shaders/gui.vs b/cwd/shaders/gui.vs new file mode 100644 index 0000000..b6f848b --- /dev/null +++ b/cwd/shaders/gui.vs @@ -0,0 +1,27 @@ +#version 330 core + +uniform vec4 transform; + +layout (location = 0) in vec3 position; +layout (location = 1) in vec2 UvCoordinates; + +out vec2 uv; + +vec2 TransfromWidgetCoord() { + vec2 origin = vec2((transform.x * 2.0f) - 1.0f, (0.5 - transform.y) * 2.0f); + + float x = transform.x; + float y = transform.y; + float w = transform.z; + float h = transform.w; + vec2 A = vec2(x, 1 - y - h); + vec2 B = vec2(x + w, 1 - y); + vec2 ret = vec2(A + position.xy * (B - A)); + return vec2(ret.x-1.0f,ret.y); +} + +void main(){ + uv = UvCoordinates; + + gl_Position = vec4(TransfromWidgetCoord(),0,1); +} \ No newline at end of file diff --git a/depedencies/include/mpark/config.hpp b/depedencies/include/mpark/config.hpp deleted file mode 100644 index b5706b2..0000000 --- a/depedencies/include/mpark/config.hpp +++ /dev/null @@ -1,69 +0,0 @@ -// MPark.Variant -// -// Copyright Michael Park, 2015-2017 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) - -#ifndef MPARK_CONFIG_HPP -#define MPARK_CONFIG_HPP - -// MSVC 2015 Update 3. -#if __cplusplus < 201103L && (!defined(_MSC_VER) || _MSC_FULL_VER < 190024215) -#error "MPark.Variant requires C++11 support." -#endif - -#ifndef __has_builtin -#define __has_builtin(x) 0 -#endif - -#ifndef __has_include -#define __has_include(x) 0 -#endif - -#ifndef __has_feature -#define __has_feature(x) 0 -#endif - -#if __has_builtin(__builtin_addressof) || \ - (defined(__GNUC__) && __GNUC__ >= 7) || defined(_MSC_VER) -#define MPARK_BUILTIN_ADDRESSOF -#endif - -#if __has_builtin(__type_pack_element) -#define MPARK_TYPE_PACK_ELEMENT -#endif - -#if defined(__cpp_constexpr) && __cpp_constexpr >= 201304 -#define MPARK_CPP14_CONSTEXPR -#endif - -#if __has_feature(cxx_exceptions) || defined(__cpp_exceptions) -#define MPARK_EXCEPTIONS -#endif - -#if defined(__cpp_generic_lambdas) || defined(_MSC_VER) -#define MPARK_GENERIC_LAMBDAS -#endif - -#if defined(__cpp_lib_integer_sequence) -#define MPARK_INTEGER_SEQUENCE -#endif - -#if defined(__cpp_return_type_deduction) || defined(_MSC_VER) -#define MPARK_RETURN_TYPE_DEDUCTION -#endif - -#if defined(__cpp_lib_transparent_operators) || defined(_MSC_VER) -#define MPARK_TRANSPARENT_OPERATORS -#endif - -#if defined(__cpp_variable_templates) || defined(_MSC_VER) -#define MPARK_VARIABLE_TEMPLATES -#endif - -#if !defined(__GLIBCXX__) || __has_include() // >= libstdc++-5 -#define MPARK_TRIVIALITY_TYPE_TRAITS -#endif - -#endif // MPARK_CONFIG_HPP diff --git a/depedencies/include/mpark/in_place.hpp b/depedencies/include/mpark/in_place.hpp deleted file mode 100644 index 56cae13..0000000 --- a/depedencies/include/mpark/in_place.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// MPark.Variant -// -// Copyright Michael Park, 2015-2017 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) - -#ifndef MPARK_IN_PLACE_HPP -#define MPARK_IN_PLACE_HPP - -#include - -#include "config.hpp" - -namespace mpark { - - struct in_place_t { explicit in_place_t() = default; }; - - template - struct in_place_index_t { explicit in_place_index_t() = default; }; - - template - struct in_place_type_t { explicit in_place_type_t() = default; }; - -#ifdef MPARK_VARIABLE_TEMPLATES - constexpr in_place_t in_place{}; - - template constexpr in_place_index_t in_place_index{}; - - template constexpr in_place_type_t in_place_type{}; -#endif - -} // namespace mpark - -#endif // MPARK_IN_PLACE_HPP diff --git a/depedencies/include/mpark/lib.hpp b/depedencies/include/mpark/lib.hpp deleted file mode 100644 index bba58d8..0000000 --- a/depedencies/include/mpark/lib.hpp +++ /dev/null @@ -1,453 +0,0 @@ -// MPark.Variant -// -// Copyright Michael Park, 2015-2017 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) - -#ifndef MPARK_LIB_HPP -#define MPARK_LIB_HPP - -#include -#include -#include -#include - -#include "config.hpp" - -#define RETURN(...) \ - noexcept(noexcept(__VA_ARGS__)) -> decltype(__VA_ARGS__) { \ - return __VA_ARGS__; \ - } - -namespace mpark { - namespace lib { - template - struct identity { using type = T; }; - - inline namespace cpp14 { - template - struct array { - constexpr const T &operator[](std::size_t index) const { - return data[index]; - } - - T data[N == 0 ? 1 : N]; - }; - - template - using add_pointer_t = typename std::add_pointer::type; - - template - using common_type_t = typename std::common_type::type; - - template - using decay_t = typename std::decay::type; - - template - using enable_if_t = typename std::enable_if::type; - - template - using remove_const_t = typename std::remove_const::type; - - template - using remove_reference_t = typename std::remove_reference::type; - - template - inline constexpr T &&forward(remove_reference_t &t) noexcept { - return static_cast(t); - } - - template - inline constexpr T &&forward(remove_reference_t &&t) noexcept { - static_assert(!std::is_lvalue_reference::value, - "can not forward an rvalue as an lvalue"); - return static_cast(t); - } - - template - inline constexpr remove_reference_t &&move(T &&t) noexcept { - return static_cast &&>(t); - } - -#ifdef MPARK_INTEGER_SEQUENCE - template - using integer_sequence = std::integer_sequence; - - template - using index_sequence = std::index_sequence; - - template - using make_index_sequence = std::make_index_sequence; - - template - using index_sequence_for = std::index_sequence_for; -#else - template - struct integer_sequence { - using value_type = T; - static constexpr std::size_t size() noexcept { return sizeof...(Is); } - }; - - template - using index_sequence = integer_sequence; - - template - struct make_index_sequence_concat; - - template - struct make_index_sequence_concat, - index_sequence> - : identity> {}; - - template - struct make_index_sequence_impl; - - template - using make_index_sequence = typename make_index_sequence_impl::type; - - template - struct make_index_sequence_impl - : make_index_sequence_concat, - make_index_sequence> {}; - - template <> - struct make_index_sequence_impl<0> : identity> {}; - - template <> - struct make_index_sequence_impl<1> : identity> {}; - - template - using index_sequence_for = make_index_sequence; -#endif - - // -#ifdef MPARK_TRANSPARENT_OPERATORS - using equal_to = std::equal_to<>; -#else - struct equal_to { - template - inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const - RETURN(lib::forward(lhs) == lib::forward(rhs)) - }; -#endif - -#ifdef MPARK_TRANSPARENT_OPERATORS - using not_equal_to = std::not_equal_to<>; -#else - struct not_equal_to { - template - inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const - RETURN(lib::forward(lhs) != lib::forward(rhs)) - }; -#endif - -#ifdef MPARK_TRANSPARENT_OPERATORS - using less = std::less<>; -#else - struct less { - template - inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const - RETURN(lib::forward(lhs) < lib::forward(rhs)) - }; -#endif - -#ifdef MPARK_TRANSPARENT_OPERATORS - using greater = std::greater<>; -#else - struct greater { - template - inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const - RETURN(lib::forward(lhs) > lib::forward(rhs)) - }; -#endif - -#ifdef MPARK_TRANSPARENT_OPERATORS - using less_equal = std::less_equal<>; -#else - struct less_equal { - template - inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const - RETURN(lib::forward(lhs) <= lib::forward(rhs)) - }; -#endif - -#ifdef MPARK_TRANSPARENT_OPERATORS - using greater_equal = std::greater_equal<>; -#else - struct greater_equal { - template - inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const - RETURN(lib::forward(lhs) >= lib::forward(rhs)) - }; -#endif - } // namespace cpp14 - - inline namespace cpp17 { - - // - template - using bool_constant = std::integral_constant; - - template - struct voider : identity {}; - - template - using void_t = typename voider::type; - - namespace detail { - namespace swappable { - - using std::swap; - - template - struct is_swappable_impl { - private: - template (), - std::declval()))> - inline static std::true_type test(int); - - template - inline static std::false_type test(...); - - public: - using type = decltype(test(0)); - }; - - template - using is_swappable = typename is_swappable_impl::type; - - template ::value> - struct is_nothrow_swappable { - static constexpr bool value = - noexcept(swap(std::declval(), std::declval())); - }; - - template - struct is_nothrow_swappable : std::false_type {}; - - } // namespace swappable - } // namespace detail - - template - using is_swappable = detail::swappable::is_swappable; - - template - using is_nothrow_swappable = detail::swappable::is_nothrow_swappable; - - // -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4100) -#endif - template - inline constexpr auto invoke(F &&f, As &&... as) - RETURN(lib::forward(f)(lib::forward(as)...)) -#ifdef _MSC_VER -#pragma warning(pop) -#endif - - template - inline constexpr auto invoke(T B::*pmv, D &&d) - RETURN(lib::forward(d).*pmv) - - template - inline constexpr auto invoke(Pmv pmv, Ptr &&ptr) - RETURN((*lib::forward(ptr)).*pmv) - - template - inline constexpr auto invoke(T B::*pmf, D &&d, As &&... as) - RETURN((lib::forward(d).*pmf)(lib::forward(as)...)) - - template - inline constexpr auto invoke(Pmf pmf, Ptr &&ptr, As &&... as) - RETURN(((*lib::forward(ptr)).*pmf)(lib::forward(as)...)) - - namespace detail { - - template - struct invoke_result {}; - - template - struct invoke_result(), std::declval()...))>, - F, - Args...> - : identity(), std::declval()...))> {}; - - } // namespace detail - - template - using invoke_result = detail::invoke_result; - - template - using invoke_result_t = typename invoke_result::type; - - namespace detail { - - template - struct is_invocable : std::false_type {}; - - template - struct is_invocable>, F, Args...> - : std::true_type {}; - - template - struct is_invocable_r : std::false_type {}; - - template - struct is_invocable_r>, - R, - F, - Args...> - : std::is_convertible, R> {}; - - } // namespace detail - - template - using is_invocable = detail::is_invocable; - - template - using is_invocable_r = detail::is_invocable_r; - - // -#ifdef MPARK_BUILTIN_ADDRESSOF - template - inline constexpr T *addressof(T &arg) { - return __builtin_addressof(arg); - } -#else - namespace detail { - - namespace has_addressof_impl { - - struct fail; - - template - inline fail operator&(T &&); - - template - inline static constexpr bool impl() { - return (std::is_class::value || std::is_union::value) && - !std::is_same()), fail>::value; - } - - } // namespace has_addressof_impl - - template - using has_addressof = bool_constant()>; - - template - inline constexpr T *addressof(T &arg, std::true_type) { - return std::addressof(arg); - } - - template - inline constexpr T *addressof(T &arg, std::false_type) { - return &arg; - } - - } // namespace detail - - template - inline constexpr T *addressof(T &arg) { - return detail::addressof(arg, detail::has_addressof{}); - } -#endif - - template - inline constexpr T *addressof(const T &&) = delete; - - } // namespace cpp17 - - template - struct remove_all_extents : identity {}; - - template - struct remove_all_extents> : remove_all_extents {}; - - template - using remove_all_extents_t = typename remove_all_extents::type; - - template - using size_constant = std::integral_constant; - - template - using bool_sequence = integer_sequence; - - template - struct indexed_type : size_constant, identity {}; - - template - using all = - std::is_same, bool_sequence>; - -#ifdef MPARK_TYPE_PACK_ELEMENT - template - using type_pack_element_t = __type_pack_element; -#else - template - struct type_pack_element_impl { - private: - template - struct set; - - template - struct set> : indexed_type... {}; - - template - inline static std::enable_if impl(indexed_type); - - inline static std::enable_if impl(...); - - public: - using type = decltype(impl(set>{})); - }; - - template - using type_pack_element = typename type_pack_element_impl::type; - - template - using type_pack_element_t = typename type_pack_element::type; -#endif - -#ifdef MPARK_TRIVIALITY_TYPE_TRAITS - template - using is_trivially_copy_constructible = - std::is_trivially_copy_constructible; - - template - using is_trivially_move_constructible = - std::is_trivially_move_constructible; - - template - using is_trivially_copy_assignable = std::is_trivially_copy_assignable; - - template - using is_trivially_move_assignable = std::is_trivially_move_assignable; -#else - template - struct is_trivially_copy_constructible - : bool_constant< - std::is_copy_constructible::value && __has_trivial_copy(T)> {}; - - template - struct is_trivially_move_constructible : bool_constant<__is_trivial(T)> {}; - - template - struct is_trivially_copy_assignable - : bool_constant< - std::is_copy_assignable::value && __has_trivial_assign(T)> {}; - - template - struct is_trivially_move_assignable : bool_constant<__is_trivial(T)> {}; -#endif - - } // namespace lib -} // namespace mpark - -#undef RETURN - -#endif // MPARK_LIB_HPP diff --git a/depedencies/include/mpark/variant.hpp b/depedencies/include/mpark/variant.hpp deleted file mode 100644 index 3faecba..0000000 --- a/depedencies/include/mpark/variant.hpp +++ /dev/null @@ -1,1827 +0,0 @@ -// MPark.Variant -// -// Copyright Michael Park, 2015-2017 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) - -#ifndef MPARK_VARIANT_HPP -#define MPARK_VARIANT_HPP - -/* - variant synopsis - -namespace std { - - // 20.7.2, class template variant - template - class variant { - public: - - // 20.7.2.1, constructors - constexpr variant() noexcept(see below); - variant(const variant&); - variant(variant&&) noexcept(see below); - - template constexpr variant(T&&) noexcept(see below); - - template - constexpr explicit variant(in_place_type_t, Args&&...); - - template - constexpr explicit variant( - in_place_type_t, initializer_list, Args&&...); - - template - constexpr explicit variant(in_place_index_t, Args&&...); - - template - constexpr explicit variant( - in_place_index_t, initializer_list, Args&&...); - - // 20.7.2.2, destructor - ~variant(); - - // 20.7.2.3, assignment - variant& operator=(const variant&); - variant& operator=(variant&&) noexcept(see below); - - template variant& operator=(T&&) noexcept(see below); - - // 20.7.2.4, modifiers - template - T& emplace(Args&&...); - - template - T& emplace(initializer_list, Args&&...); - - template - variant_alternative& emplace(Args&&...); - - template - variant_alternative& emplace(initializer_list, Args&&...); - - // 20.7.2.5, value status - constexpr bool valueless_by_exception() const noexcept; - constexpr size_t index() const noexcept; - - // 20.7.2.6, swap - void swap(variant&) noexcept(see below); - }; - - // 20.7.3, variant helper classes - template struct variant_size; // undefined - - template - constexpr size_t variant_size_v = variant_size::value; - - template struct variant_size; - template struct variant_size; - template struct variant_size; - - template - struct variant_size>; - - template struct variant_alternative; // undefined - - template - using variant_alternative_t = typename variant_alternative::type; - - template struct variant_alternative; - template struct variant_alternative; - template struct variant_alternative; - - template - struct variant_alternative>; - - constexpr size_t variant_npos = -1; - - // 20.7.4, value access - template - constexpr bool holds_alternative(const variant&) noexcept; - - template - constexpr variant_alternative_t>& - get(variant&); - - template - constexpr variant_alternative_t>&& - get(variant&&); - - template - constexpr variant_alternative_t> const& - get(const variant&); - - template - constexpr variant_alternative_t> const&& - get(const variant&&); - - template - constexpr T& get(variant&); - - template - constexpr T&& get(variant&&); - - template - constexpr const T& get(const variant&); - - template - constexpr const T&& get(const variant&&); - - template - constexpr add_pointer_t>> - get_if(variant*) noexcept; - - template - constexpr add_pointer_t>> - get_if(const variant*) noexcept; - - template - constexpr add_pointer_t - get_if(variant*) noexcept; - - template - constexpr add_pointer_t - get_if(const variant*) noexcept; - - // 20.7.5, relational operators - template - constexpr bool operator==(const variant&, const variant&); - - template - constexpr bool operator!=(const variant&, const variant&); - - template - constexpr bool operator<(const variant&, const variant&); - - template - constexpr bool operator>(const variant&, const variant&); - - template - constexpr bool operator<=(const variant&, const variant&); - - template - constexpr bool operator>=(const variant&, const variant&); - - // 20.7.6, visitation - template - constexpr see below visit(Visitor&&, Variants&&...); - - // 20.7.7, class monostate - struct monostate; - - // 20.7.8, monostate relational operators - constexpr bool operator<(monostate, monostate) noexcept; - constexpr bool operator>(monostate, monostate) noexcept; - constexpr bool operator<=(monostate, monostate) noexcept; - constexpr bool operator>=(monostate, monostate) noexcept; - constexpr bool operator==(monostate, monostate) noexcept; - constexpr bool operator!=(monostate, monostate) noexcept; - - // 20.7.9, specialized algorithms - template - void swap(variant&, variant&) noexcept(see below); - - // 20.7.10, class bad_variant_access - class bad_variant_access; - - // 20.7.11, hash support - template struct hash; - template struct hash>; - template <> struct hash; - -} // namespace std - -*/ - -#include -#include -#include -#include -#include -#include -#include - -#include "config.hpp" -#include "in_place.hpp" -#include "lib.hpp" - -namespace mpark { - -#ifdef MPARK_RETURN_TYPE_DEDUCTION - -#define AUTO auto -#define AUTO_RETURN(...) { return __VA_ARGS__; } - -#define AUTO_REFREF auto && -#define AUTO_REFREF_RETURN(...) { return __VA_ARGS__; } - -#define DECLTYPE_AUTO decltype(auto) -#define DECLTYPE_AUTO_RETURN(...) { return __VA_ARGS__; } - -#else - -#define AUTO auto -#define AUTO_RETURN(...) \ - -> lib::decay_t { return __VA_ARGS__; } - -#define AUTO_REFREF auto -#define AUTO_REFREF_RETURN(...) \ - -> decltype((__VA_ARGS__)) { \ - static_assert(std::is_reference::value, ""); \ - return __VA_ARGS__; \ - } - -#define DECLTYPE_AUTO auto -#define DECLTYPE_AUTO_RETURN(...) \ - -> decltype(__VA_ARGS__) { return __VA_ARGS__; } - -#endif - - class bad_variant_access : public std::exception { - public: - virtual const char *what() const noexcept { return "bad_variant_access"; } - }; - - [[noreturn]] inline void throw_bad_variant_access() { -#ifdef MPARK_EXCEPTIONS - throw bad_variant_access{}; -#else - std::terminate(); -#endif - } - - template - class variant; - - template - struct variant_size; - -#ifdef MPARK_VARIABLE_TEMPLATES - template - constexpr std::size_t variant_size_v = variant_size::value; -#endif - - template - struct variant_size : variant_size {}; - - template - struct variant_size : variant_size {}; - - template - struct variant_size : variant_size {}; - - template - struct variant_size> : lib::size_constant {}; - - template - struct variant_alternative; - - template - using variant_alternative_t = typename variant_alternative::type; - - template - struct variant_alternative - : std::add_const> {}; - - template - struct variant_alternative - : std::add_volatile> {}; - - template - struct variant_alternative - : std::add_cv> {}; - - template - struct variant_alternative> { - static_assert(I < sizeof...(Ts), - "Index out of bounds in std::variant_alternative<>"); - using type = lib::type_pack_element_t; - }; - - constexpr std::size_t variant_npos = static_cast(-1); - - namespace detail { - - inline constexpr bool all() { return true; } - - template - inline constexpr bool all(bool b, Bs... bs) { - return b && all(bs...); - } - - constexpr std::size_t not_found = static_cast(-1); - constexpr std::size_t ambiguous = static_cast(-2); - -#ifdef MPARK_CPP14_CONSTEXPR - template - inline constexpr std::size_t find_index() { - constexpr lib::array matches = { - {std::is_same::value...} - }; - std::size_t result = not_found; - for (std::size_t i = 0; i < sizeof...(Ts); ++i) { - if (matches[i]) { - if (result != not_found) { - return ambiguous; - } - result = i; - } - } - return result; - } -#else - inline constexpr std::size_t find_index_impl(std::size_t result, - std::size_t) { - return result; - } - - template - inline constexpr std::size_t find_index_impl(std::size_t result, - std::size_t idx, - bool b, - Bs... bs) { - return b ? (result != not_found ? ambiguous - : find_index_impl(idx, idx + 1, bs...)) - : find_index_impl(result, idx + 1, bs...); - } - - template - inline constexpr std::size_t find_index() { - return find_index_impl(not_found, 0, std::is_same::value...); - } -#endif - - template - using find_index_sfinae_impl = - lib::enable_if_t>; - - template - using find_index_sfinae = find_index_sfinae_impl()>; - - template - struct find_index_checked_impl : lib::size_constant { - static_assert(I != not_found, "the specified type is not found."); - static_assert(I != ambiguous, "the specified type is ambiguous."); - }; - - template - using find_index_checked = find_index_checked_impl()>; - - struct valueless_t {}; - - enum class Trait { TriviallyAvailable, Available, Unavailable }; - - template class IsTriviallyAvailable, - template class IsAvailable> - inline constexpr Trait trait() { - return IsTriviallyAvailable::value - ? Trait::TriviallyAvailable - : IsAvailable::value ? Trait::Available - : Trait::Unavailable; - } - -#ifdef MPARK_CPP14_CONSTEXPR - template - inline constexpr Trait common_trait(Traits... traits) { - Trait result = Trait::TriviallyAvailable; - for (Trait t : {traits...}) { - if (static_cast(t) > static_cast(result)) { - result = t; - } - } - return result; - } -#else - inline constexpr Trait common_trait_impl(Trait result) { return result; } - - template - inline constexpr Trait common_trait_impl(Trait result, - Trait t, - Traits... ts) { - return static_cast(t) > static_cast(result) - ? common_trait_impl(t, ts...) - : common_trait_impl(result, ts...); - } - - template - inline constexpr Trait common_trait(Traits... ts) { - return common_trait_impl(Trait::TriviallyAvailable, ts...); - } -#endif - - template - struct traits { - static constexpr Trait copy_constructible_trait = - common_trait(trait()...); - - static constexpr Trait move_constructible_trait = - common_trait(trait()...); - - static constexpr Trait copy_assignable_trait = - common_trait(copy_constructible_trait, - trait()...); - - static constexpr Trait move_assignable_trait = - common_trait(move_constructible_trait, - trait()...); - - static constexpr Trait destructible_trait = - common_trait(trait()...); - }; - - namespace access { - - struct recursive_union { -#ifdef MPARK_RETURN_TYPE_DEDUCTION - template - inline static constexpr auto &&get_alt(V &&v, in_place_index_t<0>) { - return lib::forward(v).head_; - } - - template - inline static constexpr auto &&get_alt(V &&v, in_place_index_t) { - return get_alt(lib::forward(v).tail_, in_place_index_t{}); - } -#else - template - struct get_alt_impl { - template - inline constexpr AUTO_REFREF operator()(V &&v) const - AUTO_REFREF_RETURN(get_alt_impl{}(lib::forward(v).tail_)) - }; - - template - struct get_alt_impl<0, Dummy> { - template - inline constexpr AUTO_REFREF operator()(V &&v) const - AUTO_REFREF_RETURN(lib::forward(v).head_) - }; - - template - inline static constexpr AUTO_REFREF get_alt(V &&v, in_place_index_t) - AUTO_REFREF_RETURN(get_alt_impl{}(lib::forward(v))) -#endif - }; - - struct base { - template - inline static constexpr AUTO_REFREF get_alt(V &&v) - AUTO_REFREF_RETURN(recursive_union::get_alt( - data(lib::forward(v)), in_place_index_t{})) - }; - - struct variant { - template - inline static constexpr AUTO_REFREF get_alt(V &&v) - AUTO_REFREF_RETURN(base::get_alt(lib::forward(v).impl_)) - }; - - } // namespace access - - namespace visitation { - - struct base { - private: - template - inline static constexpr const T &at(const T &elem) { - return elem; - } - - template - inline static constexpr const lib::remove_all_extents_t &at( - const lib::array &elems, std::size_t i, Is... is) { - return at(elems[i], is...); - } - - template - inline static constexpr int visit_visitor_return_type_check() { - static_assert(all(std::is_same::value...), - "`mpark::visit` requires the visitor to have a single " - "return type."); - return 0; - } - - template - inline static constexpr lib::array< - lib::common_type_t...>, - sizeof...(Fs)> - make_farray(Fs &&... fs) { - using result = lib::array...>, - sizeof...(Fs)>; - return visit_visitor_return_type_check...>(), - result{{lib::forward(fs)...}}; - } - - template - struct dispatcher { - template - struct impl { - inline static constexpr DECLTYPE_AUTO dispatch(F f, Vs... vs) - DECLTYPE_AUTO_RETURN(lib::invoke( - static_cast(f), - access::base::get_alt(static_cast(vs))...)) - }; - }; - - template - inline static constexpr AUTO make_dispatch(lib::index_sequence) - AUTO_RETURN(&dispatcher::template impl::dispatch) - - template - inline static constexpr AUTO make_fdiagonal_impl() - AUTO_RETURN(make_dispatch( - lib::index_sequence::value...>{})) - - template - inline static constexpr AUTO make_fdiagonal_impl( - lib::index_sequence) - AUTO_RETURN(make_farray(make_fdiagonal_impl()...)) - - template - inline static constexpr /* auto * */ auto make_fdiagonal() - -> decltype(make_fdiagonal_impl( - lib::make_index_sequence::size()>{})) { - static_assert( - all((lib::decay_t::size() == lib::decay_t::size())...), - "all of the variants must be the same size."); - return make_fdiagonal_impl( - lib::make_index_sequence::size()>{}); - } - -#ifdef MPARK_RETURN_TYPE_DEDUCTION - template - inline static constexpr auto make_fmatrix_impl( - lib::index_sequence is) { - return make_dispatch(is); - } - - template - inline static constexpr auto make_fmatrix_impl( - lib::index_sequence, lib::index_sequence, Ls... ls) { - return make_farray(make_fmatrix_impl( - lib::index_sequence{}, ls...)...); - } - - template - inline static constexpr auto make_fmatrix() { - return make_fmatrix_impl( - lib::index_sequence<>{}, - lib::make_index_sequence::size()>{}...); - } -#else - template - struct make_fmatrix_impl { - template - struct impl; - - template - struct impl> { - inline constexpr AUTO operator()() const - AUTO_RETURN( - make_dispatch(lib::index_sequence{})) - }; - - template - struct impl, - lib::index_sequence, - Ls...> { - inline constexpr AUTO operator()() const - AUTO_RETURN(make_farray( - impl, Ls...>{}()...)) - }; - }; - - template - inline static constexpr AUTO make_fmatrix() - AUTO_RETURN( - typename make_fmatrix_impl::template impl< - lib::index_sequence<>, - lib::make_index_sequence::size()>...>{}()) -#endif - - public: - template - inline static constexpr DECLTYPE_AUTO visit_alt_at(std::size_t index, - Visitor &&visitor, - Vs &&... vs) - DECLTYPE_AUTO_RETURN( - at(make_fdiagonal(vs)))...>(), - index)(lib::forward(visitor), - as_base(lib::forward(vs))...)) - - template - inline static constexpr DECLTYPE_AUTO visit_alt(Visitor &&visitor, - Vs &&... vs) - DECLTYPE_AUTO_RETURN( - at(make_fmatrix(vs)))...>(), - vs.index()...)(lib::forward(visitor), - as_base(lib::forward(vs))...)) - }; - - struct variant { - private: - template - struct visit_exhaustive_visitor_check { - static_assert( - lib::is_invocable::value, - "`mpark::visit` requires the visitor to be exhaustive."); - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4100) -#endif - inline constexpr DECLTYPE_AUTO operator()(Visitor &&visitor, - Values &&... values) const - DECLTYPE_AUTO_RETURN(lib::invoke(lib::forward(visitor), - lib::forward(values)...)) -#ifdef _MSC_VER -#pragma warning(pop) -#endif - }; - - template - struct value_visitor { - Visitor &&visitor_; - - template - inline constexpr DECLTYPE_AUTO operator()(Alts &&... alts) const - DECLTYPE_AUTO_RETURN( - visit_exhaustive_visitor_check< - Visitor, - decltype((lib::forward(alts).value))...>{}( - lib::forward(visitor_), - lib::forward(alts).value...)) - }; - - template - inline static constexpr AUTO make_value_visitor(Visitor &&visitor) - AUTO_RETURN(value_visitor{lib::forward(visitor)}) - - public: - template - inline static constexpr DECLTYPE_AUTO visit_alt_at(std::size_t index, - Visitor &&visitor, - Vs &&... vs) - DECLTYPE_AUTO_RETURN( - base::visit_alt_at(index, - lib::forward(visitor), - lib::forward(vs).impl_...)) - - template - inline static constexpr DECLTYPE_AUTO visit_alt(Visitor &&visitor, - Vs &&... vs) - DECLTYPE_AUTO_RETURN(base::visit_alt(lib::forward(visitor), - lib::forward(vs).impl_...)) - - template - inline static constexpr DECLTYPE_AUTO visit_value_at(std::size_t index, - Visitor &&visitor, - Vs &&... vs) - DECLTYPE_AUTO_RETURN( - visit_alt_at(index, - make_value_visitor(lib::forward(visitor)), - lib::forward(vs)...)) - - template - inline static constexpr DECLTYPE_AUTO visit_value(Visitor &&visitor, - Vs &&... vs) - DECLTYPE_AUTO_RETURN( - visit_alt(make_value_visitor(lib::forward(visitor)), - lib::forward(vs)...)) - }; - - } // namespace visitation - - template - struct alt { - using value_type = T; - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4244) -#endif - template - inline explicit constexpr alt(in_place_t, Args &&... args) - : value(lib::forward(args)...) {} -#ifdef _MSC_VER -#pragma warning(pop) -#endif - - T value; - }; - - template - union recursive_union; - - template - union recursive_union {}; - -#define MPARK_VARIANT_RECURSIVE_UNION(destructible_trait, destructor) \ - template \ - union recursive_union { \ - public: \ - inline explicit constexpr recursive_union(valueless_t) noexcept \ - : dummy_{} {} \ - \ - template \ - inline explicit constexpr recursive_union(in_place_index_t<0>, \ - Args &&... args) \ - : head_(in_place_t{}, lib::forward(args)...) {} \ - \ - template \ - inline explicit constexpr recursive_union(in_place_index_t, \ - Args &&... args) \ - : tail_(in_place_index_t{}, lib::forward(args)...) {} \ - \ - recursive_union(const recursive_union &) = default; \ - recursive_union(recursive_union &&) = default; \ - \ - destructor \ - \ - recursive_union &operator=(const recursive_union &) = default; \ - recursive_union &operator=(recursive_union &&) = default; \ - \ - private: \ - char dummy_; \ - alt head_; \ - recursive_union tail_; \ - \ - friend struct access::recursive_union; \ - } - - MPARK_VARIANT_RECURSIVE_UNION(Trait::TriviallyAvailable, - ~recursive_union() = default;); - MPARK_VARIANT_RECURSIVE_UNION(Trait::Available, - ~recursive_union() {}); - MPARK_VARIANT_RECURSIVE_UNION(Trait::Unavailable, - ~recursive_union() = delete;); - -#undef MPARK_VARIANT_RECURSIVE_UNION - - using index_t = unsigned int; - - template - class base { - public: - inline explicit constexpr base(valueless_t tag) noexcept - : data_(tag), index_(static_cast(-1)) {} - - template - inline explicit constexpr base(in_place_index_t, Args &&... args) - : data_(in_place_index_t{}, lib::forward(args)...), - index_(I) {} - - inline constexpr bool valueless_by_exception() const noexcept { - return index_ == static_cast(-1); - } - - inline constexpr std::size_t index() const noexcept { - return valueless_by_exception() ? variant_npos : index_; - } - - protected: - using data_t = recursive_union; - - friend inline constexpr base &as_base(base &b) { return b; } - friend inline constexpr const base &as_base(const base &b) { return b; } - friend inline constexpr base &&as_base(base &&b) { return lib::move(b); } - friend inline constexpr const base &&as_base(const base &&b) { return lib::move(b); } - - friend inline constexpr data_t &data(base &b) { return b.data_; } - friend inline constexpr const data_t &data(const base &b) { return b.data_; } - friend inline constexpr data_t &&data(base &&b) { return lib::move(b).data_; } - friend inline constexpr const data_t &&data(const base &&b) { return lib::move(b).data_; } - - inline static constexpr std::size_t size() { return sizeof...(Ts); } - - data_t data_; - index_t index_; - - friend struct access::base; - friend struct visitation::base; - }; - - struct dtor { -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4100) -#endif - template - inline void operator()(Alt &alt) const noexcept { alt.~Alt(); } -#ifdef _MSC_VER -#pragma warning(pop) -#endif - }; - -#if defined(_MSC_VER) && _MSC_VER < 1910 -#define INHERITING_CTOR(type, base) \ - template \ - inline explicit constexpr type(Args &&... args) \ - : base(lib::forward(args)...) {} -#else -#define INHERITING_CTOR(type, base) using base::base; -#endif - - template - class destructor; - -#define MPARK_VARIANT_DESTRUCTOR(destructible_trait, definition, destroy) \ - template \ - class destructor, destructible_trait> \ - : public base { \ - using super = base; \ - \ - public: \ - INHERITING_CTOR(destructor, super) \ - using super::operator=; \ - \ - destructor(const destructor &) = default; \ - destructor(destructor &&) = default; \ - definition \ - destructor &operator=(const destructor &) = default; \ - destructor &operator=(destructor &&) = default; \ - \ - protected: \ - destroy \ - } - - MPARK_VARIANT_DESTRUCTOR( - Trait::TriviallyAvailable, - ~destructor() = default;, - inline void destroy() noexcept { - this->index_ = static_cast(-1); - }); - - MPARK_VARIANT_DESTRUCTOR( - Trait::Available, - ~destructor() { destroy(); }, - inline void destroy() noexcept { - if (!this->valueless_by_exception()) { - visitation::base::visit_alt(dtor{}, *this); - } - this->index_ = static_cast(-1); - }); - - MPARK_VARIANT_DESTRUCTOR( - Trait::Unavailable, - ~destructor() = delete;, - inline void destroy() noexcept = delete;); - -#undef MPARK_VARIANT_DESTRUCTOR - - template - class constructor : public destructor { - using super = destructor; - - public: - INHERITING_CTOR(constructor, super) - using super::operator=; - - protected: -#ifndef MPARK_GENERIC_LAMBDAS - struct ctor { - template - inline void operator()(LhsAlt &lhs_alt, RhsAlt &&rhs_alt) const { - constructor::construct_alt(lhs_alt, - lib::forward(rhs_alt).value); - } - }; -#endif - - template - inline static T &construct_alt(alt &a, Args &&... args) { - ::new (static_cast(lib::addressof(a))) - alt(in_place_t{}, lib::forward(args)...); - return a.value; - } - - template - inline static void generic_construct(constructor &lhs, Rhs &&rhs) { - lhs.destroy(); - if (!rhs.valueless_by_exception()) { - visitation::base::visit_alt_at( - rhs.index(), -#ifdef MPARK_GENERIC_LAMBDAS - [](auto &lhs_alt, auto &&rhs_alt) { - constructor::construct_alt( - lhs_alt, lib::forward(rhs_alt).value); - } -#else - ctor{} -#endif - , - lhs, - lib::forward(rhs)); - lhs.index_ = rhs.index_; - } - } - }; - - template - class move_constructor; - -#define MPARK_VARIANT_MOVE_CONSTRUCTOR(move_constructible_trait, definition) \ - template \ - class move_constructor, move_constructible_trait> \ - : public constructor> { \ - using super = constructor>; \ - \ - public: \ - INHERITING_CTOR(move_constructor, super) \ - using super::operator=; \ - \ - move_constructor(const move_constructor &) = default; \ - definition \ - ~move_constructor() = default; \ - move_constructor &operator=(const move_constructor &) = default; \ - move_constructor &operator=(move_constructor &&) = default; \ - } - - MPARK_VARIANT_MOVE_CONSTRUCTOR( - Trait::TriviallyAvailable, - move_constructor(move_constructor &&that) = default;); - - MPARK_VARIANT_MOVE_CONSTRUCTOR( - Trait::Available, - move_constructor(move_constructor &&that) noexcept( - all(std::is_nothrow_move_constructible::value...)) - : move_constructor(valueless_t{}) { - this->generic_construct(*this, lib::move(that)); - }); - - MPARK_VARIANT_MOVE_CONSTRUCTOR( - Trait::Unavailable, - move_constructor(move_constructor &&) = delete;); - -#undef MPARK_VARIANT_MOVE_CONSTRUCTOR - - template - class copy_constructor; - -#define MPARK_VARIANT_COPY_CONSTRUCTOR(copy_constructible_trait, definition) \ - template \ - class copy_constructor, copy_constructible_trait> \ - : public move_constructor> { \ - using super = move_constructor>; \ - \ - public: \ - INHERITING_CTOR(copy_constructor, super) \ - using super::operator=; \ - \ - definition \ - copy_constructor(copy_constructor &&) = default; \ - ~copy_constructor() = default; \ - copy_constructor &operator=(const copy_constructor &) = default; \ - copy_constructor &operator=(copy_constructor &&) = default; \ - } - - MPARK_VARIANT_COPY_CONSTRUCTOR( - Trait::TriviallyAvailable, - copy_constructor(const copy_constructor &that) = default;); - - MPARK_VARIANT_COPY_CONSTRUCTOR( - Trait::Available, - copy_constructor(const copy_constructor &that) - : copy_constructor(valueless_t{}) { - this->generic_construct(*this, that); - }); - - MPARK_VARIANT_COPY_CONSTRUCTOR( - Trait::Unavailable, - copy_constructor(const copy_constructor &) = delete;); - -#undef MPARK_VARIANT_COPY_CONSTRUCTOR - - template - class assignment : public copy_constructor { - using super = copy_constructor; - - public: - INHERITING_CTOR(assignment, super) - using super::operator=; - - template - inline /* auto & */ auto emplace(Args &&... args) - -> decltype(this->construct_alt(access::base::get_alt(*this), - lib::forward(args)...)) { - this->destroy(); - auto &result = this->construct_alt(access::base::get_alt(*this), - lib::forward(args)...); - this->index_ = I; - return result; - } - - protected: -#ifndef MPARK_GENERIC_LAMBDAS - template - struct assigner { - template - inline void operator()(ThisAlt &this_alt, ThatAlt &&that_alt) const { - self->assign_alt(this_alt, lib::forward(that_alt).value); - } - assignment *self; - }; -#endif - - template - inline void assign_alt(alt &a, Arg &&arg) { - if (this->index() == I) { -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4244) -#endif - a.value = lib::forward(arg); -#ifdef _MSC_VER -#pragma warning(pop) -#endif - } else { - struct { - void operator()(std::true_type) const { - this_->emplace(lib::forward(arg_)); - } - void operator()(std::false_type) const { - this_->emplace(T(lib::forward(arg_))); - } - assignment *this_; - Arg &&arg_; - } impl{this, lib::forward(arg)}; - impl(lib::bool_constant< - std::is_nothrow_constructible::value || - !std::is_nothrow_move_constructible::value>{}); - } - } - - template - inline void generic_assign(That &&that) { - if (this->valueless_by_exception() && that.valueless_by_exception()) { - // do nothing. - } else if (that.valueless_by_exception()) { - this->destroy(); - } else { - visitation::base::visit_alt_at( - that.index(), -#ifdef MPARK_GENERIC_LAMBDAS - [this](auto &this_alt, auto &&that_alt) { - this->assign_alt( - this_alt, lib::forward(that_alt).value); - } -#else - assigner{this} -#endif - , - *this, - lib::forward(that)); - } - } - }; - - template - class move_assignment; - -#define MPARK_VARIANT_MOVE_ASSIGNMENT(move_assignable_trait, definition) \ - template \ - class move_assignment, move_assignable_trait> \ - : public assignment> { \ - using super = assignment>; \ - \ - public: \ - INHERITING_CTOR(move_assignment, super) \ - using super::operator=; \ - \ - move_assignment(const move_assignment &) = default; \ - move_assignment(move_assignment &&) = default; \ - ~move_assignment() = default; \ - move_assignment &operator=(const move_assignment &) = default; \ - definition \ - } - - MPARK_VARIANT_MOVE_ASSIGNMENT( - Trait::TriviallyAvailable, - move_assignment &operator=(move_assignment &&that) = default;); - - MPARK_VARIANT_MOVE_ASSIGNMENT( - Trait::Available, - move_assignment & - operator=(move_assignment &&that) noexcept( - all((std::is_nothrow_move_constructible::value && - std::is_nothrow_move_assignable::value)...)) { - this->generic_assign(lib::move(that)); - return *this; - }); - - MPARK_VARIANT_MOVE_ASSIGNMENT( - Trait::Unavailable, - move_assignment &operator=(move_assignment &&) = delete;); - -#undef MPARK_VARIANT_MOVE_ASSIGNMENT - - template - class copy_assignment; - -#define MPARK_VARIANT_COPY_ASSIGNMENT(copy_assignable_trait, definition) \ - template \ - class copy_assignment, copy_assignable_trait> \ - : public move_assignment> { \ - using super = move_assignment>; \ - \ - public: \ - INHERITING_CTOR(copy_assignment, super) \ - using super::operator=; \ - \ - copy_assignment(const copy_assignment &) = default; \ - copy_assignment(copy_assignment &&) = default; \ - ~copy_assignment() = default; \ - definition \ - copy_assignment &operator=(copy_assignment &&) = default; \ - } - - MPARK_VARIANT_COPY_ASSIGNMENT( - Trait::TriviallyAvailable, - copy_assignment &operator=(const copy_assignment &that) = default;); - - MPARK_VARIANT_COPY_ASSIGNMENT( - Trait::Available, - copy_assignment &operator=(const copy_assignment &that) { - this->generic_assign(that); - return *this; - }); - - MPARK_VARIANT_COPY_ASSIGNMENT( - Trait::Unavailable, - copy_assignment &operator=(const copy_assignment &) = delete;); - -#undef MPARK_VARIANT_COPY_ASSIGNMENT - - template - class impl : public copy_assignment> { - using super = copy_assignment>; - - public: - INHERITING_CTOR(impl, super) - using super::operator=; - - template - inline void assign(Arg &&arg) { - this->assign_alt(access::base::get_alt(*this), - lib::forward(arg)); - } - - inline void swap(impl &that) { - if (this->valueless_by_exception() && that.valueless_by_exception()) { - // do nothing. - } else if (this->index() == that.index()) { - visitation::base::visit_alt_at(this->index(), -#ifdef MPARK_GENERIC_LAMBDAS - [](auto &this_alt, auto &that_alt) { - using std::swap; - swap(this_alt.value, - that_alt.value); - } -#else - swapper{} -#endif - , - *this, - that); - } else { - impl *lhs = this; - impl *rhs = lib::addressof(that); - if (lhs->move_nothrow() && !rhs->move_nothrow()) { - std::swap(lhs, rhs); - } - impl tmp(lib::move(*rhs)); -#ifdef MPARK_EXCEPTIONS - // EXTENSION: When the move construction of `lhs` into `rhs` throws - // and `tmp` is nothrow move constructible then we move `tmp` back - // into `rhs` and provide the strong exception safety guarantee. - try { - this->generic_construct(*rhs, lib::move(*lhs)); - } catch (...) { - if (tmp.move_nothrow()) { - this->generic_construct(*rhs, lib::move(tmp)); - } - throw; - } -#else - this->generic_construct(*rhs, lib::move(*lhs)); -#endif - this->generic_construct(*lhs, lib::move(tmp)); - } - } - - private: -#ifndef MPARK_GENERIC_LAMBDAS - struct swapper { - template - inline void operator()(ThisAlt &this_alt, ThatAlt &that_alt) const { - using std::swap; - swap(this_alt.value, that_alt.value); - } - }; -#endif - - inline constexpr bool move_nothrow() const { - return this->valueless_by_exception() || - lib::array{ - {std::is_nothrow_move_constructible::value...} - }[this->index()]; - } - }; - - template - struct overload; - - template <> - struct overload<> { void operator()() const {} }; - - template - struct overload : overload { - using overload::operator(); - lib::identity operator()(T) const { return {}; } - }; - - template - using best_match_t = - typename lib::invoke_result_t, T &&>::type; - - template - struct is_in_place_index : std::false_type {}; - - template - struct is_in_place_index> : std::true_type {}; - - template - struct is_in_place_type : std::false_type {}; - - template - struct is_in_place_type> : std::true_type {}; - - } // detail - - template - class variant { - static_assert(0 < sizeof...(Ts), - "variant must consist of at least one alternative."); - - static_assert(lib::all::value...>::value, - "variant can not have an array type as an alternative."); - - static_assert(lib::all::value...>::value, - "variant can not have a reference type as an alternative."); - - static_assert(lib::all::value...>::value, - "variant can not have a void type as an alternative."); - - public: - template < - typename Front = lib::type_pack_element_t<0, Ts...>, - lib::enable_if_t::value, int> = 0> - inline constexpr variant() noexcept( - std::is_nothrow_default_constructible::value) - : impl_(in_place_index_t<0>{}) {} - - variant(const variant &) = default; - variant(variant &&) = default; - - template < - typename Arg, - typename Decayed = lib::decay_t, - lib::enable_if_t::value, int> = 0, - lib::enable_if_t::value, int> = 0, - lib::enable_if_t::value, int> = 0, - typename T = detail::best_match_t, - std::size_t I = detail::find_index_sfinae::value, - lib::enable_if_t::value, int> = 0> - inline constexpr variant(Arg &&arg) noexcept( - std::is_nothrow_constructible::value) - : impl_(in_place_index_t{}, lib::forward(arg)) {} - - template < - std::size_t I, - typename... Args, - typename T = lib::type_pack_element_t, - lib::enable_if_t::value, int> = 0> - inline explicit constexpr variant( - in_place_index_t, - Args &&... args) noexcept(std::is_nothrow_constructible::value) - : impl_(in_place_index_t{}, lib::forward(args)...) {} - - template < - std::size_t I, - typename Up, - typename... Args, - typename T = lib::type_pack_element_t, - lib::enable_if_t &, - Args...>::value, - int> = 0> - inline explicit constexpr variant( - in_place_index_t, - std::initializer_list il, - Args &&... args) noexcept(std:: - is_nothrow_constructible< - T, - std::initializer_list &, - Args...>::value) - : impl_(in_place_index_t{}, il, lib::forward(args)...) {} - - template < - typename T, - typename... Args, - std::size_t I = detail::find_index_sfinae::value, - lib::enable_if_t::value, int> = 0> - inline explicit constexpr variant( - in_place_type_t, - Args &&... args) noexcept(std::is_nothrow_constructible::value) - : impl_(in_place_index_t{}, lib::forward(args)...) {} - - template < - typename T, - typename Up, - typename... Args, - std::size_t I = detail::find_index_sfinae::value, - lib::enable_if_t &, - Args...>::value, - int> = 0> - inline explicit constexpr variant( - in_place_type_t, - std::initializer_list il, - Args &&... args) noexcept(std:: - is_nothrow_constructible< - T, - std::initializer_list &, - Args...>::value) - : impl_(in_place_index_t{}, il, lib::forward(args)...) {} - - ~variant() = default; - - variant &operator=(const variant &) = default; - variant &operator=(variant &&) = default; - - template , variant>::value, - int> = 0, - typename T = detail::best_match_t, - std::size_t I = detail::find_index_sfinae::value, - lib::enable_if_t<(std::is_assignable::value && - std::is_constructible::value), - int> = 0> - inline variant &operator=(Arg &&arg) noexcept( - (std::is_nothrow_assignable::value && - std::is_nothrow_constructible::value)) { - impl_.template assign(lib::forward(arg)); - return *this; - } - - template < - std::size_t I, - typename... Args, - typename T = lib::type_pack_element_t, - lib::enable_if_t::value, int> = 0> - inline T &emplace(Args &&... args) { - return impl_.template emplace(lib::forward(args)...); - } - - template < - std::size_t I, - typename Up, - typename... Args, - typename T = lib::type_pack_element_t, - lib::enable_if_t &, - Args...>::value, - int> = 0> - inline T &emplace(std::initializer_list il, Args &&... args) { - return impl_.template emplace(il, lib::forward(args)...); - } - - template < - typename T, - typename... Args, - std::size_t I = detail::find_index_sfinae::value, - lib::enable_if_t::value, int> = 0> - inline T &emplace(Args &&... args) { - return impl_.template emplace(lib::forward(args)...); - } - - template < - typename T, - typename Up, - typename... Args, - std::size_t I = detail::find_index_sfinae::value, - lib::enable_if_t &, - Args...>::value, - int> = 0> - inline T &emplace(std::initializer_list il, Args &&... args) { - return impl_.template emplace(il, lib::forward(args)...); - } - - inline constexpr bool valueless_by_exception() const noexcept { - return impl_.valueless_by_exception(); - } - - inline constexpr std::size_t index() const noexcept { - return impl_.index(); - } - - template < - bool Dummy = true, - lib::enable_if_t::value && - lib::is_swappable::value)...>::value, - int> = 0> - inline void swap(variant &that) noexcept( - lib::all<(std::is_nothrow_move_constructible::value && - lib::is_nothrow_swappable::value)...>::value) { - impl_.swap(that.impl_); - } - - private: - detail::impl impl_; - - friend struct detail::access::variant; - friend struct detail::visitation::variant; - }; - - template - inline constexpr bool holds_alternative(const variant &v) noexcept { - return v.index() == I; - } - - template - inline constexpr bool holds_alternative(const variant &v) noexcept { - return holds_alternative::value>(v); - } - - namespace detail { - template - struct generic_get_impl { - constexpr generic_get_impl(int) {} - - constexpr AUTO_REFREF operator()(V &&v) const - AUTO_REFREF_RETURN( - access::variant::get_alt(lib::forward(v)).value) - }; - - template - inline constexpr AUTO_REFREF generic_get(V &&v) - AUTO_REFREF_RETURN(generic_get_impl( - holds_alternative(v) ? 0 : (throw_bad_variant_access(), 0))( - lib::forward(v))) - } // namespace detail - - template - inline constexpr variant_alternative_t> &get( - variant &v) { - return detail::generic_get(v); - } - - template - inline constexpr variant_alternative_t> &&get( - variant &&v) { - return detail::generic_get(lib::move(v)); - } - - template - inline constexpr const variant_alternative_t> &get( - const variant &v) { - return detail::generic_get(v); - } - - template - inline constexpr const variant_alternative_t> &&get( - const variant &&v) { - return detail::generic_get(lib::move(v)); - } - - template - inline constexpr T &get(variant &v) { - return get::value>(v); - } - - template - inline constexpr T &&get(variant &&v) { - return get::value>(lib::move(v)); - } - - template - inline constexpr const T &get(const variant &v) { - return get::value>(v); - } - - template - inline constexpr const T &&get(const variant &&v) { - return get::value>(lib::move(v)); - } - - namespace detail { - - template - inline constexpr /* auto * */ AUTO generic_get_if(V *v) noexcept - AUTO_RETURN(v && holds_alternative(*v) - ? lib::addressof(access::variant::get_alt(*v).value) - : nullptr) - - } // namespace detail - - template - inline constexpr lib::add_pointer_t>> - get_if(variant *v) noexcept { - return detail::generic_get_if(v); - } - - template - inline constexpr lib::add_pointer_t< - const variant_alternative_t>> - get_if(const variant *v) noexcept { - return detail::generic_get_if(v); - } - - template - inline constexpr lib::add_pointer_t - get_if(variant *v) noexcept { - return get_if::value>(v); - } - - template - inline constexpr lib::add_pointer_t - get_if(const variant *v) noexcept { - return get_if::value>(v); - } - - template - inline constexpr bool operator==(const variant &lhs, - const variant &rhs) { - using detail::visitation::variant; - using lib::equal_to; -#ifdef MPARK_CPP14_CONSTEXPR - if (lhs.index() != rhs.index()) return false; - if (lhs.valueless_by_exception()) return true; - return variant::visit_value_at(lhs.index(), equal_to{}, lhs, rhs); -#else - return lhs.index() == rhs.index() && - (lhs.valueless_by_exception() || - variant::visit_value_at(lhs.index(), equal_to{}, lhs, rhs)); -#endif - } - - template - inline constexpr bool operator!=(const variant &lhs, - const variant &rhs) { - using detail::visitation::variant; - using lib::not_equal_to; -#ifdef MPARK_CPP14_CONSTEXPR - if (lhs.index() != rhs.index()) return true; - if (lhs.valueless_by_exception()) return false; - return variant::visit_value_at(lhs.index(), not_equal_to{}, lhs, rhs); -#else - return lhs.index() != rhs.index() || - (!lhs.valueless_by_exception() && - variant::visit_value_at(lhs.index(), not_equal_to{}, lhs, rhs)); -#endif - } - - template - inline constexpr bool operator<(const variant &lhs, - const variant &rhs) { - using detail::visitation::variant; - using lib::less; -#ifdef MPARK_CPP14_CONSTEXPR - if (rhs.valueless_by_exception()) return false; - if (lhs.valueless_by_exception()) return true; - if (lhs.index() < rhs.index()) return true; - if (lhs.index() > rhs.index()) return false; - return variant::visit_value_at(lhs.index(), less{}, lhs, rhs); -#else - return !rhs.valueless_by_exception() && - (lhs.valueless_by_exception() || lhs.index() < rhs.index() || - (lhs.index() == rhs.index() && - variant::visit_value_at(lhs.index(), less{}, lhs, rhs))); -#endif - } - - template - inline constexpr bool operator>(const variant &lhs, - const variant &rhs) { - using detail::visitation::variant; - using lib::greater; -#ifdef MPARK_CPP14_CONSTEXPR - if (lhs.valueless_by_exception()) return false; - if (rhs.valueless_by_exception()) return true; - if (lhs.index() > rhs.index()) return true; - if (lhs.index() < rhs.index()) return false; - return variant::visit_value_at(lhs.index(), greater{}, lhs, rhs); -#else - return !lhs.valueless_by_exception() && - (rhs.valueless_by_exception() || lhs.index() > rhs.index() || - (lhs.index() == rhs.index() && - variant::visit_value_at(lhs.index(), greater{}, lhs, rhs))); -#endif - } - - template - inline constexpr bool operator<=(const variant &lhs, - const variant &rhs) { - using detail::visitation::variant; - using lib::less_equal; -#ifdef MPARK_CPP14_CONSTEXPR - if (lhs.valueless_by_exception()) return true; - if (rhs.valueless_by_exception()) return false; - if (lhs.index() < rhs.index()) return true; - if (lhs.index() > rhs.index()) return false; - return variant::visit_value_at(lhs.index(), less_equal{}, lhs, rhs); -#else - return lhs.valueless_by_exception() || - (!rhs.valueless_by_exception() && - (lhs.index() < rhs.index() || - (lhs.index() == rhs.index() && - variant::visit_value_at(lhs.index(), less_equal{}, lhs, rhs)))); -#endif - } - - template - inline constexpr bool operator>=(const variant &lhs, - const variant &rhs) { - using detail::visitation::variant; - using lib::greater_equal; -#ifdef MPARK_CPP14_CONSTEXPR - if (rhs.valueless_by_exception()) return true; - if (lhs.valueless_by_exception()) return false; - if (lhs.index() > rhs.index()) return true; - if (lhs.index() < rhs.index()) return false; - return variant::visit_value_at(lhs.index(), greater_equal{}, lhs, rhs); -#else - return rhs.valueless_by_exception() || - (!lhs.valueless_by_exception() && - (lhs.index() > rhs.index() || - (lhs.index() == rhs.index() && - variant::visit_value_at( - lhs.index(), greater_equal{}, lhs, rhs)))); -#endif - } - - template - inline constexpr DECLTYPE_AUTO visit(Visitor &&visitor, Vs &&... vs) - DECLTYPE_AUTO_RETURN( - (detail::all(!vs.valueless_by_exception()...) - ? (void)0 - : throw_bad_variant_access()), - detail::visitation::variant::visit_value(lib::forward(visitor), - lib::forward(vs)...)) - - struct monostate {}; - - inline constexpr bool operator<(monostate, monostate) noexcept { - return false; - } - - inline constexpr bool operator>(monostate, monostate) noexcept { - return false; - } - - inline constexpr bool operator<=(monostate, monostate) noexcept { - return true; - } - - inline constexpr bool operator>=(monostate, monostate) noexcept { - return true; - } - - inline constexpr bool operator==(monostate, monostate) noexcept { - return true; - } - - inline constexpr bool operator!=(monostate, monostate) noexcept { - return false; - } - - template - inline auto swap(variant &lhs, - variant &rhs) noexcept(noexcept(lhs.swap(rhs))) - -> decltype(lhs.swap(rhs)) { - lhs.swap(rhs); - } - - namespace detail { - - template - using enabled_type = T; - - namespace hash { - - template - constexpr bool meets_requirements() { - return std::is_copy_constructible::value && - std::is_move_constructible::value && - lib::is_invocable_r::value; - } - - template - constexpr bool is_enabled() { - using H = std::hash; - return meets_requirements() && - std::is_default_constructible::value && - std::is_copy_assignable::value && - std::is_move_assignable::value; - } - - } // namespace hash - - } // namespace detail - -#undef AUTO -#undef AUTO_RETURN - -#undef AUTO_REFREF -#undef AUTO_REFREF_RETURN - -#undef DECLTYPE_AUTO -#undef DECLTYPE_AUTO_RETURN - -} // namespace mpark - -namespace std { - - template - struct hash, - mpark::lib::enable_if_t>()...>::value>>> { - using argument_type = mpark::variant; - using result_type = std::size_t; - - inline result_type operator()(const argument_type &v) const { - using mpark::detail::visitation::variant; - std::size_t result = - v.valueless_by_exception() - ? 299792458 // Random value chosen by the universe upon creation - : variant::visit_alt( -#ifdef MPARK_GENERIC_LAMBDAS - [](const auto &alt) { - using alt_type = mpark::lib::decay_t; - using value_type = mpark::lib::remove_const_t< - typename alt_type::value_type>; - return hash{}(alt.value); - } -#else - hasher{} -#endif - , - v); - return hash_combine(result, hash{}(v.index())); - } - - private: -#ifndef MPARK_GENERIC_LAMBDAS - struct hasher { - template - inline std::size_t operator()(const Alt &alt) const { - using alt_type = mpark::lib::decay_t; - using value_type = - mpark::lib::remove_const_t; - return hash{}(alt.value); - } - }; -#endif - - static std::size_t hash_combine(std::size_t lhs, std::size_t rhs) { - return lhs ^= rhs + 0x9e3779b9 + (lhs << 6) + (lhs >> 2); - } - }; - - template <> - struct hash { - using argument_type = mpark::monostate; - using result_type = std::size_t; - - inline result_type operator()(const argument_type &) const noexcept { - return 66740831; // return a fundamentally attractive random value. - } - }; - -} // namespace std - -#endif // MPARK_VARIANT_HPP diff --git a/src/Block.hpp b/src/Block.hpp index 367e559..6bd4e93 100644 --- a/src/Block.hpp +++ b/src/Block.hpp @@ -11,4 +11,9 @@ struct Block { unsigned char state : 4; unsigned char light : 4; unsigned char sky : 4; +}; + +struct BlockId { + unsigned short id : 13; + unsigned char state : 4; }; \ No newline at end of file diff --git a/src/Render.cpp b/src/Render.cpp index 7e88068..c739b77 100644 --- a/src/Render.cpp +++ b/src/Render.cpp @@ -6,12 +6,12 @@ #include "Event.hpp" Render::Render(unsigned int windowWidth, unsigned int windowHeight, std::string windowTitle) : timer(std::chrono::milliseconds(0)) { - InitSfml(windowWidth, windowHeight, windowTitle); - glCheckError(); - InitGlew(); - glCheckError(); - PrepareToRendering(); - glCheckError(); + InitSfml(windowWidth, windowHeight, windowTitle); + glCheckError(); + InitGlew(); + glCheckError(); + PrepareToRendering(); + glCheckError(); } Render::~Render() { @@ -29,7 +29,8 @@ void Render::InitSfml(unsigned int WinWidth, unsigned int WinHeight, std::string glCheckError(); window->setPosition(sf::Vector2i(sf::VideoMode::getDesktopMode().width / 2 - window->getSize().x / 2, sf::VideoMode::getDesktopMode().height / 2 - window->getSize().y / 2)); - SetMouseCapture(false); + window->setKeyRepeatEnabled(false); + SetMouseCapture(false); renderState.WindowWidth = WinWidth; renderState.WindowHeight = WinHeight; } @@ -59,6 +60,23 @@ void Render::PrepareToRendering() { AssetManager::Instance().GetTextureAtlasIndexes(); } +void Render::UpdateKeyboard() { + sf::Keyboard::Key toUpdate[] = { sf::Keyboard::A,sf::Keyboard::W,sf::Keyboard::S,sf::Keyboard::D,sf::Keyboard::Space }; + for (auto key : toUpdate) { + bool isPressed = sf::Keyboard::isKeyPressed(key); + if (!isKeyPressed[key] && isPressed) { + EventAgregator::PushEvent(EventType::KeyPressed, KeyPressedData{ key }); + } + if (isKeyPressed[key] && isPressed) { + //KeyHeld + } + if (isKeyPressed[key] && !isPressed) { + EventAgregator::PushEvent(EventType::KeyReleased, KeyReleasedData{ key }); + } + isKeyPressed[key] = isPressed; + } +} + void Render::RenderFrame() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -75,92 +93,62 @@ void Render::RenderFrame() { void Render::HandleEvents() { sf::Event event; - while (window->pollEvent(event)) { - switch (event.type) { - case sf::Event::Closed: - LOG(INFO) << "Received close event by window closing"; - isRunning = false; - break; - case sf::Event::Resized: - glViewport(0, 0, window->getSize().x, window->getSize().y); - renderState.WindowWidth = window->getSize().x; - renderState.WindowHeight = window->getSize().y; - break; - case sf::Event::KeyPressed: - if (!window->hasFocus()) break; - switch (event.key.code) { - case sf::Keyboard::Escape: - LOG(INFO) << "Received close event by esc"; - isRunning = false; - break; - case sf::Keyboard::T: - SetMouseCapture(!isMouseCaptured); - break; - case sf::Keyboard::U: - EventAgregator::PushEvent(EventType::ConnectToServer, ConnectToServerData{ "10.1.1.2", 25565 }); - break; - case sf::Keyboard::I: - EventAgregator::PushEvent(EventType::Disconnect, DisconnectData{ "Manual disconnect" }); - break; - case sf::Keyboard::K: - if (renderWorld) { - world->MaxRenderingDistance--; - if (world->MaxRenderingDistance <= 0) - world->MaxRenderingDistance = 1; - LOG(INFO) << "Decreased rendering distance: " << world->MaxRenderingDistance; - EventAgregator::PushEvent(EventType::UpdateSectionsRender, UpdateSectionsRenderData{}); - } - break; - case sf::Keyboard::L: - if (renderWorld) { - world->MaxRenderingDistance++; - LOG(INFO) << "Increased rendering distance: " << world->MaxRenderingDistance; - EventAgregator::PushEvent(EventType::UpdateSectionsRender, UpdateSectionsRenderData{}); - } - break; - case sf::Keyboard::W: - EventAgregator::PushEvent(EventType::KeyPressed, KeyPressedData{ sf::Keyboard::W }); - break; - case sf::Keyboard::A: - EventAgregator::PushEvent(EventType::KeyPressed, KeyPressedData{ sf::Keyboard::A }); - break; - case sf::Keyboard::S: - EventAgregator::PushEvent(EventType::KeyPressed, KeyPressedData{ sf::Keyboard::S }); - break; - case sf::Keyboard::D: - EventAgregator::PushEvent(EventType::KeyPressed, KeyPressedData{ sf::Keyboard::D }); - break; - case sf::Keyboard::Space: - EventAgregator::PushEvent(EventType::KeyPressed, KeyPressedData{ sf::Keyboard::Space }); - break; - default: - break; - } - case sf::Event::KeyReleased: - if (!window->hasFocus()) break; - switch (event.key.code) { - case sf::Keyboard::W: - EventAgregator::PushEvent(EventType::KeyReleased, KeyReleasedData{ sf::Keyboard::W }); - break; - case sf::Keyboard::A: - EventAgregator::PushEvent(EventType::KeyReleased, KeyReleasedData{ sf::Keyboard::A }); - break; - case sf::Keyboard::S: - EventAgregator::PushEvent(EventType::KeyReleased, KeyReleasedData{ sf::Keyboard::S }); - break; - case sf::Keyboard::D: - EventAgregator::PushEvent(EventType::KeyReleased, KeyReleasedData{ sf::Keyboard::D }); - break; - case sf::Keyboard::Space: - EventAgregator::PushEvent(EventType::KeyReleased, KeyReleasedData{ sf::Keyboard::Space }); - break; - default: - break; + while (window->pollEvent(event)) { + switch (event.type) { + case sf::Event::Closed: + LOG(INFO) << "Received close event by window closing"; + isRunning = false; + break; + case sf::Event::Resized: + glViewport(0, 0, window->getSize().x, window->getSize().y); + renderState.WindowWidth = window->getSize().x; + renderState.WindowHeight = window->getSize().y; + break; + case sf::Event::KeyPressed: + if (!window->hasFocus()) break; + switch (event.key.code) { + case sf::Keyboard::Escape: + LOG(INFO) << "Received close event by esc"; + isRunning = false; + break; + case sf::Keyboard::T: + SetMouseCapture(!isMouseCaptured); + break; + case sf::Keyboard::U: + EventAgregator::PushEvent(EventType::ConnectToServer, ConnectToServerData{ "10.1.1.2", 25565 }); + break; + case sf::Keyboard::I: + EventAgregator::PushEvent(EventType::Disconnect, DisconnectData{ "Manual disconnect" }); + break; + case sf::Keyboard::K: + if (renderWorld) { + world->MaxRenderingDistance--; + if (world->MaxRenderingDistance <= 0) + world->MaxRenderingDistance = 1; + LOG(INFO) << "Decreased rendering distance: " << world->MaxRenderingDistance; + EventAgregator::PushEvent(EventType::UpdateSectionsRender, UpdateSectionsRenderData{}); } - default: - break; - } - } + break; + case sf::Keyboard::L: + if (renderWorld) { + world->MaxRenderingDistance++; + LOG(INFO) << "Increased rendering distance: " << world->MaxRenderingDistance; + EventAgregator::PushEvent(EventType::UpdateSectionsRender, UpdateSectionsRenderData{}); + } + break; + default: + break; + } + case sf::Event::KeyReleased: + if (!window->hasFocus()) break; + switch (event.key.code) { + default: + break; + } + default: + break; + } + } } void Render::HandleMouseCapture() { @@ -216,6 +204,7 @@ void Render::ExecuteRenderLoop() { while (isRunning) { HandleEvents(); + if (window->hasFocus()) UpdateKeyboard(); if (isMouseCaptured) HandleMouseCapture(); glCheckError(); @@ -223,10 +212,7 @@ void Render::ExecuteRenderLoop() { while (listener.IsEventsQueueIsNotEmpty()) listener.HandleEvent(); if (renderWorld) { - world->renderDataMutex.lock(); - size_t size = world->renderData.size(); - world->renderDataMutex.unlock(); - window->setTitle("Size: " + std::to_string(size) + " FPS: " + std::to_string(1.0 / timer.GetRealDeltaS())); + window->setTitle("FPS: " + std::to_string(1.0 / timer.GetRealDeltaS())); } timer.Update(); } diff --git a/src/Render.hpp b/src/Render.hpp index 6b4b5a4..b7d12d0 100644 --- a/src/Render.hpp +++ b/src/Render.hpp @@ -4,16 +4,18 @@ #include "Shader.hpp" #include "RendererWorld.hpp" +#include "RendererWidget.hpp" class Render { sf::Window *window; - bool isRunning=true; + bool isRunning = true; bool isMouseCaptured = false; float mouseXDelta, mouseYDelta; std::unique_ptr world; bool renderWorld = false; RenderState renderState; LoopExecutionTimeController timer; + std::map isKeyPressed; void SetMouseCapture(bool IsCaptured); @@ -28,6 +30,8 @@ class Render { void RenderFrame(); void PrepareToRendering(); + + void UpdateKeyboard(); public: Render(unsigned int windowWidth, unsigned int windowHeight, std::string windowTitle); ~Render(); diff --git a/src/Renderer.hpp b/src/Renderer.hpp index 53f6cc8..306a310 100644 --- a/src/Renderer.hpp +++ b/src/Renderer.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include "Utility.hpp" class RenderState { GLuint ActiveVao = -1; @@ -10,12 +11,4 @@ public: void SetActiveShader(GLuint Shader); unsigned int WindowWidth, WindowHeight; long long TimeOfDay; -}; - -/*struct Renderer { - virtual ~Renderer() = default; - virtual void Render(RenderState& renderState) = 0; - virtual void PrepareResources() = 0; - virtual void PrepareRender() = 0; - virtual bool IsNeedResourcesPrepare() = 0; -};*/ \ No newline at end of file +}; \ No newline at end of file diff --git a/src/RendererSection.cpp b/src/RendererSection.cpp index 0965453..bb1a888 100644 --- a/src/RendererSection.cpp +++ b/src/RendererSection.cpp @@ -25,30 +25,18 @@ const GLfloat uv_coords[] = { const GLuint magicUniqueConstant = 88375; GLuint RendererSection::VboVertices = magicUniqueConstant; GLuint RendererSection::VboUvs = magicUniqueConstant; -std::map RendererSection::refCounterVbo; -std::map RendererSection::refCounterVao; RendererSection::~RendererSection() { - refCounterVbo[VboTextures]--; - refCounterVbo[VboModels]--; - refCounterVbo[VboColors]--; - refCounterVbo[VboLights]--; - refCounterVao[Vao]--; - - if (refCounterVbo[VboTextures] <= 0) - glDeleteBuffers(1, &VboTextures); - - if (refCounterVbo[VboModels] <= 0) - glDeleteBuffers(1, &VboTextures); - - if (refCounterVbo[VboColors] <= 0) - glDeleteBuffers(1, &VboColors); - - if (refCounterVbo[VboLights] <= 0) - glDeleteBuffers(1, &VboLights); + if (Vao != 0) + glDeleteVertexArrays(1, &Vao); + + for (int i = 0; i < VBOCOUNT; i++) + if (Vbo[i] != 0) { + glBindBuffer(GL_ARRAY_BUFFER, Vbo[i]); + glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_STATIC_DRAW); + } - if (refCounterVao[Vao] <= 0) - glDeleteVertexArrays(1, &Vao); + glDeleteBuffers(VBOCOUNT, Vbo); } void RendererSection::Render(RenderState &renderState) { @@ -84,30 +72,9 @@ RendererSection::RendererSection(RendererSectionData data) { << ") for faces"; } - glGenBuffers(1, &VboTextures); - if (refCounterVbo.find(VboTextures) == refCounterVbo.end()) - refCounterVbo[VboTextures] = 0; - refCounterVbo[VboTextures]++; - - glGenBuffers(1, &VboModels); - if (refCounterVbo.find(VboModels) == refCounterVbo.end()) - refCounterVbo[VboModels] = 0; - refCounterVbo[VboModels]++; - - glGenBuffers(1, &VboColors); - if (refCounterVbo.find(VboColors) == refCounterVbo.end()) - refCounterVbo[VboColors] = 0; - refCounterVbo[VboColors]++; - - glGenBuffers(1, &VboLights); - if (refCounterVbo.find(VboLights) == refCounterVbo.end()) - refCounterVbo[VboLights] = 0; - refCounterVbo[VboLights]++; - glGenVertexArrays(1, &Vao); - if (refCounterVao.find(Vao) == refCounterVao.end()) - refCounterVao[Vao] = 0; - refCounterVao[Vao]++; + + glGenBuffers(VBOCOUNT, Vbo); glBindVertexArray(Vao); { @@ -125,7 +92,7 @@ RendererSection::RendererSection(RendererSectionData data) { //Textures GLuint textureAttribPos = 7; - glBindBuffer(GL_ARRAY_BUFFER, VboTextures); + glBindBuffer(GL_ARRAY_BUFFER, Vbo[TEXTURES]); glVertexAttribPointer(textureAttribPos, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(textureAttribPos); glVertexAttribDivisor(textureAttribPos, 1); @@ -134,7 +101,7 @@ RendererSection::RendererSection(RendererSectionData data) { //Blocks models GLuint matAttribPos = 8; size_t sizeOfMat4 = 4 * 4 * sizeof(GLfloat); - glBindBuffer(GL_ARRAY_BUFFER, VboModels); + glBindBuffer(GL_ARRAY_BUFFER, Vbo[MODELS]); glVertexAttribPointer(matAttribPos + 0, 4, GL_FLOAT, GL_FALSE, sizeOfMat4, nullptr); glVertexAttribPointer(matAttribPos + 1, 4, GL_FLOAT, GL_FALSE, sizeOfMat4, (void *)(1 * 4 * sizeof(GLfloat))); glVertexAttribPointer(matAttribPos + 2, 4, GL_FLOAT, GL_FALSE, sizeOfMat4, (void *)(2 * 4 * sizeof(GLfloat))); @@ -150,14 +117,14 @@ RendererSection::RendererSection(RendererSectionData data) { //Color GLuint colorAttribPos = 12; - glBindBuffer(GL_ARRAY_BUFFER, VboColors); + glBindBuffer(GL_ARRAY_BUFFER, Vbo[COLORS]); glVertexAttribPointer(colorAttribPos, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(colorAttribPos); glVertexAttribDivisor(colorAttribPos, 1); //Light GLuint lightAttribPos = 13; - glBindBuffer(GL_ARRAY_BUFFER, VboLights); + glBindBuffer(GL_ARRAY_BUFFER, Vbo[LIGHTS]); glVertexAttribPointer(lightAttribPos, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(lightAttribPos); glVertexAttribDivisor(lightAttribPos, 1); @@ -169,16 +136,16 @@ RendererSection::RendererSection(RendererSectionData data) { //Upload data to VRAM - glBindBuffer(GL_ARRAY_BUFFER, VboTextures); + glBindBuffer(GL_ARRAY_BUFFER, Vbo[TEXTURES]); glBufferData(GL_ARRAY_BUFFER, data.textures.size() * sizeof(glm::vec4), data.textures.data(), GL_DYNAMIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, VboModels); + glBindBuffer(GL_ARRAY_BUFFER, Vbo[MODELS]); glBufferData(GL_ARRAY_BUFFER, data.models.size() * sizeof(glm::mat4), data.models.data(), GL_DYNAMIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, VboColors); + glBindBuffer(GL_ARRAY_BUFFER, Vbo[COLORS]); glBufferData(GL_ARRAY_BUFFER, data.colors.size() * sizeof(glm::vec3), data.colors.data(), GL_DYNAMIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, VboLights); + glBindBuffer(GL_ARRAY_BUFFER, Vbo[LIGHTS]); glBufferData(GL_ARRAY_BUFFER, data.lights.size() * sizeof(glm::vec2), data.lights.data(), GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); @@ -188,21 +155,9 @@ RendererSection::RendererSection(RendererSectionData data) { hash = data.hash; } -RendererSection::RendererSection(const RendererSection &other) { - this->VboModels = other.VboModels; - this->VboTextures = other.VboTextures; - this->VboColors = other.VboColors; - this->VboLights = other.VboLights; - this->sectionPos = other.sectionPos; - this->Vao = other.Vao; - this->numOfFaces = other.numOfFaces; - this->hash = other.hash; - - refCounterVbo[VboTextures]++; - refCounterVbo[VboModels]++; - refCounterVbo[VboColors]++; - refCounterVbo[VboLights]++; - refCounterVao[Vao]++; +RendererSection::RendererSection(RendererSection && other) { + using std::swap; + swap(*this, other); } RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) { @@ -214,7 +169,7 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) for (int y = 0; y < 16; y++) { for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) { - Block block = section.GetBlock(Vector(x, y, z)); + BlockId block = section.GetBlockId(Vector(x, y, z)); if (block.id == 0) continue; @@ -243,9 +198,9 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) if (std::find(sectionsList.begin(), sectionsList.end(), sectionPosition + offset) == sectionsList.end()) return true; const Section& blockSection = world->GetSection(sectionPosition + offset); - return blockSection.GetBlock(block).id == 0 || blockSection.GetBlock(block).id == 31 || blockSection.GetBlock(block).id == 18; + return blockSection.GetBlockId(block).id == 0 || blockSection.GetBlockId(block).id == 31 || blockSection.GetBlockId(block).id == 18; } - return section.GetBlock(block).id == 0 || section.GetBlock(block).id == 31 || section.GetBlock(block).id == 18; + return section.GetBlockId(block).id == 0 || section.GetBlockId(block).id == 31 || section.GetBlockId(block).id == 18; }; unsigned char isVisible = 0; @@ -272,7 +227,7 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) for (int i = 0; i < 4; i++) { textures.push_back(texture->second); colors.push_back(color); - lights.push_back(glm::vec2(block.light, block.sky)); + lights.push_back(glm::vec2(0, 0)); } glm::mat4 faceTransform = glm::translate(transform, glm::vec3(0.15f, 0, 0.15f)); faceTransform = glm::scale(faceTransform, glm::vec3(1.0f, 0.9f, 1.0f)); @@ -298,7 +253,7 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) textures.push_back(glm::vec4(0.0546875, 0.00442477876106194690, 0.0078125, 0.00442477876106194690)); //Fallback TNT texture colors.push_back(color); - lights.push_back(glm::vec2(block.light, block.sky)); + lights.push_back(glm::vec2(0, 0)); } if (isVisible >> 1 & 0x1) { //west side X- glm::mat4 faceTransform = glm::translate(transform, glm::vec3(1, 0, 0)); @@ -313,7 +268,7 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) textures.push_back(glm::vec4(0.0546875, 0.00442477876106194690, 0.0078125, 0.00442477876106194690)); //Fallback TNT texture colors.push_back(color); - lights.push_back(glm::vec2(block.light, block.sky)); + lights.push_back(glm::vec2(0, 0)); } if (isVisible >> 2 & 0x1) { //Top side Y+ glm::mat4 faceTransform = glm::translate(transform, glm::vec3(0, 1, 0)); @@ -328,7 +283,7 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) colors.push_back(color); else colors.push_back(biomeColor); - lights.push_back(glm::vec2(block.light, block.sky)); + lights.push_back(glm::vec2(0, 0)); } if (isVisible >> 3 & 0x1) { //Bottom side Y- glm::mat4 faceTransform = glm::translate(transform, glm::vec3(0, 0, 0)); @@ -342,7 +297,7 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) textures.push_back(glm::vec4(0.0546875, 0.00442477876106194690, 0.0078125, 0.00442477876106194690)); //Fallback TNT texture colors.push_back(color); - lights.push_back(glm::vec2(block.light, block.sky)); + lights.push_back(glm::vec2(0, 0)); } if (isVisible >> 4 & 0x1) { //south side Z+ glm::mat4 faceTransform = glm::translate(transform, glm::vec3(1, 0, 0)); @@ -356,7 +311,7 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) textures.push_back(glm::vec4(0.0546875, 0.00442477876106194690, 0.0078125, 0.00442477876106194690)); //Fallback TNT texture colors.push_back(color); - lights.push_back(glm::vec2(block.light, block.sky)); + lights.push_back(glm::vec2(0, 0)); } if (isVisible >> 5 & 0x1) { //north side Z- glm::mat4 faceTransform = glm::translate(transform, glm::vec3(0, 0, 1)); @@ -373,7 +328,7 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) textures.push_back(glm::vec4(0.0546875, 0.00442477876106194690, 0.0078125, 0.00442477876106194690)); //Fallback TNT texture colors.push_back(color); - lights.push_back(glm::vec2(block.light, block.sky)); + lights.push_back(glm::vec2(0, 0)); } } } @@ -383,9 +338,12 @@ RendererSectionData::RendererSectionData(World * world, Vector sectionPosition) textures.shrink_to_fit(); models.shrink_to_fit(); colors.shrink_to_fit(); +} - /*for (auto& it : lights) { - it.x = 8; - it.y = 16; - }*/ +void swap(RendererSection & lhs, RendererSection & rhs) { + std::swap(lhs.Vbo, rhs.Vbo); + std::swap(lhs.Vao, rhs.Vao); + std::swap(lhs.hash, rhs.hash); + std::swap(lhs.numOfFaces, rhs.numOfFaces); + std::swap(lhs.sectionPos, rhs.sectionPos); } diff --git a/src/RendererSection.hpp b/src/RendererSection.hpp index 9e5fd99..12a169e 100644 --- a/src/RendererSection.hpp +++ b/src/RendererSection.hpp @@ -23,19 +23,28 @@ struct RendererSectionData { RendererSectionData(World *world, Vector sectionPosition); }; - class RendererSection { - GLuint Vao, VboTextures, VboModels, VboColors, VboLights; + enum Vbos { + MODELS = 0, + TEXTURES, + COLORS, + LIGHTS, + VBOCOUNT, + }; + GLuint Vao = { 0 }; + GLuint Vbo[VBOCOUNT] = { 0 }; static GLuint VboVertices, VboUvs; - static std::map refCounterVbo; - static std::map refCounterVao; size_t hash; Vector sectionPos; + + RendererSection(const RendererSection &other) = delete; public: RendererSection(RendererSectionData data); - RendererSection(const RendererSection &other); + + RendererSection(RendererSection &&other); + ~RendererSection(); void Render(RenderState &renderState); @@ -44,5 +53,7 @@ public: size_t GetHash(); - size_t numOfFaces = 0; + size_t numOfFaces; + + friend void swap(RendererSection &lhs, RendererSection &rhs); }; \ No newline at end of file diff --git a/src/RendererWidget.cpp b/src/RendererWidget.cpp new file mode 100644 index 0000000..6b732e3 --- /dev/null +++ b/src/RendererWidget.cpp @@ -0,0 +1,76 @@ +#include "RendererWidget.hpp" + +const GLfloat vertices[] = { + 0.0f,0.0f,0.0f, + 1.0f,1.0f,0.0f, + 0.0f,1.0f,0.0f, + + 0.0f,0.0f,0.0f, + 1.0f,0.0f,0.0f, + 1.0f,1.0f,0.0f, +}; + +const GLfloat uvs[] = { + 0.0f,0.0f, + 1.0f,1.0f, + 0.0f,1.0f, + + 0.0f,0.0f, + 1.0f,0.0f, + 1.0f,1.0f, +}; + +static GLuint VboVertices, VboUvs, Vao; +static Shader* guiShader = nullptr; + +RendererWidget::RendererWidget(RootWidget *widget) { + this->tree = widget; + + if (guiShader == nullptr) { + guiShader = new Shader("./shaders/gui.vs", "./shaders/gui.fs"); + guiShader->Use(); + glUniform1i(glGetUniformLocation(guiShader->Program, "textureAtlas"), 0); + + glGenBuffers(1, &VboVertices); + glBindBuffer(GL_ARRAY_BUFFER, VboVertices); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); + + glGenBuffers(1, &VboUvs); + glBindBuffer(GL_ARRAY_BUFFER, VboUvs); + glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW); + + glGenVertexArrays(1, &Vao); + glBindVertexArray(Vao); + { + glBindBuffer(GL_ARRAY_BUFFER, VboVertices); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); + glEnableVertexAttribArray(0); + + glBindBuffer(GL_ARRAY_BUFFER, VboUvs); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*)0); + glEnableVertexAttribArray(1); + } + glBindVertexArray(0); + } +} + +RendererWidget::~RendererWidget() { + +} + +void RendererWidget::Render(RenderState &state) { + state.SetActiveVao(Vao); + state.SetActiveShader(guiShader->Program); + + auto toRender = tree->GetRenderList(); + for (auto& it : toRender) { + auto[x, y, w, h] = it->GetTexture(); + glUniform4f(glGetUniformLocation(guiShader->Program, "widgetTexture"), x, y, w, h); + + glUniform4f(glGetUniformLocation(guiShader->Program, "transform"), it->x, it->y, it->w, it->h); + + glDrawArrays(GL_TRIANGLES, 0, 36); + } + + glCheckError(); +} \ No newline at end of file diff --git a/src/RendererWidget.hpp b/src/RendererWidget.hpp new file mode 100644 index 0000000..a979c88 --- /dev/null +++ b/src/RendererWidget.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include "Renderer.hpp" +#include "Widget.hpp" +#include "Shader.hpp" + +class RendererWidget { + RootWidget *tree; + +public: + RendererWidget(RootWidget *widget); + ~RendererWidget(); + + void Render(RenderState &state); +}; \ No newline at end of file diff --git a/src/RendererWorld.cpp b/src/RendererWorld.cpp index dd5fdb4..7262583 100644 --- a/src/RendererWorld.cpp +++ b/src/RendererWorld.cpp @@ -94,7 +94,6 @@ RendererWorld::RendererWorld(std::shared_ptr ptr):gs(ptr) { sectionsMutex.lock(); auto it = sections.find(vec); if (it == sections.end()) { - //LOG(ERROR) << "Deleting wrong sectionRenderer"; sectionsMutex.unlock(); return; } @@ -124,7 +123,7 @@ RendererWorld::RendererWorld(std::shared_ptr ptr):gs(ptr) { sections.erase(sections.find(data.sectionPos)); } RendererSection renderer(data); - sections.insert(std::make_pair(data.sectionPos, renderer)); + sections.insert(std::make_pair(data.sectionPos, std::move(renderer))); sectionsMutex.unlock(); renderData.pop(); } @@ -155,7 +154,6 @@ RendererWorld::RendererWorld(std::shared_ptr ptr):gs(ptr) { if (isParsing.find(vec) == isParsing.end()) isParsing[vec] = false; if (isParsing[vec] == true) { - //LOG(WARNING) << "Changed parsing block"; isParsingMutex.unlock(); return; } @@ -188,6 +186,8 @@ RendererWorld::RendererWorld(std::shared_ptr ptr):gs(ptr) { for (int i = 0; i < numOfWorkers; i++) workers.push_back(std::thread(&RendererWorld::WorkerFunction, this, i)); + EventAgregator::PushEvent(EventType::UpdateSectionsRender, UpdateSectionsRenderData{}); + //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } @@ -349,7 +349,7 @@ void RendererWorld::PrepareRender() { } void RendererWorld::Update(double timeToUpdate) { - auto timeSincePreviousUpdate = std::chrono::steady_clock::now(); + static auto timeSincePreviousUpdate = std::chrono::steady_clock::now(); int i = 0; while (listener.IsEventsQueueIsNotEmpty() && i++ < 50) listener.HandleEvent(); diff --git a/src/RendererWorld.hpp b/src/RendererWorld.hpp index 5bc575c..4e098e5 100644 --- a/src/RendererWorld.hpp +++ b/src/RendererWorld.hpp @@ -37,9 +37,7 @@ public: ~RendererWorld(); void Render(RenderState& renderState); - void PrepareResources(); void PrepareRender(); - bool IsNeedResourcesPrepare(); double MaxRenderingDistance; diff --git a/src/Section.cpp b/src/Section.cpp index c9af5c6..9b4292b 100644 --- a/src/Section.cpp +++ b/src/Section.cpp @@ -2,164 +2,134 @@ #include +void Section::CalculateHash() { + std::vector rawData; + rawData.reserve(block.size() * sizeof(long long) + light.size() + sky.size()); + std::copy(block.begin(), block.end(), std::back_inserter(rawData)); + std::copy(light.begin(), light.end(), std::back_inserter(rawData)); + if (!sky.empty()) + std::copy(sky.begin(), sky.end(), std::back_inserter(rawData)); + + const unsigned char *from = reinterpret_cast(rawData.data()); + size_t length = rawData.size(); + + std::string str(from, from + length); + hash = std::hash{}(str); +} + +Section::Section(Vector pos, unsigned char bitsPerBlock, std::vector palette, std::vector blockData, std::vector lightData, std::vector skyData) { + if (bitsPerBlock < 4) + bitsPerBlock = 4; + if (bitsPerBlock > 8) + bitsPerBlock = 13; + this->bitsPerBlock = bitsPerBlock; + + this->worldPosition = pos; + this->block = std::move(blockData); + this->palette = std::move(palette); + this->light = std::move(lightData); + this->sky = std::move(skyData); + + CalculateHash(); +} + +Section::Section() { + + CalculateHash(); +} + Section::~Section() { + } Section::Section(Section && other) noexcept { using std::swap; swap(*this, other); + CalculateHash(); } -Block &Section::GetBlock(Vector pos) { - return blocks[pos.y * 256 + pos.z * 16 + pos.x]; +Section &Section::operator=(Section other) noexcept { + using std::swap; + swap(*this, other); + CalculateHash(); + return *this; } -Block Section::GetBlock(Vector pos) const -{ - if (blocks.empty()) { - static Block fallback; - return fallback; +BlockId Section::GetBlockId(Vector pos) const { + if (block.empty()) + return BlockId{ 0,0 }; + int value; + + unsigned char individualValueMask = ((1 << bitsPerBlock) - 1); + + int blockNumber = (((pos.y * 16) + pos.z) * 16) + pos.x; + int startLong = (blockNumber * bitsPerBlock) / 64; + int startOffset = (blockNumber * bitsPerBlock) % 64; + int endLong = ((blockNumber + 1) * bitsPerBlock - 1) / 64; + + unsigned short t; + + if (startLong == endLong) { + t = (block[startLong] >> startOffset); + } + else { + int endOffset = 64 - startOffset; + t = (block[startLong] >> startOffset |block[endLong] << endOffset); } - return blocks[pos.y * 256 + pos.z * 16 + pos.x]; + + t &= individualValueMask; + + + if (t >= palette.size()) { + //LOG(ERROR) << "Out of palette: " << t; + value = 0; + } + else + value = palette[t]; + + BlockId blockId; + blockId.id = value >> 4; + blockId.state = value & 0xF; + return blockId; } -double totalParsingTime = 0; +unsigned char Section::GetBlockLight(Vector pos) +{ + int blockNumber = pos.y * 256 + pos.z * 16 + pos.x; + unsigned char lightValue = this->light[blockNumber]; + return (blockNumber % 2 == 0) ? (lightValue & 0xF) : (lightValue >> 4); +} -Section::Section(PackedSection data) +unsigned char Section::GetBlockSkyLight(Vector pos) { - if (data.blocks.empty()) - return; - worldPosition = data.position; - - bool useFirst = false; - - if (useFirst) { - unsigned char *blocksData = reinterpret_cast(data.blocks.data()); - std::vector blocks; - blocks.reserve(4096); - { - auto begin = std::chrono::steady_clock::now(); - int bitPos = 0; - unsigned short t = 0; - for (size_t i = 0; i < data.blocks.size() * 8; i++) { - for (int j = 0; j < 8; j++) { - t |= (blocksData[i] & 0x01) ? 0x80 : 0x00; - t >>= 1; - blocksData[i] >>= 1; - bitPos++; - if (bitPos >= data.bitsPerBlock) { - bitPos = 0; - t >>= data.bitsPerBlock - 1; - blocks.push_back(t); - t = 0; - } - } - } - auto end = std::chrono::steady_clock::now(); - std::chrono::duration time = end - begin; - totalParsingTime += time.count(); - } - std::vector light; - light.reserve(4096); - for (int i = 0; i < 2048; i++) { - byte t = data.light[i]; - byte first = t & 0x0F; - byte second = t >> 4; - light.push_back(0); - light.push_back(0); - } - - std::vector sky; - if (!data.sky.empty()) { - sky.reserve(4096); - for (int i = 0; i < 2048; i++) { - byte t = data.sky[i]; - byte first = t & 0x0F; - byte second = t >> 4; - sky.push_back(first); - sky.push_back(second); - } - } - - for (int i = 0; i < 4096; i++) { - unsigned short blockId = !data.palette.empty() ? data.palette[blocks[i]] : blocks[i]; - Block block(blockId >> 4, blockId & 0xF, light[i], sky.empty() ? 0 : sky[i]); - this->blocks.push_back(block); - } - } else { - - std::vector blocks; - blocks.reserve(4096); - - unsigned char individualValueMask = ((1 << data.bitsPerBlock) - 1); - - for (int blockNumber = 0; blockNumber < 4096; blockNumber++) { - int startLong = (blockNumber * data.bitsPerBlock) / 64; - int startOffset = (blockNumber * data.bitsPerBlock) % 64; - int endLong = ((blockNumber + 1) * data.bitsPerBlock - 1) / 64; - - unsigned short t; - - if (startLong == endLong) { - t = (data.blocks[startLong] >> startOffset); - } - else { - int endOffset = 64 - startOffset; - t = (data.blocks[startLong] >> startOffset | data.blocks[endLong] << endOffset); - } - - t &= individualValueMask; - - - if (t >= data.palette.size()) { - //LOG(ERROR) << "Out of palette: "< light; - light.reserve(4096); - for (int i = 0; i < 2048; i++) { - unsigned char t = data.light[i]; - light.push_back(t & 0xF); - light.push_back(t >> 4 & 0xF); - } - - std::vector sky; - if (!data.sky.empty()) { - sky.reserve(4096); - for (int i = 0; i < 2048; i++) { - unsigned char t = data.sky[i]; - sky.push_back(t & 0xF); - sky.push_back(t >> 4 & 0xF); - } - } - - for (int i = 0; i < 4096; i++) { - unsigned short blockId = blocks[i]; - Block block(blockId >> 4, blockId & 0xF, light[i], sky.empty() ? 0 : sky[i]); - this->blocks.push_back(block); - } - } + int blockNumber = pos.y * 256 + pos.z * 16 + pos.x; + unsigned char skyValue = this->sky[blockNumber]; + return (blockNumber % 2 == 0) ? (skyValue & 0xF) : (skyValue >> 4); } -Section &Section::operator=(Section other) noexcept { - using std::swap; - swap(*this, other); - return *this; +void Section::SetBlockId(Vector pos, BlockId value) { + LOG(WARNING) << "Block changing not implemented!"; } void swap(Section& lhs, Section& rhs) noexcept { - std::swap(lhs.blocks, rhs.blocks); + std::swap(lhs.block, rhs.block); + std::swap(lhs.light, rhs.light); + std::swap(lhs.sky, rhs.sky); + std::swap(lhs.bitsPerBlock, rhs.bitsPerBlock); + std::swap(lhs.palette, rhs.palette); + std::swap(lhs.hash, rhs.hash); std::swap(lhs.worldPosition, rhs.worldPosition); } Section::Section(const Section &other) { worldPosition = other.worldPosition; - this->blocks = other.blocks; + this->block = other.block; + this->light = other.light; + this->sky = other.sky; + this->bitsPerBlock = other.bitsPerBlock; + this->palette = other.palette; + this->hash = other.hash; + this->worldPosition = other.worldPosition; } Vector Section::GetPosition() const { @@ -167,32 +137,5 @@ Vector Section::GetPosition() const { } size_t Section::GetHash() const { - if (blocks.empty()) return 0; - - const unsigned char *from = reinterpret_cast(blocks.data()); - size_t length = blocks.size() * sizeof(Block); - - std::string str(from, from + length); - return std::hash{}(str); -} - -PackedSection::PackedSection(Vector position, byte * dataBlocks, size_t dataBlocksLength, byte * dataLight, byte * dataSky, byte bitsPerBlock, std::vector palette) -{ - this->position = position; - - this->palette = palette; - - this->bitsPerBlock = bitsPerBlock; - - for (long long *t = reinterpret_cast(dataBlocks); (byte*)t < dataBlocks + dataBlocksLength; t++) { - long long l = *t; - endswap(l); - this->blocks.push_back(l); - } - - light.assign(dataLight, dataLight + 2048); - - if (dataSky != nullptr) { - sky.assign(dataSky, dataSky + 2048); - } -} + return hash; +} \ No newline at end of file diff --git a/src/Section.hpp b/src/Section.hpp index dfa738a..bda3584 100644 --- a/src/Section.hpp +++ b/src/Section.hpp @@ -11,47 +11,45 @@ #include "Vector.hpp" #include "Utility.hpp" -struct PackedSection { - Vector position; - - int bitsPerBlock; - - std::vector palette; - - std::vector blocks; +class Section { + std::vector block; std::vector light; std::vector sky; - - PackedSection(Vector position, byte *dataBlocks, size_t dataBlocksLength, byte *dataLight, byte *dataSky, byte bitsPerBlock, - std::vector palette); - - PackedSection() = default; -}; - -class Section { - std::vector blocks; + unsigned char bitsPerBlock; + std::vector palette; Vector worldPosition; + size_t hash; + void CalculateHash(); public: + Section(Vector pos, unsigned char bitsPerBlock, std::vector palette, std::vector blockData, std::vector lightData, std::vector skyData); - Section(PackedSection data); + Section(); ~Section(); + Section(const Section &other); + Section(Section &&other) noexcept; - Block &GetBlock(Vector pos); + Section &operator=(Section other) noexcept; - Block GetBlock(Vector pos) const; + BlockId GetBlockId(Vector pos) const; - Section &operator=(Section other) noexcept; + unsigned char GetBlockLight(Vector pos); - friend void swap(Section& lhs, Section& rhs) noexcept; + unsigned char GetBlockSkyLight(Vector pos); - Section(const Section &other); + void SetBlockId(Vector pos, BlockId value); + + void SetBlockLight(Vector pos, unsigned char value); + + void SetBlockSkyLight(Vector pos, unsigned char value); Vector GetPosition() const; size_t GetHash() const; + + friend void swap(Section& lhs, Section& rhs) noexcept; }; \ No newline at end of file diff --git a/src/Socket.cpp b/src/Socket.cpp index 519da2f..aea0c73 100644 --- a/src/Socket.cpp +++ b/src/Socket.cpp @@ -1,30 +1,37 @@ #include #include "Socket.hpp" -Socket::Socket(std::string address, unsigned short port) { - sf::Socket::Status connectionStatus = socket.connect(sf::IpAddress(address), port); - if (connectionStatus == sf::Socket::Status::Error) - throw std::runtime_error("Can't connect to remote server"); - else if (connectionStatus != sf::Socket::Status::Done) - throw std::runtime_error("Connection failed with unknown reason"); +#include + +Socket::Socket(std::string address, unsigned short port) { + if (SDLNet_Init() == -1) + throw std::runtime_error("SDL_Net initalization failed: " + std::string(SDLNet_GetError())); + + if (SDLNet_ResolveHost(&server, address.c_str(), port) == -1) + throw std::runtime_error("Hostname not resolved: " + std::string(SDLNet_GetError())); + + socket = SDLNet_TCP_Open(&server); + if (!socket) + throw std::runtime_error(std::string(SDLNet_GetError())); } Socket::~Socket() { - socket.disconnect(); + SDLNet_TCP_Close(socket); + + SDLNet_Quit(); } -void Socket::Read(unsigned char *buffPtr, size_t buffLen) { - size_t received = 0; - socket.receive(buffPtr, buffLen, received); - size_t totalReceived = received; - while (totalReceived < buffLen) { - if (socket.receive(buffPtr + totalReceived, buffLen - totalReceived, received) != sf::Socket::Done) - throw std::runtime_error("Raw socket data receiving is failed"); - totalReceived += received; - } +void Socket::Read(unsigned char *buffPtr, size_t buffLen) { + size_t totalReceived = 0; + while (buffLen > totalReceived) { + size_t received = SDLNet_TCP_Recv(socket, buffPtr + totalReceived, buffLen - totalReceived); + if ( received <= 0) + throw std::runtime_error("Data receiving failed: " + std::string(SDLNet_GetError())); + totalReceived += received; + } } void Socket::Write(unsigned char *buffPtr, size_t buffLen) { - if (socket.send(buffPtr, buffLen) != sf::Socket::Done) - throw std::runtime_error("Raw socket data sending is failed"); + if (SDLNet_TCP_Send(socket, buffPtr, buffLen) < buffLen) + throw std::runtime_error("Data sending failed: " + std::string(SDLNet_GetError())); } diff --git a/src/Socket.hpp b/src/Socket.hpp index 48bcad9..16825f0 100644 --- a/src/Socket.hpp +++ b/src/Socket.hpp @@ -4,14 +4,16 @@ #include +#include + /** * Platform independent class for working with platform dependent hardware socket * @brief Wrapper around raw sockets * @warning Connection state is based on lifetime of Socket object instance, ie connected at ctor and disconnect at dtor - * @todo Replace SFML's socket with WinSock and POSIX's socket implementation */ class Socket { - sf::TcpSocket socket; + IPaddress server; + TCPsocket socket; public: /** * Constructs Socket class instance from IP's string and Port number and connects to remote server @@ -23,7 +25,7 @@ public: /** * Destruct Socket instance and disconnect from server - * @warning There is no way to force disconnect, except use delete for manually allocated objects and scope of visibility for variables on stack + * @warning There is no way to force disconnect, except use delete for manually allocated objects and scope of visibility for auto variables */ ~Socket(); diff --git a/src/Stream.cpp b/src/Stream.cpp index a44b91c..28680c6 100644 --- a/src/Stream.cpp +++ b/src/Stream.cpp @@ -281,8 +281,9 @@ void StreamOutput::WriteByteArray(std::vector value) { void StreamBuffer::ReadData(unsigned char *buffPtr, size_t buffLen) { size_t bufferLengthLeft = buffer + bufferLength - bufferPtr; + if (bufferLengthLeft < buffLen) - throw std::runtime_error("Required data is more, than in buffer available"); + throw std::runtime_error("Internal error: StreamBuffer reader out of data"); std::memcpy(buffPtr, bufferPtr, buffLen); bufferPtr += buffLen; } @@ -290,7 +291,7 @@ void StreamBuffer::ReadData(unsigned char *buffPtr, size_t buffLen) { void StreamBuffer::WriteData(unsigned char *buffPtr, size_t buffLen) { size_t bufferLengthLeft = buffer + bufferLength - bufferPtr; if (bufferLengthLeft < buffLen) - throw std::runtime_error("Required data is more, than in buffer available"); + throw std::runtime_error("Internal error: StreamBuffer writer out of data"); std::memcpy(bufferPtr, buffPtr, buffLen); bufferPtr += buffLen; } diff --git a/src/Widget.cpp b/src/Widget.cpp new file mode 100644 index 0000000..1a522ca --- /dev/null +++ b/src/Widget.cpp @@ -0,0 +1,124 @@ +#include "Widget.hpp" + +void RootWidget::AttachWidget(std::unique_ptr widget, Widget * parent) +{ + parent->childs.push_back(widget.get()); + this->allWidgets.push_back(std::move(widget)); +} + +void RootWidget::AttachWidget(std::unique_ptr widget) { + widget->parent = nullptr; + this->childs.push_back(widget.get()); + this->allWidgets.push_back(std::move(widget)); +} + +std::vector RootWidget::GetRenderList() +{ + std::vector renderList; + + std::function treeWalker = [&](Widget* node) { + for (auto it : node->childs) + treeWalker(it); + renderList.push_back(node); + }; + + for (auto& it : this->childs) + treeWalker(it); + + return renderList; +} + +void RootWidget::UpdateEvents(double mouseX, double mouseY, bool mouseButton) { + + LOG(INFO) << mouseX << "x" << mouseY; + + auto testIsHover = [&](double x, double y, Widget* widget) { + bool isOnX = widget->x > x && widget->x + widget->w < x; + bool isOnY = widget->y > y && widget->y + widget->h < y; + if (mouseButton) + LOG(INFO) << "X: " << isOnX << " Y: " << isOnY; + return isOnX && isOnY; + }; + + std::function treeWalker = [&](Widget* node) { + for (auto it : node->childs) + treeWalker(it); + + if (testIsHover(mouseX,mouseY,node)) { + if (node->onHover) + node->onHover(node); + if (mouseButton && !prevBut) + if (node->onPress) + node->onPress(node); + else if (!mouseButton && prevBut) + if (node->onRelease) + node->onRelease(node); + } + else { + if (testIsHover(prevX, prevY, node)) + if (node->onUnhover) + node->onUnhover(node); + } + + if (node->onUpdate) + node->onUpdate(node); + }; + + for (auto it : childs) + treeWalker(it); + + prevX = mouseX; + prevY = mouseY; + prevBut = mouseButton; +} + +WidgetButton::WidgetButton() +{ + this->state = WidgetState::Idle; + + onHover = [](Widget* widget) { + WidgetButton* w = dynamic_cast(widget); + if (w->state != WidgetState::Pressed) + w->state = WidgetState::Hovering; + LOG(INFO) << "Hover"; + }; + + onPress = [](Widget* widget) { + WidgetButton* w = dynamic_cast(widget); + w->state = WidgetState::Pressed; + LOG(INFO) << "Press"; + }; + + onRelease = [](Widget* widget) { + WidgetButton* w = dynamic_cast(widget); + w->state = WidgetState::Idle; + w->onClick(w); + LOG(INFO) << "Release"; + }; + + onUnhover = [](Widget *widget) { + WidgetButton* w = dynamic_cast(widget); + if (w->state!=WidgetState::Pressed) + w->state = WidgetState::Idle; + LOG(INFO) << "Unhover"; + }; + +} + +std::tuple WidgetButton::GetTexture() +{ + double yOffset; + switch (this->state) { + case WidgetState::Idle: + yOffset = 0.2578; + break; + case WidgetState::Hovering: + yOffset = 0.3359; + break; + case WidgetState::Pressed: + yOffset = 0.1796; + } + + TextureCoordinates texture = AssetManager::Instance().GetTextureByAssetName("minecraft/textures/gui/widgets"); + return { texture.x,texture.y + texture.h * yOffset,texture.w * 0.7812,texture.h * 0.07812 }; +} diff --git a/src/Widget.hpp b/src/Widget.hpp new file mode 100644 index 0000000..6d78ebe --- /dev/null +++ b/src/Widget.hpp @@ -0,0 +1,74 @@ +#pragma once + +#include +#include +#include + +#include "AssetManager.hpp" + +class Widget; +class RootWidget { + std::vector> allWidgets; + + std::vector childs; + + double prevX, prevY; + bool prevBut; +public: + RootWidget() = default; + + ~RootWidget() = default; + + void AttachWidget(std::unique_ptr widget, Widget* parent); + + void AttachWidget(std::unique_ptr widget); + + std::vector GetRenderList(); + + void UpdateEvents(double mouseX, double mouseY, bool mouseButton); +}; + +struct Widget { + Widget() = default; + + virtual ~Widget() = default; + + Widget *parent; + + std::vector childs; + + double x, y, w, h; //In OGL screen-coordinates + + virtual std::tuple GetTexture() = 0; + + + using Handler = std::function; + + Handler onPress; + + Handler onRelease; + + Handler onHover; + + Handler onUnhover; + + Handler onUpdate; +}; + +struct WidgetButton : Widget { + WidgetButton(); + + ~WidgetButton() override = default; + + std::string Text; + + Handler onClick; + + std::tuple GetTexture() override; + + enum class WidgetState { + Idle, + Hovering, + Pressed, + } state; +}; \ No newline at end of file diff --git a/src/World.cpp b/src/World.cpp index f9edbe1..1a0e0fa 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -7,29 +7,23 @@ void World::ParseChunkData(std::shared_ptr packet) { for (int i = 0; i < 16; i++) { if (bitmask[i]) { Vector chunkPosition = Vector(packet->ChunkX, i, packet->ChunkZ); - PackedSection packedSection = ParseSection(&chunkData, chunkPosition); - Section section(packedSection); + Section section = ParseSection(&chunkData, chunkPosition); if (packet->GroundUpContinuous) { - if (!cachedSections.insert(std::make_pair(chunkPosition, section)).second) { + if (!sections.insert(std::make_pair(chunkPosition, section)).second) { LOG(ERROR) << "New chunk not created " << chunkPosition << " potential memory leak"; } } else { using std::swap; - swap(cachedSections.at(chunkPosition), section); + swap(sections.at(chunkPosition), section); } EventAgregator::PushEvent(EventType::ChunkChanged, ChunkChangedData{ chunkPosition }); } } } -PackedSection World::ParseSection(StreamInput *data, Vector position) { - unsigned char bitsPerBlock = data->ReadUByte(); - if (bitsPerBlock < 4) - bitsPerBlock = 4; - - if (bitsPerBlock > 8) - bitsPerBlock = 13; +Section World::ParseSection(StreamInput *data, Vector position) { + unsigned char bitsPerBlock = data->ReadUByte(); int paletteLength = data->ReadVarInt(); std::vector palette; @@ -42,24 +36,17 @@ PackedSection World::ParseSection(StreamInput *data, Vector position) { std::vector skyLight; if (dimension == 0) skyLight = data->ReadByteArray(2048); - return PackedSection(position, dataArray.data(), dataArray.size(), blockLight.data(), - (skyLight.size() > 0 ? skyLight.data() : nullptr), bitsPerBlock, palette); -} -World::~World() { + long long *blockData = reinterpret_cast(dataArray.data()); + for (int i = 0; i < dataArray.size() / sizeof(long long); i++) + endswap(blockData[i]); + std::vector blockArray (blockData, blockData + dataArray.size() / sizeof (long long)); + + + return Section(position, bitsPerBlock, std::move(palette), std::move(blockArray), std::move(blockLight), std::move(skyLight)); } -Block & World::GetBlock(Vector worldPosition) -{ - Vector sectionPos(std::floor(worldPosition.x / 16.0), std::floor(worldPosition.y / 16.0), std::floor(worldPosition.z / 16.0)); - auto it = cachedSections.find(sectionPos); - if (it == cachedSections.end()) { - static Block fallbackBlock; - return fallbackBlock; - } - Section& section = it->second; - Block& block = section.GetBlock(worldPosition - sectionPos * 16); - return block; +World::~World() { } World::World() { @@ -67,7 +54,7 @@ World::World() { bool World::isPlayerCollides(double X, double Y, double Z) { Vector PlayerChunk(floor(X / 16.0), floor(Y / 16.0), floor(Z / 16.0)); - if (cachedSections.find(PlayerChunk) == cachedSections.end() || cachedSections.find(PlayerChunk - Vector(0,1,0)) == cachedSections.end()) + if (sections.find(PlayerChunk) == sections.end() || sections.find(PlayerChunk - Vector(0,1,0)) == sections.end()) return true; std::vector closestSectionsCoordinates = { Vector(PlayerChunk.x, PlayerChunk.y, PlayerChunk.z), @@ -80,7 +67,7 @@ bool World::isPlayerCollides(double X, double Y, double Z) { }; std::vector closestSections; for (auto &coord:closestSectionsCoordinates) { - if (cachedSections.find(coord) != cachedSections.end()) + if (sections.find(coord) != sections.end()) closestSections.push_back(coord); } @@ -102,7 +89,7 @@ bool World::isPlayerCollides(double X, double Y, double Z) { for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { for (int z = 0; z < 16; z++) { - Block block = section.GetBlock(Vector(x, y, z)); + BlockId block = section.GetBlockId(Vector(x, y, z)); if (block.id == 0 || block.id == 31) continue; AABB blockColl{(x + it.x * 16.0), @@ -119,18 +106,18 @@ bool World::isPlayerCollides(double X, double Y, double Z) { std::vector World::GetSectionsList() { std::vector sectionsList; - for (auto& it : cachedSections) { + for (auto& it : sections) { if (std::find(sectionsList.begin(), sectionsList.end(), it.first) == sectionsList.end()) sectionsList.push_back(it.first); } return sectionsList; } -static Section fallbackSection = Section(PackedSection()); +static Section fallbackSection; const Section &World::GetSection(Vector sectionPos) { - auto result = cachedSections.find(sectionPos); - if (result == cachedSections.end()) { + auto result = sections.find(sectionPos); + if (result == sections.end()) { LOG(ERROR) << "Accessed not loaded section " << sectionPos; return fallbackSection; } else { @@ -205,14 +192,14 @@ void World::DeleteEntity(unsigned int EntityId) } void World::ParseChunkData(std::shared_ptr packet) { - Block& block = this->GetBlock(packet->Position); + /*Block& block = this->GetBlock(packet->Position); block = Block(packet->BlockId >> 4, packet->BlockId & 15, block.light, block.sky); Vector sectionPos(std::floor(packet->Position.x / 16.0), std::floor(packet->Position.y / 16.0), std::floor(packet->Position.z / 16.0)); - EventAgregator::PushEvent(EventType::ChunkChanged, ChunkChangedData{ sectionPos }); + EventAgregator::PushEvent(EventType::ChunkChanged, ChunkChangedData{ sectionPos });*/ } void World::ParseChunkData(std::shared_ptr packet) { - std::vector changedSections; + /*std::vector changedSections; for (auto& it : packet->Records) { int x = (it.HorizontalPosition >> 4 & 15) + (packet->ChunkX * 16); int y = it.YCoordinate; @@ -226,17 +213,17 @@ void World::ParseChunkData(std::shared_ptr packet) { changedSections.push_back(sectionPos); } for (auto& sectionPos: changedSections) - EventAgregator::PushEvent(EventType::ChunkChanged, ChunkChangedData{ sectionPos }); + EventAgregator::PushEvent(EventType::ChunkChanged, ChunkChangedData{ sectionPos });*/ } void World::ParseChunkData(std::shared_ptr packet) { std::vector::iterator> toRemove; - for (auto it = cachedSections.begin(); it != cachedSections.end(); ++it) { + for (auto it = sections.begin(); it != sections.end(); ++it) { if (it->first.x == packet->ChunkX && it->first.z == packet->ChunkZ) toRemove.push_back(it); } for (auto& it : toRemove) { EventAgregator::PushEvent(EventType::ChunkDeleted, ChunkDeletedData{ it->first }); - cachedSections.erase(it); + sections.erase(it); } } \ No newline at end of file diff --git a/src/World.hpp b/src/World.hpp index 6ff0619..a5cf60c 100644 --- a/src/World.hpp +++ b/src/World.hpp @@ -16,17 +16,15 @@ class World { int dimension = 0; - //std::map sections; - std::map cachedSections; - PackedSection ParseSection(StreamInput *data, Vector position); + std::map sections; + + Section ParseSection(StreamInput *data, Vector position); std::vector entities; std::mutex entitiesMutex; - Block& GetBlock(Vector worldPosition); - public: World(); diff --git a/src/main.cpp b/src/main.cpp index 0a6ad17..9c38814 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -16,12 +16,9 @@ const char *getTimeSinceProgramStart(void) { INITIALIZE_EASYLOGGINGPP -#ifdef WIN32 -int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, - _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { -#else -int main() { -#endif +#undef main + +int main(int argc, char** argv) { el::Configurations loggerConfiguration; el::Helpers::installCustomFormatSpecifier( el::CustomFormatSpecifier("%startTime", std::bind(getTimeSinceProgramStart))); @@ -37,6 +34,14 @@ int main() { LOG(WARNING) << "Sizeof EventData is " << sizeof(EventData); + try { + if (SDL_Init(0) == -1) + throw std::runtime_error("SDL initialization failed: " + std::string(SDL_GetError())); + } catch (std::exception& e) { + LOG(ERROR) << e.what(); + return -1; + } + ThreadGame game; std::thread threadGame(&ThreadGame::Execute, game); -- cgit v1.2.3