From 6a00886804c53883d919f008f6ec47a574d86607 Mon Sep 17 00:00:00 2001 From: LaG1924 <12997935+LaG1924@users.noreply.github.com> Date: Mon, 24 Jul 2017 19:52:24 +0500 Subject: 2017-07-24 --- CMakeLists.txt | 17 +- cwd/shaders/face.fs | 4 - 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 ++++++++++++++++++++++++++++++++ include/AssetManager.hpp | 75 -- include/Core.hpp | 95 -- include/GameState.hpp | 71 -- include/Nbt.hpp | 516 --------- include/Utility.hpp | 59 -- include/Vector.hpp | 116 -- include/graphics/Gui.hpp | 7 - include/graphics/RenderSection.hpp | 52 - include/graphics/Shader.hpp | 24 - include/graphics/Texture.hpp | 14 - include/graphics/Widget.hpp | 8 - include/network/Network.hpp | 26 - include/network/NetworkClient.hpp | 26 - include/network/Packet.hpp | 521 --------- include/network/Socket.hpp | 46 - include/network/Stream.hpp | 107 -- include/world/Block.hpp | 15 - include/world/Collision.hpp | 8 - include/world/Section.hpp | 51 - include/world/World.hpp | 38 - src/Nbt.hpp | 516 +++++++++ src/Utility.hpp | 59 ++ src/Vector.hpp | 116 ++ src/core/AssetManager.cpp | 2 +- src/core/AssetManager.hpp | 75 ++ src/core/Core.cpp | 4 +- src/core/Core.hpp | 95 ++ src/core/Event.cpp | 76 ++ src/core/Event.hpp | 96 ++ src/graphics/Gui.hpp | 8 + src/graphics/RenderSection.cpp | 18 +- src/graphics/RenderSection.hpp | 52 + src/graphics/Shader.hpp | 24 + src/graphics/Texture.hpp | 14 + src/graphics/Widget.hpp | 8 + src/main.cpp | 5 +- src/network/Network.cpp | 8 +- src/network/Network.hpp | 26 + src/network/NetworkClient.hpp | 26 + src/network/Packet.hpp | 521 +++++++++ src/network/Socket.hpp | 46 + src/network/Stream.hpp | 107 ++ src/world/Block.hpp | 15 + src/world/Collision.hpp | 8 + src/world/GameState.cpp | 2 +- src/world/GameState.hpp | 71 ++ src/world/Section.cpp | 55 +- src/world/Section.hpp | 51 + src/world/World.hpp | 38 + 55 files changed, 4487 insertions(+), 1935 deletions(-) create mode 100644 depedencies/include/mpark/config.hpp create mode 100644 depedencies/include/mpark/in_place.hpp create mode 100644 depedencies/include/mpark/lib.hpp create mode 100644 depedencies/include/mpark/variant.hpp delete mode 100644 include/AssetManager.hpp delete mode 100644 include/Core.hpp delete mode 100644 include/GameState.hpp delete mode 100644 include/Nbt.hpp delete mode 100644 include/Utility.hpp delete mode 100644 include/Vector.hpp delete mode 100644 include/graphics/Gui.hpp delete mode 100644 include/graphics/RenderSection.hpp delete mode 100644 include/graphics/Shader.hpp delete mode 100644 include/graphics/Texture.hpp delete mode 100644 include/graphics/Widget.hpp delete mode 100644 include/network/Network.hpp delete mode 100644 include/network/NetworkClient.hpp delete mode 100644 include/network/Packet.hpp delete mode 100644 include/network/Socket.hpp delete mode 100644 include/network/Stream.hpp delete mode 100644 include/world/Block.hpp delete mode 100644 include/world/Collision.hpp delete mode 100644 include/world/Section.hpp delete mode 100644 include/world/World.hpp create mode 100644 src/Nbt.hpp create mode 100644 src/Utility.hpp create mode 100644 src/Vector.hpp create mode 100644 src/core/AssetManager.hpp create mode 100644 src/core/Core.hpp create mode 100644 src/core/Event.cpp create mode 100644 src/core/Event.hpp create mode 100644 src/graphics/Gui.hpp create mode 100644 src/graphics/RenderSection.hpp create mode 100644 src/graphics/Shader.hpp create mode 100644 src/graphics/Texture.hpp create mode 100644 src/graphics/Widget.hpp create mode 100644 src/network/Network.hpp create mode 100644 src/network/NetworkClient.hpp create mode 100644 src/network/Packet.hpp create mode 100644 src/network/Socket.hpp create mode 100644 src/network/Stream.hpp create mode 100644 src/world/Block.hpp create mode 100644 src/world/Collision.hpp create mode 100644 src/world/GameState.hpp create mode 100644 src/world/Section.hpp create mode 100644 src/world/World.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 33affa0..5c5afaa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,27 +1,18 @@ -cmake_minimum_required(VERSION 3.0) +cmake_minimum_required(VERSION 3.8) project(AltCraft) -set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD 17) set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) ########## # SOURCES ########## -#[[set(SRC_CORE src/core/Core.cpp src/core/AssetManager.cpp) -set(SRC_GRAPHICS src/graphics/Texture.cpp src/graphics/Shader.cpp src/graphics/RenderSection.cpp src/graphics/Gui.cpp - src/graphics/Widget.cpp) -set(SRC_NBT include/Nbt.hpp) -set(SRC_NETWORK src/network/Network.cpp src/network/NetworkClient.cpp src/network/Socket.cpp src/network/Stream.cpp) -set(SRC_WORLD src/world/Block.cpp src/world/Section.cpp src/world/World.cpp src/world/Collision.cpp - src/world/GameState.cpp)*# - -set(SOURCE_FILES src/main.cpp ${SRC_CORE} ${SRC_GRAPHICS} ${SRC_NETWORK} ${SRC_WORLD})]]# file(GLOB_RECURSE SOURCES "./src/*.cpp") -file(GLOB_RECURSE HEADERS "./include/*.hpp") +file(GLOB_RECURSE HEADERS "./src/*.hpp") add_executable(AltCraft ${HEADERS} ${SOURCES}) -target_include_directories(AltCraft PUBLIC include/) +target_include_directories(AltCraft PUBLIC src/) ################ # CONFIGURATION diff --git a/cwd/shaders/face.fs b/cwd/shaders/face.fs index d132d7e..3c9904c 100644 --- a/cwd/shaders/face.fs +++ b/cwd/shaders/face.fs @@ -43,10 +43,6 @@ void main() { if (gl_FragColor.a < 0.3) discard; vec3 hsvColor = rgb2hsv(gl_FragColor.xyz); - /*hsvColor[0]+=fs_in.Color; - hsvColor[1]=0.63; - hsvColor[2]+=0.1;*/ hsvColor+=fs_in.Color; gl_FragColor = vec4(hsv2rgb(hsvColor),1); - //gl_FragColor = vec4(fs_in.Color,1); } \ No newline at end of file diff --git a/depedencies/include/mpark/config.hpp b/depedencies/include/mpark/config.hpp new file mode 100644 index 0000000..b5706b2 --- /dev/null +++ b/depedencies/include/mpark/config.hpp @@ -0,0 +1,69 @@ +// 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 new file mode 100644 index 0000000..56cae13 --- /dev/null +++ b/depedencies/include/mpark/in_place.hpp @@ -0,0 +1,35 @@ +// 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 new file mode 100644 index 0000000..bba58d8 --- /dev/null +++ b/depedencies/include/mpark/lib.hpp @@ -0,0 +1,453 @@ +// 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 new file mode 100644 index 0000000..3faecba --- /dev/null +++ b/depedencies/include/mpark/variant.hpp @@ -0,0 +1,1827 @@ +// 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/include/AssetManager.hpp b/include/AssetManager.hpp deleted file mode 100644 index 26c7eca..0000000 --- a/include/AssetManager.hpp +++ /dev/null @@ -1,75 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include - -#include -#include - -struct TextureCoordinates { - TextureCoordinates(float x = -1, float y = -1, float w = -1, float h = -1) : x(x), y(y), w(w), h(h) {} - - bool operator==(const TextureCoordinates &rhs) const { - return x == rhs.x && - y == rhs.y && - w == rhs.w && - h == rhs.h; - } - - explicit operator bool() const { - return !(*this == TextureCoordinates(-1, -1, -1, -1)); - } - - float x, y, w, h; -}; - -struct BlockTextureId { - //Block sides: 0 - bottom, 1 - top, 2 - north, 3 - south, 4 - west, 5 - east 6 - every side - BlockTextureId(int id = 0, int state = 0, int side = 6) : id(id), state(state), side(side) {} - - int id:9; - int state:4; - int side:3; - - - bool operator<(const BlockTextureId &rhs) const { - if (id < rhs.id) - return true; - if (rhs.id < id) - return false; - if (state < rhs.state) - return true; - if (rhs.state < state) - return false; - return side < rhs.side; - } -}; - -class AssetManager { - Texture *textureAtlas; - std::map assetIds; - std::map assetTextures; - std::map textureAtlasIndexes; -public: - AssetManager(); - - ~AssetManager(); - - void LoadTextureResources(); - - TextureCoordinates GetTextureByAssetName(std::string AssetName); - - std::string GetTextureAssetNameByBlockId(BlockTextureId block); - - GLuint GetTextureAtlas(); - - const std::map &GetTextureAtlasIndexes(); - - void LoadIds(); - - TextureCoordinates GetTextureByBlock(BlockTextureId block); -}; diff --git a/include/Core.hpp b/include/Core.hpp deleted file mode 100644 index 8d60ff6..0000000 --- a/include/Core.hpp +++ /dev/null @@ -1,95 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -struct MyMutex { - std::mutex mtx; - std::string str; - MyMutex(std::string name); - void lock(); - void unlock(); -}; - -class Core { - GameState *gameState; - NetworkClient *client; - sf::Window *window; - AssetManager *assetManager; - bool isMouseCaptured = false; - bool isRunning = true; - enum { - MainMenu, - Loading, - Playing, - PauseMenu, - } currentState = Playing; - float mouseXDelta, mouseYDelta; - float deltaTime; - float absTime; - - void RenderWorld(); - - void HandleMouseCapture(); - - void HandleEvents(); - - void InitSfml(unsigned int WinWidth, unsigned int WinHeight, std::string WinTitle); - - void InitGlew(); - - void SetMouseCapture(bool IsCaptured); - - void PrepareToRendering(); - - void RenderFrame(); - - unsigned int width(); - - unsigned int height(); - - void UpdateChunksToRender(); - - void UpdateGameState(); - - void UpdateSections(); - - std::thread gameStateLoopThread; - std::thread sectionUpdateLoopThread; - - Shader *shader; - //Cube verticies, Cube VAO, Cube UVs, TextureIndexes UboTextureIndexes, TextureData UboTextureIndexes, TextureData2 UboTextureIndexes, Blocks VBO, Models VBO, Line VAO, Lines VBO - bool isRendersShouldBeCreated=false; - std::condition_variable waitRendersCreated; - std::vector renders; - std::mutex toRenderMutex; - std::vector toRender; - std::map availableChunks; - std::mutex availableChunksMutex; - - int ChunkDistance = 1; - - RenderState renderState; - - double tickRate = 0; - double sectionRate = 0; - -public: - Core(); - - ~Core(); - - void Exec(); -}; diff --git a/include/GameState.hpp b/include/GameState.hpp deleted file mode 100644 index 6741882..0000000 --- a/include/GameState.hpp +++ /dev/null @@ -1,71 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include - -class GameState { - NetworkClient *nc; -public: - GameState(NetworkClient *NetClient, bool &quit); - - void Update(float deltaTime); - - //Navigation - enum Direction { - FORWARD, BACKWARD, LEFT, RIGHT, JUMP - }; - void HandleMovement(GameState::Direction direction, float deltaTime); - void HandleRotation(double yaw, double pitch); - glm::mat4 GetViewMatrix(); - void updateCameraVectors(); - - float Yaw(); - float Pitch(); - void SetYaw(float yaw); - void SetPitch(float pitch); - - glm::vec3 Position(); - void SetPosition(glm::vec3 Position); - glm::vec3 Front; - glm::vec3 Up; - glm::vec3 Right; - glm::vec3 WorldUp; - - //Everything other - World world; - bool &isRunning; - - std::string g_PlayerUuid; - std::string g_PlayerName; - bool g_IsGameStarted; - int g_PlayerEid; - int g_Gamemode; - int g_Dimension; - byte g_Difficulty; - byte g_MaxPlayers; - std::string g_LevelType; - bool g_ReducedDebugInfo; - Vector g_SpawnPosition; - bool g_PlayerInvulnerable; - bool g_PlayerFlying; - bool g_PlayerAllowFlying; - bool g_PlayerCreativeMode; - float g_PlayerFlyingSpeed; - float g_PlayerFovModifier; - float g_PlayerPitch; - float g_PlayerYaw; - double g_PlayerX; - double g_PlayerY; - double g_PlayerZ; - float g_PlayerHealth; - - bool g_OnGround = true; - double g_PlayerVelocityX = 0; - double g_PlayerVelocityY = 0; - double g_PlayerVelocityZ = 0; -}; diff --git a/include/Nbt.hpp b/include/Nbt.hpp deleted file mode 100644 index 03f5af0..0000000 --- a/include/Nbt.hpp +++ /dev/null @@ -1,516 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include - -namespace nbt { - enum TagType { - End, //nullptr - Byte, //int8_t - Short, //int16_t - Int, //int32_t - Long, //int64_t - Float, //float - Double, //double - ByteArray, //std::vector - String, //std::string - List, //std::vector - Compound, //std::vector - IntArray, //std::vector - Unknown, //dummy value - }; - - class NbtTag; - - typedef std::vector compound_t; - - typedef std::string string_t; - - typedef std::vector byteArray_t; - - typedef std::vector intArray_t; - - class NbtTag { - TagType type = Unknown; - string_t name = ""; - unsigned char *data = nullptr; - public: - NbtTag(TagType type, string_t name) : type(type), name(name) { - switch (type) { - case End: - data = nullptr; - break; - case Compound: - data = (unsigned char *) new compound_t; - break; - case String: - data = (unsigned char *) new string_t; - break; - case Int: - data = (unsigned char *) new int32_t; - break; - case Long: - data = (unsigned char *) new int64_t; - break; - case Byte: - data = (unsigned char *) new int8_t; - break; - case Short: - data = (unsigned char *) new int16_t; - break; - case Float: - data = (unsigned char *) new float; - break; - case Double: - data = (unsigned char *) new double; - break; - case ByteArray: - data = (unsigned char *) new byteArray_t; - break; - case List: - data = (unsigned char *) new compound_t; - break; - case IntArray: - data = (unsigned char *) new intArray_t; - } - } - - NbtTag(const NbtTag &other) : type(other.type), name(other.name) { - switch (type) { - case Byte: - data = (unsigned char *) new int8_t; - *((int8_t *) data) = *((int8_t *) other.data); - break; - case Short: - data = (unsigned char *) new int16_t; - *((int16_t *) data) = *((int16_t *) other.data); - break; - case Int: - data = (unsigned char *) new int32_t; - *((int32_t *) data) = *((int32_t *) other.data); - break; - case Long: - data = (unsigned char *) new int64_t; - *((int64_t *) data) = *((int64_t *) other.data); - break; - case Float: - data = (unsigned char *) new float; - *((float *) data) = *((float *) other.data); - break; - case Double: - data = (unsigned char *) new double; - *((double *) data) = *((double *) other.data); - break; - case ByteArray: - data = (unsigned char *) new byteArray_t; - *((std::vector *) data) = *((std::vector *) other.data); - break; - case String: - data = (unsigned char *) new string_t; - *((std::string *) data) = *((std::string *) other.data); - break; - case List: - data = (unsigned char *) new compound_t; - *((std::vector *) data) = *((std::vector *) other.data); - break; - case Compound: - data = (unsigned char *) new compound_t; - *((std::vector *) data) = *((std::vector *) other.data); - break; - case IntArray: - data = (unsigned char *) new intArray_t; - *((std::vector *) data) = *((std::vector *) other.data); - break; - } - } - - ~NbtTag() { - switch (type) { - case Byte: - delete ((int8_t *) data); - break; - case Short: - delete ((int16_t *) data); - break; - case Int: - delete ((int32_t *) data); - break; - case Long: - delete ((int64_t *) data); - break; - case Float: - delete ((float *) data); - break; - case Double: - delete ((double *) data); - break; - case ByteArray: - delete ((std::vector *) data); - break; - case String: - delete ((std::string *) data); - break; - case List: - delete ((std::vector *) data); - break; - case Compound: - delete ((std::vector *) data); - break; - case IntArray: - delete ((std::vector *) data); - break; - } - }; - - void swap(NbtTag &other) { - std::swap(other.data, data); - std::swap(other.name, name); - std::swap(other.type, type); - } - - NbtTag &operator=(NbtTag other) { - other.swap(*this); - return *this; - } - - TagType GetType() const { - return type; - } - - string_t GetName() const { - return name; - } - - - string_t &GetString() { - string_t &val = *reinterpret_cast(data); - return val; - } - - compound_t &GetCompound() { - std::vector &val = *reinterpret_cast *>(data); - return val; - } - - compound_t &GetList() { - std::vector &val = *reinterpret_cast *>(data); - return val; - } - - int64_t &GetLong() { - int64_t &val = *reinterpret_cast(data); - return val; - } - - float &GetFloat() { - float &val = *reinterpret_cast(data); - return val; - } - - double &GetDouble() { - double &val = *reinterpret_cast(data); - return val; - } - - byteArray_t &GetByteArray() { - auto &val = *reinterpret_cast(data); - return val; - } - - intArray_t &GetIntArray() { - auto &val = *reinterpret_cast(data); - return val; - } - - int16_t &GetShort() { - auto &val = *reinterpret_cast(data); - return val; - } - - int32_t &GetInt() { - auto &val = *reinterpret_cast(data); - return val; - } - - int8_t &GetByte() { - auto &val = *reinterpret_cast(data); - return val; - } - }; - - NbtTag ParseTag(unsigned char *data, size_t &size, TagType listItemType = Unknown) { - size = 0; - TagType type; - if (listItemType == Unknown) { - type = (TagType) *data; - data += 1; - size += 1; - } else - type = listItemType; - string_t name; - if (listItemType == Unknown && type != End) { - short nameLen = *((short *) data); - data += 2; - size += 2; - endswap(&nameLen); - name = std::string((char *) data, nameLen); - data += nameLen; - size += nameLen; - } - NbtTag tag(type, name); - switch (type) { - case Compound: { - do { - size_t s; - tag.GetCompound().push_back(ParseTag(data, s)); - data += s; - size += s; - } while (tag.GetCompound().back().GetType() != End); - tag.GetCompound().pop_back(); - return tag; - } - case String: { - short len = *((short *) data); - data += 2; - size += 2; - endswap(&len); - string_t str((char *) data, len); - data += len; - size += len; - tag.GetString() = str; - return tag; - } - case End: - return tag; - case Long: - tag.GetLong() = *((int64_t *) data); - endswap(&tag.GetLong()); - data += 8; - size += 8; - return tag; - case Short: - tag.GetShort() = *((int16_t *) data); - endswap(&tag.GetShort()); - data += 2; - size += 2; - return tag; - case Float: - tag.GetFloat() = *((float *) data); - endswap(&tag.GetFloat()); - data += 4; - size += 4; - return tag; - case Double: - tag.GetDouble() = *((double *) data); - endswap(&tag.GetDouble()); - data += 8; - size += 8; - return tag; - case Byte: - tag.GetByte() = *((int8_t *) data); - endswap(&tag.GetByte()); - data += 1; - size += 1; - return tag; - case Int: - tag.GetInt() = *((int32_t *) data); - endswap(&tag.GetInt()); - data += 4; - size += 4; - return tag; - case List: { - TagType listType = *((TagType *) data); - data += 1; - size += 1; - int32_t listLength = *((int32_t *) data); - endswap(&listLength); - data += 4; - size += 4; - for (int i = 0; i < listLength; i++) { - size_t s = 0; - std::vector &vec = tag.GetCompound(); - vec.push_back(ParseTag(data, s, listType)); - data += s; - size += s; - } - return tag; - } - case ByteArray: { - int32_t arrLength = *((int32_t *) data); - endswap(&arrLength); - data += 4; - size += 4; - for (int i = 0; i < arrLength; i++) { - signed char val = (signed char) data[i]; - std::vector &vec = tag.GetByteArray(); - vec.push_back(val); - } - data += arrLength; - size += arrLength; - return tag; - } - default: - throw 13; - } - } - - NbtTag ParseTag(unsigned char *data, size_t *optionalSize = nullptr) { - size_t s = 0; - size_t &size = (optionalSize ? *optionalSize : s); - return ParseTag(data, size); - } - - std::vector Decompress(unsigned char *data, size_t dataLen) { - const size_t decompBuffSize = 1024 * 16; - unsigned char *decompBuff = new unsigned char[decompBuffSize]; - std::vector uncompressed; - for (int i = 0; i < decompBuffSize; i++) - decompBuff[i] = 0; - - - z_stream stream; - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; - stream.next_in = data; - stream.avail_in = dataLen; - stream.next_out = decompBuff; - stream.avail_out = decompBuffSize; - - if (inflateInit2(&stream, 15 + 32) != Z_OK) { - delete[] decompBuff; - throw 171; - } - - int res; - do { - stream.avail_out = decompBuffSize; - - switch ((res = inflate(&stream, Z_NO_FLUSH))) { - case Z_MEM_ERROR: - throw 172; - case Z_DATA_ERROR: - throw 173; - case Z_NEED_DICT: - throw 174; - } - - uncompressed.resize(uncompressed.size() + decompBuffSize); - std::copy(decompBuff, decompBuff + decompBuffSize, uncompressed.end() - decompBuffSize); - } while (stream.avail_out == 0); - if (res != Z_STREAM_END) - throw 175; - if (inflateEnd(&stream) != Z_OK) - throw 176; - delete[] decompBuff; - return uncompressed; - } - - NbtTag ParseCompressed(unsigned char *data, size_t dataLen) { - auto uncompressed = Decompress(data, dataLen); - NbtTag root = ParseTag(uncompressed.data()); - return root; - } - - NbtTag Parse(unsigned char *data, size_t dataLen) { - bool isCompressed = *data != 10; - if (isCompressed) - return ParseCompressed(data, dataLen); - else - return ParseTag(data); - } - - void PrintTree(NbtTag &tree, int deepness = 0, std::ostream &ostream = std::cout) { - ostream << std::string(deepness, '\t') << "Tag "; - switch (tree.GetType()) { - case Byte: - ostream << "byte"; - break; - case Short: - ostream << "short"; - break; - case Int: - ostream << "int"; - break; - case Long: - ostream << "long"; - break; - case Float: - ostream << "float"; - break; - case Double: - ostream << "double"; - break; - case ByteArray: - ostream << "byte array"; - break; - case String: - ostream << "string"; - break; - case List: - ostream << "list"; - break; - case Compound: - ostream << "compound"; - break; - case IntArray: - ostream << "int array"; - break; - case End: - ostream << "end"; - break; - } - if (tree.GetName().length() > 0) - ostream << " (" << tree.GetName() << ")"; - ostream << ": "; - - if (tree.GetType() == Compound || tree.GetType() == List) { - std::vector &vec = (tree.GetType() == Compound ? tree.GetCompound() : tree.GetList()); - ostream << vec.size() << " entries {" << std::endl; - for (auto it = vec.begin(); it != vec.end(); ++it) { - PrintTree(*it, deepness + 1, std::cout); - } - ostream << std::string(deepness, '\t') << "}" << std::endl; - return; - } else { - switch (tree.GetType()) { - case Int: - ostream << tree.GetInt(); - break; - case String: - ostream << "\"" << tree.GetString() << "\""; - break; - case Double: - ostream << tree.GetDouble(); - break; - case Float: - ostream << tree.GetFloat(); - break; - case Short: - ostream << tree.GetShort(); - break; - case Byte: - ostream << (int) tree.GetByte(); - break; - case Long: - ostream << tree.GetLong(); - break; - case ByteArray: - ostream << "[" << tree.GetByteArray().size() << " bytes]: "; - for (int i = 0; i < (tree.GetByteArray().size() > 10 ? 10 : tree.GetByteArray().size()); i++) { - ostream << std::hex << "0x" << (tree.GetByteArray()[i] > 15 ? "" : "0") - << (int) tree.GetByteArray()[i] - << std::dec << " "; - } - break; - case IntArray: - break; - } - ostream << std::endl; - } - } -} \ No newline at end of file diff --git a/include/Utility.hpp b/include/Utility.hpp deleted file mode 100644 index 11b4ff7..0000000 --- a/include/Utility.hpp +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once - -#include - -#include - -template -void endswap(T *objp) { - unsigned char *memp = reinterpret_cast(objp); - std::reverse(memp, memp + sizeof(T)); -} - -template -void endswap(T &obj) { - unsigned char *raw = reinterpret_cast(&obj); - std::reverse(raw, raw + sizeof(T)); -} - -inline void endswap(unsigned char *arr, size_t arrLen) { - std::reverse(arr, arr + arrLen); -} - -inline GLenum glCheckError_(const char *file, int line) { - GLenum errorCode; - while ((errorCode = glGetError()) != GL_NO_ERROR) { - std::string error; - switch (errorCode) { - case GL_INVALID_ENUM: - error = "INVALID_ENUM"; - break; - case GL_INVALID_VALUE: - error = "INVALID_VALUE"; - break; - case GL_INVALID_OPERATION: - error = "INVALID_OPERATION"; - break; - case GL_STACK_OVERFLOW: - error = "STACK_OVERFLOW"; - break; - case GL_STACK_UNDERFLOW: - error = "STACK_UNDERFLOW"; - break; - case GL_OUT_OF_MEMORY: - error = "OUT_OF_MEMORY"; - break; - case GL_INVALID_FRAMEBUFFER_OPERATION: - error = "INVALID_FRAMEBUFFER_OPERATION"; - break; - } - static int t = 0; - t++; - if (t>10) - LOG(FATAL); - LOG(ERROR) << "OpenGL error: " << error << " at " << file << ":" << line; - } - return errorCode; -} - -#define glCheckError() glCheckError_(__FILE__, __LINE__) \ No newline at end of file diff --git a/include/Vector.hpp b/include/Vector.hpp deleted file mode 100644 index a2d5c6a..0000000 --- a/include/Vector.hpp +++ /dev/null @@ -1,116 +0,0 @@ -#pragma once - -#include -#include -#include - -#include - -template -class Vector3 { - T x, y, z; -public: - Vector3(T X = 0, T Y = 0, T Z = 0) : x(X), y(Y), z(Z) {} - - Vector3(const Vector3 &rhs) : x(rhs.x), y(rhs.y), z(rhs.z) {} - - ~Vector3() = default; - - void SetX(T X) { x = X; } - - void SetY(T Y) { y = Y; } - - void SetZ(T Z) { z = Z; } - - T GetX() const { return x; } - - T GetY() const { return y; } - - T GetZ() const { return z; } - - double GetMagnitude() const { return std::sqrt(std::pow(x, 2) + std::pow(y, 2) + std::pow(z, 2)); } - - operator glm::vec3() const { - return glm::vec3(x, y, z); - } - - void swap(Vector3 &rhs) { - std::swap(x, rhs.x); - std::swap(y, rhs.y); - std::swap(z, rhs.z); - } - - Vector3 &operator=(Vector3 rhs) { - rhs.swap(*this); - return *this; - } - - Vector3 operator*(T rhs) const { - return Vector3( - x * rhs, - y * rhs, - z * rhs - ); - } - - Vector3 operator/(T rhs) const { - return Vector3( - x / rhs, - y / rhs, - z / rhs - ); - } - - Vector3 operator+(const Vector3 &rhs) const { - return Vector3( - x + rhs.x, - y + rhs.y, - z + rhs.z - ); - } - - Vector3 operator-(const Vector3 &rhs) const { - return Vector3( - x - rhs.x, - y - rhs.y, - z - rhs.z - ); - } - - Vector3 operator*(const Vector3 &rhs) const { - return Vector3( - x * rhs.x, - y * rhs.y, - z * rhs.z - ); - } - - Vector3 operator/(const Vector3 &rhs) const { - return Vector3( - x / rhs.x, - y / rhs.y, - z / rhs.z - ); - } - - bool operator==(const Vector3 &rhs) const { - return (x == rhs.x && y == rhs.y && z == rhs.z); - } - - bool operator!=(const Vector3 &rhs) const { - return !(*this == rhs); - } - - bool operator<(const Vector3 &rhs) const { - return std::tie(x, y, z) < std::tie(rhs.x, rhs.y, rhs.z); - } - - - friend std::ostream &operator<<(std::ostream &os, const Vector3 &vector3) { - os << vector3.x << ", " << vector3.y << ", " << vector3.z; - return os; - } -}; - -typedef Vector3 VectorF; -typedef Vector3 Vector; \ No newline at end of file diff --git a/include/graphics/Gui.hpp b/include/graphics/Gui.hpp deleted file mode 100644 index 641b941..0000000 --- a/include/graphics/Gui.hpp +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -class Gui { - -public: - int WHY=0; -}; diff --git a/include/graphics/RenderSection.hpp b/include/graphics/RenderSection.hpp deleted file mode 100644 index 58c4acf..0000000 --- a/include/graphics/RenderSection.hpp +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -class RenderState { - GLuint ActiveVao; - GLuint ActiveShader; -public: - void SetActiveVao(GLuint Vao); - void SetActiveShader(GLuint Shader); -}; - -class RenderSection { - Vector sectionPosition; - World *world; - GLuint Vao, VboTextures, VboModels, VboColors; - std::vector models; - std::vector textures; - std::vector colors; - - static GLuint VboVertices, VboUvs; - static std::map refCounterVbo; - static std::map refCounterVao; - - size_t numOfFaces = 0; - - bool isEnabled = true; - - size_t hash = 0; -public: - RenderSection(World *world, Vector position); - RenderSection(const RenderSection &other); - ~RenderSection(); - - void UpdateState(const std::map &textureAtlas); - void Render(RenderState &state); - - void SetEnabled(bool isEnabled); - - Section *GetSection(); - - bool IsNeedUpdate(); -}; \ No newline at end of file diff --git a/include/graphics/Shader.hpp b/include/graphics/Shader.hpp deleted file mode 100644 index 17a434e..0000000 --- a/include/graphics/Shader.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include - -class Shader -{ -private: - const GLchar *vertex; - const GLchar *fragment; -public: - // Идентификатор программы - GLuint Program; - // Конструктор считывает и собирает шейдер - Shader(const GLchar* vertexPath, const GLchar* fragmentPath, const GLchar* geometryPath = nullptr); - // Использование программы - void Use(); - - void Reload(); -}; \ No newline at end of file diff --git a/include/graphics/Texture.hpp b/include/graphics/Texture.hpp deleted file mode 100644 index 277806a..0000000 --- a/include/graphics/Texture.hpp +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include -#include - -class Texture { - Texture(Texture&); - Texture&operator=(Texture&); -public: - GLuint texture; - Texture(std::string filename, GLenum textureWrapping = GL_CLAMP_TO_BORDER, GLenum textureFiltering = GL_NEAREST); - ~Texture(); -}; \ No newline at end of file diff --git a/include/graphics/Widget.hpp b/include/graphics/Widget.hpp deleted file mode 100644 index c4d5dc1..0000000 --- a/include/graphics/Widget.hpp +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -class Widget { - unsigned int x,y,w,h; -public: - Widget(Widget *parent); - ~Widget(); -}; diff --git a/include/network/Network.hpp b/include/network/Network.hpp deleted file mode 100644 index 1281289..0000000 --- a/include/network/Network.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include -#include "Socket.hpp" -#include "Packet.hpp" - -enum ConnectionState { - Handshaking, - Login, - Play, - Status, -}; - -class Network { - Socket *socket; - StreamSocket *stream; - - std::shared_ptr ReceivePacketByPacketId(int packetId, ConnectionState state, StreamInput &stream); -public: - Network(std::string address, unsigned short port); - ~Network(); - - std::shared_ptr ReceivePacket(ConnectionState state = Play); - void SendPacket(Packet &packet); - std::shared_ptr ParsePacketPlay(PacketNamePlayCB id); -}; \ No newline at end of file diff --git a/include/network/NetworkClient.hpp b/include/network/NetworkClient.hpp deleted file mode 100644 index 22b1b22..0000000 --- a/include/network/NetworkClient.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include -#include -#include - -#include - -class NetworkClient { - Network network; - std::thread networkThread; - std::mutex toSendMutex; - std::mutex toReceiveMutex; - std::queue > toSend; - std::queue > toReceive; - bool isActive=true; - bool &isRunning; - ConnectionState state; - void NetworkLoop(); -public: - NetworkClient(std::string address, unsigned short port, std::string username, bool &quit); - ~NetworkClient(); - - std::shared_ptr ReceivePacket(); - void SendPacket(std::shared_ptr packet); -}; \ No newline at end of file diff --git a/include/network/Packet.hpp b/include/network/Packet.hpp deleted file mode 100644 index 685e3da..0000000 --- a/include/network/Packet.hpp +++ /dev/null @@ -1,521 +0,0 @@ -#pragma once - -#include - -#include - -enum PacketNameLoginSB { - LoginStart = 0x00, - EncryptionResponse = 0x01, -}; -enum PacketNamePlaySB { - TeleportConfirm, - PrepareCraftingGrid, - TabCompleteSB, - ChatMessageSB, - ClientStatus, - ClientSettings, - ConfirmTransactionSB, - EnchantItem, - ClickWindow, - CloseWindowSB, - PluginMessageSB, - UseEntity, - KeepAliveSB, - Player, - PlayerPosition, - PlayerPositionAndLookSB, - PlayerLook, - VehicleMoveSB, - SteerBoat, - PlayerAbilitiesSB, - PlayerDigging, - EntityAction, - SteerVehicle, - CraftingBookData, - ResourcePackStatus, - AdvancementTab, - HeldItemChangeSB, - CreativeInventoryAction, - UpdateSign, - AnimationSB, - Spectate, - PlayerBlockPlacement, - UseItem, -}; - -enum PacketNameHandshakingCB { - Handshake = 0x00, -}; -enum PacketNameLoginCB { - Disconnect = 0x00, - EncryptionRequest = 0x01, - LoginSuccess = 0x02, - SetCompression = 0x03, -}; -enum PacketNamePlayCB { - SpawnObject = 0x00, - SpawnExperienceOrb, - SpawnGlobalEntity, - SpawnMob, - SpawnPainting, - SpawnPlayer, - AnimationCB, - Statistics, - BlockBreakAnimation, - UpdateBlockEntity, - BlockAction, - BlockChange, - BossBar, - ServerDifficulty, - TabCompleteCB, - ChatMessageCB, - MultiBlockChange, - ConfirmTransactionCB, - CloseWindowCB, - OpenWindow, - WindowItems, - WindowProperty, - SetSlot, - SetCooldown, - PluginMessageCB, - NamedSoundEffect, - DisconnectPlay, - EntityStatus, - Explosion, - UnloadChunk, - ChangeGameState, - KeepAliveCB, - ChunkData, - Effect, - Particle, - JoinGame, - Map, - EntityRelativeMove, - EntityLookAndRelativeMove, - EntityLook, - Entity, - VehicleMove, - OpenSignEditor, - PlayerAbilitiesCB, - CombatEvent, - PlayerListItem, - PlayerPositionAndLookCB, - UseBed, - UnlockRecipes, - DestroyEntities, - RemoveEntityEffect, - ResourcePackSend, - Respawn, - EntityHeadLook, - SelectAdvancementTab, - WorldBorder, - Camera, - HeldItemChangeCB, - DisplayScoreboard, - EntityMetadata, - AttachEntity, - EntityVelocity, - EntityEquipment, - SetExperience, - UpdateHealth, - ScoreboardObjective, - SetPassengers, - Teams, - UpdateScore, - SpawnPosition, - TimeUpdate, - Title, - SoundEffect, - PlayerListHeaderAndFooter, - CollectItem, - EntityTeleport, - Advancements, - EntityProperties, - EntityEffect, -}; - -struct Packet { - virtual ~Packet() = default; - virtual void ToStream(StreamOutput *stream) = 0; - virtual void FromStream(StreamInput *stream) = 0; - virtual int GetPacketId() = 0; -}; - -struct PacketHandshake : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteVarInt(protocolVersion); - stream->WriteString(serverAddress); - stream->WriteUShort(serverPort); - stream->WriteVarInt(nextState); - } - - void FromStream(StreamInput *stream) override { - protocolVersion = stream->ReadVarInt(); - serverAddress = stream->ReadString(); - serverPort = stream->ReadUShort(); - nextState = stream->ReadVarInt(); - } - - int GetPacketId() override { - return PacketNameHandshakingCB::Handshake; - } - - int protocolVersion; - std::string serverAddress; - unsigned short serverPort; - int nextState; -}; - -struct PacketLoginStart : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteString(Username); - } - - void FromStream(StreamInput *stream) override { - Username = stream->ReadString(); - } - - int GetPacketId() override { - return PacketNameLoginSB::LoginStart; - } - - std::string Username; -}; - -struct PacketLoginSuccess : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteString(Uuid); - stream->WriteString(Username); - } - - void FromStream(StreamInput *stream) override { - Uuid = stream->ReadString(); - Username = stream->ReadString(); - } - - int GetPacketId() override { - return PacketNameLoginCB::LoginSuccess; - } - - std::string Uuid; - std::string Username; -}; - -struct PacketJoinGame : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteInt(EntityId); - stream->WriteUByte(Gamemode); - stream->WriteInt(Dimension); - stream->WriteUByte(Difficulty); - stream->WriteUByte(MaxPlayers); - stream->WriteString(LevelType); - stream->WriteBool(ReducedDebugInfo); - } - - void FromStream(StreamInput *stream) override { - EntityId = stream->ReadInt(); - Gamemode = stream->ReadUByte(); - Dimension = stream->ReadInt(); - Difficulty = stream->ReadUByte(); - MaxPlayers = stream->ReadUByte(); - LevelType = stream->ReadString(); - ReducedDebugInfo = stream->ReadBool(); - } - - int GetPacketId() override { - return PacketNamePlayCB::JoinGame; - } - - int EntityId; - unsigned char Gamemode; - int Dimension; - unsigned char Difficulty; - unsigned char MaxPlayers; - std::string LevelType; - bool ReducedDebugInfo; -}; - -struct PacketDisconnectPlay : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteString(Reason); //TODO: Implement chat-wrapper - } - - void FromStream(StreamInput *stream) override { - Reason = stream->ReadChat(); - } - - int GetPacketId() override { - return PacketNamePlayCB::DisconnectPlay; - } - - std::string Reason; -}; - -struct PacketSpawnPosition : Packet { - void ToStream(StreamOutput *stream) override { - stream->WritePosition(Location); - } - - void FromStream(StreamInput *stream) override { - Location = stream->ReadPosition(); - } - - int GetPacketId() override { - return PacketNamePlayCB::SpawnPosition; - } - - Vector Location; -}; - -struct PacketKeepAliveCB : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteVarInt(KeepAliveId); - } - - void FromStream(StreamInput *stream) override { - KeepAliveId = stream->ReadVarInt(); - } - - int GetPacketId() override { - return PacketNamePlayCB::KeepAliveCB; - } - - int KeepAliveId; -}; - -struct PacketKeepAliveSB : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteVarInt(KeepAliveId); - } - - void FromStream(StreamInput *stream) override { - KeepAliveId = stream->ReadVarInt(); - } - - int GetPacketId() override { - return PacketNamePlaySB::KeepAliveSB; - } - - int KeepAliveId; - - PacketKeepAliveSB(int KeepAliveId) : KeepAliveId(KeepAliveId) {} -}; - -struct PacketPlayerPositionAndLookCB : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteDouble(X); - stream->WriteDouble(Y); - stream->WriteDouble(Z); - stream->WriteFloat(Yaw); - stream->WriteFloat(Pitch); - stream->WriteUByte(Flags); - stream->WriteVarInt(TeleportId); - } - - void FromStream(StreamInput *stream) override { - X = stream->ReadDouble(); - Y = stream->ReadDouble(); - Z = stream->ReadDouble(); - Yaw = stream->ReadFloat(); - Pitch = stream->ReadFloat(); - Flags = stream->ReadUByte(); - TeleportId = stream->ReadVarInt(); - } - - int GetPacketId() override { - return PacketNamePlayCB::PlayerPositionAndLookCB; - } - - double X; - double Y; - double Z; - float Yaw; - float Pitch; - unsigned char Flags; - int TeleportId; -}; - -struct PacketTeleportConfirm : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteVarInt(TeleportId); - } - - void FromStream(StreamInput *stream) override { - TeleportId = stream->ReadVarInt(); - } - - int GetPacketId() override { - return PacketNamePlaySB::TeleportConfirm; - } - - int TeleportId; - - PacketTeleportConfirm(int TeleportId) : TeleportId(TeleportId) {} -}; - -struct PacketClientStatus : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteVarInt(ActionId); - } - - void FromStream(StreamInput *stream) override { - ActionId = stream->ReadVarInt(); - } - - int GetPacketId() override { - return PacketNamePlaySB::ClientStatus; - } - - int ActionId; - - PacketClientStatus(int ActionId) : ActionId(ActionId) {} -}; - -struct PacketPlayerPositionAndLookSB : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteDouble(X); - stream->WriteDouble(FeetY); - stream->WriteDouble(Z); - stream->WriteFloat(Yaw); - stream->WriteFloat(Pitch); - stream->WriteBool(OnGround); - } - - void FromStream(StreamInput *stream) override { - X = stream->ReadDouble(); - FeetY = stream->ReadDouble(); - Z = stream->ReadDouble(); - Yaw = stream->ReadFloat(); - Pitch = stream->ReadFloat(); - OnGround = stream->ReadBool(); - } - - int GetPacketId() override { - return PacketNamePlaySB::PlayerPositionAndLookSB; - } - - - double X; - double FeetY; - double Z; - float Yaw; - float Pitch; - bool OnGround; - - PacketPlayerPositionAndLookSB(double X, double FeetY, double Z, - float Yaw, float Pitch, bool OnGround) : X(X), FeetY(FeetY), Z(Z), Yaw(Yaw), - Pitch(Pitch), OnGround(OnGround) {} -}; - -struct PacketChunkData : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteInt(ChunkX); - stream->WriteInt(ChunkZ); - stream->WriteBool(GroundUpContinuous); - stream->WriteInt(PrimaryBitMask); - stream->WriteVarInt(Data.size()); - stream->WriteByteArray(Data); - stream->WriteVarInt(BlockEntities.size()); - LOG(FATAL) << "Serializing unimplemented packet"; - } - - void FromStream(StreamInput *stream) override { - ChunkX = stream->ReadInt(); - ChunkZ = stream->ReadInt(); - GroundUpContinuous = stream->ReadBool(); - PrimaryBitMask = stream->ReadVarInt(); - int Size = stream->ReadVarInt(); - Data = stream->ReadByteArray(Size); - int NumberOfBlockEntities = stream->ReadVarInt(); //TODO: Need NBT - for (int i = 0; i < NumberOfBlockEntities; i++) { - //BlockEntities[i] = stream->ReadNbt(); - } - } - - int GetPacketId() override { - return PacketNamePlayCB::ChunkData; - } - - int ChunkX; - int ChunkZ; - bool GroundUpContinuous; - int PrimaryBitMask; - //int Size; - std::vector Data; - //int NumberOfBlockEntities; - std::vector BlockEntities; //TODO: Replace int with NbtTag and implement NbtTree -}; - -struct PacketPlayerPosition : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteDouble(X); - stream->WriteDouble(FeetY); - stream->WriteDouble(Z); - stream->WriteBool(OnGround); - } - - void FromStream(StreamInput *stream) override { - X = stream->ReadDouble(); - FeetY = stream->ReadDouble(); - Z = stream->ReadDouble(); - OnGround = stream->ReadBool(); - } - - int GetPacketId() override { - return PacketNamePlaySB::PlayerPosition; - } - - double X; - double FeetY; - double Z; - bool OnGround; - - PacketPlayerPosition(double X, double Y, double Z, bool ground) : X(X), FeetY(Y), Z(Z), OnGround(ground) {} -}; - -struct PacketPlayerLook : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteFloat(Yaw); - stream->WriteFloat(Pitch); - stream->WriteBool(OnGround); - } - - void FromStream(StreamInput *stream) override { - Yaw = stream->ReadFloat(); - Pitch = stream->ReadFloat(); - OnGround = stream->ReadBool(); - } - - int GetPacketId() override { - return PacketNamePlaySB::PlayerLook; - } - - float Yaw; - float Pitch; - bool OnGround; - - PacketPlayerLook(float Yaw, float Pitch, bool ground) : Yaw(Yaw), Pitch(Pitch), OnGround(ground) {} -}; - -struct PacketUpdateHealth : Packet { - void ToStream(StreamOutput *stream) override { - stream->WriteFloat(Health); - stream->WriteVarInt(Food); - stream->WriteFloat(FoodSaturation); - } - - void FromStream(StreamInput *stream) override { - Health = stream->ReadFloat(); - Food = stream->ReadVarInt(); - FoodSaturation = stream->ReadFloat(); - } - - int GetPacketId() override { - return PacketNamePlayCB::UpdateHealth; - } - - float Health; - int Food; - float FoodSaturation; -}; \ No newline at end of file diff --git a/include/network/Socket.hpp b/include/network/Socket.hpp deleted file mode 100644 index 48bcad9..0000000 --- a/include/network/Socket.hpp +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#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; -public: - /** - * Constructs Socket class instance from IP's string and Port number and connects to remote server - * @param[in] address IP address of remote server. String should be ANSI and contains 4 one-byte values separated by dots - * @param[in] port target port of remote server to connect - * @throw std::runtime_error if connection is failed - */ - Socket(std::string address, unsigned short port); - - /** - * 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 - */ - ~Socket(); - - /** - * Reads data from socket and write to buffer - * @warning This is blocking function, and execution flow will not be returned until all required data is sended - * @warning Reported buffer length must be <= actual size of buffer, or memory corruption will be caused - * @param[out] buffPtr Pointer to buffer, where data must be placed - * @param[in] buffLen Length of data, that must be readed from server and writed to buffer - */ - void Read(unsigned char *buffPtr, size_t buffLen); - - /** - * Writes data from buffer to socket - * @warning This is blocking function, and execution flow will not be returned until all required data is received - * @param[in] buffPtr Pointer to buffer that contain data to send - * @param[in] buffLen Length of buffer - */ - void Write(unsigned char *buffPtr, size_t buffLen); -}; \ No newline at end of file diff --git a/include/network/Stream.hpp b/include/network/Stream.hpp deleted file mode 100644 index a24dfbe..0000000 --- a/include/network/Stream.hpp +++ /dev/null @@ -1,107 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include - -class Stream { -public: - virtual ~Stream() {}; -}; - -class StreamInput : Stream { - virtual void ReadData(unsigned char *buffPtr, size_t buffLen) = 0; -public: - virtual ~StreamInput() = default; - bool ReadBool(); - signed char ReadByte(); - unsigned char ReadUByte(); - short ReadShort(); - unsigned short ReadUShort(); - int ReadInt(); - long long ReadLong(); - float ReadFloat(); - double ReadDouble(); - std::string ReadString(); - std::string ReadChat(); - int ReadVarInt(); - long long ReadVarLong(); - std::vector ReadEntityMetadata(); - std::vector ReadSlot(); - std::vector ReadNbtTag(); - Vector ReadPosition(); - unsigned char ReadAngle(); - std::vector ReadUuid(); - std::vector ReadByteArray(size_t arrLength); -}; - -class StreamOutput : Stream { - virtual void WriteData(unsigned char *buffPtr, size_t buffLen) = 0; -public: - virtual ~StreamOutput() = default; - void WriteBool(bool value); - void WriteByte(signed char value); - void WriteUByte(unsigned char value); - void WriteShort(short value); - void WriteUShort(unsigned short value); - void WriteInt(int value); - void WriteLong(long long value); - void WriteFloat(float value); - void WriteDouble(double value); - void WriteString(std::string value); - void WriteChat(std::string value); - void WriteVarInt(int value); - void WriteVarLong(long long value); - void WriteEntityMetadata(std::vector value); - void WriteSlot(std::vector value); - void WriteNbtTag(std::vector value); - void WritePosition(Vector value); - void WriteAngle(unsigned char value); - void WriteUuid(std::vector value); - void WriteByteArray(std::vector value); -}; - -class StreamBuffer : public StreamInput, public StreamOutput { - unsigned char *buffer; - unsigned char *bufferPtr; - size_t bufferLength; - - void ReadData(unsigned char *buffPtr, size_t buffLen) override; - void WriteData(unsigned char *buffPtr, size_t buffLen) override; - -public: - StreamBuffer(unsigned char *data, size_t dataLen); - StreamBuffer(size_t bufferLen); - ~StreamBuffer(); - - std::vector GetBuffer(); -}; - -class StreamCounter : public StreamOutput { - void WriteData(unsigned char *buffPtr, size_t buffLen) override; - - size_t size; -public: - StreamCounter(size_t initialSize = 0); - ~StreamCounter(); - - size_t GetCountedSize(); -}; - -class StreamSocket : public StreamInput, public StreamOutput { - Socket *socket; - void ReadData(unsigned char *buffPtr, size_t buffLen) override; - void WriteData(unsigned char *buffPtr, size_t buffLen) override; -public: - StreamSocket(Socket *socketPtr); - ~StreamSocket() = default; -}; \ No newline at end of file diff --git a/include/world/Block.hpp b/include/world/Block.hpp deleted file mode 100644 index 2f823fe..0000000 --- a/include/world/Block.hpp +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -struct Block { - Block(); - - Block(unsigned short id, unsigned char state); - - ~Block(); - - unsigned short id : 13; - unsigned char state : 4; - //unsigned char light:4; -}; - -bool operator<(const Block &lhs, const Block &rhs); \ No newline at end of file diff --git a/include/world/Collision.hpp b/include/world/Collision.hpp deleted file mode 100644 index b88fbf7..0000000 --- a/include/world/Collision.hpp +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -struct AABB { - double x,y,z; - double w,l,h; -}; - -bool TestCollision(AABB first, AABB second); \ No newline at end of file diff --git a/include/world/Section.hpp b/include/world/Section.hpp deleted file mode 100644 index 2df0cfe..0000000 --- a/include/world/Section.hpp +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include - -#include -#include -#include - -const int SECTION_WIDTH = 16; -const int SECTION_LENGTH = 16; -const int SECTION_HEIGHT = 16; - -class Section { - std::vector m_palette; - byte *m_dataBlocks = nullptr; - size_t m_dataBlocksLen; - byte *m_dataLight = nullptr; - byte *m_dataSkyLight = nullptr; - byte m_bitsPerBlock = 0; - std::vector m_blocks; - std::condition_variable parseWaiter; - - Section(); - - Vector worldPosition; - -public: - void Parse(); - - Section(Vector position, byte *dataBlocks, size_t dataBlocksLength, byte *dataLight, byte *dataSky, byte bitsPerBlock, - std::vector palette); - - ~Section(); - - Block &GetBlock(Vector pos); - - Section &operator=(Section other); - - friend void swap(Section &a, Section &b); - - Section(const Section &other); - - Vector GetPosition(); - - size_t GetHash(); -}; \ No newline at end of file diff --git a/include/world/World.hpp b/include/world/World.hpp deleted file mode 100644 index 6b09f1f..0000000 --- a/include/world/World.hpp +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include -#include - -#include - -#include -#include -#include -#include - -class World { - std::map sections; - std::map sectionMutexes; - int dimension = 0; - - Section ParseSection(StreamInput *data, Vector position); - - World(const World &other); - World &operator=(const World &other); -public: - World(); - - ~World(); - - void ParseChunkData(std::shared_ptr packet); - - bool isPlayerCollides(double X, double Y, double Z); - - Block &GetBlock(Vector pos); - - std::vector GetSectionsList(); - - Section &GetSection(Vector sectionPos); - - glm::vec3 Raycast(glm::vec3 position, glm::vec3 direction, float maxLength = 1000.0f, float minPrecision = 0.01f); -}; \ No newline at end of file diff --git a/src/Nbt.hpp b/src/Nbt.hpp new file mode 100644 index 0000000..03f5af0 --- /dev/null +++ b/src/Nbt.hpp @@ -0,0 +1,516 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace nbt { + enum TagType { + End, //nullptr + Byte, //int8_t + Short, //int16_t + Int, //int32_t + Long, //int64_t + Float, //float + Double, //double + ByteArray, //std::vector + String, //std::string + List, //std::vector + Compound, //std::vector + IntArray, //std::vector + Unknown, //dummy value + }; + + class NbtTag; + + typedef std::vector compound_t; + + typedef std::string string_t; + + typedef std::vector byteArray_t; + + typedef std::vector intArray_t; + + class NbtTag { + TagType type = Unknown; + string_t name = ""; + unsigned char *data = nullptr; + public: + NbtTag(TagType type, string_t name) : type(type), name(name) { + switch (type) { + case End: + data = nullptr; + break; + case Compound: + data = (unsigned char *) new compound_t; + break; + case String: + data = (unsigned char *) new string_t; + break; + case Int: + data = (unsigned char *) new int32_t; + break; + case Long: + data = (unsigned char *) new int64_t; + break; + case Byte: + data = (unsigned char *) new int8_t; + break; + case Short: + data = (unsigned char *) new int16_t; + break; + case Float: + data = (unsigned char *) new float; + break; + case Double: + data = (unsigned char *) new double; + break; + case ByteArray: + data = (unsigned char *) new byteArray_t; + break; + case List: + data = (unsigned char *) new compound_t; + break; + case IntArray: + data = (unsigned char *) new intArray_t; + } + } + + NbtTag(const NbtTag &other) : type(other.type), name(other.name) { + switch (type) { + case Byte: + data = (unsigned char *) new int8_t; + *((int8_t *) data) = *((int8_t *) other.data); + break; + case Short: + data = (unsigned char *) new int16_t; + *((int16_t *) data) = *((int16_t *) other.data); + break; + case Int: + data = (unsigned char *) new int32_t; + *((int32_t *) data) = *((int32_t *) other.data); + break; + case Long: + data = (unsigned char *) new int64_t; + *((int64_t *) data) = *((int64_t *) other.data); + break; + case Float: + data = (unsigned char *) new float; + *((float *) data) = *((float *) other.data); + break; + case Double: + data = (unsigned char *) new double; + *((double *) data) = *((double *) other.data); + break; + case ByteArray: + data = (unsigned char *) new byteArray_t; + *((std::vector *) data) = *((std::vector *) other.data); + break; + case String: + data = (unsigned char *) new string_t; + *((std::string *) data) = *((std::string *) other.data); + break; + case List: + data = (unsigned char *) new compound_t; + *((std::vector *) data) = *((std::vector *) other.data); + break; + case Compound: + data = (unsigned char *) new compound_t; + *((std::vector *) data) = *((std::vector *) other.data); + break; + case IntArray: + data = (unsigned char *) new intArray_t; + *((std::vector *) data) = *((std::vector *) other.data); + break; + } + } + + ~NbtTag() { + switch (type) { + case Byte: + delete ((int8_t *) data); + break; + case Short: + delete ((int16_t *) data); + break; + case Int: + delete ((int32_t *) data); + break; + case Long: + delete ((int64_t *) data); + break; + case Float: + delete ((float *) data); + break; + case Double: + delete ((double *) data); + break; + case ByteArray: + delete ((std::vector *) data); + break; + case String: + delete ((std::string *) data); + break; + case List: + delete ((std::vector *) data); + break; + case Compound: + delete ((std::vector *) data); + break; + case IntArray: + delete ((std::vector *) data); + break; + } + }; + + void swap(NbtTag &other) { + std::swap(other.data, data); + std::swap(other.name, name); + std::swap(other.type, type); + } + + NbtTag &operator=(NbtTag other) { + other.swap(*this); + return *this; + } + + TagType GetType() const { + return type; + } + + string_t GetName() const { + return name; + } + + + string_t &GetString() { + string_t &val = *reinterpret_cast(data); + return val; + } + + compound_t &GetCompound() { + std::vector &val = *reinterpret_cast *>(data); + return val; + } + + compound_t &GetList() { + std::vector &val = *reinterpret_cast *>(data); + return val; + } + + int64_t &GetLong() { + int64_t &val = *reinterpret_cast(data); + return val; + } + + float &GetFloat() { + float &val = *reinterpret_cast(data); + return val; + } + + double &GetDouble() { + double &val = *reinterpret_cast(data); + return val; + } + + byteArray_t &GetByteArray() { + auto &val = *reinterpret_cast(data); + return val; + } + + intArray_t &GetIntArray() { + auto &val = *reinterpret_cast(data); + return val; + } + + int16_t &GetShort() { + auto &val = *reinterpret_cast(data); + return val; + } + + int32_t &GetInt() { + auto &val = *reinterpret_cast(data); + return val; + } + + int8_t &GetByte() { + auto &val = *reinterpret_cast(data); + return val; + } + }; + + NbtTag ParseTag(unsigned char *data, size_t &size, TagType listItemType = Unknown) { + size = 0; + TagType type; + if (listItemType == Unknown) { + type = (TagType) *data; + data += 1; + size += 1; + } else + type = listItemType; + string_t name; + if (listItemType == Unknown && type != End) { + short nameLen = *((short *) data); + data += 2; + size += 2; + endswap(&nameLen); + name = std::string((char *) data, nameLen); + data += nameLen; + size += nameLen; + } + NbtTag tag(type, name); + switch (type) { + case Compound: { + do { + size_t s; + tag.GetCompound().push_back(ParseTag(data, s)); + data += s; + size += s; + } while (tag.GetCompound().back().GetType() != End); + tag.GetCompound().pop_back(); + return tag; + } + case String: { + short len = *((short *) data); + data += 2; + size += 2; + endswap(&len); + string_t str((char *) data, len); + data += len; + size += len; + tag.GetString() = str; + return tag; + } + case End: + return tag; + case Long: + tag.GetLong() = *((int64_t *) data); + endswap(&tag.GetLong()); + data += 8; + size += 8; + return tag; + case Short: + tag.GetShort() = *((int16_t *) data); + endswap(&tag.GetShort()); + data += 2; + size += 2; + return tag; + case Float: + tag.GetFloat() = *((float *) data); + endswap(&tag.GetFloat()); + data += 4; + size += 4; + return tag; + case Double: + tag.GetDouble() = *((double *) data); + endswap(&tag.GetDouble()); + data += 8; + size += 8; + return tag; + case Byte: + tag.GetByte() = *((int8_t *) data); + endswap(&tag.GetByte()); + data += 1; + size += 1; + return tag; + case Int: + tag.GetInt() = *((int32_t *) data); + endswap(&tag.GetInt()); + data += 4; + size += 4; + return tag; + case List: { + TagType listType = *((TagType *) data); + data += 1; + size += 1; + int32_t listLength = *((int32_t *) data); + endswap(&listLength); + data += 4; + size += 4; + for (int i = 0; i < listLength; i++) { + size_t s = 0; + std::vector &vec = tag.GetCompound(); + vec.push_back(ParseTag(data, s, listType)); + data += s; + size += s; + } + return tag; + } + case ByteArray: { + int32_t arrLength = *((int32_t *) data); + endswap(&arrLength); + data += 4; + size += 4; + for (int i = 0; i < arrLength; i++) { + signed char val = (signed char) data[i]; + std::vector &vec = tag.GetByteArray(); + vec.push_back(val); + } + data += arrLength; + size += arrLength; + return tag; + } + default: + throw 13; + } + } + + NbtTag ParseTag(unsigned char *data, size_t *optionalSize = nullptr) { + size_t s = 0; + size_t &size = (optionalSize ? *optionalSize : s); + return ParseTag(data, size); + } + + std::vector Decompress(unsigned char *data, size_t dataLen) { + const size_t decompBuffSize = 1024 * 16; + unsigned char *decompBuff = new unsigned char[decompBuffSize]; + std::vector uncompressed; + for (int i = 0; i < decompBuffSize; i++) + decompBuff[i] = 0; + + + z_stream stream; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + stream.opaque = Z_NULL; + stream.next_in = data; + stream.avail_in = dataLen; + stream.next_out = decompBuff; + stream.avail_out = decompBuffSize; + + if (inflateInit2(&stream, 15 + 32) != Z_OK) { + delete[] decompBuff; + throw 171; + } + + int res; + do { + stream.avail_out = decompBuffSize; + + switch ((res = inflate(&stream, Z_NO_FLUSH))) { + case Z_MEM_ERROR: + throw 172; + case Z_DATA_ERROR: + throw 173; + case Z_NEED_DICT: + throw 174; + } + + uncompressed.resize(uncompressed.size() + decompBuffSize); + std::copy(decompBuff, decompBuff + decompBuffSize, uncompressed.end() - decompBuffSize); + } while (stream.avail_out == 0); + if (res != Z_STREAM_END) + throw 175; + if (inflateEnd(&stream) != Z_OK) + throw 176; + delete[] decompBuff; + return uncompressed; + } + + NbtTag ParseCompressed(unsigned char *data, size_t dataLen) { + auto uncompressed = Decompress(data, dataLen); + NbtTag root = ParseTag(uncompressed.data()); + return root; + } + + NbtTag Parse(unsigned char *data, size_t dataLen) { + bool isCompressed = *data != 10; + if (isCompressed) + return ParseCompressed(data, dataLen); + else + return ParseTag(data); + } + + void PrintTree(NbtTag &tree, int deepness = 0, std::ostream &ostream = std::cout) { + ostream << std::string(deepness, '\t') << "Tag "; + switch (tree.GetType()) { + case Byte: + ostream << "byte"; + break; + case Short: + ostream << "short"; + break; + case Int: + ostream << "int"; + break; + case Long: + ostream << "long"; + break; + case Float: + ostream << "float"; + break; + case Double: + ostream << "double"; + break; + case ByteArray: + ostream << "byte array"; + break; + case String: + ostream << "string"; + break; + case List: + ostream << "list"; + break; + case Compound: + ostream << "compound"; + break; + case IntArray: + ostream << "int array"; + break; + case End: + ostream << "end"; + break; + } + if (tree.GetName().length() > 0) + ostream << " (" << tree.GetName() << ")"; + ostream << ": "; + + if (tree.GetType() == Compound || tree.GetType() == List) { + std::vector &vec = (tree.GetType() == Compound ? tree.GetCompound() : tree.GetList()); + ostream << vec.size() << " entries {" << std::endl; + for (auto it = vec.begin(); it != vec.end(); ++it) { + PrintTree(*it, deepness + 1, std::cout); + } + ostream << std::string(deepness, '\t') << "}" << std::endl; + return; + } else { + switch (tree.GetType()) { + case Int: + ostream << tree.GetInt(); + break; + case String: + ostream << "\"" << tree.GetString() << "\""; + break; + case Double: + ostream << tree.GetDouble(); + break; + case Float: + ostream << tree.GetFloat(); + break; + case Short: + ostream << tree.GetShort(); + break; + case Byte: + ostream << (int) tree.GetByte(); + break; + case Long: + ostream << tree.GetLong(); + break; + case ByteArray: + ostream << "[" << tree.GetByteArray().size() << " bytes]: "; + for (int i = 0; i < (tree.GetByteArray().size() > 10 ? 10 : tree.GetByteArray().size()); i++) { + ostream << std::hex << "0x" << (tree.GetByteArray()[i] > 15 ? "" : "0") + << (int) tree.GetByteArray()[i] + << std::dec << " "; + } + break; + case IntArray: + break; + } + ostream << std::endl; + } + } +} \ No newline at end of file diff --git a/src/Utility.hpp b/src/Utility.hpp new file mode 100644 index 0000000..11b4ff7 --- /dev/null +++ b/src/Utility.hpp @@ -0,0 +1,59 @@ +#pragma once + +#include + +#include + +template +void endswap(T *objp) { + unsigned char *memp = reinterpret_cast(objp); + std::reverse(memp, memp + sizeof(T)); +} + +template +void endswap(T &obj) { + unsigned char *raw = reinterpret_cast(&obj); + std::reverse(raw, raw + sizeof(T)); +} + +inline void endswap(unsigned char *arr, size_t arrLen) { + std::reverse(arr, arr + arrLen); +} + +inline GLenum glCheckError_(const char *file, int line) { + GLenum errorCode; + while ((errorCode = glGetError()) != GL_NO_ERROR) { + std::string error; + switch (errorCode) { + case GL_INVALID_ENUM: + error = "INVALID_ENUM"; + break; + case GL_INVALID_VALUE: + error = "INVALID_VALUE"; + break; + case GL_INVALID_OPERATION: + error = "INVALID_OPERATION"; + break; + case GL_STACK_OVERFLOW: + error = "STACK_OVERFLOW"; + break; + case GL_STACK_UNDERFLOW: + error = "STACK_UNDERFLOW"; + break; + case GL_OUT_OF_MEMORY: + error = "OUT_OF_MEMORY"; + break; + case GL_INVALID_FRAMEBUFFER_OPERATION: + error = "INVALID_FRAMEBUFFER_OPERATION"; + break; + } + static int t = 0; + t++; + if (t>10) + LOG(FATAL); + LOG(ERROR) << "OpenGL error: " << error << " at " << file << ":" << line; + } + return errorCode; +} + +#define glCheckError() glCheckError_(__FILE__, __LINE__) \ No newline at end of file diff --git a/src/Vector.hpp b/src/Vector.hpp new file mode 100644 index 0000000..a2d5c6a --- /dev/null +++ b/src/Vector.hpp @@ -0,0 +1,116 @@ +#pragma once + +#include +#include +#include + +#include + +template +class Vector3 { + T x, y, z; +public: + Vector3(T X = 0, T Y = 0, T Z = 0) : x(X), y(Y), z(Z) {} + + Vector3(const Vector3 &rhs) : x(rhs.x), y(rhs.y), z(rhs.z) {} + + ~Vector3() = default; + + void SetX(T X) { x = X; } + + void SetY(T Y) { y = Y; } + + void SetZ(T Z) { z = Z; } + + T GetX() const { return x; } + + T GetY() const { return y; } + + T GetZ() const { return z; } + + double GetMagnitude() const { return std::sqrt(std::pow(x, 2) + std::pow(y, 2) + std::pow(z, 2)); } + + operator glm::vec3() const { + return glm::vec3(x, y, z); + } + + void swap(Vector3 &rhs) { + std::swap(x, rhs.x); + std::swap(y, rhs.y); + std::swap(z, rhs.z); + } + + Vector3 &operator=(Vector3 rhs) { + rhs.swap(*this); + return *this; + } + + Vector3 operator*(T rhs) const { + return Vector3( + x * rhs, + y * rhs, + z * rhs + ); + } + + Vector3 operator/(T rhs) const { + return Vector3( + x / rhs, + y / rhs, + z / rhs + ); + } + + Vector3 operator+(const Vector3 &rhs) const { + return Vector3( + x + rhs.x, + y + rhs.y, + z + rhs.z + ); + } + + Vector3 operator-(const Vector3 &rhs) const { + return Vector3( + x - rhs.x, + y - rhs.y, + z - rhs.z + ); + } + + Vector3 operator*(const Vector3 &rhs) const { + return Vector3( + x * rhs.x, + y * rhs.y, + z * rhs.z + ); + } + + Vector3 operator/(const Vector3 &rhs) const { + return Vector3( + x / rhs.x, + y / rhs.y, + z / rhs.z + ); + } + + bool operator==(const Vector3 &rhs) const { + return (x == rhs.x && y == rhs.y && z == rhs.z); + } + + bool operator!=(const Vector3 &rhs) const { + return !(*this == rhs); + } + + bool operator<(const Vector3 &rhs) const { + return std::tie(x, y, z) < std::tie(rhs.x, rhs.y, rhs.z); + } + + + friend std::ostream &operator<<(std::ostream &os, const Vector3 &vector3) { + os << vector3.x << ", " << vector3.y << ", " << vector3.z; + return os; + } +}; + +typedef Vector3 VectorF; +typedef Vector3 Vector; \ No newline at end of file diff --git a/src/core/AssetManager.cpp b/src/core/AssetManager.cpp index d263c4a..14ea677 100644 --- a/src/core/AssetManager.cpp +++ b/src/core/AssetManager.cpp @@ -1,4 +1,4 @@ -#include +#include namespace fs = std::experimental::filesystem; diff --git a/src/core/AssetManager.hpp b/src/core/AssetManager.hpp new file mode 100644 index 0000000..26c7eca --- /dev/null +++ b/src/core/AssetManager.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include +#include + +#include +#include +#include + +#include +#include + +struct TextureCoordinates { + TextureCoordinates(float x = -1, float y = -1, float w = -1, float h = -1) : x(x), y(y), w(w), h(h) {} + + bool operator==(const TextureCoordinates &rhs) const { + return x == rhs.x && + y == rhs.y && + w == rhs.w && + h == rhs.h; + } + + explicit operator bool() const { + return !(*this == TextureCoordinates(-1, -1, -1, -1)); + } + + float x, y, w, h; +}; + +struct BlockTextureId { + //Block sides: 0 - bottom, 1 - top, 2 - north, 3 - south, 4 - west, 5 - east 6 - every side + BlockTextureId(int id = 0, int state = 0, int side = 6) : id(id), state(state), side(side) {} + + int id:9; + int state:4; + int side:3; + + + bool operator<(const BlockTextureId &rhs) const { + if (id < rhs.id) + return true; + if (rhs.id < id) + return false; + if (state < rhs.state) + return true; + if (rhs.state < state) + return false; + return side < rhs.side; + } +}; + +class AssetManager { + Texture *textureAtlas; + std::map assetIds; + std::map assetTextures; + std::map textureAtlasIndexes; +public: + AssetManager(); + + ~AssetManager(); + + void LoadTextureResources(); + + TextureCoordinates GetTextureByAssetName(std::string AssetName); + + std::string GetTextureAssetNameByBlockId(BlockTextureId block); + + GLuint GetTextureAtlas(); + + const std::map &GetTextureAtlasIndexes(); + + void LoadIds(); + + TextureCoordinates GetTextureByBlock(BlockTextureId block); +}; diff --git a/src/core/Core.cpp b/src/core/Core.cpp index 44e2648..e98d204 100644 --- a/src/core/Core.cpp +++ b/src/core/Core.cpp @@ -44,7 +44,7 @@ void Core::Exec() { UpdateChunksToRender(); } - /*std::ostringstream toWindow; + std::ostringstream toWindow; auto camPos = gameState->Position(); auto velPos = glm::vec3(gameState->g_PlayerVelocityX, gameState->g_PlayerVelocityY, gameState->g_PlayerVelocityZ); @@ -57,7 +57,7 @@ void Core::Exec() { toWindow << " (" << deltaTime * 1000 << "ms); "; toWindow << "Tickrate: " << tickRate << " (" << (1.0 / tickRate * 1000) << "ms); "; toWindow << "Sections: " << sectionRate << " (" << (1.0 / sectionRate * 1000) << "ms); "; - window->setTitle(toWindow.str());*/ + window->setTitle(toWindow.str()); HandleEvents(); if (isMouseCaptured) HandleMouseCapture(); diff --git a/src/core/Core.hpp b/src/core/Core.hpp new file mode 100644 index 0000000..fdbb377 --- /dev/null +++ b/src/core/Core.hpp @@ -0,0 +1,95 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +struct MyMutex { + std::mutex mtx; + std::string str; + MyMutex(std::string name); + void lock(); + void unlock(); +}; + +class Core { + GameState *gameState; + NetworkClient *client; + sf::Window *window; + AssetManager *assetManager; + bool isMouseCaptured = false; + bool isRunning = true; + enum { + MainMenu, + Loading, + Playing, + PauseMenu, + } currentState = Playing; + float mouseXDelta, mouseYDelta; + float deltaTime; + float absTime; + + void RenderWorld(); + + void HandleMouseCapture(); + + void HandleEvents(); + + void InitSfml(unsigned int WinWidth, unsigned int WinHeight, std::string WinTitle); + + void InitGlew(); + + void SetMouseCapture(bool IsCaptured); + + void PrepareToRendering(); + + void RenderFrame(); + + unsigned int width(); + + unsigned int height(); + + void UpdateChunksToRender(); + + void UpdateGameState(); + + void UpdateSections(); + + std::thread gameStateLoopThread; + std::thread sectionUpdateLoopThread; + + Shader *shader; + //Cube verticies, Cube VAO, Cube UVs, TextureIndexes UboTextureIndexes, TextureData UboTextureIndexes, TextureData2 UboTextureIndexes, Blocks VBO, Models VBO, Line VAO, Lines VBO + bool isRendersShouldBeCreated=false; + std::condition_variable waitRendersCreated; + std::vector renders; + std::mutex toRenderMutex; + std::vector toRender; + std::map availableChunks; + std::mutex availableChunksMutex; + + int ChunkDistance = 3; + + RenderState renderState; + + double tickRate = 0; + double sectionRate = 0; + +public: + Core(); + + ~Core(); + + void Exec(); +}; diff --git a/src/core/Event.cpp b/src/core/Event.cpp new file mode 100644 index 0000000..10b2eaa --- /dev/null +++ b/src/core/Event.cpp @@ -0,0 +1,76 @@ +#include +#include + +std::queue EventAgregator::eventsToHandle; +std::mutex EventAgregator::queueMutex; +bool EventAgregator::isStarted = false; +std::vector EventAgregator::listeners; +std::mutex EventAgregator::listenersMutex; + +void EventAgregator::EventHandlingLoop() { + while (true) { + queueMutex.lock(); + if (!eventsToHandle.empty()) { + auto queue = eventsToHandle; + while (!eventsToHandle.empty()) + eventsToHandle.pop(); + queueMutex.unlock(); + + while (!queue.empty()) { + auto event = queue.front(); + listenersMutex.lock(); + for (auto& listener : listeners) { + LOG(INFO)<<"Listener notified about event"; + listener->PushEvent(event); + } + listenersMutex.unlock(); + queue.pop(); + } + + queueMutex.lock(); + } + queueMutex.unlock(); + } +} + +void EventAgregator::RegisterListener(EventListener &listener) { + listenersMutex.lock(); + LOG(INFO)<<"Registered handler "<<&listener; + listeners.push_back(&listener); + listenersMutex.unlock(); +} + +void EventAgregator::UnregisterListener(EventListener &listener) { + listenersMutex.lock(); + LOG(INFO)<<"Unregistered handler "<<&listener; + listeners.erase(std::find(listeners.begin(), listeners.end(), &listener)); + listenersMutex.unlock(); +} + + + +EventListener::EventListener() { + EventAgregator::RegisterListener(*this); +} + +EventListener::~EventListener() { + EventAgregator::UnregisterListener(*this); +} + +void EventListener::PushEvent(Event event) { + eventsMutex.lock(); + LOG(INFO)<<"Pushed event to queue"; + events.push(event); + eventsMutex.unlock(); +} + +/*void EventListener::RegisterHandler(EventType type, std::function handler) { + handlers[type] = handler; +}*/ + +bool EventListener::IsEventsQueueIsNotEmpty() { + eventsMutex.lock(); + bool value = !events.empty(); + eventsMutex.unlock(); + return value; +} \ No newline at end of file diff --git a/src/core/Event.hpp b/src/core/Event.hpp new file mode 100644 index 0000000..cfa990a --- /dev/null +++ b/src/core/Event.hpp @@ -0,0 +1,96 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +enum class EventType { + Echo, + ChunkChanged, +}; + +struct EchoData { + std::chrono::time_point time; +}; + +struct ChunkChangedData { + Vector chunkPosition; +}; + +using EventData = std::variant; + +struct Event { + EventType type; + EventData data; +}; + +class EventListener { + friend class EventAgregator; + + using HandlerFunc = std::function; + + std::map handlers; //TODO: There must be more elegant solution than std::variant of all data + + std::mutex eventsMutex; + + std::queue events; + + void PushEvent(Event event); + +public: + EventListener(); + ~EventListener(); + bool IsEventsQueueIsNotEmpty(); + + void RegisterHandler(EventType type, HandlerFunc handler) { + handlers[type] = handler; + } + + void HandleEvent() { + eventsMutex.lock(); + if (events.empty()) { + eventsMutex.unlock(); + return; + } + Event event = events.front(); + events.pop(); + eventsMutex.unlock(); + auto function = handlers[event.type]; + function(event.data); + } +}; + +class EventAgregator { + friend EventListener; + + EventAgregator() = default; + static std::queue eventsToHandle; + static std::mutex queueMutex; + static bool isStarted; + static std::vector listeners; + static std::mutex listenersMutex; + + static void EventHandlingLoop(); + + static void RegisterListener(EventListener &listener); + static void UnregisterListener(EventListener &listener); + +public: + static void PushEvent(EventType type, EventData data) { + if (!isStarted) { + isStarted = true; + std::thread(&EventAgregator::EventHandlingLoop).detach(); + } + Event event; + event.type = type; + event.data = data; + eventsToHandle.push(event); + } +}; \ No newline at end of file diff --git a/src/graphics/Gui.hpp b/src/graphics/Gui.hpp new file mode 100644 index 0000000..e22a0a7 --- /dev/null +++ b/src/graphics/Gui.hpp @@ -0,0 +1,8 @@ +#pragma once + +class Gui { + +public: + int WHY=0; + +}; diff --git a/src/graphics/RenderSection.cpp b/src/graphics/RenderSection.cpp index 90d4329..ae072d6 100644 --- a/src/graphics/RenderSection.cpp +++ b/src/graphics/RenderSection.cpp @@ -138,7 +138,7 @@ RenderSection::~RenderSection() { refCounterVao[Vao]--; if (refCounterVbo[VboTextures] <= 0) glDeleteBuffers(1, &VboTextures); - + if (refCounterVbo[VboModels] <= 0) glDeleteBuffers(1, &VboTextures); if (refCounterVbo[VboColors] <= 0) @@ -297,13 +297,11 @@ void RenderSection::UpdateState(const std::map &textu } } numOfFaces = textures.size(); - hash = section.GetHash(); + hash = section.GetHash(); } void RenderSection::Render(RenderState &state) { - if (!isEnabled) { - return; - } + if (!isEnabled) return; if (!models.empty()) { glBindBuffer(GL_ARRAY_BUFFER, VboTextures); glBufferData(GL_ARRAY_BUFFER, textures.size() * sizeof(glm::vec4), textures.data(), GL_DYNAMIC_DRAW); @@ -339,7 +337,7 @@ RenderSection::RenderSection(const RenderSection &other) { this->models = other.models; this->textures = other.textures; this->colors = other.colors; - this->hash = other.hash; + this->hash = other.hash; refCounterVbo[VboTextures]++; refCounterVbo[VboModels]++; @@ -348,11 +346,11 @@ RenderSection::RenderSection(const RenderSection &other) { } void RenderSection::SetEnabled(bool isEnabled) { - this->isEnabled = isEnabled; + this->isEnabled = isEnabled; } bool RenderSection::IsNeedUpdate() { - size_t currentHash = world->GetSection(sectionPosition).GetHash(); - bool isNeedUpdate = currentHash != hash; - return isNeedUpdate; + size_t currentHash = world->GetSection(sectionPosition).GetHash(); + bool isNeedUpdate = currentHash != hash; + return isNeedUpdate; } \ No newline at end of file diff --git a/src/graphics/RenderSection.hpp b/src/graphics/RenderSection.hpp new file mode 100644 index 0000000..5973909 --- /dev/null +++ b/src/graphics/RenderSection.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +class RenderState { + GLuint ActiveVao; + GLuint ActiveShader; +public: + void SetActiveVao(GLuint Vao); + void SetActiveShader(GLuint Shader); +}; + +class RenderSection { + Vector sectionPosition; + World *world; + GLuint Vao, VboTextures, VboModels, VboColors; + std::vector models; + std::vector textures; + std::vector colors; + + static GLuint VboVertices, VboUvs; + static std::map refCounterVbo; + static std::map refCounterVao; + + size_t numOfFaces = 0; + + bool isEnabled = true; + + size_t hash = 0; +public: + RenderSection(World *world, Vector position); + RenderSection(const RenderSection &other); + ~RenderSection(); + + void UpdateState(const std::map &textureAtlas); + void Render(RenderState &state); + + void SetEnabled(bool isEnabled); + + Section *GetSection(); + + bool IsNeedUpdate(); +}; \ No newline at end of file diff --git a/src/graphics/Shader.hpp b/src/graphics/Shader.hpp new file mode 100644 index 0000000..17a434e --- /dev/null +++ b/src/graphics/Shader.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include + +#include +#include + +class Shader +{ +private: + const GLchar *vertex; + const GLchar *fragment; +public: + // Идентификатор программы + GLuint Program; + // Конструктор считывает и собирает шейдер + Shader(const GLchar* vertexPath, const GLchar* fragmentPath, const GLchar* geometryPath = nullptr); + // Использование программы + void Use(); + + void Reload(); +}; \ No newline at end of file diff --git a/src/graphics/Texture.hpp b/src/graphics/Texture.hpp new file mode 100644 index 0000000..277806a --- /dev/null +++ b/src/graphics/Texture.hpp @@ -0,0 +1,14 @@ +#pragma once + +#include +#include +#include + +class Texture { + Texture(Texture&); + Texture&operator=(Texture&); +public: + GLuint texture; + Texture(std::string filename, GLenum textureWrapping = GL_CLAMP_TO_BORDER, GLenum textureFiltering = GL_NEAREST); + ~Texture(); +}; \ No newline at end of file diff --git a/src/graphics/Widget.hpp b/src/graphics/Widget.hpp new file mode 100644 index 0000000..c4d5dc1 --- /dev/null +++ b/src/graphics/Widget.hpp @@ -0,0 +1,8 @@ +#pragma once + +class Widget { + unsigned int x,y,w,h; +public: + Widget(Widget *parent); + ~Widget(); +}; diff --git a/src/main.cpp b/src/main.cpp index aa30ff8..bcf573b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,4 +1,5 @@ -#include "../include/Core.hpp" +#include "core/Core.hpp" +#include const char *getTimeSinceProgramStart(void) { static auto initialTime = std::chrono::steady_clock().now(); @@ -25,6 +26,8 @@ int main() { el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); LOG(INFO) << "Logger is configured"; + LOG(FATAL)<<"Sizeof data is "< Network::Network(std::string address, unsigned short port) { - socket = new Socket(address, port); - stream = new StreamSocket(socket); + try { + socket = new Socket(address, port); + stream = new StreamSocket(socket); + } catch (std::exception &e) { + LOG(FATAL)< +#include "Socket.hpp" +#include "Packet.hpp" + +enum ConnectionState { + Handshaking, + Login, + Play, + Status, +}; + +class Network { + Socket *socket; + StreamSocket *stream; + + std::shared_ptr ReceivePacketByPacketId(int packetId, ConnectionState state, StreamInput &stream); +public: + Network(std::string address, unsigned short port); + ~Network(); + + std::shared_ptr ReceivePacket(ConnectionState state = Play); + void SendPacket(Packet &packet); + std::shared_ptr ParsePacketPlay(PacketNamePlayCB id); +}; \ No newline at end of file diff --git a/src/network/NetworkClient.hpp b/src/network/NetworkClient.hpp new file mode 100644 index 0000000..22b1b22 --- /dev/null +++ b/src/network/NetworkClient.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include + +#include + +class NetworkClient { + Network network; + std::thread networkThread; + std::mutex toSendMutex; + std::mutex toReceiveMutex; + std::queue > toSend; + std::queue > toReceive; + bool isActive=true; + bool &isRunning; + ConnectionState state; + void NetworkLoop(); +public: + NetworkClient(std::string address, unsigned short port, std::string username, bool &quit); + ~NetworkClient(); + + std::shared_ptr ReceivePacket(); + void SendPacket(std::shared_ptr packet); +}; \ No newline at end of file diff --git a/src/network/Packet.hpp b/src/network/Packet.hpp new file mode 100644 index 0000000..685e3da --- /dev/null +++ b/src/network/Packet.hpp @@ -0,0 +1,521 @@ +#pragma once + +#include + +#include + +enum PacketNameLoginSB { + LoginStart = 0x00, + EncryptionResponse = 0x01, +}; +enum PacketNamePlaySB { + TeleportConfirm, + PrepareCraftingGrid, + TabCompleteSB, + ChatMessageSB, + ClientStatus, + ClientSettings, + ConfirmTransactionSB, + EnchantItem, + ClickWindow, + CloseWindowSB, + PluginMessageSB, + UseEntity, + KeepAliveSB, + Player, + PlayerPosition, + PlayerPositionAndLookSB, + PlayerLook, + VehicleMoveSB, + SteerBoat, + PlayerAbilitiesSB, + PlayerDigging, + EntityAction, + SteerVehicle, + CraftingBookData, + ResourcePackStatus, + AdvancementTab, + HeldItemChangeSB, + CreativeInventoryAction, + UpdateSign, + AnimationSB, + Spectate, + PlayerBlockPlacement, + UseItem, +}; + +enum PacketNameHandshakingCB { + Handshake = 0x00, +}; +enum PacketNameLoginCB { + Disconnect = 0x00, + EncryptionRequest = 0x01, + LoginSuccess = 0x02, + SetCompression = 0x03, +}; +enum PacketNamePlayCB { + SpawnObject = 0x00, + SpawnExperienceOrb, + SpawnGlobalEntity, + SpawnMob, + SpawnPainting, + SpawnPlayer, + AnimationCB, + Statistics, + BlockBreakAnimation, + UpdateBlockEntity, + BlockAction, + BlockChange, + BossBar, + ServerDifficulty, + TabCompleteCB, + ChatMessageCB, + MultiBlockChange, + ConfirmTransactionCB, + CloseWindowCB, + OpenWindow, + WindowItems, + WindowProperty, + SetSlot, + SetCooldown, + PluginMessageCB, + NamedSoundEffect, + DisconnectPlay, + EntityStatus, + Explosion, + UnloadChunk, + ChangeGameState, + KeepAliveCB, + ChunkData, + Effect, + Particle, + JoinGame, + Map, + EntityRelativeMove, + EntityLookAndRelativeMove, + EntityLook, + Entity, + VehicleMove, + OpenSignEditor, + PlayerAbilitiesCB, + CombatEvent, + PlayerListItem, + PlayerPositionAndLookCB, + UseBed, + UnlockRecipes, + DestroyEntities, + RemoveEntityEffect, + ResourcePackSend, + Respawn, + EntityHeadLook, + SelectAdvancementTab, + WorldBorder, + Camera, + HeldItemChangeCB, + DisplayScoreboard, + EntityMetadata, + AttachEntity, + EntityVelocity, + EntityEquipment, + SetExperience, + UpdateHealth, + ScoreboardObjective, + SetPassengers, + Teams, + UpdateScore, + SpawnPosition, + TimeUpdate, + Title, + SoundEffect, + PlayerListHeaderAndFooter, + CollectItem, + EntityTeleport, + Advancements, + EntityProperties, + EntityEffect, +}; + +struct Packet { + virtual ~Packet() = default; + virtual void ToStream(StreamOutput *stream) = 0; + virtual void FromStream(StreamInput *stream) = 0; + virtual int GetPacketId() = 0; +}; + +struct PacketHandshake : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteVarInt(protocolVersion); + stream->WriteString(serverAddress); + stream->WriteUShort(serverPort); + stream->WriteVarInt(nextState); + } + + void FromStream(StreamInput *stream) override { + protocolVersion = stream->ReadVarInt(); + serverAddress = stream->ReadString(); + serverPort = stream->ReadUShort(); + nextState = stream->ReadVarInt(); + } + + int GetPacketId() override { + return PacketNameHandshakingCB::Handshake; + } + + int protocolVersion; + std::string serverAddress; + unsigned short serverPort; + int nextState; +}; + +struct PacketLoginStart : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteString(Username); + } + + void FromStream(StreamInput *stream) override { + Username = stream->ReadString(); + } + + int GetPacketId() override { + return PacketNameLoginSB::LoginStart; + } + + std::string Username; +}; + +struct PacketLoginSuccess : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteString(Uuid); + stream->WriteString(Username); + } + + void FromStream(StreamInput *stream) override { + Uuid = stream->ReadString(); + Username = stream->ReadString(); + } + + int GetPacketId() override { + return PacketNameLoginCB::LoginSuccess; + } + + std::string Uuid; + std::string Username; +}; + +struct PacketJoinGame : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteInt(EntityId); + stream->WriteUByte(Gamemode); + stream->WriteInt(Dimension); + stream->WriteUByte(Difficulty); + stream->WriteUByte(MaxPlayers); + stream->WriteString(LevelType); + stream->WriteBool(ReducedDebugInfo); + } + + void FromStream(StreamInput *stream) override { + EntityId = stream->ReadInt(); + Gamemode = stream->ReadUByte(); + Dimension = stream->ReadInt(); + Difficulty = stream->ReadUByte(); + MaxPlayers = stream->ReadUByte(); + LevelType = stream->ReadString(); + ReducedDebugInfo = stream->ReadBool(); + } + + int GetPacketId() override { + return PacketNamePlayCB::JoinGame; + } + + int EntityId; + unsigned char Gamemode; + int Dimension; + unsigned char Difficulty; + unsigned char MaxPlayers; + std::string LevelType; + bool ReducedDebugInfo; +}; + +struct PacketDisconnectPlay : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteString(Reason); //TODO: Implement chat-wrapper + } + + void FromStream(StreamInput *stream) override { + Reason = stream->ReadChat(); + } + + int GetPacketId() override { + return PacketNamePlayCB::DisconnectPlay; + } + + std::string Reason; +}; + +struct PacketSpawnPosition : Packet { + void ToStream(StreamOutput *stream) override { + stream->WritePosition(Location); + } + + void FromStream(StreamInput *stream) override { + Location = stream->ReadPosition(); + } + + int GetPacketId() override { + return PacketNamePlayCB::SpawnPosition; + } + + Vector Location; +}; + +struct PacketKeepAliveCB : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteVarInt(KeepAliveId); + } + + void FromStream(StreamInput *stream) override { + KeepAliveId = stream->ReadVarInt(); + } + + int GetPacketId() override { + return PacketNamePlayCB::KeepAliveCB; + } + + int KeepAliveId; +}; + +struct PacketKeepAliveSB : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteVarInt(KeepAliveId); + } + + void FromStream(StreamInput *stream) override { + KeepAliveId = stream->ReadVarInt(); + } + + int GetPacketId() override { + return PacketNamePlaySB::KeepAliveSB; + } + + int KeepAliveId; + + PacketKeepAliveSB(int KeepAliveId) : KeepAliveId(KeepAliveId) {} +}; + +struct PacketPlayerPositionAndLookCB : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteDouble(X); + stream->WriteDouble(Y); + stream->WriteDouble(Z); + stream->WriteFloat(Yaw); + stream->WriteFloat(Pitch); + stream->WriteUByte(Flags); + stream->WriteVarInt(TeleportId); + } + + void FromStream(StreamInput *stream) override { + X = stream->ReadDouble(); + Y = stream->ReadDouble(); + Z = stream->ReadDouble(); + Yaw = stream->ReadFloat(); + Pitch = stream->ReadFloat(); + Flags = stream->ReadUByte(); + TeleportId = stream->ReadVarInt(); + } + + int GetPacketId() override { + return PacketNamePlayCB::PlayerPositionAndLookCB; + } + + double X; + double Y; + double Z; + float Yaw; + float Pitch; + unsigned char Flags; + int TeleportId; +}; + +struct PacketTeleportConfirm : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteVarInt(TeleportId); + } + + void FromStream(StreamInput *stream) override { + TeleportId = stream->ReadVarInt(); + } + + int GetPacketId() override { + return PacketNamePlaySB::TeleportConfirm; + } + + int TeleportId; + + PacketTeleportConfirm(int TeleportId) : TeleportId(TeleportId) {} +}; + +struct PacketClientStatus : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteVarInt(ActionId); + } + + void FromStream(StreamInput *stream) override { + ActionId = stream->ReadVarInt(); + } + + int GetPacketId() override { + return PacketNamePlaySB::ClientStatus; + } + + int ActionId; + + PacketClientStatus(int ActionId) : ActionId(ActionId) {} +}; + +struct PacketPlayerPositionAndLookSB : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteDouble(X); + stream->WriteDouble(FeetY); + stream->WriteDouble(Z); + stream->WriteFloat(Yaw); + stream->WriteFloat(Pitch); + stream->WriteBool(OnGround); + } + + void FromStream(StreamInput *stream) override { + X = stream->ReadDouble(); + FeetY = stream->ReadDouble(); + Z = stream->ReadDouble(); + Yaw = stream->ReadFloat(); + Pitch = stream->ReadFloat(); + OnGround = stream->ReadBool(); + } + + int GetPacketId() override { + return PacketNamePlaySB::PlayerPositionAndLookSB; + } + + + double X; + double FeetY; + double Z; + float Yaw; + float Pitch; + bool OnGround; + + PacketPlayerPositionAndLookSB(double X, double FeetY, double Z, + float Yaw, float Pitch, bool OnGround) : X(X), FeetY(FeetY), Z(Z), Yaw(Yaw), + Pitch(Pitch), OnGround(OnGround) {} +}; + +struct PacketChunkData : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteInt(ChunkX); + stream->WriteInt(ChunkZ); + stream->WriteBool(GroundUpContinuous); + stream->WriteInt(PrimaryBitMask); + stream->WriteVarInt(Data.size()); + stream->WriteByteArray(Data); + stream->WriteVarInt(BlockEntities.size()); + LOG(FATAL) << "Serializing unimplemented packet"; + } + + void FromStream(StreamInput *stream) override { + ChunkX = stream->ReadInt(); + ChunkZ = stream->ReadInt(); + GroundUpContinuous = stream->ReadBool(); + PrimaryBitMask = stream->ReadVarInt(); + int Size = stream->ReadVarInt(); + Data = stream->ReadByteArray(Size); + int NumberOfBlockEntities = stream->ReadVarInt(); //TODO: Need NBT + for (int i = 0; i < NumberOfBlockEntities; i++) { + //BlockEntities[i] = stream->ReadNbt(); + } + } + + int GetPacketId() override { + return PacketNamePlayCB::ChunkData; + } + + int ChunkX; + int ChunkZ; + bool GroundUpContinuous; + int PrimaryBitMask; + //int Size; + std::vector Data; + //int NumberOfBlockEntities; + std::vector BlockEntities; //TODO: Replace int with NbtTag and implement NbtTree +}; + +struct PacketPlayerPosition : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteDouble(X); + stream->WriteDouble(FeetY); + stream->WriteDouble(Z); + stream->WriteBool(OnGround); + } + + void FromStream(StreamInput *stream) override { + X = stream->ReadDouble(); + FeetY = stream->ReadDouble(); + Z = stream->ReadDouble(); + OnGround = stream->ReadBool(); + } + + int GetPacketId() override { + return PacketNamePlaySB::PlayerPosition; + } + + double X; + double FeetY; + double Z; + bool OnGround; + + PacketPlayerPosition(double X, double Y, double Z, bool ground) : X(X), FeetY(Y), Z(Z), OnGround(ground) {} +}; + +struct PacketPlayerLook : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteFloat(Yaw); + stream->WriteFloat(Pitch); + stream->WriteBool(OnGround); + } + + void FromStream(StreamInput *stream) override { + Yaw = stream->ReadFloat(); + Pitch = stream->ReadFloat(); + OnGround = stream->ReadBool(); + } + + int GetPacketId() override { + return PacketNamePlaySB::PlayerLook; + } + + float Yaw; + float Pitch; + bool OnGround; + + PacketPlayerLook(float Yaw, float Pitch, bool ground) : Yaw(Yaw), Pitch(Pitch), OnGround(ground) {} +}; + +struct PacketUpdateHealth : Packet { + void ToStream(StreamOutput *stream) override { + stream->WriteFloat(Health); + stream->WriteVarInt(Food); + stream->WriteFloat(FoodSaturation); + } + + void FromStream(StreamInput *stream) override { + Health = stream->ReadFloat(); + Food = stream->ReadVarInt(); + FoodSaturation = stream->ReadFloat(); + } + + int GetPacketId() override { + return PacketNamePlayCB::UpdateHealth; + } + + float Health; + int Food; + float FoodSaturation; +}; \ No newline at end of file diff --git a/src/network/Socket.hpp b/src/network/Socket.hpp new file mode 100644 index 0000000..48bcad9 --- /dev/null +++ b/src/network/Socket.hpp @@ -0,0 +1,46 @@ +#pragma once + +#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; +public: + /** + * Constructs Socket class instance from IP's string and Port number and connects to remote server + * @param[in] address IP address of remote server. String should be ANSI and contains 4 one-byte values separated by dots + * @param[in] port target port of remote server to connect + * @throw std::runtime_error if connection is failed + */ + Socket(std::string address, unsigned short port); + + /** + * 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 + */ + ~Socket(); + + /** + * Reads data from socket and write to buffer + * @warning This is blocking function, and execution flow will not be returned until all required data is sended + * @warning Reported buffer length must be <= actual size of buffer, or memory corruption will be caused + * @param[out] buffPtr Pointer to buffer, where data must be placed + * @param[in] buffLen Length of data, that must be readed from server and writed to buffer + */ + void Read(unsigned char *buffPtr, size_t buffLen); + + /** + * Writes data from buffer to socket + * @warning This is blocking function, and execution flow will not be returned until all required data is received + * @param[in] buffPtr Pointer to buffer that contain data to send + * @param[in] buffLen Length of buffer + */ + void Write(unsigned char *buffPtr, size_t buffLen); +}; \ No newline at end of file diff --git a/src/network/Stream.hpp b/src/network/Stream.hpp new file mode 100644 index 0000000..a24dfbe --- /dev/null +++ b/src/network/Stream.hpp @@ -0,0 +1,107 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +class Stream { +public: + virtual ~Stream() {}; +}; + +class StreamInput : Stream { + virtual void ReadData(unsigned char *buffPtr, size_t buffLen) = 0; +public: + virtual ~StreamInput() = default; + bool ReadBool(); + signed char ReadByte(); + unsigned char ReadUByte(); + short ReadShort(); + unsigned short ReadUShort(); + int ReadInt(); + long long ReadLong(); + float ReadFloat(); + double ReadDouble(); + std::string ReadString(); + std::string ReadChat(); + int ReadVarInt(); + long long ReadVarLong(); + std::vector ReadEntityMetadata(); + std::vector ReadSlot(); + std::vector ReadNbtTag(); + Vector ReadPosition(); + unsigned char ReadAngle(); + std::vector ReadUuid(); + std::vector ReadByteArray(size_t arrLength); +}; + +class StreamOutput : Stream { + virtual void WriteData(unsigned char *buffPtr, size_t buffLen) = 0; +public: + virtual ~StreamOutput() = default; + void WriteBool(bool value); + void WriteByte(signed char value); + void WriteUByte(unsigned char value); + void WriteShort(short value); + void WriteUShort(unsigned short value); + void WriteInt(int value); + void WriteLong(long long value); + void WriteFloat(float value); + void WriteDouble(double value); + void WriteString(std::string value); + void WriteChat(std::string value); + void WriteVarInt(int value); + void WriteVarLong(long long value); + void WriteEntityMetadata(std::vector value); + void WriteSlot(std::vector value); + void WriteNbtTag(std::vector value); + void WritePosition(Vector value); + void WriteAngle(unsigned char value); + void WriteUuid(std::vector value); + void WriteByteArray(std::vector value); +}; + +class StreamBuffer : public StreamInput, public StreamOutput { + unsigned char *buffer; + unsigned char *bufferPtr; + size_t bufferLength; + + void ReadData(unsigned char *buffPtr, size_t buffLen) override; + void WriteData(unsigned char *buffPtr, size_t buffLen) override; + +public: + StreamBuffer(unsigned char *data, size_t dataLen); + StreamBuffer(size_t bufferLen); + ~StreamBuffer(); + + std::vector GetBuffer(); +}; + +class StreamCounter : public StreamOutput { + void WriteData(unsigned char *buffPtr, size_t buffLen) override; + + size_t size; +public: + StreamCounter(size_t initialSize = 0); + ~StreamCounter(); + + size_t GetCountedSize(); +}; + +class StreamSocket : public StreamInput, public StreamOutput { + Socket *socket; + void ReadData(unsigned char *buffPtr, size_t buffLen) override; + void WriteData(unsigned char *buffPtr, size_t buffLen) override; +public: + StreamSocket(Socket *socketPtr); + ~StreamSocket() = default; +}; \ No newline at end of file diff --git a/src/world/Block.hpp b/src/world/Block.hpp new file mode 100644 index 0000000..2f823fe --- /dev/null +++ b/src/world/Block.hpp @@ -0,0 +1,15 @@ +#pragma once + +struct Block { + Block(); + + Block(unsigned short id, unsigned char state); + + ~Block(); + + unsigned short id : 13; + unsigned char state : 4; + //unsigned char light:4; +}; + +bool operator<(const Block &lhs, const Block &rhs); \ No newline at end of file diff --git a/src/world/Collision.hpp b/src/world/Collision.hpp new file mode 100644 index 0000000..b88fbf7 --- /dev/null +++ b/src/world/Collision.hpp @@ -0,0 +1,8 @@ +#pragma once + +struct AABB { + double x,y,z; + double w,l,h; +}; + +bool TestCollision(AABB first, AABB second); \ No newline at end of file diff --git a/src/world/GameState.cpp b/src/world/GameState.cpp index 79e2f1b..d3a6bd3 100644 --- a/src/world/GameState.cpp +++ b/src/world/GameState.cpp @@ -1,4 +1,4 @@ -#include +#include GameState::GameState(NetworkClient *Net, bool &quit) : nc(Net), isRunning(quit) { Front = glm::vec3(0.0f, 0.0f, -1.0f); diff --git a/src/world/GameState.hpp b/src/world/GameState.hpp new file mode 100644 index 0000000..6741882 --- /dev/null +++ b/src/world/GameState.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +class GameState { + NetworkClient *nc; +public: + GameState(NetworkClient *NetClient, bool &quit); + + void Update(float deltaTime); + + //Navigation + enum Direction { + FORWARD, BACKWARD, LEFT, RIGHT, JUMP + }; + void HandleMovement(GameState::Direction direction, float deltaTime); + void HandleRotation(double yaw, double pitch); + glm::mat4 GetViewMatrix(); + void updateCameraVectors(); + + float Yaw(); + float Pitch(); + void SetYaw(float yaw); + void SetPitch(float pitch); + + glm::vec3 Position(); + void SetPosition(glm::vec3 Position); + glm::vec3 Front; + glm::vec3 Up; + glm::vec3 Right; + glm::vec3 WorldUp; + + //Everything other + World world; + bool &isRunning; + + std::string g_PlayerUuid; + std::string g_PlayerName; + bool g_IsGameStarted; + int g_PlayerEid; + int g_Gamemode; + int g_Dimension; + byte g_Difficulty; + byte g_MaxPlayers; + std::string g_LevelType; + bool g_ReducedDebugInfo; + Vector g_SpawnPosition; + bool g_PlayerInvulnerable; + bool g_PlayerFlying; + bool g_PlayerAllowFlying; + bool g_PlayerCreativeMode; + float g_PlayerFlyingSpeed; + float g_PlayerFovModifier; + float g_PlayerPitch; + float g_PlayerYaw; + double g_PlayerX; + double g_PlayerY; + double g_PlayerZ; + float g_PlayerHealth; + + bool g_OnGround = true; + double g_PlayerVelocityX = 0; + double g_PlayerVelocityY = 0; + double g_PlayerVelocityZ = 0; +}; diff --git a/src/world/Section.cpp b/src/world/Section.cpp index 279d2b2..ff2a4fb 100644 --- a/src/world/Section.cpp +++ b/src/world/Section.cpp @@ -47,28 +47,28 @@ void Section::Parse() { endswap(&longArray[i]); 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 < m_dataBlocksLen; i++) { - for (int j = 0; j < 8; j++) { - t |= (m_dataBlocks[i] & 0x01) ? 0x80 : 0x00; - t >>= 1; - m_dataBlocks[i] >>= 1; - bitPos++; - if (bitPos >= m_bitsPerBlock) { - bitPos = 0; - t >>= m_bitsPerBlock - 1; - blocks.push_back(t); - t = 0; - } - } - } - auto end = std::chrono::steady_clock::now(); - std::chrono::duration time = end - begin; - totalParsingTime += time.count(); - } + { + auto begin = std::chrono::steady_clock::now(); + int bitPos = 0; + unsigned short t = 0; + for (size_t i = 0; i < m_dataBlocksLen; i++) { + for (int j = 0; j < 8; j++) { + t |= (m_dataBlocks[i] & 0x01) ? 0x80 : 0x00; + t >>= 1; + m_dataBlocks[i] >>= 1; + bitPos++; + if (bitPos >= m_bitsPerBlock) { + bitPos = 0; + t >>= m_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++) { @@ -137,8 +137,11 @@ Vector Section::GetPosition() { } size_t Section::GetHash() { - if (m_blocks.empty()) - return 0; - std::string str((unsigned char*)m_blocks.data(), (unsigned char*)m_blocks.data() + m_blocks.size() * sizeof(Block)); - return std::hash{}(str); + if (m_blocks.empty()) return 0; + + unsigned char *from = reinterpret_cast(m_blocks.data()); + size_t length = m_blocks.size() * sizeof(Block); + + std::string str(from, from + length); + return std::hash{}(str); } \ No newline at end of file diff --git a/src/world/Section.hpp b/src/world/Section.hpp new file mode 100644 index 0000000..2df0cfe --- /dev/null +++ b/src/world/Section.hpp @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include +#include + +#include + +#include +#include +#include + +const int SECTION_WIDTH = 16; +const int SECTION_LENGTH = 16; +const int SECTION_HEIGHT = 16; + +class Section { + std::vector m_palette; + byte *m_dataBlocks = nullptr; + size_t m_dataBlocksLen; + byte *m_dataLight = nullptr; + byte *m_dataSkyLight = nullptr; + byte m_bitsPerBlock = 0; + std::vector m_blocks; + std::condition_variable parseWaiter; + + Section(); + + Vector worldPosition; + +public: + void Parse(); + + Section(Vector position, byte *dataBlocks, size_t dataBlocksLength, byte *dataLight, byte *dataSky, byte bitsPerBlock, + std::vector palette); + + ~Section(); + + Block &GetBlock(Vector pos); + + Section &operator=(Section other); + + friend void swap(Section &a, Section &b); + + Section(const Section &other); + + Vector GetPosition(); + + size_t GetHash(); +}; \ No newline at end of file diff --git a/src/world/World.hpp b/src/world/World.hpp new file mode 100644 index 0000000..6b09f1f --- /dev/null +++ b/src/world/World.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include +#include + +#include + +#include +#include +#include +#include + +class World { + std::map sections; + std::map sectionMutexes; + int dimension = 0; + + Section ParseSection(StreamInput *data, Vector position); + + World(const World &other); + World &operator=(const World &other); +public: + World(); + + ~World(); + + void ParseChunkData(std::shared_ptr packet); + + bool isPlayerCollides(double X, double Y, double Z); + + Block &GetBlock(Vector pos); + + std::vector GetSectionsList(); + + Section &GetSection(Vector sectionPos); + + glm::vec3 Raycast(glm::vec3 position, glm::vec3 direction, float maxLength = 1000.0f, float minPrecision = 0.01f); +}; \ No newline at end of file -- cgit v1.2.3